path stringlengths 5 169 | owner stringlengths 2 34 | repo_id int64 1.49M 755M | is_fork bool 2 classes | languages_distribution stringlengths 16 1.68k ⌀ | content stringlengths 446 72k | issues float64 0 1.84k | main_language stringclasses 37 values | forks int64 0 5.77k | stars int64 0 46.8k | commit_sha stringlengths 40 40 | size int64 446 72.6k | name stringlengths 2 64 | license stringclasses 15 values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
src/cn/leetcode/codes/offer/o42/Inter42.kt | shishoufengwise1234 | 258,793,407 | false | {"Java": 771296, "Kotlin": 68641} | package cn.leetcode.codes.offer.o42
import cn.leetcode.codes.out
import kotlin.math.max
fun main() {
val nums = intArrayOf(-2, 1, -3, 4, -1, 2, 1, -5, 4)
// val nums = intArrayOf(1)
out(maxSubArray(nums))
}
/*
剑指 Offer 42. 连续子数组的最大和
输入一个整型数组,数组中的一个或连续多个整数组成一个子数组。求所有子数组的和的最大值。
要求时间复杂度为O(n)。
示例1:
输入: nums = [-2,1,-3,4,-1,2,1,-5,4]
输出: 6
解释: 连续子数组 [4,-1,2,1] 的和最大,为 6。
提示:
1 <= arr.length <= 10^5
-100 <= arr[i] <= 100
注意:本题与主站 53 题相同:https://leetcode-cn.com/problems/maximum-subarray/
*/
//正数增益
// https://leetcode-cn.com/problems/maximum-subarray/solution/hua-jie-suan-fa-53-zui-da-zi-xu-he-by-guanpengchn/
fun maxSubArray(nums: IntArray): Int {
if (nums.isEmpty()) return 0
var sum = 0
var ans = nums[0]
nums.forEach { n ->
//之前sum大于零 对整体总和有帮助
if (sum > 0) {
sum += n
} else { //向后进 以当前值为开始 重新开始计算总和
sum = n
}
ans = max(ans, sum)
}
return ans
}
| 0 | Java | 0 | 0 | f917a262bcfae8cd973be83c427944deb5352575 | 1,231 | LeetCodeSimple | Apache License 2.0 |
src/Day07.kt | niltsiar | 572,887,970 | false | {"Kotlin": 16548} | fun main() {
fun part1(input: List<String>): Int {
val fileSystem = parseFileSystem(input)
return fileSystem.findNodes { node ->
node is Directory && node.size <= 100_000
}.sumOf { node -> node.size }
}
fun part2(input: List<String>): Int {
val fileSystem = parseFileSystem(input)
val unusedSpace = 70_000_000 - fileSystem.size
val neededSpace = 30_000_000 - unusedSpace
return fileSystem
.findNodes { node ->
node is Directory && node.size >= neededSpace
}.minBy { node -> node.size }
.size
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day07_test")
check(part1(testInput) == 95437)
check(part2(testInput) == 24933642)
val input = readInput("Day07")
println(part1(input))
println(part2(input))
}
sealed interface Node {
val name: String
val size: Int
val parent: Node?
}
class Directory(
override val name: String,
override val parent: Directory?,
val nodes: MutableList<Node> = mutableListOf(),
) : Node {
override val size: Int
get() = nodes.sumOf { node -> node.size }
}
class File(
override val name: String,
override val size: Int,
override val parent: Node?,
) : Node
fun parseFileSystem(input: List<String>): Directory {
val root = Directory("/", null)
parseFileSystem(input, root, root)
return root
}
tailrec fun parseFileSystem(input: List<String>, currentDirectory: Directory, root: Directory) {
if (input.isEmpty()) {
return
}
val line = input.first()
val newDirectory = if (line.first() == '$') {
val command = line.split(' ').drop(1)
when (command[0]) {
"cd" -> {
when (val destinationName = command[1]) {
".." -> currentDirectory.parent ?: root
"/" -> root
else -> {
val destinationDirectory = currentDirectory.nodes
.filterIsInstance<Directory>()
.single { it.name == destinationName }
destinationDirectory
}
}
}
"ls" -> currentDirectory
else -> error("BAD INPUT")
}
} else {
val output = line.split(" ")
when (output[0]) {
"dir" -> currentDirectory.nodes.add(Directory(output[1], currentDirectory))
else -> currentDirectory.nodes.add(File(output[1], output[0].toInt(), currentDirectory))
}
currentDirectory
}
parseFileSystem(input.drop(1), newDirectory, root)
}
fun Node.findNodes(predicate: (Node) -> Boolean): List<Node> {
return if (predicate(this)) {
listOf(this)
} else {
emptyList()
} + if (this is Directory) {
nodes.flatMap { node -> node.findNodes(predicate) }
} else {
emptyList()
}
}
| 0 | Kotlin | 0 | 0 | 766b3e168fc481e4039fc41a90de4283133d3dd5 | 3,037 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/aoc2022/day13/AoC13.kt | Saxintosh | 576,065,000 | false | {"Kotlin": 30013} | package aoc2022.day13
import readLines
fun main() {
fun String.isAnInteger() = firstOrNull()?.isDigit() == true
fun String.isAList() = firstOrNull() == '['
fun String.isEndOfList() = firstOrNull() == ']'
fun String.firstElement() = split(",", "]", limit = 2)[0]
fun String.dropFirstElement(): String {
var i = indexOfFirst { it == ',' || it == ']' }
if (get(i) == ',') i++
return drop(i)
}
fun String.removeEndOfList(): String {
var i = 1
if (getOrNull(1) == ',') i++
return drop(i)
}
fun isRightOrder(left: String, right: String): Boolean {
when {
left.isEndOfList() && !right.isEndOfList() -> return true
!left.isEndOfList() && right.isEndOfList() -> return false
left.isEndOfList() && right.isEndOfList() -> return isRightOrder(left.removeEndOfList(), right.removeEndOfList())
left.isAnInteger() && right.isAnInteger() -> {
val chL = left.firstElement().toInt()
val chR = right.firstElement().toInt()
return when {
chL < chR -> true
chL > chR -> false
else -> isRightOrder(left.dropFirstElement(), right.dropFirstElement())
}
}
left.isAList() && right.isAList() -> return isRightOrder(left.drop(1), right.drop(1))
left.isAList() && right.isAnInteger() -> return isRightOrder(left.drop(1), right.firstElement() + "]" + right.dropFirstElement())
left.isAnInteger() && right.isAList() -> return isRightOrder(left.firstElement() + "]" + left.dropFirstElement(), right.drop(1))
else -> TODO()
}
}
fun part1(lines: List<String>): Int {
var index = 0
val x = lines.windowed(3, 3, partialWindows = true) {
index++
val (left, right) = it
if (isRightOrder(left, right))
index
else
0
}
return x.sum()
}
fun part2(lines: List<String>): Int {
val l = lines.filter { it.isNotEmpty() }
.plus("[[2]]")
.plus("[[6]]")
.sortedWith { a, b ->
if (isRightOrder(a, b)) -1 else 1
}
return (l.indexOf("[[2]]") + 1) * (l.indexOf("[[6]]") + 1)
}
readLines(13, 140, ::part1, ::part2)
} | 0 | Kotlin | 0 | 0 | 877d58367018372502f03dcc97a26a6f831fc8d8 | 2,077 | aoc2022 | Apache License 2.0 |
src/Day19.kt | mjossdev | 574,439,750 | false | {"Kotlin": 81859} | import java.util.*
import java.util.stream.Collectors
import java.util.stream.Stream
import kotlin.math.max
private enum class Material {
OBSIDIAN, CLAY, ORE;
}
fun main() {
data class Blueprint(
val id: Int,
val costs: Map<Material, Map<Material, Int>>,
val geodeCosts: Map<Material, Int>
)
fun Map<Material, Int>.meets(cost: Map<Material, Int>) =
cost.all { (material, amount) -> this.getValue(material) >= amount }
fun Map<Material, Int>.subtract(cost: Map<Material, Int>) =
mapValues { (material, amount) -> amount - cost.getValue(material) }
fun Map<Material, Int>.plus(production: Map<Material, Int>) =
mapValues { (material, amount) -> amount + production.getValue(material) }
fun Map<Material, Int>.increment(material: Material) =
EnumMap(this).apply { this[material] = this.getValue(material) + 1 }
fun createMap(ore: Int = 0, clay: Int = 0, obsidian: Int = 0) = EnumMap<Material, Int>(Material::class.java).apply {
this[Material.OBSIDIAN] = obsidian
this[Material.CLAY] = clay
this[Material.ORE] = ore
}
val blueprintRegex =
Regex("""Blueprint (\d+): Each ore robot costs (\d+) ore\. Each clay robot costs (\d+) ore\. Each obsidian robot costs (\d+) ore and (\d+) clay\. Each geode robot costs (\d+) ore and (\d+) obsidian\.""")
fun readBlueprints(input: List<String>): List<Blueprint> = input.map { line ->
blueprintRegex.matchEntire(line)!!.groupValues.drop(1).map { it.toInt() }
.let { (id, oreOre, clayOre, obsidianOre, obsidianClay, geodeOre, geodeObsidian) ->
Blueprint(
id,
EnumMap(
mapOf(
Material.ORE to createMap(ore = oreOre),
Material.CLAY to createMap(ore = clayOre),
Material.OBSIDIAN to createMap(ore = obsidianOre, clay = obsidianClay)
)
),
createMap(ore = geodeOre, obsidian = geodeObsidian)
)
}
}
fun calculateGeodes(blueprint: Blueprint, minutes: Int): Int {
data class State(val stock: Map<Material, Int>, val production: Map<Material, Int>, val geodes: Int)
var maxGeodes = 0
var states = setOf(State(createMap(), createMap(ore = 1), 0))
repeat(minutes) { m ->
val remainingMinutes = minutes - m
states = states.parallelStream().flatMap { (stock, production, geodes) ->
val newStock = stock.plus(production)
Stream.builder<State>().also {
if (stock.meets(blueprint.geodeCosts)) {
it.add(State(newStock.subtract(blueprint.geodeCosts), production, geodes + remainingMinutes - 1))
} else {
for ((material, costs) in blueprint.costs) {
val maxUsage = remainingMinutes * max(
blueprint.costs.values.maxOf { it.getValue(material) },
blueprint.geodeCosts.getValue(material)
)
if (newStock.getValue(material) < maxUsage && stock.meets(costs)) {
it.add(State(newStock.subtract(costs), production.increment(material), geodes))
}
}
it.add(State(newStock, production, geodes))
}
}.build()
}.filter { it.geodes + (0 ..remainingMinutes - 2).sum() > maxGeodes }
.collect(Collectors.toSet())
states.maxOfOrNull { it.geodes }?.let {
maxGeodes = max(it, maxGeodes)
}
}
println("blueprint ${blueprint.id} done")
return maxGeodes
}
fun part1(input: List<String>): Int = readBlueprints(input).sumOf { calculateGeodes(it, 24) * it.id }
fun part2(input: List<String>): Int = readBlueprints(input.take(3)).parallelStream().mapToInt { calculateGeodes(it, 32) }.reduce(Int::times).asInt
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day19_test")
check(part1(testInput) == 33)
check(part2(testInput) == 56 * 62)
val input = readInput("Day19")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | afbcec6a05b8df34ebd8543ac04394baa10216f0 | 4,474 | advent-of-code-22 | Apache License 2.0 |
src/com/ncorti/aoc2023/Day21.kt | cortinico | 723,409,155 | false | {"Kotlin": 76642} | package com.ncorti.aoc2023
fun main() {
fun parseInput(): Array<CharArray> {
return getInputAsText("21") {
split("\n").filter(String::isNotBlank).map {
it.toCharArray()
}.toTypedArray()
}
}
fun parseInputTimes5(): Array<CharArray> {
val world = parseInput()
val newWorld = Array(world.size * 5) { CharArray(world[0].size * 5) }
val startx = world.indexOfFirst { it.contains('S') }
val starty = world[startx].indexOf('S')
world[startx][starty] = '.'
for (i in world.indices) {
for (j in world[i].indices) {
for (k in 0 until 5) {
for (l in 0 until 5) {
newWorld[i + (world.size * k)][j + (world[i].size * l)] = world[i][j]
}
}
}
}
newWorld[startx + (world.size * 2)][starty + (world[startx].size * 2)] = 'S'
return newWorld
}
val neighbors = listOf(-1 to 0, 0 to -1, 0 to 1, 1 to 0)
fun iterateOnWorldAndCompute(world: Array<CharArray>, iterations: Long): Int {
val startx = world.indexOfFirst { it.contains('S') }
val starty = world[startx].indexOf('S')
world[startx][starty] = 'O'
repeat(iterations.toInt()) {
val toFlip = mutableListOf<Pair<Int, Int>>()
for (i in world.indices) {
for (j in world[i].indices) {
if (world[i][j] == 'O') {
toFlip.add(i to j)
neighbors.map { (di, dj) ->
i + di to j + dj
}.filter { (ni, nj) ->
ni in world.indices && nj in world[i].indices && world[ni][nj] == '.'
}.apply { toFlip.addAll(this) }
}
}
}
toFlip.distinct().forEach { (i, j) ->
if (world[i][j] == '.') {
world[i][j] = 'O'
} else {
world[i][j] = '.'
}
}
}
return world.sumOf { it.count { it == 'O' } }
}
fun part1(): Int = iterateOnWorldAndCompute(parseInput(), 64)
fun part2(): Long {
val size = parseInput().size.toLong()
val requestedIterations = 26501365
val div = (requestedIterations / size)
val rem = (requestedIterations % size)
val y0 = iterateOnWorldAndCompute(parseInputTimes5(), rem)
val y1 = iterateOnWorldAndCompute(parseInputTimes5(), rem + size)
val y2 = iterateOnWorldAndCompute(parseInputTimes5(), rem + (size * 2))
val c = y0
val b = (y2 - y0 - (4 * y1) + (4 * y0)) / -2
val a = y1 - y0 - b
return (a * div * div) + (b * div) + c
}
println(part1())
println(part2())
}
| 1 | Kotlin | 0 | 1 | 84e06f0cb0350a1eed17317a762359e9c9543ae5 | 2,895 | adventofcode-2023 | MIT License |
src/year2023/day14/Day14.kt | lukaslebo | 573,423,392 | false | {"Kotlin": 222221} | package year2023.day14
import check
import readInput
fun main() {
val testInput1 = readInput("2023", "Day14_test_part1")
val testInput2 = readInput("2023", "Day14_test_part1")
check(part1(testInput1), 136)
check(part2(testInput2), 64)
val input = readInput("2023", "Day14")
println(part1(input))
println(part2(input))
}
private fun part1(input: List<String>) = input.parseDish().tilt(Tilt.North).beamLoad()
private fun part2(input: List<String>): Int {
var dish = input.parseDish()
val beamLoadSequence = mutableListOf<Int>()
var cycles = 1000000000
var patternSize: Int? = null
while (cycles > 0) {
dish = dish.tilt(Tilt.North).tilt(Tilt.West).tilt(Tilt.South).tilt(Tilt.East)
cycles--
beamLoadSequence += dish.beamLoad()
patternSize = patternSize ?: beamLoadSequence.patternSize()
if (patternSize != null) {
cycles %= patternSize
}
}
return dish.beamLoad()
}
private data class Pos(val x: Int, val y: Int) {
fun north() = Pos(x, y - 1)
fun south(): Pos = Pos(x, y + 1)
fun east(): Pos = Pos(x + 1, y)
fun west(): Pos = Pos(x - 1, y)
}
private data class Dish(
val solidRocks: Set<Pos>,
val roundRocks: Set<Pos>,
val xRange: IntRange,
val yRange: IntRange,
)
private fun List<String>.parseDish(): Dish {
val solidRocks = mutableSetOf<Pos>()
val roundRocks = mutableSetOf<Pos>()
val maxX = first().indices
val maxY = indices
for ((y, line) in withIndex()) {
for ((x, c) in line.withIndex()) {
when (c) {
'#' -> solidRocks += Pos(x, y)
'O' -> roundRocks += Pos(x, y)
}
}
}
return Dish(solidRocks, roundRocks, maxX, maxY)
}
private enum class Tilt(
val slide: Pos.() -> Pos,
val sort: Set<Pos>.() -> List<Pos>,
) {
North(Pos::north, { sortedBy { it.y } }),
South(Pos::south, { sortedByDescending { it.y } }),
West(Pos::west, { sortedBy { it.x } }),
East(Pos::east, { sortedByDescending { it.x } }),
}
private fun Dish.tilt(tilt: Tilt): Dish {
val newRoundRocks = mutableSetOf<Pos>()
with(tilt) {
for (rock in roundRocks.sort()) {
var pos = rock
var slidedPos = pos.slide()
while (slidedPos.x in xRange && slidedPos.y in yRange && slidedPos !in solidRocks && slidedPos !in newRoundRocks) {
pos = pos.slide()
slidedPos = slidedPos.slide()
}
newRoundRocks += pos
}
}
return copy(roundRocks = newRoundRocks)
}
private fun Dish.beamLoad(): Int {
return roundRocks.sumOf { yRange.last - it.y + 1 }
}
private fun Dish.print() {
for (y in xRange) {
for (x in yRange) {
val symbol = when (Pos(x, y)) {
in solidRocks -> '#'
in roundRocks -> 'O'
else -> '.'
}
print(symbol)
}
println()
}
}
// Pattern size starts at 2 to prevent repeating numbers from counting as pattern
private fun List<Int>.patternSize(minSize: Int = 2): Int? {
if (size < minSize * 2) return null
for (patternSize in minSize..size / 2) {
val part1 = reversed().subList(0, patternSize)
val part2 = reversed().subList(patternSize, patternSize * 2)
if (part1.zip(part2).all { it.first == it.second }) {
return patternSize
}
}
return null
}
| 0 | Kotlin | 0 | 1 | f3cc3e935bfb49b6e121713dd558e11824b9465b | 3,485 | AdventOfCode | Apache License 2.0 |
src/main/kotlin/io/github/clechasseur/adventofcode/y2022/Day19.kt | clechasseur | 567,968,171 | false | {"Kotlin": 493887} | package io.github.clechasseur.adventofcode.y2022
import io.github.clechasseur.adventofcode.y2022.data.Day19Data
object Day19 {
private val input = Day19Data.input
private val blueprintRegex = """^Blueprint (\d+): Each ore robot costs (\d+) ore. Each clay robot costs (\d+) ore. Each obsidian robot costs (\d+) ore and (\d+) clay. Each geode robot costs (\d+) ore and (\d+) obsidian.$""".toRegex()
fun part1(): Int = input.lines().map { it.toBlueprint() }.sumOf { it.geodesAfter(24) * it.id }
fun part2(): Int = input.lines().take(3).map { it.toBlueprint().geodesAfter(32) }.reduce { a, b -> a * b }
private fun Blueprint.geodesAfter(minutes: Int): Int = generateSequence(setOf(State(this)) to 1) { (states, minute) ->
val nextStates = states.asSequence().flatMap { it.nextStates() }.toSet()
val mostGeodes = nextStates.maxOf { it.resources[ResourceType.GEODE]!! }
nextStates.filter {
mostGeodes - it.resources[ResourceType.GEODE]!! <= minutes - minute
}.groupBy {
it.robots
}.values.flatMap { bestStates ->
bestStates.filter { state -> bestStates.none {
it != state && it.resources.all { (resource, inStock) ->
state.resources[resource]!! <= inStock
}
} }
}.toSet() to minute + 1
}.drop(minutes).first().first.maxOf { state ->
state.resources[ResourceType.GEODE]!!
}
private enum class ResourceType {
ORE,
CLAY,
OBSIDIAN,
GEODE,
}
private data class RobotBlueprint(val cost: Map<ResourceType, Int>)
private data class Blueprint(val id: Int, val robotBlueprints: Map<ResourceType, RobotBlueprint>)
private data class State(
val blueprint: Blueprint,
val resources: Map<ResourceType, Int>,
val robots: Map<ResourceType, Int>,
) {
constructor(blueprint: Blueprint) : this(
blueprint,
ResourceType.values().associateWith { 0 },
ResourceType.values().associateWith {
if (it == ResourceType.ORE) 1 else 0
}
)
fun nextStates(): List<State> {
val possibleRobots = ResourceType.values().filter { robot ->
robots.canBuildEventually(robot)
}.map { robot ->
if (resources.canBuild(robot)) robot else null
}.distinct()
val collected = resources.collect()
return possibleRobots.map { robot -> copy(
resources = collected.buildRobot(robot),
robots = robots.addRobot(robot),
) }
}
private fun Map<ResourceType, Int>.canBuildEventually(robot: ResourceType): Boolean = blueprint.robotBlueprints[robot]!!.cost.all { (resource, _) ->
this[resource]!! >= 1
}
private fun Map<ResourceType, Int>.canBuild(robot: ResourceType): Boolean = blueprint.robotBlueprints[robot]!!.cost.all { (resource, amount) ->
this[resource]!! >= amount
}
private fun Map<ResourceType, Int>.collect(): Map<ResourceType, Int> = mapValues { (resource, inStock) ->
inStock + robots[resource]!!
}
private fun Map<ResourceType, Int>.buildRobot(robot: ResourceType?): Map<ResourceType, Int> = mapValues { (resource, inStock) ->
inStock - if (robot != null) blueprint.robotBlueprints[robot]!!.cost[resource] ?: 0 else 0
}
private fun Map<ResourceType, Int>.addRobot(robot: ResourceType?): Map<ResourceType, Int> = mapValues { (robotType, num) ->
num + if (robotType == robot) 1 else 0
}
}
private fun String.toBlueprint(): Blueprint {
val match = blueprintRegex.matchEntire(this) ?: error("Wrong blueprint: $this")
val (id, oreOreCost, clayOreCost, obsidianOreCost, obsidianClayCost, geodeOreCost, geodeObsidianCost) = match.destructured
return Blueprint(
id.toInt(),
mapOf(
ResourceType.ORE to RobotBlueprint(mapOf(ResourceType.ORE to oreOreCost.toInt())),
ResourceType.CLAY to RobotBlueprint(mapOf(ResourceType.ORE to clayOreCost.toInt())),
ResourceType.OBSIDIAN to RobotBlueprint(mapOf(
ResourceType.ORE to obsidianOreCost.toInt(),
ResourceType.CLAY to obsidianClayCost.toInt(),
)),
ResourceType.GEODE to RobotBlueprint(mapOf(
ResourceType.ORE to geodeOreCost.toInt(),
ResourceType.OBSIDIAN to geodeObsidianCost.toInt(),
)),
)
)
}
}
| 0 | Kotlin | 0 | 0 | 7ead7db6491d6fba2479cd604f684f0f8c1e450f | 4,693 | adventofcode2022 | MIT License |
src/Day09.kt | wmichaelshirk | 573,031,182 | false | {"Kotlin": 19037} | import kotlin.math.abs
fun main() {
val dirs = mapOf(
"U" to (0 to -1),
"R" to (1 to 0),
"D" to (0 to 1),
"L" to (-1 to 0)
)
fun visualize(rope: List<Pair<Int, Int>>) {
for (y in -10 .. 10) {
for (x in -10..10) {
val knot = rope.indexOf(x to y)
if (knot == -1) print (".")
else if (knot == 0) print("H")
else print(knot)
}
print("\n")
}
}
fun next(head: Pair<Int, Int>, tail: Pair<Int, Int>):Pair<Int, Int> {
val oldX = tail.first
val oldY = tail.second
var newX = tail.first
var newY = tail.second
if (head.first == oldX && head.second != oldY) {
newY = if (head.second > oldY) head.second - 1 else head.second + 1
} else if (head.second == oldY && head.first != oldX) {
newX = if (head.first > oldX) head.first - 1 else head.first + 1
} else if (abs(head.first - oldX) + abs(head.second - oldY) > 2) {
// move diagonal...
// ..H .*H ..H
// .*. T.. ..*
// T.. ... .T,
if (abs(head.first - oldX) == 2) {
newY = if (head.second < oldY) oldY - 1 else oldY + 1
newX = if (head.first > oldX) head.first - 1 else head.first + 1
} else {
newX = if (head.first < oldX) oldX - 1 else oldX + 1
newY = if (head.second > oldY) head.second - 1 else head.second + 1
}
}
return newX to newY
}
fun part1(input: List<String>): Int {
var tails = mutableSetOf(0 to 0)
var head = 0 to 0
var tail = 0 to 0
input.forEach {
val (dir, times) = it.split(" ")
repeat(times.toInt()) {
head = (head.first + (dirs[dir]?.first ?: 0)) to (head.second + (dirs[dir]?.second ?: 0))
tail = next(head, tail)
tails.add(tail)
}
}
return tails.size
}
fun part2(input: List<String>): Int {
var tails = mutableSetOf(0 to 0)
var rope = List(10) { 0 to 0 }
var tail = 0 to 0
input.forEach {
val (dir, times) = it.split(" ")
repeat(times.toInt()) { _ ->
var head = rope.first().first + (dirs[dir]?.first ?: 0) to rope.first().second + (dirs[dir]?.second ?: 0)
var prev = head
rope = rope.mapIndexed { idx, knot ->
if (idx == 0) head
else {
prev = next(prev, knot)
prev
}
}
tail = rope.last()
tails.add(tail)
}
}
return tails.size
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day09_test")
val testInput2 = readInput("Day09_test2")
check(part1(testInput) == 13)
check(part2(testInput2) == 36)
val input = readInput("Day09")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 2 | b748c43e9af05b9afc902d0005d3ba219be7ade2 | 3,184 | 2022-Advent-of-Code | Apache License 2.0 |
src/Day09.kt | jamie23 | 573,156,415 | false | {"Kotlin": 19195} | import kotlin.math.absoluteValue
import kotlin.math.sign
fun main() {
fun adjacent(head: Pair<Int, Int>, tail: Pair<Int, Int>) =
(tail.first - head.first).absoluteValue <= 1 && (tail.second - head.second).absoluteValue <= 1
fun solve(points: Int, instructions: List<String>): Int {
val pointList = MutableList(points) { Pair(0, 0) }
val visited = hashSetOf<Pair<Int, Int>>()
instructions.forEach {
val (direction, i) = it.split(' ')
repeat(i.toInt()) {
pointList[0] = when (direction) {
"U" -> pointList[0].copy(second = pointList[0].second + 1)
"D" -> pointList[0].copy(second = pointList[0].second - 1)
"R" -> pointList[0].copy(first = pointList[0].first + 1)
else -> pointList[0].copy(first = pointList[0].first - 1)
}
for (point in 1 until pointList.size) {
val currentHead = pointList[point - 1]
val tail = pointList[point]
if (!adjacent(currentHead, tail)) {
val xSign = (currentHead.first - tail.first).sign
val ySign = (currentHead.second - tail.second).sign
pointList[point] = tail.copy(
first = tail.first + xSign,
second = tail.second + ySign
)
}
}
visited.add(pointList.last())
// Debug:
// println("HEAD: ${pointList[0].first} ${pointList[1].second} - TAIL: ${pointList[pointList.size - 1].first} ${pointList[pointList.size - 1].second}")
}
}
println(visited.size)
return visited.size
}
fun part1(input: List<String>): Int {
return solve(points = 2, input)
}
fun part2(input: List<String>): Int {
return solve(points = 10, input)
}
val testInput = readInput("Day09_test")
val testInput2 = readInput("Day09_test2")
check(part1(testInput) == 13)
check(part2(testInput) == 1)
check(part2(testInput2) == 36)
val input = readInput("Day09")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | cfd08064654baabea03f8bf31c3133214827289c | 2,298 | Aoc22 | Apache License 2.0 |
src/main/kotlin/day02/day02.kt | corneil | 572,437,852 | false | {"Kotlin": 93311, "Shell": 595} | package day02
import utils.readFile
import utils.readLines
enum class Rps(val identifiers: String, val shapeScore: Int) {
ROCK("AX", 1),
PAPER("BY", 2),
SCISSORS("CZ", 3)
}
enum class Outcome(val identifier: String, val score: Int) {
LOSE("X", 0),
DRAW("Y", 3),
WIN("Z", 6)
}
data class Hand(val them: Rps, val me: Rps)
object Rules {
data class Rule(val loser: Rps, val winner: Rps)
private val beats = mapOf(
Rps.ROCK to Rule(Rps.SCISSORS, Rps.PAPER),
Rps.PAPER to Rule(Rps.ROCK, Rps.SCISSORS),
Rps.SCISSORS to Rule(Rps.PAPER, Rps.ROCK)
)
fun winner(shape: Rps): Rps {
val winner = beats[shape] ?: error("Cannot find $shape")
return winner.winner
}
fun loser(shape: Rps): Rps {
val loser = beats[shape] ?: error("Cannot find $shape")
return loser.loser
}
fun didIWin(round: Hand): Boolean {
val shape = loser(round.me)
return shape == round.them
}
}
fun main() {
fun toRps(hint: String): Rps {
return Rps.values().find { it.identifiers.contains(hint) } ?: error("Invalid RPS $hint")
}
fun toOutcome(outcome: String): Outcome {
return Outcome.values().find { it.identifier == outcome } ?: error("Invalid Outcome:$outcome")
}
fun readRounds(input: List<String>): List<Hand> {
return input.map {
val hints = it.split(" ")
Hand(toRps(hints[0]), toRps(hints[1]))
}
}
// choose a shape to match the outcome
fun chooseShape(shape: Rps, outcome: Outcome): Rps {
return when (outcome) {
Outcome.DRAW -> shape
Outcome.WIN -> Rules.winner(shape)
Outcome.LOSE -> Rules.loser(shape)
}
}
// convert 2nd to outcome and then find a shape to match outcome given first
fun readRounds2(input: List<String>): List<Hand> {
return input.map {
val hints = it.split(" ")
Pair(toRps(hints[0]), toOutcome(hints[1]))
}.map {
Hand(it.first, chooseShape(it.first, it.second))
}
}
fun calcRound(round: Hand): Int {
return when {
round.them == round.me -> Outcome.DRAW.score
Rules.didIWin(round) -> Outcome.WIN.score
else -> Outcome.LOSE.score
}
}
fun calcScore(round: Hand): Int {
return round.me.shapeScore + calcRound(round)
}
fun calcTotal(rounds: List<Hand>): Int {
return rounds.sumOf { calcScore(it) }
}
val test = """A Y
B X
C Z"""
fun part1() {
val testInput = readRounds(readLines(test))
val testScore = calcTotal(testInput)
println("Test Total = $testScore")
check(testScore == 15)
val input = readRounds(readFile("day02"))
val total = calcTotal(input)
println("Total = $total")
// answer for my data. check will be used during refactoring
check(total == 13446)
}
fun part2() {
val testInput2 = readRounds2(readLines(test))
val testScore2 = calcTotal(testInput2)
println("Test Total 2 = $testScore2")
check(testScore2 == 12)
val input2 = readRounds2(readFile("day02"))
val total2 = calcTotal(input2)
println("Total 2 = $total2")
// answer for my data. check will be used during refactoring
check(total2 == 13509)
}
println("Day - 02")
part1()
part2()
}
| 0 | Kotlin | 0 | 0 | dd79aed1ecc65654cdaa9bc419d44043aee244b2 | 3,167 | aoc-2022-in-kotlin | Apache License 2.0 |
src/day22/Day22.kt | daniilsjb | 726,047,752 | false | {"Kotlin": 66638, "Python": 1161} | package day22
import java.io.File
import kotlin.math.max
fun main() {
val data = parse("src/day22/Day22.txt")
val (supports, standsOn) = simulate(data)
println("🎄 Day 22 🎄")
println()
println("[Part 1]")
println("Answer: ${part1(data.size, supports, standsOn)}")
println()
println("[Part 2]")
println("Answer: ${part2(data.size, supports, standsOn)}")
}
private data class Brick(
val x0: Int, val x1: Int,
val y0: Int, val y1: Int,
val z0: Int, val z1: Int,
)
private fun String.toBrick(): Brick {
val (lhs, rhs) = this.split('~')
val (x0, y0, z0) = lhs.split(',')
val (x1, y1, z1) = rhs.split(',')
return Brick(
x0 = x0.toInt(), x1 = x1.toInt(),
y0 = y0.toInt(), y1 = y1.toInt(),
z0 = z0.toInt(), z1 = z1.toInt(),
)
}
private fun parse(path: String): List<Brick> =
File(path)
.readLines()
.map(String::toBrick)
.sortedBy { it.z0 }
private fun overlap(a: Brick, b: Brick): Boolean =
(a.x1 >= b.x0 && b.x1 >= a.x0) && (a.y1 >= b.y0 && b.y1 >= a.y0)
private fun simulate(data: List<Brick>): Pair<List<Set<Int>>, List<Set<Int>>> {
val bricks = data.toMutableList()
for ((i, upper) in bricks.withIndex()) {
var z = 1
for (lower in bricks.subList(0, i)) {
if (overlap(upper, lower)) {
z = max(z, lower.z1 + 1)
}
}
bricks[i] = upper.copy(
z0 = z,
z1 = z + (upper.z1 - upper.z0),
)
}
bricks.sortBy { it.z0 }
val supports = bricks.map { mutableSetOf<Int>() }
val standsOn = bricks.map { mutableSetOf<Int>() }
for ((i, upper) in bricks.withIndex()) {
for ((j, lower) in bricks.subList(0, i).withIndex()) {
if (upper.z0 == lower.z1 + 1) {
if (overlap(upper, lower)) {
supports[j] += i
standsOn[i] += j
}
}
}
}
return Pair(supports, standsOn)
}
private fun part1(n: Int, supports: List<Set<Int>>, standsOn: List<Set<Int>>): Int =
(0..<n).count { i -> supports[i].all { j -> standsOn[j].size > 1 } }
private fun part2(n: Int, supports: List<Set<Int>>, standsOn: List<Set<Int>>): Int {
var count = 0
for (i in 0..<n) {
val queue = ArrayDeque<Int>()
.apply { addAll(supports[i].filter { j -> standsOn[j].size == 1 }) }
val falling = mutableSetOf(i)
falling += queue
while (queue.isNotEmpty()) {
val j = queue.removeFirst()
for (k in supports[j]) {
if (k !in falling && falling.containsAll(standsOn[k])) {
queue += k
falling += k
}
}
}
count += falling.size - 1
}
return count
}
| 0 | Kotlin | 0 | 0 | 46a837603e739b8646a1f2e7966543e552eb0e20 | 2,971 | advent-of-code-2023 | MIT License |
src/Day06.kt | MisterTeatime | 561,848,263 | false | {"Kotlin": 20300} | fun main() {
fun instructions2program(input: List<String>): List<Command> {
val regex = """(\D+) (\d+,\d+) through (\d+,\d+)""".toRegex()
return input
.map { regex.find(it)!!.groupValues.drop(1) }
.map { (instruction, start, end) -> Command(instruction, start, end) }
.filterNot { it.instruction == Inst.NOP }
}
fun getAllLights(startPoint: Point2D, endPoint: Point2D) = IntRange(startPoint.x, endPoint.x).flatMap { x ->
IntRange(startPoint.y, endPoint.y).map { y ->
Point2D(x, y)
}
}.toSet()
fun evolve(input: List<String>, dimX: Int, dimY: Int, on: (_: Int) -> Int, off: (_: Int) -> Int, toggle: (_: Int) -> Int): IntArray {
val regex = """(\D+) (\d+,\d+) through (\d+,\d+)""".toRegex()
val program = input
.map { regex.find(it)!!.groupValues.drop(1) }
.map { (instruction, start, end) -> Command(instruction, start, end) }
.filterNot { it.instruction == Inst.NOP }
val lights = IntArray(dimX * dimY)
program.forEach { cmd ->
IntRange(cmd.startPoint.x, cmd.endPoint.x).forEach { x ->
IntRange(cmd.startPoint.y, cmd.endPoint.y).forEach { y ->
val index = dimX * x + y
lights[index] = when (cmd.instruction) {
Inst.ON -> on(lights[index])
Inst.OFF -> off(lights[index])
Inst.TOGGLE -> toggle(lights[index])
else -> lights[index]
}
}
}
}
return lights
}
fun part1FirstTry(input: List<String>): Int {
//Eingabe in Instructions umwandeln
val program = instructions2program(input)
//Programm abarbeiten
val activeLights = mutableSetOf<Point2D>()
program.forEach { i ->
when (i.instruction) {
Inst.ON -> activeLights.addAll(getAllLights(i.startPoint, i.endPoint))
Inst.OFF -> activeLights.removeAll(getAllLights(i.startPoint, i.endPoint))
Inst.TOGGLE -> {
val splitLights = getAllLights(i.startPoint, i.endPoint).partition { activeLights.contains(it) }
activeLights.removeAll(splitLights.first.toSet())
activeLights.addAll(splitLights.second.toSet())
}
Inst.NOP -> {}
}
}
return activeLights.size
}
fun part1(input: List<String>, dimX: Int, dimY: Int) = evolve(input, dimX, dimY,
{ 1 }, //on
{ 0 }, //off
{ if (it == 0) 1 else 0}) //toggle
.count { it == 1 }
fun part2(input: List<String>, dimX: Int, dimY: Int) = evolve(input, dimX, dimY,
{ it + 1 }, //on
{ if (it == 0) 0 else it - 1 }, //off
{ it + 2 }) //toggle
.sum()
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day06_test")
//check(part1FirstTry(testInput) == 16)
check(part1(testInput, 6, 6) == 16)
check(part2(testInput, 6, 6) == 92)
val input = readInput("Day06")
//println(part1FirstTry(input)
println(part1(input, 1000, 1000))
println(part2(input, 1000, 1000))
}
data class Command(val instructionIn: String, val start: String, val end: String) {
val instruction: Inst = when (instructionIn) {
"turn on" -> Inst.ON
"turn off" -> Inst.OFF
"toggle" -> Inst.TOGGLE
else -> Inst.NOP
}
val startPoint: Point2D
val endPoint: Point2D
init {
val startCoords = start.split(",").map { it.toInt() }
val endCoords = end.split(",").map { it.toInt() }
startPoint = Point2D(startCoords[0], startCoords[1])
endPoint = Point2D(endCoords[0], endCoords[1])
}
}
enum class Inst {
ON, OFF, TOGGLE, NOP
} | 0 | Kotlin | 0 | 0 | d684bd252a9c6e93106bdd8b6f95a45c9924aed6 | 3,940 | AoC2015 | Apache License 2.0 |
src/Day09.kt | dakr0013 | 572,861,855 | false | {"Kotlin": 105418} | import kotlin.test.assertEquals
fun main() {
fun part1(input: List<String>): Int {
val seriesOfMotions = parseSeriesOfMotions(input)
return simulateSeriesOfMotions(seriesOfMotions, Rope(2))
}
fun part2(input: List<String>): Int {
val seriesOfMotions = parseSeriesOfMotions(input)
return simulateSeriesOfMotions(seriesOfMotions, Rope(10))
}
// test if implementation meets criteria from the description, like:
assertEquals(13, part1(readInput("Day09_test")))
assertEquals(36, part2(readInput("Day09_test2")))
val input = readInput("Day09")
println(part1(input))
println(part2(input))
}
private fun simulateSeriesOfMotions(motions: List<Motion>, rope: Rope): Int {
val visitedTailPositions = mutableSetOf(rope.tail())
for (motion in motions) {
repeat(motion.steps) {
rope.moveHead(motion.direction)
visitedTailPositions.add(rope.tail())
}
}
return visitedTailPositions.size
}
private fun parseSeriesOfMotions(input: List<String>): List<Motion> {
return input.map {
val (direction, stepsString) = it.split(" ")
val steps = stepsString.toInt()
when (direction) {
"R" -> Motion(Vector(1, 0), steps)
"L" -> Motion(Vector(-1, 0), steps)
"U" -> Motion(Vector(0, 1), steps)
"D" -> Motion(Vector(0, -1), steps)
else -> error("unknown direction, should not happen")
}
}
}
private data class Rope(val numberOfKnots: Int) {
private val knotPositions = Array(numberOfKnots) { Vector(0, 0) }
fun moveHead(direction: Vector) {
knotPositions[0] += direction
for (i in 0 until numberOfKnots - 1) {
if (knotPositions[i + 1].isNotAdjacent(knotPositions[i])) {
knotPositions[i + 1] = knotPositions[i + 1].moveTowards(knotPositions[i])
}
}
}
fun tail() = knotPositions.last()
}
private data class Motion(val direction: Vector, val steps: Int)
private data class Vector(val x: Int, val y: Int) {
operator fun plus(other: Vector) = Vector(this.x + other.x, this.y + other.y)
operator fun minus(other: Vector) = Vector(this.x - other.x, this.y - other.y)
fun isNotAdjacent(other: Vector) =
!(this.x in (other.x - 1)..(other.x + 1) && this.y in (other.y - 1)..(other.y + 1))
fun moveTowards(other: Vector): Vector {
val direction = (other - this).coerceIn(1)
return this + direction
}
fun coerceIn(maxAbsoluteValue: Int) =
Vector(
this.x.coerceIn(-maxAbsoluteValue, maxAbsoluteValue),
this.y.coerceIn(-maxAbsoluteValue, maxAbsoluteValue),
)
}
| 0 | Kotlin | 0 | 0 | 6b3adb09f10f10baae36284ac19c29896d9993d9 | 2,545 | aoc2022 | Apache License 2.0 |
src/main/kotlin/de/tek/adventofcode/y2022/day03/RucksackReorganization.kt | Thumas | 576,671,911 | false | {"Kotlin": 192328} | package de.tek.adventofcode.y2022.day03
import de.tek.adventofcode.y2022.util.readInputLines
class ItemType(private val id: Char) {
val priority: Int = when (id) {
in CharRange('a', 'z') -> {
1 + (id.code - 'a'.code)
}
in CharRange('A', 'Z') -> {
27 + (id.code - 'A'.code)
}
else -> {
throw IllegalArgumentException("Only letters are allowed as item type ids.")
}
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is ItemType) return false
return (id == other.id)
}
override fun hashCode(): Int {
return id.hashCode()
}
}
class Rucksack(contentCode: String) {
private val firstCompartment: List<ItemType>
private val secondCompartment: List<ItemType>
init {
if (contentCode.length.mod(2) != 0) {
throw IllegalArgumentException("Invalid content, both compartments must contain the same number of items.")
}
val compartmentSize = contentCode.length / 2
firstCompartment = contentCode.take(compartmentSize).map { ItemType(it) }
secondCompartment = contentCode.drop(compartmentSize).map { ItemType(it) }
}
fun determineSharedItemTypes() = firstCompartment intersect secondCompartment.toSet()
fun getItemTypes(): Set<ItemType> = (firstCompartment + secondCompartment).toSet()
}
class Group(private val rucksacks: List<Rucksack>) {
fun getCommonItemTypes() = rucksacks.map { it.getItemTypes() }.reduce { a, b -> a intersect b }
}
fun Sequence<Set<ItemType>>.sumPriorities() = this.flatten().sumOf { it.priority }
fun main() {
val input = readInputLines(Rucksack::class)
fun part1(input: List<String>) =
input.asSequence().map { Rucksack(it).determineSharedItemTypes() }.sumPriorities()
fun part2(input: List<String>) =
input.asSequence().map { Rucksack(it) }.chunked(3).map { Group(it).getCommonItemTypes() }.sumPriorities()
println("The sum of the priorities of the shared item types in each rucksack is ${part1(input)}.")
println("The sum of the priorities of the shared item types in each group of elves is ${part2(input)}.")
}
| 0 | Kotlin | 0 | 0 | 551069a21a45690c80c8d96bce3bb095b5982bf0 | 2,316 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/aoc2021/Day05.kt | j4velin | 572,870,735 | false | {"Kotlin": 285016, "Python": 1446} | package aoc2021
import Point
import readInput
import kotlin.math.absoluteValue
import kotlin.math.max
import kotlin.math.sign
/**
* Creates a new [Point] by moving this instance 1 step in the direction of the given [end] point
*
* @param end the destination in which direction to move the new point
* @return a new point instance which is moved 1 step in the direction of [end]
*/
fun Point.moveTo(end: Point): Point {
val nextX = x + (end.x - x).sign
val nextY = y + (end.y - y).sign
return Point(nextX, nextY)
}
private data class Line(val start: Point, val end: Point) : Iterable<Point> {
val isHorizontal = start.x == end.x
val isVertical = start.y == end.y
val isDiagonal = (start.x - end.x).absoluteValue == (start.y - end.y).absoluteValue
companion object {
fun fromString(data: String) =
data.split(" -> ").map { point -> point.split(",").map { it.toInt() } }.map { Point(it[0], it[1]) }
.let { Line(it[0], it[1]) }
}
override fun iterator(): Iterator<Point> {
return object : Iterator<Point> {
private var currentPosition: Point? = null
override fun hasNext() = currentPosition != end
override fun next(): Point {
currentPosition = currentPosition?.moveTo(end) ?: start
return currentPosition ?: start
}
}
}
}
/**
* Gets the most dangerous points along the given lines.
*
* @param lines the lines covering all the points to consider
* @param dangerousLimit the threshold, at which a point is considered to be 'dangerous'
* @return a set of points, which are covered by at least [dangerousLimit] lines of [lines]
*/
private fun getMostDangerousPoints(lines: List<Line>, dangerousLimit: Int): Set<Point> {
val maxX = lines.maxOf { max(it.start.x, it.end.x) } + 1
val maxY = lines.maxOf { max(it.start.y, it.end.y) } + 1
val diagram = Array(maxX) { IntArray(maxY) }
val mostDangerousPoints = mutableSetOf<Point>()
lines.flatten().forEach {
if (++diagram[it.x][it.y] >= dangerousLimit) {
mostDangerousPoints.add(it)
}
}
return mostDangerousPoints
}
private fun part1(input: List<String>): Int {
val lines = input.map(Line.Companion::fromString).filter { it.isHorizontal || it.isVertical }
return getMostDangerousPoints(lines, 2).size
}
private fun part2(input: List<String>): Int {
val lines = input.map(Line.Companion::fromString).filter { it.isHorizontal || it.isVertical || it.isDiagonal }
return getMostDangerousPoints(lines, 2).size
}
fun main() {
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day05_test")
check(part1(testInput) == 5)
check(part2(testInput) == 12)
val input = readInput("Day05")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | f67b4d11ef6a02cba5b206aba340df1e9631b42b | 2,899 | adventOfCode | Apache License 2.0 |
src/day05/Day05.kt | martinhrvn | 724,678,473 | false | {"Kotlin": 27307, "Jupyter Notebook": 1336} | package day05
import println
import readInput
data class Mapping(val source: Long, val destination: Long, val range: Long) {
fun contains(seed: Long): Boolean {
return seed in source ..< source + range
}
fun getDestination(seed: Long): Long {
return destination + (seed - source)
}
}
fun List<Mapping>.getDestination(seed: Long): Long {
return this.firstOrNull { it.contains(seed) }?.getDestination(seed) ?: seed
}
data class SeedMapping(
val seeds: List<Long>,
val seedToSouil: List<Mapping>,
val souilToFertilizer: List<Mapping>,
val fertilizerToWater: List<Mapping>,
val waterToLight: List<Mapping>,
val ligthToTemperature: List<Mapping>,
val temperatureToHumidity: List<Mapping>,
val humidityToLocation: List<Mapping>
) {
fun getDestination(seed: Long): Long {
return humidityToLocation.getDestination(
temperatureToHumidity.getDestination(
ligthToTemperature.getDestination(
waterToLight.getDestination(
fertilizerToWater.getDestination(
souilToFertilizer.getDestination(seedToSouil.getDestination(seed)))))))
}
fun getSeedDestinations(): List<Long> {
return seeds.map { getDestination(it) }
}
fun getExtendedSeedDestinations(): List<Long> {
// val hlMap = humidityToLocation.fold(mapOf<Long,Long>()) { acc, curr ->
// acc.plus(initMap(curr, acc))
// }
// val thMap = rangesToMap(temperatureToHumidity, hlMap)
// val ltMap = rangesToMap(ligthToTemperature, thMap)
// val wlMap = rangesToMap(waterToLight, ltMap)
// val fwMap = rangesToMap(fertilizerToWater, wlMap)
// val sfMap = rangesToMap(souilToFertilizer, fwMap)
// val ssMap = rangesToMap(seedToSouil, sfMap)
return seeds.chunked(2).map { (start, range) ->
(start ..< start + range).minBy { i -> getSeedDestinations().min() }
}
}
companion object {
fun parse(input: List<String>): SeedMapping {
val (label, seedStr) = input.first().split(": ")
val seeds = seedStr.split(" ").map { it.toLong() }
val seedToSoilMapping = getMapping(input, "seed-to-soil map:")
val soilToFertilizer = getMapping(input, "soil-to-fertilizer map:")
val fertilizerToWater = getMapping(input, "fertilizer-to-water map:")
val waterToLight = getMapping(input, "water-to-light map:")
val ligthToTemperature = getMapping(input, "light-to-temperature map:")
val temperatureToHumidity = getMapping(input, "temperature-to-humidity map:")
val humidityToLocation = getMapping(input, "humidity-to-location map:")
return SeedMapping(
seeds,
seedToSoilMapping,
soilToFertilizer,
fertilizerToWater,
waterToLight,
ligthToTemperature,
temperatureToHumidity,
humidityToLocation)
}
fun rangesToMap(sources: List<Mapping>, destination: Map<Long, Long>): Map<Long, Long> {
return sources.fold(destination) { acc, curr -> acc.plus(rangeToMap(curr, acc)) }
}
fun initMap(source: Mapping, destination: Map<Long, Long>): Map<Long, Long> {
return (source.destination - source.range ..< source.range)
.mapNotNull { i -> (source.source + i) to (source.destination + i) }
.toMap()
}
fun rangeToMap(source: Mapping, destination: Map<Long, Long>): Map<Long, Long> {
return (source.destination - source.range ..< source.range)
.mapNotNull { i ->
destination.getOrDefault(source.destination + i, null)?.let {
(source.source + i) to it
}
}
.toMap()
}
fun getMapping(input: List<String>, label: String): List<Mapping> {
return input
.dropWhile { !it.startsWith(label) }
.drop(1)
.takeWhile { "\\d+ \\d+ \\d+".toRegex().matches(it) }
.map {
val (destination, source, range) = it.split(" ")
Mapping(source.toLong(), destination.toLong(), range.toLong())
}
}
}
}
class SoilChecker(private val input: List<String>) {
fun part1(): Long {
return SeedMapping.parse(input).getSeedDestinations().min()
}
fun part2(): Long {
return SeedMapping.parse(input).getExtendedSeedDestinations().min()
}
}
fun main() {
val input = readInput("day05/Day05")
val soilChecker = SoilChecker(input)
soilChecker.part1().println()
soilChecker.part2().println()
}
| 0 | Kotlin | 0 | 0 | 59119fba430700e7e2f8379a7f8ecd3d6a975ab8 | 4,519 | advent-of-code-2023-kotlin | Apache License 2.0 |
archive/2022/Day16_dp.kt | mathijs81 | 572,837,783 | false | {"Kotlin": 167658, "Python": 725, "Shell": 57} | import java.util.*
import kotlin.time.ExperimentalTime
import kotlin.time.measureTime
private const val EXPECTED_1 = 1651
private const val EXPECTED_2 = 1707
/**
* Reworked solution: DP by treating 1 minute at a time (ignoring useless valves) to find the
* highest value path through the state space for part1.
*
* The result of a single 26-round evaluation can be used for part2. Each valve gets opened by
* one of the two agents (or neither) and then the result of the longest path can just
* be looked up.
*/
private class Day16_alt(isTest: Boolean) : Solver(isTest) {
private val edges = mutableMapOf<String, List<String>>()
private val num = mutableMapOf<String, Int>()
private val flowList = mutableListOf<Int>()
init {
readAsLines().withIndex().forEach { (index, line) ->
val parts = line.split(" ")
val key = parts[1]
flowList.add(parts[4].removeSurrounding("rate=", ";").toInt())
val parts2 = line.split(", ")
edges[key] = parts2.map { it.substringAfterLast(' ', it) }
num[key] = index
}
}
data class State(val open: Long, val loc: String)
fun dp(start: State, rounds: Int): Map<State, Int> {
var states = mapOf(start to 0)
repeat(rounds) { t ->
val newStates = mutableMapOf<State, Int>()
for ((state, score) in states.entries) {
val locNum = num[state.loc]!!
if (flowList[locNum] > 0 && (state.open and (1L shl locNum)) == 0L) {
val newScore = score + (rounds - t - 1) * flowList[locNum];
val newState = state.copy(open = state.open or (1L shl locNum))
newStates.compute(newState) { _, prev -> maxOf(newScore, prev ?: 0) }
}
for (dest in edges[state.loc]!!) {
val newState = state.copy(loc = dest)
newStates.compute(newState) { _, prev -> maxOf(score, prev ?: 0) }
}
}
states = newStates
}
return states
}
fun part1() = dp(State(0, "AA"), 30).maxOf { it.value }
fun partition(startIndex: Int, assignment1: Long, assignment2: Long, openToScore: Map<Long, Int>): Int {
var index = startIndex
while (index < flowList.size && flowList[index] == 0) index++
return if (index < flowList.size) {
// This valve gets opened either by user1, by user2 or by neither
maxOf(
partition(index + 1, assignment1 or (1L shl index), assignment2, openToScore),
partition(index + 1, assignment1, assignment2 or (1L shl index), openToScore),
partition(index + 1, assignment1, assignment2, openToScore)
)
} else {
// Evaluate: just look up what score we can get by opening the valves as assigned
(openToScore[assignment1] ?: 0) + (openToScore[assignment2] ?: 0)
}
}
fun part2(): Any {
val bestMap = dp(State(0, "AA"), 26).entries.groupBy { it.key.open }.
mapValues { (_, entryList) -> entryList.maxOf { it.value }}
return partition(0, 0L, 0L, bestMap)
}
}
@OptIn(ExperimentalTime::class)
fun main() {
val testInstance = Day16_alt(true)
val instance = Day16_alt(false)
println(measureTime {
testInstance.part1().let { check(it == EXPECTED_1) { "part1: $it != $EXPECTED_1" } }
println("part1 ANSWER: ${instance.part1()}")
})
println(measureTime {
testInstance.part2().let {
check(it == EXPECTED_2) { "part2: $it != $EXPECTED_2" }
println("part2 ANSWER: ${instance.part2()}")
}
})
}
| 0 | Kotlin | 0 | 2 | 92f2e803b83c3d9303d853b6c68291ac1568a2ba | 3,752 | advent-of-code-2022 | Apache License 2.0 |
src/Day08.kt | dmarmelo | 573,485,455 | false | {"Kotlin": 28178} | fun main() {
fun List<String>.parseInput() = map {
it.map { c -> c.digitToInt() }
}
fun <T> List<List<T>>.viewFrom(rowIndex: Int, columnIndex: Int): Sequence<List<T>> = sequence {
yield((rowIndex - 1 downTo 0).map { this@viewFrom[it][columnIndex] }) // Top
yield((columnIndex - 1 downTo 0).map { this@viewFrom[rowIndex][it] }) // Right
yield((rowIndex + 1 until this@viewFrom.size).map { this@viewFrom[it][columnIndex] }) // Bottom
yield((columnIndex + 1 until this@viewFrom[0].size).map { this@viewFrom[rowIndex][it] }) // Left
}
fun part1(input: List<List<Int>>): Int {
var visibleTreeCount = 0
visibleTreeCount += input.size * 2 + input[0].size * 2 - 4
for (rowIndex in 1 until input.lastIndex) {
val row = input[rowIndex]
for (columnIndex in 1 until row.lastIndex) {
val currentHeight = row[columnIndex]
val isVisible = input.viewFrom(rowIndex, columnIndex).any { direction ->
direction.all { it < currentHeight }
}
if (isVisible) {
visibleTreeCount++
}
}
}
return visibleTreeCount
}
fun <T> Iterable<T>.takeUntil(predicate: (T) -> Boolean): List<T> {
val list = ArrayList<T>()
for (item in this) {
list.add(item)
if (!predicate(item))
break
}
return list
}
fun part2(input: List<List<Int>>): Int {
var scenicScore = 0
for ((rowIndex, row) in input.withIndex()) {
for ((columnIndex, _) in row.withIndex()) {
val currentHeight = row[columnIndex]
val score = input.viewFrom(rowIndex, columnIndex).map { direction ->
direction.takeUntil { it < currentHeight }.count()
}.product()
if (score > scenicScore) {
scenicScore = score
}
}
}
return scenicScore
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day08_test").parseInput()
check(part1(testInput) == 21)
check(part2(testInput) == 8)
val input = readInput("Day08").parseInput()
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 5d3cbd227f950693b813d2a5dc3220463ea9f0e4 | 2,390 | advent-of-code-2022 | Apache License 2.0 |
src/Day11.kt | ShuffleZZZ | 572,630,279 | false | {"Kotlin": 29686} | private val template = """
Monkey (\d+):
Starting items: (.*?)
Operation: new = old (.) (.+)
Test: divisible by (\d+)
If true: throw to monkey (\d+)
If false: throw to monkey (\d+)
""".trim().toRegex()
private data class MonkeyBusiness(
val items: MutableList<ULong>,
val op: (ULong, ULong) -> ULong,
val value: String,
val divider: ULong,
val onTrue: Int,
val onFalse: Int,
var inspected: ULong = 0U,
) {
fun throwDecision(worryLevel: ULong) = if (worryLevel % divider == 0.toULong()) onTrue else onFalse
fun roundEnd() {
inspected += items.size.toUInt()
items.clear()
}
}
private fun parseMonkeys(input: List<String>) = input.map { monkey ->
val (_, list, sign, value, divider, onTrue, onFalse) = template.matchEntire(monkey)!!.destructured
val items = list.split(", ").map(String::toULong).toMutableList()
val operation: (ULong, ULong) -> ULong = when (sign.first()) {
'+' -> ULong::plus
'*' -> ULong::times
else -> error("Incorrect input")
}
MonkeyBusiness(items, operation, value, divider.toULong(), onTrue.toInt(), onFalse.toInt())
}
private fun throwRounds(monkeys: List<MonkeyBusiness>, times: Int, calming: (ULong) -> ULong): ULong {
val greatDivider = monkeys.map { it.divider }.reduce(ULong::times)
repeat(times) {
for (monkey in monkeys) {
for (item in monkey.items) {
val numberValue = monkey.value.toULongOrNull() ?: item
val worryLevel = calming(monkey.op(item, numberValue)) % greatDivider
monkeys[monkey.throwDecision(worryLevel)].items.add(worryLevel)
}
monkey.roundEnd()
}
}
return monkeys.map { it.inspected }.sorted().takeLast(2).reduce(ULong::times)
}
fun main() {
fun part1(input: List<String>) = throwRounds(parseMonkeys(input), 20) { it / 3U }
fun part2(input: List<String>) = throwRounds(parseMonkeys(input), 10_000) { it }
// test if implementation meets criteria from the description, like:
val testInput = readRawBlocks("Day11_test")
check(part1(testInput) == 10_605.toULong())
check(part2(testInput) == 2_713_310_158.toULong())
val input = readRawBlocks("Day11")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 5a3cff1b7cfb1497a65bdfb41a2fe384ae4cf82e | 2,322 | advent-of-code-kotlin | Apache License 2.0 |
src/Day07.kt | jinie | 572,223,871 | false | {"Kotlin": 76283} | class Day07 {
fun parseInput(input: List<String>): Map<String, Int>{
val currentDir = StringBuilder()
val dirTree: MutableMap<String, Int> = mutableMapOf()
var i = 0
while(i < input.size){
val it = input[i]
val cmd = it.removePrefix("$").trim()
if(cmd.startsWith("cd")) {
when (val nd = cmd.split(" ").last()) {
"/" -> currentDir.clear().append("/")
".." -> {
val lastDirInd = currentDir.dropLast(1).lastIndexOf('/') + 1
currentDir.delete(lastDirInd, currentDir.length)
}
else -> currentDir.append("$nd/")
}
i++
}else{
val files: MutableList<String> = mutableListOf()
while(++i < input.size){
if(input[i].startsWith("$"))
break
files.add(input[i])
}
dirTree[currentDir.toString()] = files
.filter { it.startsWith("dir").not() }
.fold(initial = 0) { acc, str -> acc + str.split(" ").first().toInt() }
}
}
return calculateDirectorySizes(dirTree)
}
private fun calculateDirectorySizes(dirTree: Map<String,Int>): Map<String,Int>{
val sizedTree = mutableMapOf<String,Int>()
dirTree.entries.forEach{
var curDir = it.key
while(curDir.isNotEmpty()){
curDir = curDir.dropLast(1)
val key = curDir.ifBlank { "/" }
sizedTree.merge(key, it.value) { a,b -> a+b }
curDir = curDir.dropLastWhile { itt -> itt != '/' }
}
}
return sizedTree
}
fun part1(dirMap: Map<String,Int>): Int{
return dirMap.values.filter { it <= 100000 }.sum()
}
fun part2(dirMap: Map<String, Int>): Int {
return dirMap.values.groupBy { it > (30000000 - (70000000 - dirMap["/"]!!)) }[true]!!.min()
}
}
fun main() {
val d7 = Day07()
val testInput = readInput("Day07_test")
val test = d7.parseInput(testInput)
check(d7.part1(test) == 95437)
measureTimeMillisPrint {
val tree = d7.parseInput(readInput("Day07"))
println(d7.part1(tree))
println(d7.part2(tree))
}
} | 0 | Kotlin | 0 | 0 | 4b994515004705505ac63152835249b4bc7b601a | 2,403 | aoc-22-kotlin | Apache License 2.0 |
src/Day02.kt | lbilger | 574,227,846 | false | {"Kotlin": 5366} | enum class Shape {
ROCK, PAPER, SCISSORS
}
enum class Outcome {
LOSS, DRAW, WIN
}
fun main() {
fun String.toShape() = when (this) {
"A", "X" -> Shape.ROCK
"B", "Y" -> Shape.PAPER
"C", "Z" -> Shape.SCISSORS
else -> error("Unexpected input $this")
}
fun String.toOutcome() = when (this) {
"X" -> Outcome.LOSS
"Y" -> Outcome.DRAW
"Z" -> Outcome.WIN
else -> error("Unexpected input $this")
}
fun shapeScore(shape: Shape) = when (shape) {
Shape.ROCK -> 1
Shape.PAPER -> 2
Shape.SCISSORS -> 3
}
fun resultScore(opponentShape: Shape, myShape: Shape) = when (opponentShape) {
myShape -> 3
Shape.ROCK -> if (myShape == Shape.PAPER) 6 else 0
Shape.PAPER -> if (myShape == Shape.SCISSORS) 6 else 0
Shape.SCISSORS -> if (myShape == Shape.ROCK) 6 else 0
}
fun part1(input: List<String>): Int {
return input.map { it.split(" ") }.sumOf { shapeScore(it[1].toShape()) + resultScore(it[0].toShape(), it[1].toShape()) }
}
fun myShape(opponentShape: Shape, desiredOutcome: Outcome) = when(desiredOutcome) {
Outcome.DRAW->opponentShape
Outcome.WIN -> Shape.values()[(opponentShape.ordinal + 1) % 3]
Outcome.LOSS -> Shape.values()[(opponentShape.ordinal - 1 + 3) % 3]
}
fun part2(input: List<String>): Int {
return input.map { it.split(" ") }.sumOf {
val opponentShape = it[0].toShape()
val myShape = myShape(opponentShape, it[1].toOutcome())
shapeScore(myShape) + resultScore(opponentShape, myShape)
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day02_test")
checkTestAnswer(part1(testInput), 15, part = 1)
checkTestAnswer(part2(testInput), 12, part = 2)
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 40d94a4bb9621af822722d20675684555cbee877 | 1,970 | aoc-2022-in-kotlin | Apache License 2.0 |
src/day17/Day17.kt | ayukatawago | 572,742,437 | false | {"Kotlin": 58880} | package day17
import readInput
fun main() {
val testInput = readInput("day17/test")
val windPattern = testInput[0].map {
when (it) {
'<' -> -1
'>' -> 1
else -> error("Invalid input")
}
}
println(solve(windPattern, 2022))
println(solve(windPattern, 1000000000000))
}
private const val INITIAL_X = 2
private const val WIDTH = 7
private const val START_HEIGHT = 4
private fun solve(windPattern: List<Int>, totalRockCount: Long): Long {
var windIndex = 0
val cave: MutableSet<Position> = (0..6).map { Position(it, 0) }.toMutableSet()
val stateMap: HashMap<State, Pair<Long, Int>> = hashMapOf()
var loops = 0L
var loopHeight = 0
var rockCount = 0L
var isLoopFound = false
while (rockCount < totalRockCount) {
val rockIndex = (rockCount % RockShape.values().size).toInt()
val rockShape = RockShape.values()[rockIndex]
var rockPosition = Position(INITIAL_X, cave.maxY() + START_HEIGHT)
while (rockShape.canFall(cave, rockPosition)) {
val direction = windPattern[windIndex]
windIndex = (windIndex + 1) % windPattern.size
if (rockShape.canShift(cave, direction, rockPosition)) {
rockPosition = Position(rockPosition.x + direction, rockPosition.y)
}
rockPosition = Position(rockPosition.x, rockPosition.y - 1)
}
rockShape.rocks.forEach {
cave.add(Position(it.x + rockPosition.x, it.y + rockPosition.y + 1))
}
val newState = State(cave.getTopShape(), rockIndex, windIndex)
if (stateMap.containsKey(newState) && !isLoopFound) {
val (loopStart, loopBaseHeight) = stateMap[newState]!!
println("$rockCount -> Hit ($newState) $loopStart $loopBaseHeight")
val rocksPerLoop = rockCount - loopStart
println("rocksPerLoop = $rocksPerLoop")
loops = (totalRockCount - loopStart) / rocksPerLoop - 1
loopHeight = cave.maxY() - loopBaseHeight
rockCount += rocksPerLoop * (loops - 1) + 1
isLoopFound = true
} else {
stateMap[newState] = rockCount to cave.maxY()
rockCount++
}
}
// cave.render()
return cave.maxY() + loopHeight * (loops - 1)
}
private data class State(val caveSnapshot: List<Int>, val rockIndex: Int, val windIndex: Int)
private fun Set<Position>.maxY(): Int = maxOf { it.y }
private fun Set<Position>.getTopShape(): List<Int> =
groupBy { it.x }.entries.sortedBy { it.key }.map { it.value.maxBy { point -> point.y } }
.let {
it.map { point -> maxY() - point.y }
}
private fun Set<Position>.render() {
groupBy { it.y }.entries.sortedByDescending { it.key }.map { it.value }.forEach { positions ->
(0..6).forEach { x ->
print(if (x in positions.map { it.x }) '#' else '.')
}
println()
}
}
private enum class RockShape(val rocks: List<Position>, val width: Int, val height: Int) {
SHAPE1(listOf(Position(0, 0), Position(1, 0), Position(2, 0), Position(3, 0)), 4, 1),
SHAPE2(listOf(Position(1, 0), Position(0, 1), Position(1, 1), Position(2, 1), Position(1, 2)), 3, 3),
SHAPE3(listOf(Position(0, 0), Position(1, 0), Position(2, 0), Position(2, 1), Position(2, 2)), 3, 3),
SHAPE4(listOf(Position(0, 0), Position(0, 1), Position(0, 2), Position(0, 3)), 1, 4),
SHAPE5(listOf(Position(0, 0), Position(1, 0), Position(0, 1), Position(1, 1)), 2, 2);
fun canFall(cave: Set<Position>, position: Position): Boolean =
rocks.all {
!cave.contains(Position(it.x + position.x, it.y + position.y))
}
fun canShift(cave: Set<Position>, direction: Int, position: Position): Boolean =
rocks.all {
position.x + direction >= 0 &&
position.x + width + direction <= WIDTH &&
!cave.contains(Position(it.x + position.x + direction, it.y + position.y))
}
}
private data class Position(val x: Int, val y: Int)
| 0 | Kotlin | 0 | 0 | 923f08f3de3cdd7baae3cb19b5e9cf3e46745b51 | 4,095 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/mkuhn/aoc/Day16.kt | mtkuhn | 572,236,871 | false | {"Kotlin": 53161} | package mkuhn.aoc
fun day16part1(input: List<String>): Int {
val valves = input.map { Valve.fromString(it) }
val mins = 30
val init = valves.find { it.name == "AA" }!!
val you = ValveWalker(init, 0)
val finder = ValvePathFinder(mins, valves)
return finder.findOptimalPathValDFS(listOf(you), valves)
}
fun day16part2(input: List<String>): Int {
val valves = input.map { Valve.fromString(it) }
val mins = 30
val init = valves.find { it.name == "AA" }!!
val you = ValveWalker(init, 4)
val elephant = ValveWalker(init, 4)
val finder = ValvePathFinder(mins, valves)
return finder.findOptimalPathValDFS(listOf(you, elephant), valves)
}
class ValvePathFinder(private val minsAllowed: Int, valves: List<Valve>) {
private val distMap: Map<Pair<Valve, Valve>, Int> = valves.toDistanceMap()
fun findOptimalPathValDFS(workers: List<ValveWalker>,
valves: List<Valve>): Int {
val valvePath = ValvePath(
workers,
valves.filter { it.flowRate > 0 }, //the 0 flow valves may as well be closed, and the stuck AA valve
0
)
return valvePath.findBestPathScore()
}
private fun ValvePath.findBestPathScore(): Int {
val paths = this.viableMoves()
return if(paths.isEmpty()) 0
else if(paths.all { p -> p.walkers.all { it.minsUsed == minsAllowed } }) paths.maxOf { it.pressureRelieved }
else paths.maxOf { it.findBestPathScore() }
}
private fun List<Valve>.toDistanceMap(): Map<Pair<Valve, Valve>, Int> {
return this.flatMap { v1 ->
this.map { v2 -> v1 to v2 }
}.associateWith { this.distanceBetween(it.first, it.second) }
}
private fun ValvePath.viableMoves(): List<ValvePath> {
val walker = walkers.first()
return if(walker.minsUsed == minsAllowed) listOf(this)
else {
val moves = remainingValves.map { rv -> walker.currPos to rv }
.map { rv -> moveTo(walker, rv.second, distMap[rv]!!) } //map out to these destinations
.plus(this.copy(walkers = (walkers-walker+ValveWalker(walker.currPos, minsAllowed)).sortedBy { it.minsUsed })) //or maybe just do nothing?
.filter { it.walkers.all { w -> w.minsUsed <= minsAllowed } }//don't go over allowed mins
moves.ifEmpty {
//this means there's nothing else helpful to move to, just set workers to 30 mins to close the loop
listOf(this.copy(walkers = walkers.map { ValveWalker(it.currPos, minsAllowed) }))
}
}
}
private fun ValvePath.moveTo(walker: ValveWalker, newValve: Valve, distance: Int): ValvePath {
val mm = walker.minsUsed+distance+1
val newPressure = newValve.flowRate*(minsAllowed-mm)
val newWalkers = (walkers - walker + ValveWalker(newValve, mm)).sortedBy { it.minsUsed }
return ValvePath(
newWalkers,
remainingValves-newValve,
pressureRelieved + newPressure
)
}
private fun List<Valve>.distanceBetween(a: Valve, b: Valve): Int {
var nodes = listOf(a)
val nodesVisited = mutableSetOf(a)
var dist = 0
while(b !in nodes) {
nodes = nodes.flatMap { curr ->
curr.paths.map { n -> this.find { it.name == n }!! }
.filter { it !in nodesVisited }
}
nodesVisited += nodes
dist++
}
return dist
}
}
data class ValveWalker(val currPos: Valve, val minsUsed: Int)
data class ValvePath(val walkers: List<ValveWalker>, val remainingValves: List<Valve>, val pressureRelieved: Int)
data class Valve(val name: String, val flowRate: Int, val paths: List<String>) {
companion object {
private val valveRegex = """Valve (.+) has flow rate=(\d+); tunnels? leads? to valves? (.+)""".toRegex()
fun fromString(s: String): Valve =
valveRegex.matchEntire(s)?.destructured?.let {
(n, r, p) -> Valve(n, r.toInt(), p.split(", "))
}?: error("invalid input: $s")
}
} | 0 | Kotlin | 0 | 1 | 89138e33bb269f8e0ef99a4be2c029065b69bc5c | 4,160 | advent-of-code-2022 | Apache License 2.0 |
src/day09/Day09.kt | spyroid | 433,555,350 | false | null | package day09
import readInput
import kotlin.system.measureTimeMillis
fun main() {
data class Point(val x: Int, val y: Int, val v: Int)
class Area(input: List<String>) {
val points = readPoints(input)
val areaWidth = input.first().length
fun readPoints(seq: List<String>) = mutableListOf<Point>().apply {
seq.forEachIndexed { y, line -> line.forEachIndexed { x, v -> this += Point(x, y, v.digitToInt()) } }
}
fun at(x: Int, y: Int): Point? {
if (x < 0 || x >= areaWidth || y < 0) return null
return points.getOrNull(x + areaWidth * y)
}
fun neighbors(x: Int, y: Int) = listOfNotNull(at(x + 1, y), at(x - 1, y), at(x, y + 1), at(x, y - 1))
fun lowestPoints() = points.filter { p -> neighbors(p.x, p.y).all { it.v > p.v } }
fun basinsMaxSizes(count: Int) = lowestPoints()
.map { findBasin(it).size }
.sortedByDescending { it }
.take(count)
.fold(1) { acc, i -> acc * i }
private fun findBasin(p: Point): MutableSet<Point> {
fun deeper(p: Point, basin: MutableSet<Point>) {
basin.add(p)
neighbors(p.x, p.y).filter { n -> p.v < n.v && n.v < 9 }.forEach { deeper(it, basin) }
}
return mutableSetOf<Point>().apply { deeper(p, this) }
}
}
fun part1(input: List<String>) = Area(input).lowestPoints().sumOf { it.v + 1 }
fun part2(input: List<String>) = Area(input).basinsMaxSizes(3)
/* init */
val testData = readInput("day09/test")
val inputData = readInput("day09/input")
var res1 = part1(testData)
check(res1 == 15) { "Expected 15 but got $res1" }
var time = measureTimeMillis { res1 = part1(inputData) }
println("Part1: $res1 in $time ms")
res1 = part2(testData)
check(res1 == 1134) { "Expected 1134 but got $res1" }
time = measureTimeMillis { res1 = part2(inputData) }
println("Part2: $res1 in $time ms")
}
| 0 | Kotlin | 0 | 0 | 939c77c47e6337138a277b5e6e883a7a3a92f5c7 | 2,027 | Advent-of-Code-2021 | Apache License 2.0 |
src/Day15.kt | cypressious | 572,916,585 | false | {"Kotlin": 40281} | import java.util.PriorityQueue
fun main() {
val neighbors = listOf(
-1 to 0,
1 to 0,
0 to -1,
0 to 1,
)
data class Node(val x: Int, val y: Int, val risk: Int) : Comparable<Node> {
var distance = Int.MAX_VALUE
fun neighbors(grid: List<List<Node>>) = neighbors.mapNotNull { (dx, dy) ->
grid.getOrNull(y + dy)?.getOrNull(x + dx)
}
override fun compareTo(other: Node) = distance.compareTo(other.distance)
}
fun findPath(input: List<String>, wrap: Boolean): Int {
var grid = input.mapIndexed { y, row ->
row.toCharArray().mapIndexed { x, c -> Node(x, y, c - '0') }
}
if (wrap) {
val originalHeight = grid.size
val originalWidth = grid[0].size
grid = List(originalHeight * 5) { y ->
val yy = y % originalHeight
val dy = y / originalHeight
List(originalWidth * 5) { x ->
val xx = x % originalWidth
val dx = x / originalWidth
Node(x, y, ((grid[yy][xx].risk + dx + dy - 1) % 9) + 1)
}
}
}
val unvisited = PriorityQueue<Node>()
val visited = mutableSetOf<Node>()
grid[0][0].let {
it.distance = 0
unvisited.add(it)
}
while (unvisited.isNotEmpty()) {
val node = unvisited.poll()
for (neighbor in node.neighbors(grid)) {
if (neighbor !in visited && neighbor.distance > node.distance + neighbor.risk) {
unvisited.remove(neighbor)
neighbor.distance = node.distance + neighbor.risk
unvisited.add(neighbor)
if (neighbor.y == grid.lastIndex && neighbor.x == grid.last().lastIndex) {
return neighbor.distance
}
}
}
visited += node
}
return 0
}
fun part1(input: List<String>): Int {
return findPath(input, false)
}
fun part2(input: List<String>): Int {
return findPath(input, true)
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day15_test")
check(part1(testInput) == 40)
check(part2(testInput) == 315)
val input = readInput("Day15")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 169fb9307a34b56c39578e3ee2cca038802bc046 | 2,488 | AdventOfCode2021 | Apache License 2.0 |
src/Day02.kt | mrugacz95 | 572,881,300 | false | {"Kotlin": 102751} | private fun abcIndex(s: String) = s[0] - 'A'
private fun xyzIndex(s: String) = s[0] - 'X'
private fun xyzScore(s: String) = xyzIndex(s) + 1
private fun roundResult(opponentSymb: String, yourSymb: String): Int {
return listOf(
listOf(3, 6, 0),
listOf(0, 3, 6),
listOf(6, 0, 3),
)[abcIndex(opponentSymb)][xyzIndex(yourSymb)] + xyzScore(yourSymb)
}
private fun whatChoose(opponentSymb: String, result: String): String {
return listOf(
listOf("Z", "X", "Y"),
listOf("X", "Y", "Z"),
listOf("Y", "Z", "X"),
)[abcIndex(opponentSymb)][xyzIndex(result)]
}
fun main() {
fun part1(input: List<Pair<String, String>>): Int {
return input.sumOf {
val (a, b) = it
roundResult(a, b)
}
}
fun part2(input: List<Pair<String, String>>): Int {
return input.sumOf {
val (a, b) = it
val yourSymb = whatChoose(a, b)
roundResult(a, yourSymb)
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day02_test")
.map {
val (a, b) = it.split(' ')
Pair(a, b)
}
println(part1(testInput))
println(part2(testInput))
val input = readInput("Day02").map {
val (a, b) = it.split(' ')
Pair(a, b)
}
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 29aa4f978f6507b182cb6697a0a2896292c83584 | 1,419 | advent-of-code-2022 | Apache License 2.0 |
src/Day8.kt | sitamshrijal | 574,036,004 | false | {"Kotlin": 34366} | fun main() {
fun parse(input: List<String>): List<List<Tree>> {
val grid = buildList {
input.forEach { row ->
add(row.map { Tree(it.digitToInt()) })
}
}
for (i in grid.indices) {
for (j in grid[0].indices) {
val tree = grid[i][j]
tree.left = grid[i].take(j)
tree.right = grid[i].drop(j + 1)
tree.up = grid.map { it[j] }.take(i)
tree.down = grid.map { it[j] }.drop(i + 1)
}
}
return grid
}
fun part1(input: List<String>): Int {
val grid = parse(input)
return grid.flatten().count { it.isVisible() }
}
fun part2(input: List<String>): Int {
val grid = parse(input)
return grid.flatten().maxOf { it.scenicScore() }
}
val input = readInput("input8")
println(part1(input))
println(part2(input))
}
data class Tree(val height: Int) {
var left = listOf<Tree>()
var right = listOf<Tree>()
var up = listOf<Tree>()
var down = listOf<Tree>()
fun isVisible(): Boolean =
isVisible(left) || isVisible(right) || isVisible(up) || isVisible(down)
private fun isVisible(trees: List<Tree>): Boolean = trees.all { it.height < height }
private fun score(trees: List<Tree>): Int {
var score = 0
for (tree in trees) {
score++
if (tree.height >= height) {
break
}
}
return score
}
fun scenicScore(): Int =
score(left.reversed()) * score(right) * score(up.reversed()) * score(down)
}
| 0 | Kotlin | 0 | 0 | fd55a6aa31ba5e3340be3ea0c9ef57d3fe9fd72d | 1,655 | advent-of-code-2022 | Apache License 2.0 |
src/day04/solution.kt | bohdandan | 729,357,703 | false | {"Kotlin": 80367} | package day04
import println
import readInput
fun main() {
class Card (val id: Int, val winningNumbers: Set<Int>, val numbersYouHave: Set<Int>, var numberOfCopies: Int = 1) {
fun matches(): Int {
val overlap = winningNumbers.intersect(numbersYouHave)
return overlap.size
}
}
class CardStack {
var cards: List<Card> = emptyList();
constructor(input: List<String>) {
cards = input.stream().map{parseCard(it)}.toList()
}
fun splitIntoNumbers(input: String): Set<Int> {
return input.split(" ").filter { it.isNotEmpty() }.map { it.toInt() }.toSet()
}
fun parseCard(input: String): Card {
val cardPattern = Regex("Card\\s*(\\d+): (.*)")
val match = cardPattern.findAll(input).first()
val cardId = match.groupValues[1].toInt()
val numberGroups = match.groupValues[2].split("|")
var winningNumbers = splitIntoNumbers(numberGroups[0])
var numbersYouHave = splitIntoNumbers(numberGroups[1])
return Card(cardId, winningNumbers, numbersYouHave)
}
fun winningPointLogic1(): Int {
return cards.map { it.matches() }
.filter { it > 0 }
.map {
Math.pow(2.0, (it - 1).toDouble()).toInt()
}.sum()
}
fun numberOfCardsLogic2(): Int {
cards.forEach { card ->
val matches = card.matches()
if (matches > 0) {
var rangeToDuplicate = card.id + 1 .. card.id + matches
cards.filter { rangeToDuplicate.contains(it.id) }
.forEach{
it.numberOfCopies += card.numberOfCopies
}
}
}
return cards.sumOf { it.numberOfCopies }
}
}
val testCardStack = CardStack(readInput("day04/test1"))
check(testCardStack.winningPointLogic1() == 13)
check(testCardStack.numberOfCardsLogic2() == 30)
val cardStack = CardStack(readInput("day04/input"))
cardStack.winningPointLogic1().println()
cardStack.numberOfCardsLogic2().println()
}
| 0 | Kotlin | 0 | 0 | 92735c19035b87af79aba57ce5fae5d96dde3788 | 2,246 | advent-of-code-2023 | Apache License 2.0 |
src/main/kotlin/nl/dirkgroot/adventofcode/year2020/Day24.kt | dirkgroot | 317,968,017 | false | {"Kotlin": 187862} | package nl.dirkgroot.adventofcode.year2020
import nl.dirkgroot.adventofcode.util.Input
import nl.dirkgroot.adventofcode.util.Puzzle
class Day24(input: Input) : Puzzle() {
private val flip by lazy {
input.lines().map { parseRoute(it) }
}
private val directionRegex = "(e|se|sw|w|nw|ne)".toRegex()
private tailrec fun parseRoute(route: String, directions: List<String> = listOf()): List<String> =
if (route == "") directions
else {
val match = directionRegex.find(route)!!
parseRoute(route.substring(match.groupValues[1].length), directions + match.groupValues[1])
}
override fun part1() = blackTiles().size
override fun part2(): Int {
val initialBlackTiles = blackTiles()
val initialWidth = initialBlackTiles.maxOf { it.first } - initialBlackTiles.minOf { it.first }
val initialHeight = initialBlackTiles.maxOf { it.second } - initialBlackTiles.minOf { it.second }
val turns = 100
val increase = turns * 2 + 4
val originX = (initialWidth + increase) / 2
val originY = (initialHeight + increase) / 2
val blackTiles = initialBlackTiles.map { (x, y) -> originX + x to originY + y }.toMutableSet()
val grid = Array(initialHeight + increase) { y ->
BooleanArray(initialWidth + increase) { x -> x to y in blackTiles }
}
repeat(turns) {
val flipToBlack = blackTiles.asSequence()
.flatMap { (x, y) -> adjacentTiles(x, y) }
.distinct()
.filter { (x, y) -> !grid[y][x] && adjacentBlackTiles(grid, x, y) == 2 }
.toList()
val flipToWhite = blackTiles.asSequence()
.filter { (x, y) ->
val adjacentBlackTileCount = adjacentBlackTiles(grid, x, y)
adjacentBlackTileCount == 0 || adjacentBlackTileCount > 2
}
.toList()
blackTiles.addAll(flipToBlack)
flipToBlack.forEach { (x, y) -> grid[y][x] = true }
blackTiles.removeAll(flipToWhite.toSet())
flipToWhite.forEach { (x, y) -> grid[y][x] = false }
}
return grid.sumOf { it.count { isBlack -> isBlack } }
}
private fun adjacentBlackTiles(grid: Array<BooleanArray>, x: Int, y: Int) =
adjacentTiles(x, y).count { (tx, ty) -> grid[ty][tx] }
private fun adjacentTiles(x: Int, y: Int) =
listOf(x - 1 to y + 1, x + 1 to y - 1, x - 1 to y, x + 1 to y, x to y + 1, x to y - 1)
private fun blackTiles() = flip.asSequence()
.map { getCoordinate(it) }
.groupBy { it }
.map { (coord, occurrences) -> coord to occurrences.size }
.filter { (_, count) -> count % 2 > 0 }
.map { (coord, _) -> coord }
private tailrec fun getCoordinate(directions: List<String>, x: Int = 0, y: Int = 0): Pair<Int, Int> =
if (directions.isEmpty()) x to y
else when (directions[0]) {
"e" -> getCoordinate(directions.drop(1), x + 1, y)
"se" -> getCoordinate(directions.drop(1), x, y + 1)
"sw" -> getCoordinate(directions.drop(1), x - 1, y + 1)
"w" -> getCoordinate(directions.drop(1), x - 1, y)
"nw" -> getCoordinate(directions.drop(1), x, y - 1)
"ne" -> getCoordinate(directions.drop(1), x + 1, y - 1)
else -> throw IllegalStateException()
}
} | 1 | Kotlin | 1 | 1 | ffdffedc8659aa3deea3216d6a9a1fd4e02ec128 | 3,453 | adventofcode-kotlin | MIT License |
src/day7/Day07.kt | dinoolivo | 573,723,263 | false | null | package day7
import readInput
fun main() {
fun part1(tree: Tree): Long {
return tree.getAllNodesByCondition { treeNode -> treeNode.metadata.isDir() && treeNode.metadata.size <= 100000}
.sumOf { treeNode -> treeNode.metadata.size }
}
fun part2(tree: Tree): Long {
val currentFreeSpace = 70000000L -tree.root.metadata.size
val neededSpace = 30000000 - currentFreeSpace
return tree.getAllNodesByCondition { treeNode -> treeNode.metadata.isDir() && treeNode.metadata.size >= neededSpace }
.map { node -> node.metadata.size }.minOf { it }
}
fun loadTree(input: List<String>): Tree {
val tree = Tree()
for(line in input){
if(line.startsWith("$")){
val lineParts = line.split(" ")
if(lineParts[1] == "cd"){
if(lineParts[2] == "/"){
tree.addRoot(TreeNode(Metadata("/", Type.Dir, 0), null))
}else if(lineParts[2] == ".."){
tree.moveUp()
}else{
tree.moveTo(lineParts[2])
}
}else if(lineParts[1] == "ls"){
continue
}
}else{
val lineParts = line.split(" ")
if(lineParts[0] == Type.Dir.toString()){
tree.currentNode?.addChild(TreeNode(Metadata(lineParts[1], Type.Dir, 0), tree.currentNode))
}else{
val fileSize = lineParts[0].toLong()
tree.currentNode?.addChild(TreeNode(Metadata(lineParts[1], Type.File, fileSize), tree.currentNode))
tree.propagateUp { currentNode -> currentNode.metadata.addSize(fileSize) }
}
}
}
return tree
}
val testInput = loadTree(readInput("inputs/Day07_test"))
testInput.printTree()
println("Test Part 1: " + part1(testInput))
println("Test Part 2: " + part2(testInput))
//execute the two parts on the real input
val input = loadTree(readInput("inputs/Day07"))
//input.printTree()
println("Part1: " + part1(input))
println("Part2: " + part2(input))
}
| 0 | Kotlin | 0 | 0 | 6e75b42c9849cdda682ac18c5a76afe4950e0c9c | 2,232 | aoc2022-kotlin | Apache License 2.0 |
src/main/kotlin/com/github/ferinagy/adventOfCode/aoc2015/2015-16.kt | ferinagy | 432,170,488 | false | {"Kotlin": 787586} | package com.github.ferinagy.adventOfCode.aoc2015
import com.github.ferinagy.adventOfCode.readInputLines
fun main() {
val input = readInputLines(2015, "16-input")
println("Part1:")
println(part1(input))
println()
println("Part2:")
println(part2(input))
}
private fun part1(input: List<String>): Int {
val infos = input.map { SueInfo.parse(it) }
val tape = """
children: 3
cats: 7
samoyeds: 2
pomeranians: 3
akitas: 0
vizslas: 0
goldfish: 5
trees: 3
cars: 2
perfumes: 1
""".trimIndent()
.lines().associate { it.split(": ").let { (a, b) -> a to b.toInt() } }
return infos.single { it.map.all { (key, value) -> tape[key] == value } }.num
}
private fun part2(input: List<String>): Int {
val infos = input.map { SueInfo.parse(it) }
val tape = mapOf(
"children" to 3 .. 3,
"cats" to 8 .. 1000,
"samoyeds" to 2 .. 2,
"pomeranians" to -1000 .. 2,
"akitas" to 0 .. 0,
"vizslas" to 0 .. 0,
"goldfish" to -1000 .. 4,
"trees" to 4 .. 1000,
"cars" to 2 .. 2,
"perfumes" to 1 .. 1,
)
return infos.single { it.map.all { (key, value) -> value in tape[key]!! } }.num
}
private data class SueInfo(val num: Int, val map: Map<String, Int>) {
companion object {
fun parse(input: String): SueInfo {
val (num, i1, c1, i2, c2, i3, c3) = regex.matchEntire(input)!!.destructured
val map = mapOf(
i1 to c1.toInt(),
i2 to c2.toInt(),
i3 to c3.toInt(),
)
return SueInfo(num.toInt(), map)
}
}
}
private val regex = """Sue (\d+): (\w+): (\d+), (\w+): (\d+), (\w+): (\d+)""".toRegex()
| 0 | Kotlin | 0 | 1 | f4890c25841c78784b308db0c814d88cf2de384b | 1,808 | advent-of-code | MIT License |
src/Day18.kt | MarkTheHopeful | 572,552,660 | false | {"Kotlin": 75535} | import java.util.*
import kotlin.math.abs
private typealias Point = List<Int>
fun main() {
fun areConnected(a: Point, b: Point): Boolean {
return a.withIndex().count { it.value != b[it.index] } == 1 && a.withIndex()
.count { abs(it.value - b[it.index]) == 1 } == 1
}
fun countOutsides(cubes: Set<Point>) = 6 * cubes.size - cubes.sumOf {
cubes.count { it2 ->
areConnected(it, it2)
}
}
fun parseCubes(input: List<String>) = input.map { it.split(',').map { it2 -> it2.toInt() } }.toSet()
fun part1(input: List<String>): Int {
val cubes = parseCubes(input)
return countOutsides(cubes)
}
fun walkBfs(
cubes: Set<Point>,
pointStart: Point,
used: MutableMap<Point, Int>,
bounds: Point,
alreadyExternal: MutableSet<Point>,
iter: Int
): Boolean {
val q: Queue<Point> = LinkedList()
q.add(pointStart)
used[pointStart] = iter
var reachedTheEnd = false
while (q.isNotEmpty()) {
val point = q.remove()
if (point.any { it == 0 } || point in alreadyExternal) {
reachedTheEnd = true
}
for (i in point.indices) {
for (j in -1..1 step 2) {
val newPoint = List(point.size) { point[it] + (if (it == i) j else 0) }
if (newPoint in used || newPoint in cubes) continue
if (newPoint.withIndex().any { it.value < 0 || it.value > bounds[it.index] }) continue
q.add(newPoint)
used[newPoint] = iter
}
}
}
return reachedTheEnd
}
fun getAllInternalPoints(cubes: Set<Point>): Set<Point> {
// 0,0,0 is definitely external
val bounds = List(cubes.first().size) { cubes.maxOf { it2 -> it2[it] + 1 } }
val foundInternal = mutableSetOf<Point>()
val foundExternal = mutableSetOf<Point>()
val used = mutableMapOf<Point, Int>()
var iter = 0
for (x in 0..bounds[0]) {
for (y in 0..bounds[1]) {
for (z in 0..bounds[2]) {
val point = listOf(x, y, z)
if (point in used || point in cubes) continue
if (walkBfs(cubes, point, used, bounds, foundExternal, iter)) {
foundExternal.addAll(used.filter { it.value == iter }.keys)
} else {
foundInternal.addAll(used.filter { it.value == iter }.keys)
}
iter++
}
}
}
return foundInternal
}
fun part2(input: List<String>): Int {
val cubes = parseCubes(input).toMutableSet()
cubes.addAll(getAllInternalPoints(cubes))
return countOutsides(cubes)
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day18_test")
check(part1(testInput) == 64)
check(part2(testInput) == 58)
val input = readInput("Day18")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 8218c60c141ea2d39984792fddd1e98d5775b418 | 3,176 | advent-of-kotlin-2022 | Apache License 2.0 |
test/exercism/SumOfMultiples.kt | andrej-dyck | 340,964,799 | false | null | package exercism
import org.junit.jupiter.api.*
import org.junit.jupiter.api.Assertions.assertEquals
/**
* https://exercism.io/tracks/kotlin/exercises/sum-of-multiples
*
* Sum Of Multiples
* [Medium]
*
* Given a number, find the sum of all the multiples of particular numbers up to but not including that number.
*/
interface SumOfMultiples {
val sum: Int
companion object {
fun sum(numbers: Set<Int>, multiplesExclusiveUpperLimit: Int) =
when (numbers.size) {
in 0..3 -> ArithmeticSumOfMultiples(numbers, multiplesExclusiveUpperLimit - 1).sum
else -> BrutForceSumOfMultiples(numbers, multiplesExclusiveUpperLimit - 1).sum
}
}
}
/**
* Brute-force Approach
*/
class BrutForceSumOfMultiples(numbers: Set<Int>, maxMultiple: Int) : SumOfMultiples {
/**
* Idea: list all multiples (starting with the min number) and add up only those
* that are divisible by any of the given numbers.
*/
override val sum by lazy {
numbers.minOrNull()?.let { min ->
(min..maxMultiple).filter { numbers.anyIsDivisorOf(it) }.sum()
} ?: 0
}
private fun Iterable<Int>.anyIsDivisorOf(multiple: Int) = any { multiple.isDivisibleBy(it) }
private fun Int.isDivisibleBy(divisor: Int) = this % divisor == 0
}
/**
* A arithmetic/geometric approach to the problem
*
* Note that the sum of multiples of a number n is calculated as follows:
* n*1 + n*2 + n*3 + ... OR n * (1 + 2 + 3 + ...)
*
* Since we have an upper limit L for the multiples, the sequence of multipliers
* is limited by a max multiplier M as well; i.e.: n * (1 + 2 + 3 + ... + M)
*
* The second term, the sum of the multipliers sequence, can be determined by
* Gauss' formula for arithmetic series: 1 + 2 + ... M == M * (M + 1) / 2
*
* Where M is the max. Multiplier for a n, such that n*M <= L -> M = L / n
*
* So, the sum of multiples of a number n, limited by (excluding) L, is:
* n * (1 + 2 + 3 + ... + L / n) [=: S(n)]
*
* For two or three numbers only distinct multiples have to be considered considered.
* Here, set theory (symmetric difference) is used to determine the sum of multiples.
*
* For two numbers n1, n2 its the sum of the individual sums S(n1) + S(n2) minus
* the sum of "intersecting" multiples S(LCM(n1, n2)) where LCM is the
* least common multiple.
*
* For three numbers n1, n2, n3 its the sum of the individual sums
* S(n1) + S(n2) + S(n3) minus the sum of "intersecting" multiples
* S(LCM(n1, n2) + S(LMC(n2, n3) + S(LMC(n1, n2, n3)).
*
* @param numbers A set of 0 to 3 numbers
* @param maxMultiple The max. multiple considered for the sum (upper limit L)
*/
class ArithmeticSumOfMultiples(numbers: Set<Int>, maxMultiple: Int) : SumOfMultiples {
init {
require(numbers.size <= 3) {
"arithmetic solution only works for up to three numbers"
}
require(numbers.all { it >= 0 } && maxMultiple >= 0) {
"only natural numbers possible"
}
}
/**
* Sum of (distinct) multiples (smaller that the max multiple) of numbers using
* set theory [symm. diff.].
*/
override val sum by lazy {
numbers.sumOfAllMultiplesUpTo(maxMultiple) - numbers.sumOfCommonMultiplesUpTo(maxMultiple)
}
/**
* Sum of all multiples: S(n1) + S(n2) + S(n3) + ...
*/
private fun Set<Int>.sumOfAllMultiplesUpTo(maxMultiple: Int) =
sumOf { sumOfMultiplesOfUpTo(it, maxMultiple) }
/**
* Sum of n*(1..N) where N = (L-1) / n
*/
private fun sumOfMultiplesOfUpTo(n: Int, maxMultiple: Int) =
n * sumOfNaturalNumbersUpTo(maxMultiple / n)
/**
* Sum of 1..n using the Gauss' formula
*/
private fun sumOfNaturalNumbersUpTo(n: Int) = n * (n + 1) / 2
/**
* Sum of intersecting multiples
* For empty sets or sets of one number, this sum is 0.
* For two numbers: S(LCM(n1, n2) where LCM is the least common multiple
* For three numbers: S(LCM(n1, n2) + S(LMC(n2, n3) + S(LMC(n1, n2, n3))
*
* FIXME this implementation doesn't work for more than three numbers!
*/
private fun Set<Int>.sumOfCommonMultiplesUpTo(maxMultiple: Int) =
if (size == 0) 0
else (2..size).sumOf {
windowed(it).sumOf { slice ->
sumOfMultiplesOfUpTo(slice.lcm(), maxMultiple)
}
}
}
/**
* Math Stuff
*/
internal fun Collection<Int>.lcm() = this.reduce { acc: Int, i: Int -> lcm(acc, i) }
internal fun lcm(a: Int, b: Int) = a / gcd(a, b) * b
internal tailrec fun gcd(a: Int, b: Int): Int = if (b == 0) a else gcd(b, a % b)
/**
* Unit tests
*/
class SumOfMultiplesTest {
@Test
fun `multiples of 3 or 5 up to 1`() {
assertEquals(0, SumOfMultiples.sum(setOf(3, 5), 1))
}
@Test
fun `multiples of 3 or 5 up to 4`() {
assertEquals(3, SumOfMultiples.sum(setOf(3, 5), 4))
}
@Test
fun `multiples of 3 up to 7`() {
assertEquals(9, SumOfMultiples.sum(setOf(3), 7))
}
@Test
fun `multiples of 3 or 5 up to 10`() {
assertEquals(23, SumOfMultiples.sum(setOf(3, 5), 10))
}
@Test
fun `multiples of 3 or 5 up to 100`() {
assertEquals(2318, SumOfMultiples.sum(setOf(3, 5), 100))
}
@Test
fun `multiples of 3 or 5 up to 1000`() {
assertEquals(233_168, SumOfMultiples.sum(setOf(3, 5), 1000))
}
@Test
fun `multiples of 7, 13 or 17 up to 20`() {
assertEquals(51, SumOfMultiples.sum(setOf(7, 13, 17), 20))
}
@Test
fun `multiples of 4 or 6 up to 15`() {
assertEquals(30, SumOfMultiples.sum(setOf(4, 6), 15))
}
@Test
fun `multiples of 5, 6 or 8 up to 150`() {
assertEquals(4419, SumOfMultiples.sum(setOf(5, 6, 8), 150))
}
@Test
fun `multiples of 5 or 25 up to 51`() {
assertEquals(275, SumOfMultiples.sum(setOf(5, 25), 51))
}
@Test
fun `multiples of 43 or 47 up to 10000`() {
assertEquals(2_203_160, SumOfMultiples.sum(setOf(43, 47), 10000))
}
@Test
fun `multiples of 1 up to 100`() {
assertEquals(4950, SumOfMultiples.sum(setOf(1), 100))
}
@Test
fun `multiples of an empty set up to 10000`() {
assertEquals(0, SumOfMultiples.sum(emptySet(), 10000))
}
} | 0 | Kotlin | 0 | 0 | 3e3baf8454c34793d9771f05f330e2668fda7e9d | 6,341 | coding-challenges | MIT License |
src/Day11.kt | WhatDo | 572,393,865 | false | {"Kotlin": 24776} | import java.math.BigDecimal
fun main() {
val input = readInput("Day11")
val monkies = input.windowed(6, 7) { list ->
list.fold(Monkey()) { monkey, s ->
val trimmed = s.trim()
when {
trimmed.startsWith("Monkey") -> monkey.copy(idx = trimmed.split(" ").last().replace(":", "").toInt())
trimmed.startsWith("Starting items:") -> monkey.copy(
items = trimmed.split(" ").drop(2).map { Item(it.replace(",", "").toLong()) }
)
trimmed.startsWith("Operation: ") -> monkey.copy(
op = trimmed.split(" ").takeLast(2).let { (op, target) ->
when {
target == "old" -> Pow2
op == "+" -> Add(target.toInt())
op == "*" -> Mult(target.toInt())
else -> TODO("$op not supported")
}
}
)
trimmed.startsWith("Test:") -> monkey.copy(test = trimmed.split(" ").last().toInt())
trimmed.startsWith("If true:") -> monkey.copy(trueTarget = trimmed.split(" ").last().toInt())
trimmed.startsWith("If false:") -> monkey.copy(falseTarget = trimmed.split(" ").last().toInt())
else -> monkey
}
}
}.let(::MonkeyState)
val result = runMonkies(20, monkies)
println(result.monkies.joinToString("\n"))
println(
result.monkies.sortedBy { it.inspectionLevel }.takeLast(2)
.fold(1) { acc, monkey -> acc * monkey.inspectionLevel })
val result10k = runMonkies(10000, monkies, stressed = true)
println(result10k.monkies.joinToString("\n"))
println(
result10k.monkies.sortedBy { it.inspectionLevel }.takeLast(2)
.fold(1L) { acc, monkey -> acc * monkey.inspectionLevel })
// 21816744824
}
private fun runMonkies(times: Int, state: MonkeyState, stressed: Boolean = false): MonkeyState {
var currentState = state
repeat(times) {
val size = state.monkies.size
repeat(size) { idx ->
currentState = runMonkey(currentState, currentState.monkies[idx], stressed)
}
}
return currentState
}
private fun runMonkey(state: MonkeyState, monkey: Monkey, withStress: Boolean): MonkeyState {
val mutableMonkies = state.monkies.toMutableList()
monkey.items.forEach { item ->
var worryItem = apply(op = monkey.op, item)
worryItem = if (!withStress) apply(op = Div(3), worryItem) else worryItem
worryItem = apply(op = state.commonDivisor, worryItem)
val targetMonkey = if (worryItem.worryLevel % monkey.test == 0L) {
monkey.trueTarget
} else {
monkey.falseTarget
}
mutableMonkies[targetMonkey] = mutableMonkies[targetMonkey].run { copy(items = items + worryItem) }
}
mutableMonkies[monkey.idx] = monkey.copy(
items = emptyList(),
inspectionLevel = monkey.inspectionLevel + monkey.items.size
)
return state.copy(monkies = mutableMonkies)
}
private data class MonkeyState(
val monkies: List<Monkey>,
val commonDivisor: WorryOp = Mod(monkies.fold(1) { acc, monkey -> acc * monkey.test })
)
private data class Monkey(
val idx: Int = 0,
val op: WorryOp = Add(0),
val test: Int = 0,
val trueTarget: Int = 0,
val falseTarget: Int = 0,
val inspectionLevel: Int = 0,
val items: List<Item> = emptyList(),
)
private fun apply(op: WorryOp, item: Item): Item {
return Item(
when (op) {
is Add -> item.worryLevel + (op.value)
is Mult -> item.worryLevel * (op.factor)
is Div -> item.worryLevel / (op.factor)
Pow2 -> item.worryLevel * item.worryLevel
is Mod -> item.worryLevel % op.factor
}
)
}
private data class Item(
val worryLevel: Long
)
private sealed class WorryOp
private data class Mult(val factor: Int) : WorryOp()
private data class Add(val value: Int) : WorryOp()
private data class Div(val factor: Int = 3) : WorryOp()
private data class Mod(val factor: Int) : WorryOp()
private object Pow2 : WorryOp()
| 0 | Kotlin | 0 | 0 | 94abea885a59d0aa3873645d4c5cefc2d36d27cf | 4,234 | aoc-kotlin-2022 | Apache License 2.0 |
src/day07/Task.kt | dniHze | 433,447,720 | false | {"Kotlin": 35403} | package day07
import readInput
import kotlin.math.max
import kotlin.collections.sumOf
import kotlin.math.abs
import kotlin.math.min
fun main() {
val input = readInput("day07")
println(solvePartOne(input))
println(solvePartTwo(input))
}
fun solvePartOne(input: List<String>): Int = input.toInput()
.minValue { position -> linearConsumption(position) }
fun solvePartTwo(input: List<String>): Int = input.toInput()
.minValue { position -> progressiveConsumption(position) }
private fun List<String>.toInput() = first().split(',').map { value -> value.toInt() }
private fun List<Int>.linearConsumption(position: Int) = sumOf { value -> abs(position - value) }
private fun List<Int>.progressiveConsumption(position: Int) = sumOf { value ->
val stepsCount = abs(position - value)
(stepsCount + 1) * stepsCount / 2
}
private fun List<Int>.minValue(
block: List<Int>.(position: Int) -> Int,
): Int {
var maxValue = Int.MIN_VALUE
var minValue = Int.MAX_VALUE
onEach { value ->
maxValue = max(maxValue, value)
minValue = min(minValue, value)
}
return recursiveBinarySearch(
start = minValue,
end = maxValue,
) { index -> block(index) }
}
private fun recursiveBinarySearch(
start: Int,
end: Int,
selector: (position: Int) -> Int
): Int {
if (start == end) return selector(start)
val startSelector = selector(start)
val endSelector = selector(end)
val middle = (start + end) / 2
return when {
startSelector < endSelector -> recursiveBinarySearch(
start = start,
end = middle,
selector = selector
)
else -> recursiveBinarySearch(
start = if (start == middle) middle + 1 else middle,
end = end,
selector = selector
)
}
}
| 0 | Kotlin | 0 | 1 | f81794bd57abf513d129e63787bdf2a7a21fa0d3 | 1,845 | aoc-2021 | Apache License 2.0 |
src/Day04.kt | RobvanderMost-TomTom | 572,005,233 | false | {"Kotlin": 47682} | fun main() {
fun part1(input: List<String>): Int {
return input.map {
it.split(",", limit = 2)
.map { e -> e.split("-", limit = 2).map { e -> e.toInt() } }
}.count {
(it[0][0] <= it[1][0] && it[0][1] >= it[1][1]) ||
(it[1][0] <= it[0][0] && it[1][1] >= it[0][1])
}
}
fun part2(input: List<String>): Int {
return input.map {
it.split(",", limit = 2)
.map { e -> e.split("-", limit = 2).map { e -> e.toInt() } }
}.count {
(it[1][0] in it[0][0]..it[0][1]) ||
(it[1][1] in it[0][0]..it[0][1]) ||
(it[0][0] in it[1][0]..it[1][1]) ||
(it[0][1] in it[1][0]..it[1][1])
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day04_test")
check(part1(testInput) == 2)
check(part2(testInput) == 4)
val input = readInput("Day04")
println(part1(input))
println(part2(input))
}
| 5 | Kotlin | 0 | 0 | b7143bceddae5744d24590e2fe330f4e4ba6d81c | 1,064 | advent-of-code-2022 | Apache License 2.0 |
src/Day12.kt | fercarcedo | 573,142,185 | false | {"Kotlin": 60181} | fun main() {
fun transformElevation(elevation: Char) = when(elevation) {
'S' -> 'a'
'E' -> 'z'
else -> elevation
}
fun checkElevation(from: Char, to: Char) = transformElevation(to) - transformElevation(from) <= 1
fun adjacent(node: Pair<Int, Int>, grid: List<CharArray>): Set<Pair<Int, Int>> {
val adjacentList = mutableSetOf<Pair<Int, Int>>()
if (node.first + 1 < grid.size && checkElevation(grid[node.first][node.second], grid[node.first + 1][node.second])) {
adjacentList.add(node.first + 1 to node.second)
}
if (node.first - 1 >= 0 && checkElevation(grid[node.first][node.second], grid[node.first - 1][node.second])) {
adjacentList.add(node.first - 1 to node.second)
}
if (node.second + 1 < grid[node.first].size && checkElevation(grid[node.first][node.second], grid[node.first][node.second + 1])) {
adjacentList.add(node.first to node.second + 1)
}
if (node.second - 1 >= 0 && checkElevation(grid[node.first][node.second], grid[node.first][node.second - 1])) {
adjacentList.add(node.first to node.second - 1)
}
return adjacentList
}
fun bfs(startingNode: Pair<Int, Int>,
endNode: Pair<Int, Int>,
grid: List<CharArray>,
visitedNodes: MutableSet<Pair<Int, Int>>,
distancesMap: MutableMap<Pair<Int, Int>, Int>,
parentsMap: MutableMap<Pair<Int, Int>, Pair<Int, Int>>): Pair<Int, Int>? {
val queue = ArrayDeque<Pair<Int, Int>>()
for (i in grid.indices) {
for (j in 0 until grid[i].size) {
distancesMap[i to j] = Integer.MAX_VALUE
}
}
queue.add(startingNode)
distancesMap[startingNode] = 0
visitedNodes.add(startingNode)
while (!queue.isEmpty()) {
val node = queue.removeFirst()
if (node == endNode) {
return node
}
for (edge in adjacent(node, grid)) {
if (!visitedNodes.contains(edge)) {
visitedNodes.add(edge)
distancesMap[edge] = distancesMap[node]!! + 1
parentsMap[edge] = node
queue.add(edge)
}
}
}
return null
}
fun part1(input: List<String>): Int {
val grid = input.map {
it.toCharArray()
}
val visitedNodes = mutableSetOf<Pair<Int, Int>>()
val distancesMap = mutableMapOf<Pair<Int, Int>, Int>()
val parentsMap = mutableMapOf<Pair<Int, Int>, Pair<Int, Int>>()
val startPosition = grid.mapIndexed { index, it -> index to it.indexOf('S') }.first { it.second >= 0 }
val endPosition = grid.mapIndexed { index, it -> index to it.indexOf('E') }.first { it.second >= 0 }
bfs(startPosition, endPosition, grid, visitedNodes, distancesMap, parentsMap)
return distancesMap[endPosition]!!
}
fun part2(input: List<String>): Int {
val grid = input.map {
it.toCharArray()
}
val startPositions = grid.flatMapIndexed { index, it -> it.mapIndexed { i, c -> index to if (c == 'S' || c == 'a') i else -1 } }
.filter { it.second >= 0 }
val endPosition = grid.mapIndexed { index, it -> index to it.indexOf('E') }.first { it.second >= 0 }
var minDistance = Integer.MAX_VALUE
for (startPosition in startPositions) {
val visitedNodes = mutableSetOf<Pair<Int, Int>>()
val distancesMap = mutableMapOf<Pair<Int, Int>, Int>()
val parentsMap = mutableMapOf<Pair<Int, Int>, Pair<Int, Int>>()
bfs(startPosition, endPosition, grid, visitedNodes, distancesMap, parentsMap)
val distance = distancesMap[endPosition]!!
if (distance < minDistance) {
minDistance = distance
}
}
return minDistance
}
val testInput = readInput("Day12_test")
check(part1(testInput) == 31)
check(part2(testInput) == 29)
val input = readInput("Day12")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | e34bc66389cd8f261ef4f1e2b7f7b664fa13f778 | 4,214 | Advent-of-Code-2022-Kotlin | Apache License 2.0 |
src/Day05.kt | jorander | 571,715,475 | false | {"Kotlin": 28471} | import java.util.Stack
fun main() {
val day = "Day05"
// Some utility functions for Pair
fun <A, B, R> Pair<A, B>.mapFirst(operation: (A) -> R) = operation(first) to second
fun <A, B, R> Pair<A, B>.mapSecond(operation: (B) -> R) = first to operation(second)
fun <A, B, R> Pair<Iterable<A>, B>.foldFirst(initial: R, operation: (acc: R, A) -> R): Pair<R, B> =
first.fold(initial, operation) to second
fun <A, B, R> Pair<A, Iterable<B>>.foldSecond(initial: R, operation: (acc: R, B) -> R): Pair<A, R> =
first to second.fold(initial, operation)
fun <E> List<E>.chunkedAsPairs() = chunked(2).map { list -> list[0] to list[1] }
fun List<String>.parse(): Pair<Array<Stack<Char>>, List<String>> {
val startingStacksAndRearrangementInstructions = chunked(String::isEmpty).chunkedAsPairs().first()
return startingStacksAndRearrangementInstructions.mapFirst { startingStacks ->
val numberOfStacks = startingStacks.last().split(" ").last().toInt()
val emptyStacks = Array(numberOfStacks) { Stack<Char>() }
startingStacks.dropLast(1).reversed()
.fold(emptyStacks) { stacks, crates ->
("$crates ").chunked(4).foldIndexed(stacks) { index, acc, crate ->
if (crate.isNotBlank()) {
acc[index].push(crate.substring(1..2).first())
}
acc
}
stacks
}
}
}
fun Pair<Array<Stack<Char>>, List<String>>.rearrangeWithMoveStrategy(moveStrategy: (Stack<Char>, Stack<Char>) -> List<Stack<Char>>) =
foldSecond(first) { stacks, rearrangeInstruction ->
val (_, numberOf, _, from, _, to) = rearrangeInstruction.split((" "))
moveStrategy(stacks[from.toInt() - 1], stacks[to.toInt() - 1]).windowed(2)
.forEach { (from, to) ->
repeat(numberOf.toInt()) {
to.push(from.pop())
}
}
stacks
}.first
fun Array<Stack<Char>>.collectTopCrates() = map(Stack<Char>::pop).joinToString("")
fun part1(input: List<String>): String {
return input.parse()
.rearrangeWithMoveStrategy { from, to -> listOf(from, to) }
.collectTopCrates()
}
fun part2(input: List<String>): String {
return input.parse()
.rearrangeWithMoveStrategy { from, to -> listOf(from, Stack(), to) }
.collectTopCrates()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("${day}_test")
val input = readInput(day)
check(part1(testInput) == "CMZ")
val result1 = part1(input)
println(result1)
check(result1 == "GFTNRBZPF")
check(part2(testInput) == "MCD")
val result2 = part2(input)
println(result2)
check(result2 == "VRQWPDSGP")
}
private operator fun <E> List<E>.component6() = this[5]
| 0 | Kotlin | 0 | 0 | 1681218293cce611b2c0467924e4c0207f47e00c | 3,043 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/com/github/ferinagy/adventOfCode/aoc2022/2022-07.kt | ferinagy | 432,170,488 | false | {"Kotlin": 787586} | package com.github.ferinagy.adventOfCode.aoc2022
import com.github.ferinagy.adventOfCode.println
import com.github.ferinagy.adventOfCode.readInputLines
fun main() {
val input = readInputLines(2022, "07-input")
val testInput1 = readInputLines(2022, "07-test1")
println("Part1:")
part1(testInput1).println()
part1(input).println()
println()
println("Part2:")
part2(testInput1).println()
part2(input).println()
}
private fun part1(input: List<String>): Long {
val root = exploreFiles(input)
val sizes = root.calculateDirSizes()
return sizes.filter { it <= 100000 }.sum()
}
private fun part2(input: List<String>): Long {
val root = exploreFiles(input)
val sizes = root.calculateDirSizes()
val total = 70000000
val min = 30000000
val free = total - root.size
val toDelete = min - free
return sizes.filter { it >= toDelete }.minOrNull()!!
}
private fun exploreFiles(input: List<String>): Node.Dir {
val root = Node.Dir("/", null)
var current: Node.Dir = root
input.forEach { line ->
val parts = line.split(' ')
when {
parts.first() == "$" -> {
when (parts[1]) {
"cd" -> {
current = when {
parts[2] == ".." -> current.parent!!
parts[2] == "/" -> root
else -> current.content[parts[2]] as Node.Dir
}
}
"ls" -> Unit
else -> error("unexpected '${parts[1]}")
}
}
parts.first().toIntOrNull() != null -> {
val next = Node.File(parts[1], current, parts[0].toLong())
current.content[next.name] = next
}
parts.first() == "dir" -> {
if (current.content[parts[1]] == null) {
current.content[parts[1]] = Node.Dir(parts[1], current)
}
}
}
}
return root
}
private sealed class Node {
abstract val size: Long
data class Dir(val name: String, val parent: Dir?, val content: MutableMap<String, Node> = mutableMapOf(), override var size: Long = -1): Node()
data class File(val name: String, val parent: Dir?, override val size: Long): Node()
}
private fun Node.calculateDirSizes(): List<Long> = when (this) {
is Node.File -> emptyList()
is Node.Dir -> {
val sizes = mutableListOf<Long>()
size = content.values.sumOf {
sizes += it.calculateDirSizes()
it.size
}
sizes += size
sizes
}
}
private fun Node.print(indent: Int = 0): Unit = when (this) {
is Node.File -> println(" ".repeat(indent) + "- $name (file, size=$size)")
is Node.Dir -> {
println(" ".repeat(indent) + "- $name (dir: $size)")
content.values.forEach { node: Node ->
node.print(indent + 2)
}
}
}
| 0 | Kotlin | 0 | 1 | f4890c25841c78784b308db0c814d88cf2de384b | 3,010 | advent-of-code | MIT License |
src/day04/Day04.kt | pnavais | 574,712,395 | false | {"Kotlin": 54079} | package day04
import readInput
private fun overlapsTotally(
firstRangeDef: LongRange,
secondStart: Long,
secondEnd: Long,
secondRangeDef: LongRange,
firstStart: Long,
firstEnd: Long
): Boolean {
return (firstRangeDef.contains(secondStart) && firstRangeDef.contains(secondEnd)) ||
(secondRangeDef.contains(firstStart) && secondRangeDef.contains(firstEnd))
}
private fun overlapsPartially(
firstRangeDef: LongRange,
secondStart: Long,
secondEnd: Long,
secondRangeDef: LongRange,
firstStart: Long,
firstEnd: Long
): Boolean {
return (firstRangeDef.contains(secondStart) || firstRangeDef.contains(secondEnd)) ||
(secondRangeDef.contains(firstStart) || secondRangeDef.contains(firstEnd))
}
fun checkOverlaps(input: List<String>, comparator: (
firstRangeDef: LongRange,
secondStart: Long,
secondEnd: Long,
secondRangeDef: LongRange,
firstStart: Long,
firstEnd: Long
) -> Boolean): Long {
var totalOverlaps = 0L
for (rangePair in input) {
val (firstRange, secondRange) = rangePair.split(",")
val (firstStart, firstEnd) = firstRange.split("-").map { s -> s.toLong() }
val (secondStart, secondEnd) = secondRange.split("-").map { s -> s.toLong() }
val firstRangeDef = firstStart..firstEnd
val secondRangeDef = secondStart..secondEnd
val overlaps = comparator(firstRangeDef, secondStart, secondEnd, secondRangeDef, firstStart, firstEnd)
if (overlaps) {
totalOverlaps++
}
}
return totalOverlaps
}
fun part1(input: List<String>): Long {
return checkOverlaps(input, ::overlapsTotally)
}
fun part2(input: List<String>): Long {
return checkOverlaps(input, ::overlapsPartially)
}
fun main() {
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day04/Day04_test")
println(part1(testInput))
println(part2(testInput))
}
| 0 | Kotlin | 0 | 0 | ed5f521ef2124f84327d3f6c64fdfa0d35872095 | 2,051 | advent-of-code-2k2 | Apache License 2.0 |
src/day03/Day03.kt | zypus | 573,178,215 | false | {"Kotlin": 33417, "Shell": 3190} | package day03
import AoCTask
// https://adventofcode.com/2022/day/3
fun Char.priority() = when {
isLowerCase() -> code - 97 + 1
isUpperCase() -> code - 65 + 27
else -> throw Exception("Invalid char '$this' to get priority for")
}
fun testPriorities() {
('a'..'z').toList().plus(('A'..'Z')).forEachIndexed { index, c ->
val expectedPriority = index + 1
check(expectedPriority == c.priority()) {
"Expected priority $expectedPriority for '$c'(${c.code}), but got ${c.priority()}"
}
}
}
fun part1(input: List<String>): Int {
val mispackedItems = input.map { rucksack ->
val compartment1 = rucksack.substring(0 until rucksack.length/2)
val compartment2 = rucksack.substring((rucksack.length/2) until rucksack.length)
check(compartment1.length == compartment2.length) {
"Compartments are of unequal length: ${compartment1.length} != ${compartment2.length}"
}
val uniqueItemsInCompartment1 = compartment1.toSet()
val uniqueItemsInCompartment2 = compartment2.toSet()
uniqueItemsInCompartment1.intersect(uniqueItemsInCompartment2).first()
}
return mispackedItems.sumOf(Char::priority)
}
fun part2(input: List<String>): Int {
val badges = input.windowed(3, step = 3).map { group ->
group
.map(String::toSet)
.reduce(Set<Char>::intersect)
.first()
}
return badges.sumOf(Char::priority)
}
fun main() = AoCTask("day03").run {
testPriorities()
// test if implementation meets criteria from the description, like:
check(part1(testInput) == 157)
check(part2(testInput) == 70)
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | f37ed8e9ff028e736e4c205aef5ddace4dc73bfc | 1,734 | aoc-2022 | Apache License 2.0 |
src/Day04.kt | armandmgt | 573,595,523 | false | {"Kotlin": 47774} | fun main() {
val pairDescPattern = Regex("(\\d+)-(\\d+),(\\d+)-(\\d+)")
fun toPair(pairDesc: String): Pair<Pair<Int, Int>, Pair<Int, Int>> {
val m = pairDescPattern.matchEntire(pairDesc)!!
return Pair(
Pair(m.groups[1]!!.value.toInt(), m.groups[2]!!.value.toInt()),
Pair(m.groups[3]!!.value.toInt(), m.groups[4]!!.value.toInt())
)
}
fun contains(first: Pair<Int, Int>, second: Pair<Int, Int>): Boolean {
return first.first <= second.first && first.second >= second.second
}
fun part1(input: List<String>): Int {
return input.count { pairDesc ->
val pair = toPair(pairDesc)
contains(pair.first, pair.second) || contains(pair.second, pair.first)
}
}
fun overlaps(first: Pair<Int, Int>, second: Pair<Int, Int>): Boolean {
return (first.first <= second.first && first.second >= second.first) ||
(first.first <= second.second && first.second >= second.second)
}
fun part2(input: List<String>): Int {
return input.count { pairDesc ->
val pair = toPair(pairDesc)
contains(pair.first, pair.second) || contains(pair.second, pair.first) || overlaps(pair.first, pair.second)
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("resources/Day04_test")
check(part1(testInput) == 2)
val input = readInput("resources/Day04")
println(part1(input))
check(part2(testInput) == 4)
println(part2(input))
}
| 0 | Kotlin | 0 | 1 | 0d63a5974dd65a88e99a70e04243512a8f286145 | 1,571 | advent_of_code_2022 | Apache License 2.0 |
year2017/src/main/kotlin/net/olegg/aoc/year2017/day21/Day21.kt | 0legg | 110,665,187 | false | {"Kotlin": 511989} | package net.olegg.aoc.year2017.day21
import net.olegg.aoc.someday.SomeDay
import net.olegg.aoc.year2017.DayOf2017
/**
* See [Year 2017, Day 21](https://adventofcode.com/2017/day/21)
*/
object Day21 : DayOf2017(21) {
override fun first(): Any? {
return countOn(5)
}
override fun second(): Any? {
return countOn(18)
}
private fun countOn(iterations: Int): Int {
val ops = lines
.map { it.split(" => ") }
.map { part -> part.map { row -> row.split("/").map { it.toList() }.toList() } }
.associate { lex(it.first()) to it.last() }
val sizes = ops.keys.map { it.size }.toSortedSet()
val start = ".#./..#/###".split("/").map { it.toList() }
return (0..<iterations)
.fold(start) { acc, _ ->
sizes.firstOrNull { acc.size % it == 0 }
?.let { size ->
val chunks = acc.size / size
acc.asSequence()
.chunked(size)
.map { rows ->
val perRow = rows.map { it.chunked(size) }
return@map (0..<chunks).map { cols ->
lex(perRow.map { it[cols] })
}
}
.map { rows ->
rows.map { row ->
ops[row] ?: ops.entries.first { it.key.size == size }.value
}
}
.flatMap { rows ->
(0..size).map { row ->
rows.flatMap { it[row] }
}
}
.toList()
} ?: acc
}
.sumOf { row -> row.count { it == '#' } }
}
private fun lex(grid: List<List<Char>>): List<List<Char>> {
val size = grid.size
val flips = setOf(
grid,
grid.reversed(),
grid.map { it.reversed() },
grid.reversed().map { it.reversed() },
)
val rotations = flips
.flatMap { flip ->
(0..<3).scan(flip) { acc, _ ->
(0..<size).map { first ->
(0..<size).map { second ->
acc[second][first]
}
}
}
}
.toSet()
return rotations.minBy { rot ->
rot.joinToString(separator = "") { it.joinToString(separator = "") }
}
}
}
fun main() = SomeDay.mainify(Day21)
| 0 | Kotlin | 1 | 7 | e4a356079eb3a7f616f4c710fe1dfe781fc78b1a | 2,226 | adventofcode | MIT License |
src/Day09.kt | fasfsfgs | 573,562,215 | false | {"Kotlin": 52546} | import kotlin.math.abs
fun main() {
fun part1(input: List<String>): Int {
val initialHead = Knot()
val headPath = input.toMotions()
.fold(listOf(initialHead)) { acc, motion -> acc.plus(acc.last().move(motion)) }
return headPath.follower()
.distinct()
.size
}
fun part2(input: List<String>): Int {
val initialHead = Knot()
val headPath = input.toMotions()
.fold(listOf(initialHead)) { acc, motion -> acc.plus(acc.last().move(motion)) }
// val paths = mutableListOf<List<Knot>>()
val tailPath = List(9) { it }
.fold(headPath) { acc, _ ->
val follower = acc.follower()
// paths.add(follower)
follower
}
// paths.add(0, headPath)
// visualize(paths)
return tailPath
.distinct()
.size
}
val testInput01 = readInput("Day09_test01")
check(part1(testInput01) == 13)
check(part2(testInput01) == 1)
val testInput02 = readInput("Day09_test02")
check(part2(testInput02) == 36)
val input = readInput("Day09")
println(part1(input))
println(part2(input))
}
fun List<String>.toMotions(): List<String> = flatMap {
val (direction, strTimes) = it.split(" ")
List(strTimes.toInt()) { direction }
}
fun List<Knot>.follower() =
fold(listOf<Knot>()) { acc, knot ->
if (acc.isEmpty()) listOf(knot) else acc.plus(acc.last().follow(knot))
}
data class Knot(val x: Int = 0, val y: Int = 0) {
fun move(motion: String): Knot = when (motion) {
"U" -> Knot(x, y + 1)
"D" -> Knot(x, y - 1)
"L" -> Knot(x - 1, y)
"R" -> Knot(x + 1, y)
else -> error("unknown motion ($motion)")
}
fun follow(head: Knot): Knot = when {
abs(head.x - x) <= 1 && abs(head.y - y) <= 1 -> copy()
x == head.x && head.y == y + 2 -> copy(y = y + 1)
x == head.x && head.y == y - 2 -> copy(y = y - 1)
y == head.y && head.x == x + 2 -> copy(x = x + 1)
y == head.y && head.x == x - 2 -> copy(x = x - 1)
abs(head.x - x) == 1 && head.y == y + 2 -> head.copy(y = y + 1)
abs(head.x - x) == 1 && head.y == y - 2 -> head.copy(y = y - 1)
abs(head.y - y) == 1 && head.x == x + 2 -> head.copy(x = x + 1)
abs(head.y - y) == 1 && head.x == x - 2 -> head.copy(x = x - 1)
head.x == x + 2 && head.y == y + 2 -> copy(x = x + 1, y = y + 1)
head.x == x + 2 && head.y == y - 2 -> copy(x = x + 1, y = y - 1)
head.x == x - 2 && head.y == y + 2 -> copy(x = x - 1, y = y + 1)
head.x == x - 2 && head.y == y - 2 -> copy(x = x - 1, y = y - 1)
else -> error("$this can't follow $head")
}
}
fun visualize(paths: List<List<Knot>>) {
val numberOfMotions = paths.first().size
val flattenKnots = paths.flatten()
val maxX = flattenKnots.map { it.x }.max()
val maxY = flattenKnots.map { it.y }.max()
for (i in 0 until numberOfMotions) {
val state = paths.map { it[i] }
visualize(state, maxX, maxY, i)
}
}
fun visualize(state: List<Knot>, maxX: Int, maxY: Int, iteration: Int = 0) {
println("ITERATION $iteration")
val visualArray = MutableList(maxY + 1) { MutableList(maxX + 1) { "." } }
for (i in state.lastIndex downTo 0) {
val knot = state[i]
visualArray[knot.y][knot.x] = i.toString()
}
visualArray
.reversed()
.forEach { println(it) }
println()
}
| 0 | Kotlin | 0 | 0 | 17cfd7ff4c1c48295021213e5a53cf09607b7144 | 3,541 | advent-of-code-2022 | Apache License 2.0 |
src/Day05.kt | Nplu5 | 572,211,950 | false | {"Kotlin": 15289} | import Operation.Companion.fromString
import java.util.*
fun main() {
fun createInitialConfiguration(input: List<String>): MutableList<Stack<ContentCrate>> {
val initialBoardGame = input.takeWhile { line -> line.isNotEmpty() }
.map { configurationString ->
configurationString.split("")
.windowed(4, 4) { it.joinToString("") }
.map { field ->
when (true) {
field.isBlank() -> EmptyCrate
else -> ContentCrate(field)
}
}
}.reversed() // to start adding crates from the bottom
.drop(1)
.foldIndexed(mutableListOf<Stack<ContentCrate>>()) { index, acc, currentRow ->
if (index == 0) {
currentRow.forEachIndexed { rowIndex, crate ->
when (crate) {
is EmptyCrate -> acc.add(rowIndex, Stack())
is ContentCrate -> acc.add(Stack<ContentCrate>().apply { push(crate) })
}
}
} else {
currentRow.forEachIndexed { rowIndex, crate ->
when (crate) {
is ContentCrate -> acc[rowIndex].push(crate)
}
}
}
acc
}
return initialBoardGame
}
fun part1(input: List<String>): String {
val initialBoardGame = createInitialConfiguration(input)
return input.takeLastWhile { line -> line.isNotEmpty() }
.flatMap { operationString -> fromString(operationString) }
.fold(Board(initialBoardGame)){ acc, operation ->
acc.execute(operation)
}.getSolution()
}
fun part2(input: List<String>): String {
val initialBoard = createInitialConfiguration(input)
return input.takeLastWhile { line -> line.isNotEmpty() }
.map { operationString -> Operation9001.fromString(operationString) }
.fold(Board(initialBoard)){ acc, operation ->
acc.execute(operation)
}.getSolution()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day05_test")
println(part2(testInput))
check(part2(testInput) == "MCD")
val input = readInput("Day05")
println(part1(input))
println(part2(input))
}
typealias CrateIndex = Int
sealed interface Crate
object EmptyCrate
class ContentCrate(field: String){
val letter = field.trim()
.replace("[","")
.replace("]", "")[0]
.toString()
}
data class Operation(val source: CrateIndex, val dest: CrateIndex){
companion object{
fun fromString(operationString: String): List<Operation>{
val numberOfRepeats = operationString.split(" ")[1].toInt()
val source = operationString.split(" ")[3].toInt() - 1
val destination = operationString.split(" ")[5].toInt() -1
return mutableListOf<Operation>().apply {
repeat(numberOfRepeats){add(Operation(source, destination))}
}
}
}
}
data class Operation9001(val numberOfRepeats: Int, val source: CrateIndex, val dest: CrateIndex) {
companion object{
fun fromString(operationString: String):Operation9001{
val numberOfRepeats = operationString.split(" ")[1].toInt()
val source = operationString.split(" ")[3].toInt() - 1
val destination = operationString.split(" ")[5].toInt() -1
return Operation9001(numberOfRepeats, source, destination)
}
}
}
class Board(private val initialConfiguration: List<Stack<ContentCrate>>) {
fun execute(operation: Operation) : Board{
initialConfiguration[operation.source].pop().let { crate ->
initialConfiguration[operation.dest].push(crate)
}
return Board(initialConfiguration)
}
fun execute(operation: Operation9001) : Board {
initialConfiguration[operation.source].takeLast(operation.numberOfRepeats).also {
repeat(operation.numberOfRepeats){ initialConfiguration[operation.source].pop() }
}.let { crates ->
crates.forEach { crate -> initialConfiguration[operation.dest].push(crate) }
}
return Board(initialConfiguration)
}
fun getSolution(): String{
return initialConfiguration.joinToString("") { stack -> stack.peek().letter }
}
}
| 0 | Kotlin | 0 | 0 | a9d228029f31ca281bd7e4c7eab03e20b49b3b1c | 4,636 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/eu/michalchomo/adventofcode/year2023/Day07.kt | MichalChomo | 572,214,942 | false | {"Kotlin": 56758} | package eu.michalchomo.adventofcode.year2023
import eu.michalchomo.adventofcode.Day
import eu.michalchomo.adventofcode.main
object Day07 : Day {
override val number: Int = 7
private val cardsOrder = listOf('2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A')
private val cardsOrderJoker = cardsOrder.toMutableList().apply { remove('J'); addFirst('J') }
override fun part1(input: List<String>): String = input.totalWinnings(cardsOrder, ::toType)
override fun part2(input: List<String>): String = input.totalWinnings(cardsOrderJoker, ::toTypeJoker)
private fun List<String>.totalWinnings(cardsOrder: List<Char>, toTypeFun: (String) -> Type) =
this.map { it.toHand(toTypeFun) }
.sortedWith { a, b ->
val typeCompare = a.type.compareTo(b.type)
if (typeCompare != 0) {
typeCompare
} else {
a.cards.zip(b.cards).asSequence()
.map { (ac, bc) -> cardsOrder.indexOf(ac).compareTo(cardsOrder.indexOf(bc)) }
.filter { it != 0 }.firstOrNull() ?: 0
}
}
.mapIndexed { index, hand -> (index + 1) * hand.bid }
.sum()
.toString()
data class Hand(val cards: String, val bid: Int, val type: Type)
private fun String.toHand(toTypeFun: (String) -> Type): Hand =
this.split(" ").let { Hand(it[0], it[1].toInt(), toTypeFun(it[0])) }
enum class Type {
HIGH_CARD, ONE_PAIR, TWO_PAIRS, THREE_OF_A_KIND, FULL_HOUSE, FOUR_OF_A_KIND, FIVE_OF_A_KIND
}
private fun toType(cards: String): Type {
val cardsCount = cards.groupBy { it }.values.map { it.size }.sortedDescending()
return when (cardsCount) {
listOf(5) -> Type.FIVE_OF_A_KIND
listOf(4, 1) -> Type.FOUR_OF_A_KIND
listOf(3, 2) -> Type.FULL_HOUSE
listOf(3, 1, 1) -> Type.THREE_OF_A_KIND
listOf(2, 2, 1) -> Type.TWO_PAIRS
listOf(2, 1, 1, 1) -> Type.ONE_PAIR
else -> Type.HIGH_CARD
}
}
private fun toTypeJoker(cards: String): Type {
if ('J' !in cards) return toType(cards)
val cardsCount = cards.groupingBy { it }.eachCount().values.sortedDescending()
return if (cardsCount.size < 3) {
// [5], [4, 1], [3, 2]
Type.FIVE_OF_A_KIND
} else {
when (cardsCount) {
listOf(3, 1, 1) -> Type.FOUR_OF_A_KIND
listOf(2, 2, 1) -> if (cards.jokersCount() == 2) Type.FOUR_OF_A_KIND else Type.FULL_HOUSE
listOf(2, 1, 1, 1) -> Type.THREE_OF_A_KIND
else -> Type.ONE_PAIR
}
}
}
private fun String.jokersCount(): Int = this.count { it == 'J' }
}
fun main() {
main(Day07)
}
| 0 | Kotlin | 0 | 0 | a95d478aee72034321fdf37930722c23b246dd6b | 2,862 | advent-of-code | Apache License 2.0 |
src/Day08.kt | oleskrede | 574,122,679 | false | {"Kotlin": 24620} | fun main() {
val maxTreeHeight = 9
data class Tree(
val height: Int,
var visible: Boolean = false,
val viewingDistances: MutableList<Int> = mutableListOf(),
)
class Forest(input: List<String>) {
val trees = input.map { line ->
line.map { height ->
Tree(height.digitToInt())
}
}
init {
for (horizontalLine in trees) {
updateTreeValuesForTreeLine(horizontalLine)
updateTreeValuesForTreeLine(horizontalLine.reversed())
}
val transposedTrees = trees.flatten()
.withIndex()
.groupBy { it.index % trees.size }
.map { indexed -> indexed.value.map { it.value } }
for (verticalLine in transposedTrees) {
updateTreeValuesForTreeLine(verticalLine)
updateTreeValuesForTreeLine(verticalLine.reversed())
}
}
// Stupid function name for a function that does the grunt work of solving part 1 and 2
fun updateTreeValuesForTreeLine(trees: List<Tree>) {
var highest = -1
val viewingDistances = MutableList(10) { 0 } // pos = height, value = position
for ((position, tree) in trees.withIndex()) {
if (tree.height > highest) {
highest = tree.height
tree.visible = true
}
val positionsOfHigherTrees = viewingDistances.takeLast(maxTreeHeight - tree.height + 1)
val viewingDistance = position - positionsOfHigherTrees.max()
tree.viewingDistances.add(viewingDistance)
viewingDistances[tree.height] = position
}
}
}
fun part1(input: List<String>): Int {
val forest = Forest(input)
return forest.trees.flatten().count { it.visible }
}
fun part2(input: List<String>): Int {
val forest = Forest(input)
return forest.trees.flatten().map { tree ->
tree.viewingDistances.fold(1) { t, r ->
t * r
}
}.max()
}
val testInput = readInput("Day08_test")
test(part1(testInput), 21)
test(part2(testInput), 8)
val input = readInput("Day08")
timedRun { part1(input) }
timedRun { part2(input) }
}
| 0 | Kotlin | 0 | 0 | a3484088e5a4200011335ac10a6c888adc2c1ad6 | 2,381 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/Day11.kt | Ostkontentitan | 434,500,914 | false | {"Kotlin": 73563} | fun puzzleDayElevenPartOne() {
val inputs = readInput(11)
val octos = inputs.mapIndexed { y, octoList ->
octoList.mapIndexed { x, octoChar ->
Octopus(
octoChar.toString().toInt(), x, y
)
}
}
(1..100).forEach { step ->
octos.forEach { octoList ->
octoList.forEach { octo ->
octoCharger(step, octos, listOf(octo))
}
}
}
val flashes = octos.sumOf { it.sumOf { octo -> octo.history.size } }
println("Octo flashes after 100 steps: $flashes")
}
fun puzzleDayElevenPartTwo() {
val inputs = readInput(11)
val octos = inputs.mapIndexed { y, octoList ->
octoList.mapIndexed { x, octoChar ->
Octopus(
octoChar.toString().toInt(), x, y
)
}
}
val totalOctos = octos.sumOf { it.size }
var step = 1
var foundMegaFlash = false
while (!foundMegaFlash) {
octos.forEach { octoList ->
octoList.forEach { octo ->
octoCharger(step, octos, listOf(octo))
}
}
val flashes = octos.sumOf { octoList -> octoList.map { if (it.history.contains(step)) 1 else 0 }.sum() }
if (flashes == totalOctos) {
foundMegaFlash = true
println("All octos flashed at step: $step")
}
step++
}
}
tailrec fun octoCharger(step: Int, octos: OctoList, octopus: List<Octopus>) {
val flashedOcti = octopus.filter { it.increaseCharge(step) }.flatMap { getSurroundingOctos(octos, it) }
if (flashedOcti.isEmpty()) return
octoCharger(step, octos, flashedOcti)
}
fun getSurroundingOctos(octoList: OctoList, octopus: Octopus): Set<Octopus> {
val x = octopus.posX
val y = octopus.posY
val above = octoList.get(x, y + 1)
val aboveRight = octoList.get(x + 1, y + 1)
val aboveLeft = octoList.get(x - 1, y + 1)
val below = octoList.get(x, y - 1)
val belowRight = octoList.get(x + 1, y - 1)
val belowLeft = octoList.get(x - 1, y - 1)
val left = octoList.get(x - 1, y)
val right = octoList.get(x + 1, y)
return setOfNotNull(above, aboveRight, aboveLeft, below, belowRight, belowLeft, left, right)
}
typealias OctoList = List<List<Octopus>>
fun OctoList.get(x: Int, y: Int) = if (x in 0..this[0].lastIndex && y in 0..this.lastIndex) {
this[y][x]
} else null
data class Octopus(var charge: Int, val posX: Int, val posY: Int) {
val history = mutableSetOf<Int>()
fun increaseCharge(step: Int): Boolean {
if (history.contains(step) && charge == 0) {
return false
}
charge++
return if (charge > 9) {
history.add(step)
charge = 0
true
} else false
}
}
| 0 | Kotlin | 0 | 0 | e0e5022238747e4b934cac0f6235b92831ca8ac7 | 2,796 | advent-of-kotlin-2021 | Apache License 2.0 |
src/main/kotlin/dev/siller/aoc2022/Day05.kt | chearius | 575,352,798 | false | {"Kotlin": 41999} | package dev.siller.aoc2022
private val example = """
[D]
[N] [C]
[Z] [M] [P]
1 2 3
move 1 from 2 to 1
move 3 from 1 to 3
move 2 from 2 to 1
move 1 from 1 to 2
""".trimIndent()
private data class Instruction(val count: Int, val from: Int, val to: Int)
private fun part1(input: List<String>): String = getStacks(input).let { stacks ->
getInstructions(input).forEach { i ->
repeat(i.count) {
val e = stacks.getOrDefault(i.from, emptyList()).takeLast(1)
stacks[i.from] = stacks.getOrDefault(i.from, emptyList()).dropLast(1)
stacks[i.to] = stacks.getOrDefault(i.to, emptyList()) + e
}
}
stacks.mapValues { (_, v) -> v.last() }.toSortedMap().values.joinToString("")
}
private fun part2(input: List<String>): String = getStacks(input).let { stacks ->
getInstructions(input).forEach { i ->
val e = stacks.getOrDefault(i.from, emptyList()).takeLast(i.count)
stacks[i.from] = stacks.getOrDefault(i.from, emptyList()).dropLast(i.count)
stacks[i.to] = stacks.getOrDefault(i.to, emptyList()) + e
}
stacks.mapValues { (_, v) -> v.last() }.toSortedMap().values.joinToString("")
}
private fun getStacks(input: List<String>) = input
.takeWhile { l -> l.trim().matches("(\\[[A-Z]]\\s*)+".toRegex()) }
.map { l -> l.chunked(4).mapIndexed { index, s -> index to s.trim().drop(1).dropLast(1) }.toMap() }
.fold(mutableMapOf<Int, List<String>>()) { acc, map ->
map.forEach { (k, v) -> acc.merge(k, listOf(v)) { old, new -> old + new } }
acc
}
.mapValues { (_, v) -> v.filter(String::isNotBlank).reversed() }
.toMutableMap()
private fun getInstructions(input: List<String>) = input
.dropWhile { l -> !l.matches("move [0-9]+ from [0-9]+ to [0-9]+".toRegex()) }
.map { l ->
val count = l.substringAfter("move ").substringBefore(" from").toInt()
val from = l.substringAfter("from ").substringBefore(" to").toInt() - 1
val to = l.substringAfter("to ").toInt() - 1
Instruction(count, from, to)
}
fun aocDay05() = aocTaskWithExample(
day = 5,
part1 = ::part1,
part2 = ::part2,
exampleInput = example,
expectedOutputPart1 = "CMZ",
expectedOutputPart2 = "MCD"
)
fun main() {
aocDay05()
}
| 0 | Kotlin | 0 | 0 | e070c0254a658e36566cc9389831b60d9e811cc5 | 2,321 | advent-of-code-2022 | MIT License |
src/Day02.kt | lsimeonov | 572,929,910 | false | {"Kotlin": 66434} | import java.io.IOException
import kotlin.math.abs
fun main() {
// R, P, S
// P, S, R
val ref = mapOf("A" to listOf(3, 1), "B" to listOf(1, 2), "C" to listOf(2, 3))
val ref2 = mapOf("X" to listOf(3, 1), "Y" to listOf(1, 2), "Z" to listOf(2, 3))
val winLoseMap = mapOf("X" to -1, "Y" to 0, "Z" to 1)
fun calcScore(input: List<String>): Int {
val oindex = ref.getValue(input[0])
val mindex = ref2.getValue(input[1])
val players = listOf(oindex[0], mindex[0])
val winnerNumber = abs(mindex[0] - oindex[0])
return when (winnerNumber) {
0 -> 3 + mindex[1]
1 -> {
if (players.max() == mindex[0]) {
6 + mindex[1]
} else {
mindex[1]
}
}
else -> if (players.min() == mindex[0]) {
6 + mindex[1]
} else {
mindex[1]
}
}
}
fun findLosing(s: String): String {
val index = ref.getValue(s)
val f =
ref2.filter { (_, v) -> (v[0] < index[0] && abs(v[0] - index[0]) == 1) || (v[0] > index[0] && abs(v[0] - index[0]) > 1) }
return f.keys.first()
}
fun findWining(s: String): String {
val index = ref.getValue(s)
val f =
ref2.filter { (_, v) -> (v[0] > index[0] && abs(v[0] - index[0]) == 1) || (v[0] < index[0] && abs(v[0] - index[0]) > 1) }
return f.keys.first()
}
fun findDraw(s: String): String {
val index = ref.getValue(s)
val f =
ref2.filter { (_, v) -> (v[0] == index[0]) }
return f.keys.last()
}
fun winLoseDraw(input: List<String>): Int {
return when (winLoseMap.getValue(input[1])) {
0 -> calcScore(listOf(input[0], findDraw(input[0])))
-1 -> calcScore(listOf(input[0], findLosing(input[0])))
1 -> calcScore(listOf(input[0], findWining(input[0])))
else -> throw IOException()
}
}
fun part1(input: List<String>): Int {
val t = input.fold(0) { total, v -> total + calcScore(v.split(" ")) }
return t
}
fun part2(input: List<String>): Int {
return input.fold(0) { total, v -> total + winLoseDraw(v.split(" ")) }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day02_test")
check(part1(testInput) == 15)
// check(part2(testInput) == 3900)
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 9d41342f355b8ed05c56c3d7faf20f54adaa92f1 | 2,605 | advent-of-code-2022 | Apache License 2.0 |
src/day09/Day09.kt | Volifter | 572,720,551 | false | {"Kotlin": 65483} | package day09
import utils.*
import kotlin.math.sqrt
data class Coords(var x: Int, var y: Int) {
val delta: Float get() = sqrt((x * x + y * y) * 1f)
operator fun plus(other: Coords): Coords = Coords(x + other.x, y + other.y)
operator fun minus(other: Coords): Coords = Coords(x - other.x, y - other.y)
}
fun parseInput(input: List<String>): List<Pair<Coords, Int>> =
input.map { line ->
val (dirName, amount) = line.split(" ")
val dir = when(dirName.single()) {
'R' -> Coords(1, 0)
'L' -> Coords(-1, 0)
'U' -> Coords(0, 1)
'D' -> Coords(0, -1)
else -> throw Error("invalid direction $dirName")
}
Pair(dir, amount.toInt())
}
fun countVisitedCells(
movements: List<Pair<Coords, Int>>,
chainLength: Int
): Int {
val chain = MutableList(chainLength) { Coords(0, 0) }
val visited = mutableSetOf(chain.last())
movements.forEach { (delta, amount) ->
repeat(amount) {
chain[0] += delta
chain.indices.windowed(2) { (leadingIdx, followingIdx) ->
val diff = chain[leadingIdx] - chain[followingIdx]
if (diff.delta >= 2) {
chain[followingIdx] += Coords(
diff.x.coerceIn(-1..1),
diff.y.coerceIn(-1..1)
)
}
}
visited.add(chain.last())
}
}
return visited.size
}
fun part1(input: List<String>): Int = countVisitedCells(parseInput(input), 2)
fun part2(input: List<String>): Int = countVisitedCells(parseInput(input), 10)
fun main() {
val testInputA = readInput("Day09_test_a")
val testInputB = readInput("Day09_test_b")
expect(part1(testInputA), 13)
expect(part2(testInputB), 36)
val input = readInput("Day09")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | c2c386844c09087c3eac4b66ee675d0a95bc8ccc | 1,923 | AOC-2022-Kotlin | Apache License 2.0 |
src/Day04.kt | janbina | 157,854,025 | false | null | import kotlin.test.assertEquals
object Day04 {
private fun createSleepStats(input: List<Event>): Map<Int, IntArray> {
val map = mutableMapOf<Int, IntArray>()
var currentGuardId = -1
var beginMinute = -1
input.forEach {
when (it.type) {
Event.Type.BEGIN_SHIFT -> currentGuardId = it.guardId
Event.Type.FALL_ASLEEP -> beginMinute = it.minute
Event.Type.WAKE_UP -> {
val arr = map.getOrPut(currentGuardId) { IntArray(60) }
(beginMinute until it.minute).forEach { i -> arr[i]++ }
}
}
}
return map
}
fun part1(input: List<Event>): Int {
val sleepStats = createSleepStats(input)
val max = sleepStats.maxBy { it.value.sum() }!!
val maxMinute = max.value.withIndex().maxBy { it.value }!!.index
return max.key * maxMinute
}
fun part2(input: List<Event>): Int {
val sleepStats = createSleepStats(input)
val max = sleepStats.map {
it.key to it.value.withIndex().maxBy { x -> x.value }!!
}.maxBy { it.second.value } ?: return 0
return max.first * max.second.index
}
}
data class Event(
val month: Int,
val day: Int,
val hour: Int,
val minute: Int,
val guardId: Int,
val type: Type
) {
enum class Type {
BEGIN_SHIFT, FALL_ASLEEP, WAKE_UP
}
companion object {
private val REGEX = Regex("\\d+")
fun fromString(s: String): Event {
val (m, d, h, min, guardId) = REGEX.findAll(s)
.map { it.value.toInt() }
.plus(-1)
.drop(1)
.take(5)
.toList()
val type = when {
s.contains("wakes") -> Type.WAKE_UP
s.contains("falls") -> Type.FALL_ASLEEP
else -> Type.BEGIN_SHIFT
}
return Event(m, d, h, min, guardId, type)
}
}
}
fun main(args: Array<String>) {
val input = getInput(4)
.readLines()
.map { Event.fromString(it) }
.sortedWith(compareBy({ it.month }, { it.day }, { it.hour }, { it.minute }))
assertEquals(99911, Day04.part1(input))
assertEquals(65854, Day04.part2(input))
}
| 0 | Kotlin | 0 | 0 | 522d93baf9ff4191bc2fc416d95b06208be32325 | 2,331 | advent-of-code-2018 | MIT License |
src/Day07.kt | inssein | 573,116,957 | false | {"Kotlin": 47333} | sealed class Node {
abstract val name: String
abstract val size: Int
data class File(override val name: String, override val size: Int) : Node()
data class Directory(
override val name: String,
val parent: Directory?,
val children: MutableList<Node> = mutableListOf()
) : Node() {
override val size get() = children.sumOf { it.size }
fun findDirectories(predicate: (Directory) -> Boolean): List<Directory> {
val directories = children.filterIsInstance(Directory::class.java)
return directories.filter(predicate) + directories.flatMap { it.findDirectories(predicate) }
}
override fun toString() = "Directory(name=$name, size=${size})"
}
companion object {
fun build(input: List<String>): Directory {
val root = Directory("/", null)
input.fold(root) { cwd, line ->
val parts = line.split(" ")
when {
// change directory
parts.getOrNull(1) == "cd" -> when (parts[2]) {
"/" -> root
".." -> cwd.parent ?: error("invalid state")
else -> cwd.findDirectories { it.name == parts[2] }.first()
}
// noop
parts.getOrNull(1) == "ls" -> cwd
// add directory
parts[0] == "dir" -> cwd.children.add(Directory(parts[1], cwd)).let { cwd }
// add file
else -> cwd.children.add(File(parts[1], parts[0].toInt())).let { cwd }
}
}
return root
}
}
}
fun main() {
fun part1(input: List<String>): Int {
return Node
.build(input)
.findDirectories { it.size <= 100_000 }
.sumOf { it.size }
}
fun part2(input: List<String>): Int {
val root = Node.build(input)
val unused = 70_000_000 - root.size
val minSpace = 30_000_000 - unused
return root
.findDirectories { it.size >= minSpace }
.minBy { it.size }
.size
}
val testInput = readInput("Day07_test")
check(part1(testInput) == 95437)
check(part2(testInput) == 24933642)
val input = readInput("Day07")
println(part1(input)) // 1206825
println(part2(input)) // 9608311
}
| 0 | Kotlin | 0 | 0 | 095d8f8e06230ab713d9ffba4cd13b87469f5cd5 | 2,435 | advent-of-code-2022 | Apache License 2.0 |
solutions/src/Day07.kt | khouari1 | 573,893,634 | false | {"Kotlin": 132605, "HTML": 175} | import DirItem.Dir
import DirItem.File
fun main() {
fun part1(input: List<String>): Int = getAllDirs(input).map { it.getDirSize() }.filter { it < 100_000 }.sum()
fun part2(input: List<String>): Int {
val totalDiskSpaceAvailable = 70_000_000
val spaceRequired = 30_000_000
val dirSizesAscending = getAllDirs(input).map { it.getDirSize() }.sorted()
val outermostDirSize = dirSizesAscending.last()
val spaceToFreeUp = spaceRequired - (totalDiskSpaceAvailable - outermostDirSize)
return dirSizesAscending.first { it >= spaceToFreeUp }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day07_test")
check(part1(testInput) == 95_437)
check(part2(testInput) == 24_933_642)
val input = readInput("Day07")
println(part1(input))
println(part2(input))
}
private fun getAllDirs(input: List<String>): List<Dir> {
val rootDir = Dir("/")
var cwd = rootDir
val dirs = mutableListOf<Dir>()
input.forEach { line ->
val firstChar = line[0]
when {
firstChar == '$' -> {
val command = line.substring(2, 4)
when (command) {
"cd" -> {
cwd = when (val dirName = line.substring(5)) {
"/" -> rootDir
".." -> cwd.parent!!
else -> {
val dir = Dir(dirName, cwd)
cwd.children.add(dir)
dirs.add(dir)
dir
}
}
}
}
}
!line.startsWith("dir") -> {
val (size, fileName) = line.split(" ")
val file = File(fileName, size.toInt())
cwd.children.add(file)
}
}
}
dirs.add(rootDir)
return dirs
}
private fun Dir.getDirSize(): Int = children.sumOf {
when (it) {
is Dir -> it.getDirSize()
is File -> it.size
}
}
sealed class DirItem {
data class Dir(val name: String, val parent: Dir? = null) : DirItem() {
val children = mutableListOf<DirItem>()
}
data class File(val name: String, val size: Int) : DirItem()
}
| 0 | Kotlin | 0 | 1 | b00ece4a569561eb7c3ca55edee2496505c0e465 | 2,379 | advent-of-code-22 | Apache License 2.0 |
app/src/main/kotlin/com/engineerclark/advent2022/Day03.kt | engineerclark | 577,449,596 | false | {"Kotlin": 10394} | package com.engineerclark.advent2022
import com.engineerclark.advent2022.utils.readInput
fun main() {
val rucks = readRucksacks(readInput(3))
println("Day 3, challenge 1 -- Sum of priorities of common item types: ${rucks.sumOfCommonItemPriorities()}")
val elfGroups = rucks.asElfGroups()
println("Day 3, challenge 2 -- Sum of priorities of group badges: ${elfGroups.sumOfBadgePriorities()}")
}
fun List<Rucksack>.sumOfCommonItemPriorities(): Int = this.sumOf { ruck -> ruck.commonItems.first().priority }
fun List<ElfGroup>.sumOfBadgePriorities(): Int = this.sumOf { group -> group.badge.priority }
private fun List<Rucksack>.asElfGroups(): List<ElfGroup> = this.chunked(3)
.map { rucks -> ElfGroup(rucks[0], rucks[1], rucks[2]) }
private fun readRucksacks(input: String): List<Rucksack> = input.splitToSequence("\n").map(::Rucksack).toList()
private val priorityMap = sequenceOf(CharRange('a', 'z').asSequence(), CharRange('A', 'Z').asSequence()).flatten()
.mapIndexed { i, c -> Pair(c, i + 1) }
.toMap()
private val Char.priority
get() = priorityMap.getOrElse(this) { throw RuntimeException("Character priority unknown") }
data class Rucksack(val contents: String) {
val firstCompartment = contents.substring(0, contents.length / 2)
val secondCompartment = contents.substring(contents.length / 2)
val commonItems = firstCompartment.asIterable().intersect(secondCompartment.asIterable().toSet())
}
data class ElfGroup(val first: Rucksack, val second: Rucksack, val third: Rucksack) {
val badge: Char = first.contents.asIterable().intersect(second.contents.asIterable().toSet())
.intersect(third.contents.asIterable().toSet())
.first()
} | 0 | Kotlin | 0 | 0 | 3d03ab2cc9c83b3691fede465a6e3936e7c091e9 | 1,712 | advent-of-code-2022 | MIT License |
src/day03/solution.kt | bohdandan | 729,357,703 | false | {"Kotlin": 80367} | package day03
import println
import readInput
fun main() {
class Gear(val position: Pair<Int, Int>, val numbers: List<Int>)
class EngineSchematic {
val EMPTY_CHAR: Char = '.'
var schema: List<List<Char>>
var maxColumns = 0
var maxRows = 0
constructor(data: List<String>) {
maxRows = data.size
maxColumns = data[0].length
schema = data.map { it.toList() }
}
fun getChar(x: Int, y: Int): Char {
if (x < 0 || x >= maxColumns) return EMPTY_CHAR;
if (y < 0 || y >= maxRows) return EMPTY_CHAR;
return schema[y][x]
}
fun isEnginePart(char: Char): Boolean {
if (char == EMPTY_CHAR) return false
return char.isLetterOrDigit().not()
}
fun isGear(char: Char): Boolean {
if (char == EMPTY_CHAR) return false
return char.isLetterOrDigit().not()
}
fun getNumberNeighbourPositions(number: String, x: Int, y: Int): List<Pair<Int, Int>> {
val startX = x - number.length
val endX = x + 1
val xCoordinatesRange = startX ..endX
val neighbourPositions = xCoordinatesRange.asSequence().map { Pair(it, y - 1) }.toList().toMutableList()
neighbourPositions += Pair(startX, y)
neighbourPositions += Pair(endX, y)
neighbourPositions += xCoordinatesRange.asSequence().map { Pair(it, y + 1) }.toList()
return neighbourPositions;
}
fun checkIfEnginePart(number: String, x: Int, y: Int): Int {
if (number.isEmpty()) return 0
if (getNumberNeighbourPositions(number, x, y).any{isEnginePart(getChar(it.first, it.second))}) {
return number.toInt()
} else {
return 0
}
}
fun sumEngineParts(): Int {
var sum = 0
for ((y, row) in schema.withIndex()) {
var number = ""
for ((x, char) in row.withIndex()) {
if (char.isDigit()) {
number += char
} else {
sum += checkIfEnginePart(number, x - 1, y)
number = ""
}
}
sum += checkIfEnginePart(number, maxColumns - 1, y)
}
return sum
}
fun getNeighboringGears(number: String, x: Int, y: Int): List<Gear> {
if (number.isEmpty()) return emptyList()
return getNumberNeighbourPositions(number, x, y)
.filter { isGear(getChar(it.first, it.second))}
.map { Gear(it, listOf(number.toInt())) }
.toList();
}
fun getGearRatio(): Int {
var gearCandidates = emptyList<Gear>()
for ((y, row) in schema.withIndex()) {
var number = ""
for ((x, char) in row.withIndex()) {
if (char.isDigit()) {
number += char
} else {
gearCandidates += getNeighboringGears(number, x - 1, y)
number = ""
}
}
gearCandidates += getNeighboringGears(number, maxColumns - 1, y)
}
val groupedByPosition = gearCandidates.groupBy { it.position }
var result = 0
groupedByPosition.forEach { (position, numbers) ->
if (numbers.size == 2) {
result += numbers[0].numbers[0] * numbers[1].numbers[0]
}
}
return result
}
}
val testInput1 = readInput("day03/test1")
var testEngineSchematic = EngineSchematic(testInput1);
check(testEngineSchematic.sumEngineParts() == 4361)
check(testEngineSchematic.getGearRatio() == 467835)
val input = readInput("day03/input")
var engineSchematic = EngineSchematic(input);
engineSchematic.sumEngineParts().println()
engineSchematic.getGearRatio().println()
}
| 0 | Kotlin | 0 | 0 | 92735c19035b87af79aba57ce5fae5d96dde3788 | 4,140 | advent-of-code-2023 | Apache License 2.0 |
scripts/Day16.kts | matthewm101 | 573,325,687 | false | {"Kotlin": 63435} | import java.io.File
import kotlin.math.max
data class Valve(val name: String, val flow: Int, val neighbors: Set<String>)
val allValves = File("../inputs/16.txt").readLines().map {
val splits = it.split("Valve ", " has flow rate=", "; tunnels lead to valves ", "; tunnel leads to valve ").filter { s -> s.isNotEmpty() }
Valve(splits[0], splits[1].toInt(), splits[2].split(", ").toSet())
}.associateBy { it.name }
val bestValves = allValves.values.filter { it.flow > 0 }.associateBy { it.name }
val bestValvesIndex = listOf(allValves["AA"]!!).plus(bestValves.values.toList())
val BVRI = bestValvesIndex.mapIndexed { index, valve -> Pair(valve.name, index) }.toMap()
val nValves = bestValvesIndex.size
val flowIndex = bestValvesIndex.map { it.flow }
fun calcDist(a: Valve, b: Valve): Int {
var frontier: Set<String> = mutableSetOf(a.name)
var dist = 0
while (b.name !in frontier) {
frontier = frontier.flatMap { allValves[it]!!.neighbors }.toSet()
dist++
}
return dist
}
// To index into dist: start_index * nValves + end_index
val dist = bestValvesIndex.flatMap { a -> bestValvesIndex.map { b -> Pair(BVRI[a.name]!! * nValves + BVRI[b.name]!!, calcDist(a,b))} }.sortedBy { it.first }.map { it.second }
data class State(val pos: Int, val score: Int, val time: Int, val rem: Int) {
fun expand() = (1 until nValves).mapNotNull {
val remainingTime = time - dist[pos * nValves + it] - 1
val mask = (1).shl(it)
if (rem.and(mask) != 0 && remainingTime >= 0) State(it, score + remainingTime * flowIndex[it], remainingTime, rem.and(mask.inv())) else null
}
}
run {
val start = State(0, 0, 30, (1).shl(nValves) - 2)
val visited = mutableSetOf(start)
var frontier = visited.toSet()
while (true) {
frontier = frontier.flatMap { it.expand() }.toSet()
if (frontier.isEmpty()) break
visited.addAll(frontier)
}
val pressureHighScore = visited.maxOf { it.score }
println("The max possible pressure released by one person in 30 minutes is ${pressureHighScore}.")
}
run {
val start = State(0, 0, 26, (1).shl(nValves) - 2)
val visited = mutableSetOf(start)
var frontier = visited.toSet()
while (true) {
frontier = frontier.flatMap { it.expand() }.toSet()
if (frontier.isEmpty()) break
visited.addAll(frontier)
}
val visitedList = visited.toList()
val scores = visitedList.map { it.score }
val twists = visitedList.map { it.rem.xor((1).shl(nValves) - 2) }
var maxScore = 0
for (i in twists.indices) {
for (j in i+1 until twists.size) {
if (twists[i].and(twists[j]) == 0) maxScore = max(maxScore, scores[i] + scores[j])
}
}
println("The max possible pressure released by one person and one elephant in 26 minutes is ${maxScore}.")
} | 0 | Kotlin | 0 | 0 | bbd3cf6868936a9ee03c6783d8b2d02a08fbce85 | 2,913 | adventofcode2022 | MIT License |
2021/kotlin/src/main/kotlin/nl/sanderp/aoc/aoc2021/day22/Day22.kt | sanderploegsma | 224,286,922 | false | {"C#": 233770, "Kotlin": 126791, "F#": 110333, "Go": 70654, "Python": 64250, "Scala": 11381, "Swift": 5153, "Elixir": 2770, "Jinja": 1263, "Ruby": 1171} | package nl.sanderp.aoc.aoc2021.day22
import nl.sanderp.aoc.common.*
import kotlin.math.max
import kotlin.math.min
fun main() {
val input = readResource("Day22.txt").lines().map { parse(it) }
val (answer1, duration1) = measureDuration<Int> { partOne(input) }
println("Part one: $answer1 (took ${duration1.prettyPrint()})")
val (answer2, duration2) = measureDuration<Long> { partTwo(input) }
println("Part two: $answer2 (took ${duration2.prettyPrint()})")
}
private data class Cuboid(val x: IntRange, val y: IntRange, val z: IntRange)
private enum class CuboidState { On, Off }
private data class RebootStep(val state: CuboidState, val cuboid: Cuboid)
private fun parse(line: String): RebootStep {
val (state, coordinates) = line.split(' ')
val (x, y, z) = coordinates.split(',').map { c ->
val (lo, hi) = c.drop(2).split("..").map { it.toInt() }
lo..hi
}
return RebootStep(if (state == "on") CuboidState.On else CuboidState.Off, Cuboid(x, y, z))
}
private fun partOne(steps: List<RebootStep>): Int {
val roi = -50..50
val state = steps
.filter { roi.contains(it.cuboid.x) && roi.contains(it.cuboid.y) && roi.contains(it.cuboid.z) }
.fold(emptySet<Point3D>()) { cubes, step ->
val cuboid = step.cuboid.cubes().toSet()
when (step.state) {
CuboidState.On -> cubes.union(cuboid)
CuboidState.Off -> cubes.minus(cuboid)
}
}
return state.size
}
private fun partTwo(steps: List<RebootStep>): Long {
val cuboids = mutableMapOf<Cuboid, Int>()
for ((newState, cuboid) in steps) {
val diff = mutableMapOf<Cuboid, Int>()
for ((other, count) in cuboids) {
val (minX, maxX) = (max(other.x.first, cuboid.x.first) to min(other.x.last, cuboid.x.last))
val (minY, maxY) = (max(other.y.first, cuboid.y.first) to min(other.y.last, cuboid.y.last))
val (minZ, maxZ) = (max(other.z.first, cuboid.z.first) to min(other.z.last, cuboid.z.last))
if (maxX >= minX && maxY >= minY && maxZ >= minZ) {
val overlap = Cuboid(minX..maxX, minY..maxY, minZ..maxZ)
diff.increaseBy(overlap, -count)
}
}
if (newState == CuboidState.On) {
diff.increaseBy(cuboid, 1)
}
for (x in diff) {
cuboids.increaseBy(x.key, x.value)
}
}
return cuboids.entries.sumOf { it.key.size() * it.value }
}
private fun IntRange.contains(other: IntRange) = this.contains(other.first) && this.contains(other.last)
private fun IntRange.size() = last - first + 1
private fun Cuboid.cubes() = allTriples(x, y, z)
private fun Cuboid.size() = x.size().toLong() * y.size().toLong() * z.size().toLong() | 0 | C# | 0 | 6 | 8e96dff21c23f08dcf665c68e9f3e60db821c1e5 | 2,794 | advent-of-code | MIT License |
src/main/day08/day08.kt | rolf-rosenbaum | 572,864,107 | false | {"Kotlin": 80772} | package day08
import Point
import readInput
typealias Forest = List<Tree>
fun main() {
val input = readInput("main/day08/Day08")
val forest = input.flatMapIndexed { y, line ->
line.mapIndexed { x, height ->
Tree(x, y, height.digitToInt())
}
}
println(part1(forest))
println(part2(forest))
}
fun part1(forest: Forest): Int {
return forest.count {
it.isVisibleFromLeft(forest) || it.isVisibleFromRight(forest) || it.isVisibleFromTop(forest) || it.isVisibleFromBottom(forest)
}
}
fun part2(forest: Forest): Int {
return forest.maxOf {
it.scenicScore(forest.associateBy { tree -> Point(tree.x, tree.y) })
}
}
data class Tree(val x: Int, val y: Int, val height: Int) {
operator fun compareTo(other: Tree) = this.height.compareTo(other.height)
override fun equals(other: Any?): Boolean {
return if (other is Tree) x == other.x && y == other.y else false
}
override fun hashCode(): Int {
return x.hashCode() * 31 + y.hashCode()
}
fun isVisibleFromLeft(otherTrees: Forest): Boolean = otherTrees.none { it.y == y && it >= this && it.x < this.x }
fun isVisibleFromRight(otherTrees: Forest): Boolean = otherTrees.none { it.y == y && it >= this && it.x > this.x }
fun isVisibleFromTop(otherTrees: Forest): Boolean = otherTrees.none { it.x == x && it >= this && it.y < this.y }
fun isVisibleFromBottom(otherTrees: Forest): Boolean = otherTrees.none { it.x == x && it >= this && it.y > this.y }
fun scenicScore(treeMap: Map<Point, Tree>): Int {
return countVisibleTreesLeft(treeMap) * countVisibleTreesDown(treeMap) * countVisibleTreesRight(treeMap) * countVisibleTreesUp(treeMap)
}
private fun countVisibleTreesLeft(treeMap: Map<Point, Tree>): Int {
var result = 0
var xpos = x - 1
while (xpos >= 0 && this > treeMap[Point(xpos, y)]!!) {
result++
xpos--
}
return result + if (xpos < 0) 0 else 1
}
private fun countVisibleTreesRight(treeMap: Map<Point, Tree>): Int {
val maxX = treeMap.maxOf { it.key.x }
var result = 0
var xpos = x + 1
while (xpos <= maxX && this > treeMap[Point(xpos, y)]!!) {
result++
xpos++
}
return result + if (xpos > maxX) 0 else 1
}
private fun countVisibleTreesUp(treeMap: Map<Point, Tree>): Int {
var result = 0
var ypos = y - 1
while (ypos >= 0 && this > treeMap[Point(x, ypos)]!!) {
result++
ypos--
}
return result + if (ypos < 0) 0 else 1
}
private fun countVisibleTreesDown(treeMap: Map<Point, Tree>): Int {
val maxY = treeMap.maxOf { it.key.y }
var result = 0
var ypos = y + 1
while (ypos <= maxY && this > treeMap[Point(x, ypos)]!!) {
result++
ypos++
}
return result + if (ypos > maxY) 0 else 1
}
}
| 0 | Kotlin | 0 | 2 | 59cd4265646e1a011d2a1b744c7b8b2afe482265 | 2,991 | aoc-2022 | Apache License 2.0 |
src/Day08.kt | imavroukakis | 572,438,536 | false | {"Kotlin": 12355} | fun main() {
fun topVisible(
outerIdx: Int,
map: List<List<Int>>,
innerIdx: Int,
v: Int,
): Pair<Boolean, Int> {
var l = outerIdx
var score = 0
while (l >= 0) {
val element = map[l--][innerIdx]
score++
if (v <= element) return Pair(false, score)
}
return Pair(true, score)
}
fun bottomVisible(
outerIdx: Int,
map: List<List<Int>>,
innerIdx: Int,
v: Int,
): Pair<Boolean, Int> {
var l = outerIdx
var score = 0
while (l <= map.size - 1) {
val element = map[l++][innerIdx]
score++
if (v <= element) return Pair(false, score)
}
return Pair(true, score)
}
fun leftVisible(
outerIdx: Int,
map: List<List<Int>>,
innerIdx: Int,
v: Int,
): Pair<Boolean, Int> {
var l = innerIdx
var score = 0
while (l >= 0) {
val element = map[outerIdx][l--]
score++
if (v <= element) return Pair(false, score)
}
return Pair(true, score)
}
fun rightVisible(
outerIdx: Int,
map: List<List<Int>>,
innerIdx: Int,
v: Int,
): Pair<Boolean, Int> {
var l = innerIdx
var score = 0
while (l < map[outerIdx].size - 1) {
val element = map[outerIdx][++l]
score++
if (v <= element) return Pair(false, score)
}
return Pair(true, score)
}
fun doScore(map: List<List<Int>>) =
map.drop(1).dropLast(1).mapIndexed { outerIdx, line ->
val dropLast = line.drop(1).dropLast(1)
dropLast.mapIndexed { innerIdx, v ->
listOf(
topVisible(outerIdx, map, innerIdx + 1, v),
bottomVisible(outerIdx + 2, map, innerIdx + 1, v),
leftVisible(outerIdx + 1, map, innerIdx, v),
rightVisible(outerIdx + 1, map, innerIdx + 1, v)
)
}
}.flatten()
fun part1(input: List<String>): Int {
val map = input.map {
it.toList().map { it.digitToInt() }
}
val boundaryCount = ((map.first().size - 2) * 4) + 4
val edgeVisibleTrees = doScore(map).map {
val (topVisible, bottomVisible, leftVisible, rightVisible) = it
if (topVisible.first || bottomVisible.first || leftVisible.first || rightVisible.first) {
1
} else 0
}.sum()
return edgeVisibleTrees + boundaryCount
}
fun part2(input: List<String>): Int {
val map = input.map {
it.toList().map { it.digitToInt() }
}
val mostTreesVisible =doScore(map).map {
val (topVisible, bottomVisible, leftVisible, rightVisible) = it
topVisible.second * bottomVisible.second * leftVisible.second * rightVisible.second
}.max()
return mostTreesVisible
}
val testInput = readInput("Day08_test")
var test = part1(testInput)
check(test == 21)
println(part1(readInput("Day08")))
test = part2(testInput)
check(test == 8)
println(part2(readInput("Day08")))
}
| 0 | Kotlin | 0 | 0 | bb823d49058aa175d1e0e136187b24ef0032edcb | 3,303 | advent-of-code-kotlin | Apache License 2.0 |
y2016/src/main/kotlin/adventofcode/y2016/Day24.kt | Ruud-Wiegers | 434,225,587 | false | {"Kotlin": 503769} | package adventofcode.y2016
import adventofcode.io.AdventSolution
import adventofcode.util.algorithm.IState
import adventofcode.util.algorithm.aStar
import adventofcode.util.collections.permutations
import kotlin.math.abs
object Day24 : AdventSolution(2016, 24, "Air Duct Spelunking") {
lateinit var maze: List<BooleanArray>
private lateinit var checkPoints: Array<Pair<Int, Int>>
override fun solvePartOne(input: String): String {
val distanceTable = buildDistanceTable(input)
val checkpointPermutations = (1..7).permutations()
val routes = checkpointPermutations.map { listOf(0) + it }
val costOfRoutes = routes.map { it.zipWithNext { a, b -> distanceTable[a][b] }.sum() }
val cheapestRoute = costOfRoutes.minOrNull()
return cheapestRoute.toString()
}
override fun solvePartTwo(input: String): Int? {
val distanceTable = buildDistanceTable(input)
return (1..7).permutations()
.map { listOf(0) + it + listOf(0) }
.map { it.zipWithNext { a, b -> distanceTable[a][b] }.sum() }
.minOrNull()
}
private fun buildDistanceTable(input: String): List<List<Int>> {
val lines = input.lines()
maze = lines.map { row -> row.map { it != '#' }.toBooleanArray() }
checkPoints = buildCheckpoints(lines)
return checkPoints.indices.map { start ->
checkPoints.indices.map { end ->
val path = aStar(MazeState(checkPoints[start], checkPoints[end])) ?: throw IllegalStateException()
path.cost
}
}
}
data class MazeState(private val x: Int,
private val y: Int,
private val gX: Int,
private val gY: Int) : IState {
constructor(start: Pair<Int, Int>, goal: Pair<Int, Int>) : this(start.first, start.second, goal.first, goal.second)
override val isGoal: Boolean
get() = x == gX && y == gY
override val heuristic: Int
get() = abs(gX - x) + abs(gY - y)
override fun getNeighbors() = sequenceOf(
copy(y = y - 1),
copy(y = y + 1),
copy(x = x - 1),
copy(x = x + 1)
).filter { maze[it.y][it.x] }
}
private fun buildCheckpoints(lines: List<String>): Array<Pair<Int, Int>> {
val checkpoints = mutableMapOf<Int, Pair<Int, Int>>()
lines.forEachIndexed { y, line ->
line.forEachIndexed { x, ch ->
if (ch in '0'..'7')
checkpoints[ch.toString().toInt()] = Pair(x, y)
}
}
return Array(8) { checkpoints[it] ?: throw IllegalStateException() }
}
}
| 0 | Kotlin | 0 | 3 | fc35e6d5feeabdc18c86aba428abcf23d880c450 | 2,764 | advent-of-code | MIT License |
src/Day11.kt | wujingwe | 574,096,169 | false | null | object Day11 {
class Monkey(
val id: Int,
val levels: MutableList<Long>,
val op: Int,
val operand: Int,
val divider: Int,
val pos: Int,
val neg: Int,
var count: Int = 0
)
private const val OP_ADD = 0
private const val OP_MUL = 1
private const val OP_SQUARE = 2
private fun parse(inputs: String): List<Monkey> {
return inputs.split("\n\n").map { s ->
val tokens = s.split("\n")
val id = tokens[0].split(" ")[1].trimEnd(':').toInt() // Monkey 0
val levels = tokens[1]
.trim()
.split(" ")
.drop(2)
.map { it.trimEnd(',').toLong() }
.toMutableList()
val (_op, _operand) = tokens[2].trim().split(" ").drop(4)
val (op, operand) = if (_op == "+") {
OP_ADD to _operand.toInt()
} else if (_op == "*" && _operand == "old") {
OP_SQUARE to 0
} else {
OP_MUL to _operand.toInt()
}
val divider = tokens[3].trim().split(" ")[3].toInt()
val pos = tokens[4].trim().split(" ")[5].toInt()
val neg = tokens[5].trim().split(" ")[5].toInt()
Monkey(id, levels, op, operand, divider, pos, neg)
}
}
private fun iteration(monkeys: List<Monkey>, count: Int, mitigateFunc: (Long) -> Long) {
repeat(count) {
monkeys.forEach { monkey ->
val levels = monkey.levels.toList()
monkey.levels.clear()
levels.forEach { level ->
val newLevel = when (monkey.op) {
OP_ADD -> (level + monkey.operand)
OP_SQUARE -> (level * level)
else -> (level * monkey.operand)
}
val worry = mitigateFunc(newLevel)
if (worry % monkey.divider == 0L) {
monkeys[monkey.pos].levels.add(worry)
} else {
monkeys[monkey.neg].levels.add(worry)
}
monkey.count++
}
}
}
}
fun part1(inputs: String): Long {
val monkeys = parse(inputs)
iteration(monkeys, 20) { it / 3 }
val (a, b) = monkeys.sortedByDescending { it.count }
return a.count.toLong() * b.count
}
fun part2(inputs: String): Long {
val monkeys = parse(inputs)
val divider = monkeys.map(Monkey::divider).reduce(Int::times).toLong()
iteration(monkeys, 10_000) { it % divider }
val (a, b) = monkeys.sortedByDescending { it.count }
return a.count.toLong() * b.count
}
}
fun main() {
fun part1(inputs: String): Long {
return Day11.part1(inputs)
}
fun part2(inputs: String): Long {
return Day11.part2(inputs)
}
val testInput = readText("../data/Day11_test")
check(part1(testInput) == 10605L)
check(part2(testInput) == 2713310158L)
val input = readText("../data/Day11")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | a5777a67d234e33dde43589602dc248bc6411aee | 3,211 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/main/kotlin/days/Day15.kt | butnotstupid | 433,717,137 | false | {"Kotlin": 55124} | package days
import java.util.*
class Day15 : Day(15) {
private val di = listOf(-1, 0, 0, 1)
private val dj = listOf(0, -1, 1, 0)
override fun partOne(): Any {
val map = inputList.map { it.map { Character.getNumericValue(it) } }
return findPath(map)
}
override fun partTwo(): Any {
val map = inputList.map { it.map { Character.getNumericValue(it) } }
val (n, m) = map.size to map.first().size
val extended = Array(n * 5) { Array(m * 5) { 0 } }
for (i in 0 until n * 5) {
for (j in 0 until m * 5) {
val distFromSource = i / n + j / m
val (srcI, srcJ) = i % n to j % m
extended[i][j] = 1 + (map[srcI][srcJ] + distFromSource - 1) % 9
}
}
return findPath(extended.map { it.toList() })
}
private fun findPath(map: List<List<Int>>): Int {
val queue = PriorityQueue<PathEntry>()
val distTo = Array(map.size) { Array(map.first().size) { -1 } }
val start = 0 to 0
val end = map.size - 1 to map.first().size - 1
queue.add(PathEntry(0, start.first, start.second))
distTo[start.first][start.second] = 0
while (queue.isNotEmpty()) {
val (dist, i, j) = queue.poll()
for ((dii, djj) in di.zip(dj)) {
if (i + dii in map.indices && j + djj in map.first().indices) {
val prevDist = distTo[i + dii][j + djj]
if (prevDist == -1 || prevDist > dist + map[i + dii][j + djj]) {
if (prevDist != -1) {
queue.removeIf { it.i to it.j == i + dii to j + djj }
}
distTo[i + dii][j + djj] = dist + map[i + dii][j + djj]
queue.add(PathEntry(distTo[i + dii][j + djj], i + dii, j + djj))
}
}
}
}
return distTo[end.first][end.second]
}
data class PathEntry(val distance: Int, val i: Int, val j: Int): Comparable<PathEntry> {
override fun compareTo(other: PathEntry): Int {
return distance.compareTo(other.distance)
}
}
}
| 0 | Kotlin | 0 | 0 | a06eaaff7e7c33df58157d8f29236675f9aa7b64 | 2,223 | aoc-2021 | Creative Commons Zero v1.0 Universal |
solutions/aockt/y2015/Y2015D15.kt | Jadarma | 624,153,848 | false | {"Kotlin": 435090} | package aockt.y2015
import io.github.jadarma.aockt.core.Solution
object Y2015D15 : Solution {
private val inputRegex =
Regex("""(\w+): capacity (-?\d+), durability (-?\d+), flavor (-?\d+), texture (-?\d+), calories (-?\d+)""")
/** Parses a single line of input and returns an [Ingredient] and its properties. */
private fun parseInput(input: String): Ingredient {
val (name, capacity, durability, flavor, texture, calories) = inputRegex.matchEntire(input)!!.destructured
return Ingredient(name, capacity.toInt(), durability.toInt(), flavor.toInt(), texture.toInt(), calories.toInt())
}
/** Cookie making properties and nutritional values of an ingredient. */
private data class Ingredient(
val name: String,
val capacity: Int,
val durability: Int,
val flavor: Int,
val texture: Int,
val calories: Int,
)
/** The required ingredients */
private data class CookieRecipe(val ingredients: Map<Ingredient, Int>) {
val calories by lazy {
ingredients.entries.sumOf { (it, count) -> it.calories * count }
}
val score by lazy {
with(ingredients.entries) {
listOf(
sumOf { (it, count) -> it.capacity * count },
sumOf { (it, count) -> it.durability * count },
sumOf { (it, count) -> it.flavor * count },
sumOf { (it, count) -> it.texture * count },
).map { maxOf(0, it) }.reduce(Int::times)
}
}
}
/** Finds all different way you can use [ingredientCount] to add up to [capacity] units. */
private fun bruteForceMeasurements(ingredientCount: Int, capacity: Int): List<List<Int>> = when (ingredientCount) {
in Int.MIN_VALUE..0 -> throw IllegalArgumentException("What would you want to cook with no ingredients?")
1 -> listOf(listOf(capacity))
else -> (0..capacity).flatMap { measure ->
bruteForceMeasurements(ingredientCount - 1, capacity - measure).map { listOf(measure) + it }
}
}
/**
* With the available [ingredients] and using exactly [capacity] units of measurement in total, finds the right
* combination that maximises the cookie score. Optionally adds [calorieRequirement] on the final recipe.
* Returns the perfect [CookieRecipe] or `null` if it's impossible to bake one to the given specifications.
*/
private fun findPerfectRecipe(
ingredients: List<Ingredient>,
capacity: Int = 100,
calorieRequirement: Int? = null,
): CookieRecipe? =
bruteForceMeasurements(ingredients.size, capacity)
.map { ingredients.zip(it).toMap() }
.map(::CookieRecipe)
.filter { calorieRequirement == null || it.calories == calorieRequirement }
.maxByOrNull { it.score }
override fun partOne(input: String): Any {
val ingredients = input.lineSequence().map(this::parseInput).toList()
return findPerfectRecipe(ingredients)!!.score
}
override fun partTwo(input: String): Any {
val ingredients = input.lineSequence().map(this::parseInput).toList()
return findPerfectRecipe(ingredients, calorieRequirement = 500)!!.score
}
}
| 0 | Kotlin | 0 | 3 | 19773317d665dcb29c84e44fa1b35a6f6122a5fa | 3,319 | advent-of-code-kotlin-solutions | The Unlicense |
src/Day12.kt | Allagash | 572,736,443 | false | {"Kotlin": 101198} | import java.io.File
import java.util.*
import kotlin.math.abs
// Advent of Code 2022, Day 12, Hill Climbing Algorithm
typealias Graph = List<List<Int>>
typealias Cell = Pair<Int, Int>
// Manhattan distance
fun Cell.distance(other: Cell) = abs(this.first - other.first) + abs(this.second - other.second)
fun Graph.neighbors(curr: Cell, part1: Boolean) : List<Cell> {
val neighbors = mutableListOf<Cell>()
val currVal = this[curr.first][curr.second]
for (i in listOf(Pair(-1, 0), Pair(1, 0), Pair(0, -1), Pair(0, 1))) {
val pt = Pair(curr.first + i.first, curr.second + i.second)
if (pt.first >= 0 && pt.first < this.size && pt.second >=0 && pt.second < this[0].size) {
val nextVal = this[pt.first][pt.second]
if ((part1 && currVal + 1 >= nextVal) || (!part1 && currVal <= nextVal + 1)) {
neighbors.add(pt)
}
}
}
return neighbors
}
// A* search
// https://www.redblobgames.com/pathfinding/a-star/implementation.html
fun aStarSearch(graph: Graph, start: Cell, goal: Set<Cell>, part1: Boolean) : Int {
val openSet = PriorityQueue {t1: Pair<Cell, Int>, t2 : Pair<Cell, Int> -> (t1.second - t2.second) }
openSet.add(Pair(start, 0))
val cameFrom = mutableMapOf<Cell, Cell?>()
val costSoFar = mutableMapOf<Cell, Int>()
cameFrom[start] = null
costSoFar[start] = 0
var cost = 0
while (openSet.isNotEmpty()) {
val current = openSet.remove()
if (current.first in goal) {
cost = costSoFar[current.first]!!
break
}
val neighbors = graph.neighbors(current.first, part1)
for (next in neighbors) {
val newCost = costSoFar[current.first]!! + 1
if (next !in costSoFar || newCost < costSoFar[next]!!) {
costSoFar[next] = newCost
val priority = newCost + goal.minOf{next.distance(it)}
openSet.add(Pair(next, priority))
cameFrom[next] = current.first
}
}
}
return cost
}
fun main() {
val START_MARKER = -1
val END_MARKER = 'z'.code - 'a'.code + 1
// Read a 2D grid as input. Each cell is one letter.
fun readSingleDigitGrid(name: String): List<List<Int>> {
// convert each ASCII char to an int, so 'a' -> 0, 'b' -> 1, etc.
return File("src", "$name.txt").readLines().map {
it.trim().map { j ->
when (j) {
'S' -> START_MARKER
'E' -> END_MARKER
else -> j.code - 'a'.code
}
}
}
}
fun part1(grid: List<List<Int>>): Int {
var start = Pair(0, 0)
var end = Pair(0, 0)
for (i in grid.indices) {
for (j in grid[i].indices) {
if (grid[i][j] == START_MARKER) {
start = Pair(i, j)
} else if (grid[i][j] == END_MARKER) {
end = Pair(i, j)
}
}
}
return aStarSearch(grid, start, setOf(end), true)
}
fun part2(grid: List<List<Int>>): Int {
var start = Pair(0, 0)
val end = mutableSetOf<Pair<Int, Int>>()
for (i in grid.indices) {
for (j in grid[i].indices) {
if (grid[i][j] <= 0) {
end.add(Pair(i, j))
} else if (grid[i][j] == END_MARKER) {
start = Pair(i, j)
}
}
}
return aStarSearch(grid, start, end, false)
}
val testInput = readSingleDigitGrid("Day12_test")
check(part1(testInput) == 31)
check(part2(testInput) == 29)
val input = readSingleDigitGrid("Day12")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 8d5fc0b93f6d600878ac0d47128140e70d7fc5d9 | 3,793 | AdventOfCode2022 | Apache License 2.0 |
src/Day02.kt | melo0187 | 576,962,981 | false | {"Kotlin": 15984} | import Codes.elvenShapeCodes
import Codes.outcomeByCode
import Codes.shapeByCode
sealed interface Shape {
val score: Int
val defeat: Shape
object ROCK : Shape {
override val score: Int = 1
override val defeat: Shape = SCISSORS
}
object PAPER : Shape {
override val score: Int = 2
override val defeat: Shape = ROCK
}
object SCISSORS : Shape {
override val score: Int = 3
override val defeat: Shape = PAPER
}
fun matchWith(opponentShape: Shape): Outcome =
when (opponentShape) {
this -> Outcome.DRAW
defeat -> Outcome.WIN
else -> Outcome.LOSS
}
fun findMatchingShapeFor(outcome: Outcome): Shape = when (outcome) {
Outcome.LOSS -> defeat
Outcome.DRAW -> this
Outcome.WIN -> findShapeThatDefeats(this)
}
private tailrec fun findShapeThatDefeats(shape: Shape): Shape =
if (shape.defeat == this) {
shape
} else {
findShapeThatDefeats(shape.defeat)
}
enum class Outcome(val score: Int) {
LOSS(0),
DRAW(3),
WIN(6),
}
}
object Codes {
val elvenShapeCodes = listOf('A', 'B', 'C')
private val myShapeCodes = listOf('X', 'Y', 'Z')
val shapeByCode = (elvenShapeCodes + myShapeCodes)
.associate {
when (it) {
'A', 'X' -> it to Shape.ROCK
'B', 'Y' -> it to Shape.PAPER
'C', 'Z' -> it to Shape.SCISSORS
else -> error("Unknown shape code!")
}
}
val outcomeByCode =
mapOf(
'X' to Shape.Outcome.LOSS,
'Y' to Shape.Outcome.DRAW,
'Z' to Shape.Outcome.WIN
)
}
fun main() {
fun List<String>.toCodePairs() = map { line ->
val (elfCode, myCode) = line.slice(listOf(0, 2))
.partition { shapeCode -> shapeCode in elvenShapeCodes }
elfCode.single() to myCode.single()
}
fun part1(input: List<String>): Int =
input.toCodePairs()
.map { (elfCode, myCode) ->
shapeByCode.getValue(elfCode) to shapeByCode.getValue(myCode)
}
.sumOf { (elfShape, myShape) ->
myShape.score + myShape.matchWith(elfShape).score
}
fun part2(input: List<String>): Int =
input.toCodePairs()
.map { (elfCode, myCode) ->
shapeByCode.getValue(elfCode) to outcomeByCode.getValue(myCode)
}
.sumOf { (elfShape, myDesiredOutcome) ->
val myDesiredShape = elfShape.findMatchingShapeFor(myDesiredOutcome)
myDesiredShape.score + myDesiredShape.matchWith(elfShape).score
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day02_test")
check(part1(testInput) == 15)
check(part2(testInput) == 12)
val input = readInput("Day02")
part1(input).println()
part2(input).println()
} | 0 | Kotlin | 0 | 0 | 97d47b84e5a2f97304a078c3ab76bea6672691c5 | 3,056 | kotlin-aoc-2022 | Apache License 2.0 |
src/day15/Day15.kt | HGilman | 572,891,570 | false | {"Kotlin": 109639, "C++": 5375, "Python": 400} | package day15
import lib.Point2D
import lib.Vector2D
import readInput
import kotlin.math.abs
fun main() {
val day = 15
val testInput = readInput("day$day/testInput")
// check(part1(testInput, 10) == 26)
// val testRes = part2(testInput, 20)
// check(testRes == 56000011)
val input = readInput("day$day/input")
// println(part1(input, 2000000))
println(part2(input, 4000000))
}
fun part1(input: List<String>, lineNumber: Int): Int {
val pairs = pairs(input)
val occupiedPoints = mutableSetOf<Point2D>()
pairs.forEach {
val distance = it.first.manhattanDistanceTo(it.second)
val distanceToLine = abs(it.first.y - lineNumber)
if (distanceToLine <= distance) {
val diff = abs(distance - distanceToLine)
for (i in -diff until diff + 1) {
occupiedPoints.add(Point2D(it.first.x + i, lineNumber))
}
}
}
// removing beacons from occupied set
pairs.forEach {
if (occupiedPoints.contains(it.second)) {
occupiedPoints.remove(it.second)
}
}
return occupiedPoints.size
}
fun part2(input: List<String>, borderSize: Int): Long {
val pairs = pairs(input)
val xRange = (0..borderSize)
val yRange = (0..borderSize)
pairs.forEach { p ->
val distance = p.first.manhattanDistanceTo(p.second) + 1
(0..distance).forEach { dx ->
val borderPoints = listOf<Point2D>(
// left top
p.first + Vector2D(-distance + dx, dx),
// right top
p.first + Vector2D(distance - dx, dx),
// left bottom
p.first + Vector2D(-distance + dx, -dx),
// right bottom
p.first + Vector2D(distance - dx, -dx)
)
for (border in borderPoints) {
if (border.x in xRange && border.y in yRange) {
if (pairs.all { it.first.manhattanDistanceTo(it.second) < it.first.manhattanDistanceTo(border) }) {
return getTuningFrequency(border)
}
}
}
}
}
return -1L
}
private fun pairs(input: List<String>): List<Pair<Point2D, Point2D>> {
val pairs = input.map {
val sensX = it.substringAfter("x=").substringBefore(",").toInt()
val sensY = it.substringAfter("y=").substringBefore(":").toInt()
val beaconX = it.substringAfterLast("x=").substringBefore(",").toInt()
val beaconY = it.substringAfterLast("y=").toInt()
Pair(Point2D(sensX, sensY), Point2D(beaconX, beaconY))
}
return pairs
}
fun getTuningFrequency(p: Point2D): Long {
return p.x * 4_000_000L + p.y
}
| 0 | Kotlin | 0 | 1 | d05a53f84cb74bbb6136f9baf3711af16004ed12 | 2,751 | advent-of-code-2022 | Apache License 2.0 |
src/Day10.kt | rweekers | 573,305,041 | false | {"Kotlin": 38747} | import kotlin.math.absoluteValue
fun main() {
fun part1(signalStrengths: List<Int>): Int {
val cycles = listOf(20, 60, 100, 140, 180, 220)
return cycles.fold(mutableListOf<Int>()) { acc, curr ->
acc.add(signalStrengths[curr - 1] * curr)
acc
}.sum()
}
fun part2(signalStrengths: List<Int>) {
val pixelList = signalStrengths.mapIndexed { index, signal ->
(signal - index % 40).absoluteValue <= 1
}.map { if (it) "#" else "." }
pixelList.windowed(40, 40) { row ->
row.forEach { pixel -> print(pixel) }
println()
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day10_test")
val testCpuInstructions = determineCpuInstructions(testInput)
val testSignalStrengths = determineSignalStrengths(testCpuInstructions)
check(part1(testSignalStrengths) == 13140)
// no check for part 2, visual check
val input = readInput("Day10")
val cpuInstructions = determineCpuInstructions(input)
val signalStrengths = determineSignalStrengths(cpuInstructions)
println(part1(signalStrengths))
println(part2(signalStrengths))
}
private fun determineCpuInstructions(input: List<String>): List<CpuInstruction> {
return input.map {
val rawInstruction = it.split(" ")
val isNoop = rawInstruction[0] == "noop"
val increment = if (isNoop) 0 else rawInstruction[1].toInt()
val cycles = if (isNoop) 1 else 2
CpuInstruction(increment, cycles)
}
}
private fun determineSignalStrengths(input: List<CpuInstruction>) =
input.fold(mutableListOf(1)) { acc, curr ->
val lastSignalStrength = acc.last()
if (curr.cycles > 1) {
acc.add(lastSignalStrength)
}
acc.add(lastSignalStrength + curr.increment)
acc
}
private data class CpuInstruction(val increment: Int, val cycles: Int)
| 0 | Kotlin | 0 | 1 | 276eae0afbc4fd9da596466e06866ae8a66c1807 | 1,974 | adventofcode-2022 | Apache License 2.0 |
kotlin/src/com/s13g/aoc/aoc2020/Day17.kt | shaeberling | 50,704,971 | false | {"Kotlin": 300158, "Go": 140763, "Java": 107355, "Rust": 2314, "Starlark": 245} | package com.s13g.aoc.aoc2020
import com.s13g.aoc.Result
import com.s13g.aoc.Solver
/**
* --- Day 17: Conway Cubes ---
* https://adventofcode.com/2020/day/17
*/
class Day17 : Solver {
override fun solve(lines: List<String>): Result {
val map = mutableMapOf<XYZW, Boolean>()
for (y in lines.indices) {
for (x in lines[y].indices) {
map[XYZW(x, y)] = lines[y][x] == '#'
}
}
var currentMap = map as Map<XYZW, Boolean>
var currentMapB = map.toMap()
for (x in 1..6) currentMap = runCycle(currentMap)
for (x in 1..6) currentMapB = runCycle(currentMapB, true)
return Result("${currentMap.values.count { it }}", "${currentMapB.values.count { it }}")
}
private fun runCycle(map: Map<XYZW, Boolean>, countW: Boolean = false): Map<XYZW, Boolean> {
val result = mutableMapOf<XYZW, Boolean>()
val (min, max) = listOf(map.mapKeys { it.min()!! }, map.mapKeys { it.max()!! })
for (x in (min.x - 1)..(max.x + 1)) {
for (y in (min.y - 1)..(max.y + 1)) {
for (z in (min.z - 1)..(max.z + 1)) {
for (w in (if (countW) (min.w - 1) else 0)..(if (countW) (max.w + 1) else 0)) {
val pos = XYZW(x, y, z, w)
val numNeighbors = countNeighbors(map, pos)
if (map.isActive(pos) && (numNeighbors in 2..3)) result[pos] = true
else result[pos] = !map.isActive(pos) && numNeighbors == 3
}
}
}
}
return result
}
private fun countNeighbors(map: Map<XYZW, Boolean>, pos: XYZW): Int {
var result = 0
for (x in (pos.x - 1)..(pos.x + 1)) {
for (y in (pos.y - 1)..(pos.y + 1)) {
for (z in (pos.z - 1)..(pos.z + 1)) {
for (w in (pos.w - 1)..(pos.w + 1)) {
XYZW(x, y, z, w).apply { if (this != pos && map.isActive(this)) result++ }
}
}
}
}
return result
}
private fun Map<XYZW, Boolean>.isActive(xyz: XYZW) = (xyz in this && this[xyz]!!)
private fun Map<XYZW, Boolean>.mapKeys(f: (List<Int>) -> Int): XYZW {
keys.apply { return XYZW(f(map { it.x }), f(map { it.y }), f(map { it.z }), f(map { it.w })) }
}
private data class XYZW(val x: Int, val y: Int, val z: Int = 0, val w: Int = 0)
}
| 0 | Kotlin | 1 | 2 | 7e5806f288e87d26cd22eca44e5c695faf62a0d7 | 2,221 | euler | Apache License 2.0 |
src/day4.kt | SerggioC | 573,171,085 | false | {"Kotlin": 8824} | fun main() {
val input: List<String> = readInput("day4")
val map = input.map { sections ->
val (pair1, pair2) = sections.split(",")
val section1 = pair1.split("-").map(String::toInt)
val section2 = pair2.split("-").map(String::toInt)
val range1 = IntRange(section1.get(0), section1.get(1))
val range2 = IntRange(section2.get(0), section2.get(1))
range1 to range2
}
fun part1(): Int {
return map.count { it: Pair<IntRange, IntRange> ->
val range1 = it.first
val range2 = it.second
range1.first in range2 && range1.last in range2 || range2.first in range1 && range2.last in range1
}
}
fun part2(): Int {
return map.count {
val range1 = it.first
val range2 = it.second
range1.intersect(range2).isNotEmpty()
}
}
println("Total part 1 is ${part1()}")
println("Total part 2 is ${part2()}")
fun parse(input: List<String>) = input
.map { line ->
val (a1, a2) = line.substringBefore(',').split('-').map(String::toInt)
val (b1, b2) = line.substringAfter(',').split('-').map(String::toInt)
(a1..a2) to (b1..b2)
}
operator fun IntRange.contains(other: IntRange) =
other.first in this && other.last in this
fun part1(input: List<String>) = parse(input)
.count { (r1, r2) -> r1 in r2 || r2 in r1 }
fun part2(input: List<String>) = parse(input)
.count { (r1, r2) -> r1.intersect(r2).isNotEmpty() }
}
| 0 | Kotlin | 0 | 0 | d56fb119196e2617868c248ae48dcde315e5a0b3 | 1,578 | aoc-2022 | Apache License 2.0 |
src/aoc2022/Day07.kt | miknatr | 576,275,740 | false | {"Kotlin": 413403} | package aoc2022
fun main() {
data class File(
val name: String,
val size: Int
)
data class Dir(
val parent: Dir?,
val name: String,
val isDeleted: Boolean = false,
val dirs: MutableList<Dir> = mutableListOf(),
val files: MutableList<File> = mutableListOf()
) {
val size: Int get() = files.sumOf { it.size } + dirs.sumOf { it.size }
fun getSumDirSizesAtMost(atMost: Int): Int {
var sumSize = 0
if (size < atMost) {
sumSize += size
}
sumSize += dirs.sumOf { it.getSumDirSizesAtMost(atMost) }
return sumSize
}
fun getAllDirs(): List<Dir> {
val allDirs = mutableListOf<Dir>()
allDirs.addAll(dirs)
dirs.forEach {
allDirs.addAll(it.getAllDirs())
}
return allDirs
}
}
fun parseRoot(input: List<String>): Dir {
val root = Dir(null, "/")
var currentDir = root
// $ cd ..
// $ cd tfwgg
// $ ls
// dir ddnfmsjc
// 252616 fvj
input
.filter { it != "" }
.forEach { command ->
when {
command == "$ cd /" -> Unit
command == "$ ls" -> Unit
command == "$ cd .." -> {
currentDir = currentDir.parent!!
}
command.startsWith("$ cd ") -> {
val dirName = command.substring(5)
currentDir = currentDir.dirs.first { it.name == dirName } // hashmaps would be better
}
command.startsWith("dir ") -> {
val dirName = command.substring(4)
currentDir.dirs.add(Dir(currentDir, dirName))
}
else -> {
val (size, fileName) = command.split(" ")
currentDir.files.add(File(fileName, size.toInt()))
}
}
}
return root
}
fun part1(input: List<String>): Int = parseRoot(input)
.getSumDirSizesAtMost(100000)
fun part2(input: List<String>): Int {
val root = parseRoot(input)
val spaceLeft = 70000000 - root.size
val needMoreSpace = 30000000 - spaceLeft
return root
.getAllDirs()
.sortedBy { it.size }
.filter { it.size >= needMoreSpace }
.first()
.size
}
val testInput = readInput("Day07_test")
part1(testInput).println()
part2(testInput).println()
val input = readInput("Day07")
part1(input).println()
part2(input).println()
}
| 0 | Kotlin | 0 | 0 | 400038ce53ff46dc1ff72c92765ed4afdf860e52 | 2,825 | aoc-in-kotlin | Apache License 2.0 |
advent-of-code-2023/src/Day01.kt | osipxd | 572,825,805 | false | {"Kotlin": 141640, "Shell": 4083, "Scala": 693} | private const val DAY = "Day01"
fun main() {
val input = readInput(DAY)
val testInput1 = readInput("${DAY}_test1")
val testInput2 = readInput("${DAY}_test2")
"Part 1" {
part1(testInput1) shouldBe 142
measureAnswer { part1(input) }
}
"Part 2 (Regex)" {
part2Regex(testInput2) shouldBe 281
measureAnswer { part2Regex(input) }
}
"Part 2 (findAnyOf)" {
part2FindAnyOf(testInput2) shouldBe 281
measureAnswer { part2FindAnyOf(input) }
}
}
private fun part1(input: List<String>): Int = input.sumOf(::extractSimpleCalibrationValue)
private fun extractSimpleCalibrationValue(line: String): Int {
val firstDigit = line.first { it.isDigit() }
val secondDigit = line.last { it.isDigit() }
return "$firstDigit$secondDigit".toInt()
}
//////////////////////////////////
private fun part2Regex(input: List<String>): Int = input.sumOf(::extractCalibrationValueWithRegex)
private const val DIGITS_REGEX = "one|two|three|four|five|six|seven|eight|nine"
private val realDigitRegex = Regex("""\d|$DIGITS_REGEX""")
private val realDigitRegexReversed = Regex("""\d|${DIGITS_REGEX.reversed()}""")
private fun extractCalibrationValueWithRegex(line: String): Int {
val firstDigit = realDigitRegex.requireValue(line).digitToInt()
val secondDigit = realDigitRegexReversed.requireValue(line.reversed()).reversed().digitToInt()
return firstDigit * 10 + secondDigit
}
private fun Regex.requireValue(input: String) = requireNotNull(find(input)).value
//////////////////////////////////
private fun part2FindAnyOf(input: List<String>): Int = input.sumOf(::extractCalibrationValueWithFindAnyOf)
private val digits = setOf(
"1", "2", "3", "4", "5", "6", "7", "8", "9",
"one", "two", "three", "four", "five", "six", "seven", "eight", "nine",
)
private fun extractCalibrationValueWithFindAnyOf(line: String): Int {
val firstDigit = line.findAnyOf(digits).requireDigit()
val secondDigit = line.findLastAnyOf(digits).requireDigit()
return firstDigit * 10 + secondDigit
}
private fun Pair<Int, String>?.requireDigit(): Int {
checkNotNull(this)
return second.digitToInt()
}
//////////////////////////////////
private fun String.digitToInt(): Int = when (this) {
"one" -> 1
"two" -> 2
"three" -> 3
"four" -> 4
"five" -> 5
"six" -> 6
"seven" -> 7
"eight" -> 8
"nine" -> 9
else -> single().digitToInt()
}
private fun readInput(name: String) = readLines(name)
| 0 | Kotlin | 0 | 5 | 6a67946122abb759fddf33dae408db662213a072 | 2,510 | advent-of-code | Apache License 2.0 |
src/main/kotlin/Day9.kt | i-redbyte | 433,743,675 | false | {"Kotlin": 49932} | import java.util.*
fun main() {
val data = readInputFile("day9")
fun getCandidates(i: Int, heights: List<List<Int>>, j: Int): Int {
val candidates = mutableListOf<Int>()
if (i > 0) candidates += heights[i - 1][j]
if (j > 0) candidates += heights[i][j - 1]
if (i < heights.size - 1) candidates += heights[i + 1][j]
if (j < heights[i].size - 1) candidates += heights[i][j + 1]
return minOf(candidates.minOrNull()!!)
}
fun part1(): Int {
val heights = data.map { it.map { it.digitToInt() } }
var risks = 0
repeat(heights.size) { i ->
repeat(heights[i].size) { j ->
val height = getCandidates(i, heights, j)
if (height > heights[i][j]) risks += (heights[i][j] + 1)
}
}
return risks
}
fun part2(): Long {
val heights = data.map { it.map { it.digitToInt() } }
val lowPoints = mutableListOf<Pair<Int, Int>>()
repeat(heights.size) { i ->
repeat(heights[i].size) { j ->
val height = getCandidates(i, heights, j)
if (height > heights[i][j]) lowPoints += i to j
}
}
return lowPoints.map { point ->
val visited = mutableSetOf(point)
val queue = LinkedList<Pair<Int, Int>>().apply { add(point) }
while (queue.isNotEmpty()) {
val (i, j) = queue.poll()
if (i > 0) {
val point = (i - 1) to j
if (heights[i - 1][j] < 9 && point !in visited) {
visited.add(point)
queue.add(point)
}
}
if (j > 0) {
val point = i to (j - 1)
if (heights[i][j - 1] < 9 && point !in visited) {
visited.add(point)
queue.add(point)
}
}
if (i < heights.size - 1) {
val point = (i + 1) to j
if (heights[i + 1][j] < 9 && point !in visited) {
visited.add(point)
queue.add(point)
}
}
if (j < heights[i].size - 1) {
val point = i to (j + 1)
if (heights[i][j + 1] < 9 && point !in visited) {
visited.add(point)
queue.add(point)
}
}
}
visited.size.toLong()
}.sortedDescending()
.take(3)
.fold(1L) { a, v -> a * v }
}
println("Result part1: ${part1()}")
println("Result part2: ${part2()}")
}
| 0 | Kotlin | 0 | 0 | 6d4f19df3b7cb1906052b80a4058fa394a12740f | 2,793 | AOC2021 | Apache License 2.0 |
src/main/kotlin/Problem24.kt | jimmymorales | 496,703,114 | false | {"Kotlin": 67323} | /**
* Lexicographic permutations
*
* A permutation is an ordered arrangement of objects. For example, 3124 is one possible permutation of the digits 1, 2,
* 3 and 4. If all of the permutations are listed numerically or alphabetically, we call it lexicographic order. The
* lexicographic permutations of 0, 1 and 2 are:
*
* 012 021 102 120 201 210
*
* What is the millionth lexicographic permutation of the digits 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9?
*
* https://projecteuler.net/problem=24
*/
fun main() {
println(lexicographicPermutations(listOf('0', '1', '2')))
println(lexicographicPermutationsAt(listOf('0', '1', '2', '3', '4', '5', '6', '7', '8', '9'), 1_000_000))
}
private fun lexicographicPermutations(digits: List<Char>): List<String> = buildList {
val arr = digits.toCharArray()
while (true) {
add(String(arr))
if (!arr.nextPermutation()) break
}
}
private fun lexicographicPermutationsAt(digits: List<Char>, n: Int): String {
val arr = digits.toCharArray()
var count = 0
while (true) {
count++
if (count == n) {
return String(arr)
}
if (!arr.nextPermutation()) break
}
return ""
}
private fun CharArray.nextPermutation(): Boolean {
// Find the rightmost character which is smaller than its next character.
val i = ((lastIndex - 1) downTo 0).firstOrNull { this[it] < this[it + 1] } ?: return false
// Find the ceil of 'first char' in right of first character. Ceil of a character is the smallest character
// greater than it.
val ceilIndex = findCeil(this[i], i + 1, lastIndex)
// Swap first and second characters
swap(i, ceilIndex)
// reverse the string on right of 'first char'
reverse(i + 1, lastIndex)
return true
}
// This function finds the index of the smallest
// character which is greater than 'first' and is
// present in str[l..h]
private fun CharArray.findCeil(first: Char, l: Int, h: Int): Int {
// initialize index of ceiling element
var ceilIndex = l
// Now iterate through rest of the elements and find
// the smallest character greater than 'first'
for (i in l + 1..h) {
if (this[i] > first && this[i] < this[ceilIndex]) {
ceilIndex = i
}
}
return ceilIndex
}
// A utility function two swap two characters a and b
private fun CharArray.swap(i: Int, j: Int) {
val t = this[i]
this[i] = this[j]
this[j] = t
}
// A utility function to reverse a string str[l..h]
private fun CharArray.reverse(l: Int, h: Int) {
var low = l
var high = h
while (low < high) {
swap(low, high)
low++
high--
}
}
| 0 | Kotlin | 0 | 0 | e881cadf85377374e544af0a75cb073c6b496998 | 2,693 | project-euler | MIT License |
src/main/kotlin/se/saidaspen/aoc/aoc2022/Day11.kt | saidaspen | 354,930,478 | false | {"Kotlin": 301372, "CSS": 530} | package se.saidaspen.aoc.aoc2022
import se.saidaspen.aoc.util.*
import java.math.BigInteger
fun main() = Day11.run()
data class Monkey(val items: MutableList<BigInteger>, val op: (BigInteger) -> BigInteger, val divisor : BigInteger, val throwTo: (BigInteger) -> Int, var inspections: BigInteger = BigInteger.ZERO)
object Day11 : Day(2022, 11) {
override fun part1(): Any {
val monkeys = parseMonkeys()
for (round in 1..20) {
for (m in monkeys){
while (m.items.isNotEmpty()) {
m.inspections += BigInteger.ONE
val old = m.items.removeAt(0)
val new = m.op(old) / BigInteger.valueOf(3)
monkeys[m.throwTo(new)].items.add(new)
}
}
}
return monkeys.map { it.inspections }.sortedByDescending { it }.take(2).reduce { acc, i -> acc * i }
}
override fun part2(): Any {
val monkeys = parseMonkeys()
val modBy = monkeys.map { it.divisor }.reduce { a, b -> a * b }
for (round in 1..10_000) {
for (m in monkeys){
while (m.items.isNotEmpty()) {
m.inspections += BigInteger.ONE
val old = m.items.removeAt(0)
val new = m.op(old) % modBy
monkeys[m.throwTo(new)].items.add(new)
}
}
}
return monkeys.map { it.inspections }.sortedByDescending { it }.take(2).reduce { acc, i -> acc * i }
}
private fun parseMonkeys() = input.split("\n\n").map { m -> m.lines() }.map {
val items = ints(it[1]).map { i -> i.toBigInteger() }.toMutableList()
val nums = ints(it[2])
val operand2 = if (nums.isNotEmpty()) nums[0].toBigInteger() else BigInteger.ZERO
val square = (nums.isEmpty())
val op = if (square) { i: BigInteger -> i * i } else if (it[2].contains("+")) { i: BigInteger -> i + operand2 } else { i: BigInteger -> i * operand2 }
val divisor = ints(it[3])[0].toBigInteger()
val trueTo = ints(it[4])[0]
val falseTo = ints(it[5])[0]
val throwTo = { i: BigInteger -> if (i % divisor == BigInteger.ZERO) trueTo else falseTo }
Monkey(items, op, divisor, throwTo)
}.toList()
}
| 0 | Kotlin | 0 | 1 | be120257fbce5eda9b51d3d7b63b121824c6e877 | 2,305 | adventofkotlin | MIT License |
y2020/src/main/kotlin/adventofcode/y2020/Day19.kt | Ruud-Wiegers | 434,225,587 | false | {"Kotlin": 503769} | package adventofcode.y2020
import adventofcode.io.AdventSolution
fun main() = Day19.solve()
object Day19 : AdventSolution(2020, 19, "Monster Messages")
{
override fun solvePartOne(input: String): Int
{
val (rulesInput, messages) = input.split("\n\n")
val rules: List<Rule> = parseRules(rulesInput)
return messages.lines().count { matches(it, listOf(0), rules) }
}
override fun solvePartTwo(input: String): Int
{
val (rulesInput, messages) = input.split("\n\n")
val rules: List<Rule> = parseRules(rulesInput).toMutableList().apply {
//the first index in each branch (42) will always produce terminals,
//so 'looping' will consume part of the message
//so the algorithm will always terminate
set(8, parseRule("42 | 42 8"))
set(11, parseRule("42 31 | 42 11 31"))
}
return messages.lines().count { matches(it, listOf(0), rules) }
}
private fun parseRules(input: String): List<Rule> = input.lines()
.map { it.split(": ") }
.sortedBy { it[0].toInt() }
.map { parseRule(it[1]) }
private fun parseRule(input: String): Rule = if (input.startsWith('"'))
Rule.Terminal(input[1])
else
input.split(" | ").map { it.split(" ").map(String::toInt) }.let(Rule::Dnf)
private fun matches(unmatchedMessage: String, unmatchedRules: List<Int>, grammar: List<Rule>): Boolean =
when (val rule = unmatchedRules.firstOrNull()?.let(grammar::get))
{
null -> unmatchedMessage.isEmpty()
is Rule.Terminal -> rule.ch == unmatchedMessage.firstOrNull() && matches(unmatchedMessage.drop(1), unmatchedRules.drop(1), grammar)
is Rule.Dnf -> rule.alternatives.any { alt -> matches(unmatchedMessage, alt + unmatchedRules.drop(1), grammar) }
}
private sealed class Rule
{
data class Terminal(val ch: Char) : Rule()
data class Dnf(val alternatives: List<List<Int>>) : Rule()
}
} | 0 | Kotlin | 0 | 3 | fc35e6d5feeabdc18c86aba428abcf23d880c450 | 2,050 | advent-of-code | MIT License |
Advent-of-Code-2023/src/Day01.kt | Radnar9 | 726,180,837 | false | {"Kotlin": 93593} | private const val AOC_DAY = "Day01"
private const val TEST_FILE = "${AOC_DAY}_test"
private const val INPUT_FILE = AOC_DAY
private fun part1(input: List<String>): Int {
return input.sumOf { line ->
line.first { it.isDigit() }.digitToInt() * 10 + line.last { it.isDigit() }.digitToInt()
}
}
private val digitsLetters = listOf("one", "two", "three", "four", "five", "six", "seven", "eight", "nine")
private data class CalibrationValue(val index: Int, val value: Int)
private fun part2(input: List<String>): Int {
return input.sumOf { line ->
var firstVal = CalibrationValue(Int.MAX_VALUE, 0)
var lastVal = CalibrationValue(Int.MIN_VALUE, 0)
for ((i, digit) in digitsLetters.withIndex()) {
if (digit in line) {
val firstIdx = line.indexOf(digit)
val lastIdx = line.lastIndexOf(digit)
if (firstIdx < firstVal.index) {
firstVal = CalibrationValue(firstIdx, i + 1)
}
if (lastIdx > lastVal.index) {
lastVal = CalibrationValue(lastIdx, i + 1)
}
}
}
val firstIdx = line.indexOfFirst { it.isDigit() }
val lastIdx = line.indexOfLast { it.isDigit() }
if (firstIdx >= 0 && firstIdx < firstVal.index) {
firstVal = CalibrationValue(firstIdx, line[firstIdx].digitToInt())
}
if (lastIdx >= 0 && lastIdx > lastVal.index) {
lastVal = CalibrationValue(lastIdx, line[lastIdx].digitToInt())
}
firstVal.value * 10 + lastVal.value
}
}
private fun getNumber(line: String, digitsLetters: List<String>): Int {
val (letterIdx, letterValue) = line.findAnyOf(digitsLetters) ?: (Int.MAX_VALUE to "")
val digitIdx = line.indexOfFirst { it.isDigit() }
return if (digitIdx < 0 || letterIdx < digitIdx) {
digitsLetters.indexOf(letterValue) + 1
} else {
line[digitIdx].digitToInt()
}
}
/**
* Instead of searching from the end of each line, by reversing the line and the digits' letters, it searches for
* the last number in the same order but with the line reversed: eno, owt, eerht, ruof, ...
*/
private fun part2Improved(input: List<String>): Int {
return input.sumOf { line ->
getNumber(line, digitsLetters) * 10 + getNumber(line.reversed(), digitsLetters.map { it.reversed() })
}
}
fun main() {
val testInput = readInputToList(TEST_FILE)
part2(testInput).println()
val input = readInputToList(INPUT_FILE)
part1(input).println()
part2(input).println()
part2Improved(input).println()
}
| 0 | Kotlin | 0 | 0 | e6b1caa25bcab4cb5eded12c35231c7c795c5506 | 2,643 | Advent-of-Code-2023 | Apache License 2.0 |
src/main/kotlin/days/y22/Day07.kt | kezz | 572,635,766 | false | {"Kotlin": 20772} | package days.y22
import arrow.core.Either
import arrow.core.Either.Left
import arrow.core.Either.Right
import util.Day
public fun main() {
Day07().run()
}
public class Day07 : Day(22, 7) {
override fun part1(input: List<String>): Any = input
.mapNotNull { line ->
when {
line.startsWith("$ cd") -> Left(line.substringAfterLast(' '))
line.startsWith("$ ls") -> null
else -> line.substringBefore(' ').toIntOrNull()?.let(::Right)
}
}
.fold<Either<String, Int>, Pair<List<String>, Map<String, Int>>>(Pair(listOf("~"), mapOf())) { acc, element ->
element.fold(
ifLeft = { movement ->
when (movement) {
".." -> acc.copy(first = acc.first.dropLast(1))
"/" -> acc.copy(first = listOf("~"))
else -> acc.first.plus(movement).let { tree -> acc.copy(tree, acc.second.toMutableMap().apply { merge(tree.joinToString("/"), 0, Int::plus) }) }
}
},
ifRight = { fileSize ->
acc.copy(second = acc.second.toMutableMap().apply { merge(acc.first.joinToString("/"), fileSize, Int::plus) })
}
)
}
.second
.let { map ->
map.entries.mapNotNull { (path, fileContentsSize) ->
map.filter { (key) -> key != path && key.startsWith(path) && key.removePrefix(path).first() == '/' }
.values
.sum()
.plus(fileContentsSize)
.takeIf { size -> size <= 100_000 }
}
}
.sum()
override fun part2(input: List<String>): Any = input
.mapNotNull { line ->
when {
line.startsWith("$ cd") -> Left(line.substringAfterLast(' '))
line.startsWith("$ ls") -> null
else -> line.substringBefore(' ').toIntOrNull()?.let(::Right)
}
}
.fold<Either<String, Int>, Triple<List<String>, Map<String, Int>, Int>>(Triple(listOf("~"), mapOf(), 0)) { acc, element ->
element.fold(
ifLeft = { movement ->
when (movement) {
".." -> acc.copy(first = acc.first.dropLast(1))
"/" -> acc.copy(first = listOf("~"))
else -> acc.first.plus(movement).let { tree -> acc.copy(tree, acc.second.toMutableMap().apply { merge(tree.joinToString("/"), 0, Int::plus) }) }
}
},
ifRight = { fileSize ->
acc.copy(
second = acc.second.toMutableMap().apply { merge(acc.first.joinToString("/"), fileSize, Int::plus) },
third = acc.third + fileSize
)
}
)
}
.let { triple -> triple.copy(third = 30_000_000 - (70_000_000 - triple.third)) }
.let { (_, map, target) ->
target to map.mapValues { (path, fileContentsSize) ->
map.filter { (key) -> key != path && key.startsWith(path) && key.removePrefix(path).first() == '/' }
.values
.sum()
.plus(fileContentsSize)
}
}
.let { (target, map) ->
map.entries
.sortedBy(Map.Entry<String, Int>::value)
.first { (_, size) -> size > target }
}
.value
}
| 0 | Kotlin | 0 | 0 | 1cef7fe0f72f77a3a409915baac3c674cc058228 | 3,571 | aoc | Apache License 2.0 |
src/Day02.kt | CrazyBene | 573,111,401 | false | {"Kotlin": 50149} | fun main() {
fun List<String>.toGameRounds(myHandShapeMapping: (HandShape, String) -> HandShape): List<GameRound> = this.map { line ->
val shapeInputs = line.split(" ")
if (shapeInputs.size != 2) error("Each round/line needs exactly 2 hand shapes")
val opponentHandShape = HandShape.fromValue(shapeInputs[0])
val myHandShape = myHandShapeMapping(opponentHandShape, shapeInputs[1])
GameRound(opponentHandShape, myHandShape)
}
fun part1(input: List<String>): Int {
val gameRounds = input.toGameRounds { _, myShapeInput ->
HandShape.fromValue(
when(myShapeInput) {
"X" -> "A"
"Y" -> "B"
"Z" -> "C"
else -> error("The second move must be XYZ.")
}
)
}
return gameRounds.sumOf { it.evaluate() }
}
fun part2(input: List<String>): Int {
val gameRounds = input.toGameRounds { opponentHandShape, myShapeInput ->
when (myShapeInput) {
"X" -> HandShape.getLosingShape(opponentHandShape)
"Y" -> opponentHandShape
"Z" -> HandShape.getWinningShape(opponentHandShape)
else -> error("The second move must be XYZ.")
}
}
return gameRounds.sumOf { it.evaluate() }
}
val testInput = readInput("Day02Test")
check(part1(testInput) == 15)
check(part2(testInput) == 12)
val input = readInput("Day02")
println("Question 1 - Answer: ${part1(input)}")
println("Question 2 - Answer: ${part2(input)}")
}
data class GameRound(val opponentHandShape: HandShape, val myHandShape: HandShape) {
fun evaluate(): Int {
val pointsFromResult = when (Pair(opponentHandShape, myHandShape)) {
Pair(HandShape.SCISSORS, HandShape.PAPER),
Pair(HandShape.ROCK, HandShape.SCISSORS),
Pair(HandShape.PAPER, HandShape.ROCK) -> 0
Pair(HandShape.ROCK, HandShape.ROCK),
Pair(HandShape.PAPER, HandShape.PAPER),
Pair(HandShape.SCISSORS, HandShape.SCISSORS) -> 3
Pair(HandShape.ROCK, HandShape.PAPER),
Pair(HandShape.PAPER, HandShape.SCISSORS),
Pair(HandShape.SCISSORS, HandShape.ROCK) -> 6
else -> error("The combination of $opponentHandShape and $myHandShape is not possible.")
}
return pointsFromResult + myHandShape.points
}
}
enum class HandShape(val points: Int) {
ROCK(1), PAPER(2), SCISSORS(3);
companion object {
fun fromValue(value: String): HandShape {
return when (value) {
"A" -> ROCK
"B" -> PAPER
"C" -> SCISSORS
else -> error("A hand shape which is not ABC was selected.")
}
}
fun getWinningShape(otherShape: HandShape): HandShape {
return when (otherShape) {
ROCK -> PAPER
PAPER -> SCISSORS
SCISSORS -> ROCK
}
}
fun getLosingShape(otherShape: HandShape): HandShape {
return when (otherShape) {
ROCK -> SCISSORS
PAPER -> ROCK
SCISSORS -> PAPER
}
}
}
} | 0 | Kotlin | 0 | 0 | dfcc5ba09ca3e33b3ec75fe7d6bc3b9d5d0d7d26 | 3,333 | AdventOfCode2022 | Apache License 2.0 |
src/main/kotlin/aoc2023/Day01.kt | Ceridan | 725,711,266 | false | {"Kotlin": 110767, "Shell": 1955} | package aoc2023
import kotlin.math.min
class Day01 {
fun part1(input: List<String>): Int = input
.map { line -> line.filter { it.isDigit() } }
.sumOf { digits -> digits.first().digitToInt() * 10 + digits.last().digitToInt() }
fun part2(input: List<String>): Int {
val firstDigits = input.map { line -> findFirstDigit(line) }
val lastDigits = input.map { line -> findFirstDigit(line, isBackward = true) }
return firstDigits.zip(lastDigits).sumOf { it.first * 10 + it.second }
}
private fun findFirstDigit(line: String, isBackward: Boolean = false): Int {
val range: IntProgression = if (isBackward) line.length - 1 downTo 0 else line.indices
for (i in range) {
if (line[i].isDigit()) {
return line[i].digitToInt()
}
for (j in MIN_KEY_SIZE..MAX_KEY_SIZE) {
val possibleKey = line.substring(i, min(i + j, line.length))
if (possibleKey in TEXT_TO_DIGIT) {
return TEXT_TO_DIGIT[possibleKey]!!
}
}
}
return 0
}
private companion object {
val TEXT_TO_DIGIT = mapOf(
"zero" to 0,
"one" to 1,
"two" to 2,
"three" to 3,
"four" to 4,
"five" to 5,
"six" to 6,
"seven" to 7,
"eight" to 8,
"nine" to 9,
)
val MIN_KEY_SIZE = TEXT_TO_DIGIT.keys.minOf { it.length }
val MAX_KEY_SIZE = TEXT_TO_DIGIT.keys.maxOf { it.length }
}
}
fun main() {
val day01 = Day01()
val input = readInputAsStringList("day01.txt")
println("Day 01, part 1: ${day01.part1(input)}")
println("Day 01, part 2: ${day01.part2(input)}")
}
| 0 | Kotlin | 0 | 0 | 18b97d650f4a90219bd6a81a8cf4d445d56ea9e8 | 1,798 | advent-of-code-2023 | MIT License |
2023/src/main/kotlin/de/skyrising/aoc2023/day5/solution.kt | skyrising | 317,830,992 | false | {"Kotlin": 411565} | package de.skyrising.aoc2023.day5
import de.skyrising.aoc.*
import it.unimi.dsi.fastutil.longs.LongArrayList
import it.unimi.dsi.fastutil.longs.LongList
val test = TestInput("""
seeds: 79 14 55 13
seed-to-soil map:
50 98 2
52 50 48
soil-to-fertilizer map:
0 15 37
37 52 2
39 0 15
fertilizer-to-water map:
49 53 8
0 11 42
42 0 7
57 7 4
water-to-light map:
88 18 7
18 25 70
light-to-temperature map:
45 77 23
81 45 19
68 64 13
temperature-to-humidity map:
0 69 1
1 0 69
humidity-to-location map:
60 56 37
56 93 4
""")
data class Range(val destStart: Long, val sourceStart: Long, val length: Long) {
val source = sourceStart until sourceStart + length
override fun toString() = "$source->${destStart..<destStart+length}"
}
class RangeMap(val ranges: List<Range>) {
private var splitPoints = LongArrayList()
private var sorted = false
init {
for (range in ranges) {
splitPoints.add(range.sourceStart)
splitPoints.add(range.sourceStart + range.length)
}
}
operator fun get(key: Long): Long {
return ranges.firstOrNull { key in it.source }?.let { it.destStart + (key - it.sourceStart) } ?: key
}
operator fun get(range: LongRange): List<LongRange> {
return range.splitAt(splitPoints).map {
get(it.first)..get(it.last)
}.toList()
}
override fun toString() = "RangeMap(${ranges.joinToString(", ")})"
}
data class Almanac(val seeds: LongList, val maps: List<RangeMap>)
fun parse(input: PuzzleInput): Almanac {
val lists = input.lines.splitOnEmpty()
return Almanac(
lists[0][0].longs(),
lists.map { list ->
RangeMap(list.subList(1, list.size).map {
val entry = it.longs()
Range(entry.getLong(0), entry.getLong(1), entry.getLong(2))
}.sortedBy { it.sourceStart })
}
)
}
@PuzzleName("If You Give A Seed A Fertilizer")
fun PuzzleInput.part1(): Any {
val almanac = parse(this)
return almanac.seeds.minOf {
almanac.maps.fold(it) { value, map -> map[value] }
}
}
fun PuzzleInput.part2(): Any {
val almanac = parse(this)
val seedRanges = almanac.seeds.chunked(2).map { it[0] until it[0] + it[1] }
return seedRanges.minOf {
almanac.maps.fold(setOf(it)) { ranges, map ->
joinRanges(ranges.flatMap(map::get))
}.first().first
}
}
| 0 | Kotlin | 0 | 0 | 19599c1204f6994226d31bce27d8f01440322f39 | 2,536 | aoc | MIT License |
src/Day07.kt | ShuffleZZZ | 572,630,279 | false | {"Kotlin": 29686} | private const val MAX_DIR_SIZE = 100_000
private const val DISK_SPACE = 70_000_000
private const val UPDATE_SIZE = 30_000_000
private data class FS(
val name: String,
val parent: FS?, // null for root dir only.
) {
val files: MutableList<Int> = mutableListOf()
val folders: MutableList<FS> = mutableListOf()
var size: Int = 0
get() {
if (field == 0) field = files.sum() + folders.sumOf { it.size }
return field
}
fun fill(instructions: List<String>): FS {
var curDir = this
for (instruction in instructions) {
when {
instruction.startsWith("cd ") -> curDir = curDir.handleCd(instruction)
instruction.startsWith("ls ") -> curDir.handleLs(instruction)
else -> error("Incorrect input")
}
}
return this
}
private fun handleCd(instruction: String): FS {
val dir = instruction.split(" ").last()
if (dir == "/") return this
return if (dir == "..") this.parent!! else this.cd(dir)
}
private fun cd(name: String) = this.folders.first { it.name == name } // presuming absolute paths unique.
private fun handleLs(instruction: String): FS {
val content = instruction.split(" ").drop(1).chunked(2).map { it.first() to it.last() }
for ((first, second) in content) {
when {
first == "dir" -> this.folders.add(FS(second, this))
first.toIntOrNull() != null -> this.files.add(first.toInt()) // presuming file names unique.
else -> error("Incorrect input")
}
}
return this
}
fun <T> map(f: (FS) -> T): List<T> {
val res = mutableListOf(f(this))
res.addAll(folders.flatMap { it.map(f) })
return res
}
fun print(indent: Int = 0) {
repeat(indent) { print(" - ") }
println(this)
folders.map { it.print(indent + 1) }
}
override fun toString() = "FS($name, $files, $size)"
}
fun getInstructions(input: List<String>) = input.joinToString(" ").split("$ ").drop(1).map(String::trim)
fun main() {
fun part1(input: List<String>) =
FS("/", null).fill(getInstructions(input)).map { it.size }.filter { it <= MAX_DIR_SIZE }.sum()
fun part2(input: List<String>): Int {
val root = FS("/", null)
root.fill(getInstructions(input))
val sizes = root.map { it.size }
val required = UPDATE_SIZE - (DISK_SPACE - sizes.first())
return sizes.filter { it >= required }.min()
}
// test if implementation meets criteria from the description, like:
val testInput = readBlocks("Day07_test").first()
check(part1(testInput) == 95_437)
check(part2(testInput) == 24_933_642)
val input = readBlocks("Day07").first()
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 5a3cff1b7cfb1497a65bdfb41a2fe384ae4cf82e | 2,904 | advent-of-code-kotlin | Apache License 2.0 |
src/day16/Day16.kt | andreas-eberle | 573,039,929 | false | {"Kotlin": 90908} | package day16
import combinations
import readInput
import java.lang.Integer.max
const val day = "16"
data class Valve(val name: String, val rate: Int, var neighbors: List<Pair<Int, Valve>> = emptyList()) {
override fun toString(): String {
return "Valve(name='$name', rate=$rate, neighbors=${neighbors.map { neighbor -> "${neighbor.first}|${neighbor.second.name}" }})"
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as Valve
if (name != other.name) return false
return true
}
override fun hashCode(): Int {
return name.hashCode()
}
}
fun main() {
fun calculatePart1Score(input: List<String>): Int {
val contractedGraph = input.parseGraph()
return findPathOne(contractedGraph.getValue("AA"), 30, 0, contractedGraph.keys)
}
fun calculatePart2Score(input: List<String>): Int {
val contractedGraph = input.parseGraph()
val startNode = contractedGraph.getValue("AA")
return findPathTwo(startNode, 26, startNode, 26, 0, contractedGraph.keys)
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("/day$day/Day${day}_test")
val input = readInput("/day$day/Day${day}")
val part1TestPoints = calculatePart1Score(testInput)
println("Part1 test points: $part1TestPoints")
check(part1TestPoints == 1651)
val part1points = calculatePart1Score(input)
println("Part1 points: $part1points")
val part2TestPoints = calculatePart2Score(testInput)
println("Part2 test points: $part2TestPoints")
check(part2TestPoints == 1707)
val part2points = calculatePart2Score(input)
println("Part2 points: $part2points")
}
fun List<String>.parseGraph(): Map<String, Valve> {
val valvesStringMap = associate {
val name = it.substringAfter("Valve ").substringBefore(" has flow")
val rate = it.substringAfter("rate=").substringBefore("; tunnel").toInt()
val neighbors = it.substringAfter("to valve").removePrefix("s ").trim().split(", ")
name to Pair(rate, neighbors)
}
val valves = valvesStringMap
.mapValues { (name, valve) -> Valve(name, valve.first) }
val contractedGraph = valvesStringMap
.mapValues { (_, valve) -> valve.second }
.contractGraph()
val graph = contractedGraph.mapValues { (name, neighbors) ->
val valve = valves.getValue(name)
valve.neighbors = neighbors
.map { (steps, neighbor) -> steps to valves.getValue(neighbor) }
.filter { it.second.rate > 0 }
valve
}.filterValues { it.rate > 0 || it.name == "AA" }
return graph
}
fun Map<String, List<String>>.contractGraph(): Map<String, List<Pair<Int, String>>> {
val graph = this.mapValues { (_, neighbors) -> neighbors.map { 1 to it } }
val contracted = graph.mapValues { (_, valve) ->
val queue = mutableListOf(0 to valve)
val visited = mutableSetOf<String>()
val allNeighbors = mutableListOf<Pair<Int, String>>()
while (queue.isNotEmpty()) {
val (currentSteps, currentValve) = queue.removeFirst()
currentValve.forEach { (steps, neighborName) ->
if (!visited.contains(neighborName)) {
visited.add(neighborName)
val neighbor = graph.getValue(neighborName)
queue.add((currentSteps + steps) to neighbor)
allNeighbors.add((currentSteps + steps) to neighborName)
}
}
}
allNeighbors
}
return contracted
}
data class State(val valve: String, val pressureRelease: Int, val remainingTime: Int, val remainingValves: Set<String>)
fun findPathOne(valve: Valve, remainingTime: Int, pressureRelease: Int, remainingValves: Set<String>): Int {
if(remainingValves.isEmpty()){
return pressureRelease
}
val neighborValues = valve.neighbors
.asSequence()
.filter { remainingValves.contains(it.second.name) }
.filter { (distance, _) -> distance < remainingTime }
.map { (distance, valve) ->
val newRemainingTime = remainingTime - distance - 1
findPathOne(valve, newRemainingTime, pressureRelease + valve.rate * newRemainingTime, remainingValves.minus(valve.name))
}
return neighborValues.maxOrNull() ?: pressureRelease
}
fun findPathTwo(v1: Valve, remainingTime1: Int, v2: Valve, remainingTime2: Int, pressureRelease: Int, remainingValves: Set<String>): Int {
val v1Neighbors = v1.neighbors.asSequence()
.filter { remainingValves.contains(it.second.name) }
.filter { (distance, _) -> distance < remainingTime1 }
val v2Neighbors = v2.neighbors.asSequence()
.filter { remainingValves.contains(it.second.name) }
.filter { (distance, _) -> distance < remainingTime2 }
val pairNeighborValues = combinations(v1Neighbors, v2Neighbors)
.filter { it.first.second.name != it.second.second.name }
.map { (step1, step2) ->
val newRemainingTime1 = remainingTime1 - step1.first - 1
val newRemainingTime2 = remainingTime2 - step2.first - 1
val newPressureRelease = pressureRelease + step1.second.rate * newRemainingTime1 + step2.second.rate * newRemainingTime2
findPathTwo(
step1.second, newRemainingTime1,
step2.second, newRemainingTime2,
newPressureRelease,
remainingValves.minus(step1.second.name).minus(step2.second.name)
)
}
val pairMax = pairNeighborValues.maxOrNull()
if (pairMax != null) {
return pairMax
}
return max(
findPathOne(v1, remainingTime1, pressureRelease, remainingValves),
findPathOne(v2, remainingTime2, pressureRelease, remainingValves)
)
}
| 0 | Kotlin | 0 | 0 | e42802d7721ad25d60c4f73d438b5b0d0176f120 | 5,990 | advent-of-code-22-kotlin | Apache License 2.0 |
src/Day11.kt | davidkna | 572,439,882 | false | {"Kotlin": 79526} |
private enum class MonkeyOp { ADD, MUL, SQUARE }
fun main() {
class Monkey(
var items: ArrayDeque<Long>,
var op: Pair<MonkeyOp, Long>,
var test: Long,
var decision: Pair<Long, Long>,
) {
var count = 0
fun add(x: Long) {
items.addLast(x)
}
fun take(): Long {
count++
return items.removeFirst()
}
}
fun solution(input: List<List<String>>, relief: Boolean, rounds: Long): Long {
val monkeys = input.map {
description ->
val items = description[1].substring(18).split(", ").map { it.toLong() }
val op = when (description[2][23]) {
'+' -> Pair(MonkeyOp.ADD, description[2].substring(25).toLong())
'*' -> {
if (description[2].substring(25) == "old") {
Pair(MonkeyOp.SQUARE, 1L)
} else {
Pair(MonkeyOp.MUL, description[2].substring(25).toLong())
}
}
else -> throw Exception("Unknown op")
}
val test = description[3].substring(21).toLong()
val decision = Pair(description[4].substring(29).toLong(), description[5].substring(30).toLong())
Monkey(ArrayDeque(items), op, test, decision)
}.toMutableList()
val modBy = monkeys.map(Monkey::test).reduce { acc, i -> acc * i }
for (round in 1..rounds) {
for (monkey in monkeys) {
for (j in 1..monkey.items.size) {
var item = monkey.take()
when (monkey.op.first) {
MonkeyOp.ADD -> item += monkey.op.second
MonkeyOp.MUL -> item *= monkey.op.second
MonkeyOp.SQUARE -> item *= item
}
if (relief) {
item /= 3.toLong()
}
item %= modBy
if (item % monkey.test == 0L) {
monkeys[monkey.decision.first.toInt()].add(item)
} else {
monkeys[monkey.decision.second.toInt()].add(item)
}
}
}
if (listOf(1, 20, 1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000).contains(round.toInt())) {
println("Round $round")
for (monkey in monkeys) {
println(" Monkey ${monkeys.indexOf(monkey)}: ${monkey.count}")
}
}
}
monkeys.sortBy(Monkey::count)
return monkeys.last().count.toLong() * monkeys[monkeys.size - 2].count.toLong()
}
val testInput = readInputDoubleNewline("Day11_test")
check(solution(testInput, true, 20) == 10605L)
check(solution(testInput, false, 10000) == 2713310158)
val input = readInputDoubleNewline("Day11")
println(solution(input, true, 20))
println(solution(input, false, 10000))
}
| 0 | Kotlin | 0 | 0 | ccd666cc12312537fec6e0c7ca904f5d9ebf75a3 | 3,074 | aoc-2022 | Apache License 2.0 |
2023/src/day08/day08.kt | Bridouille | 433,940,923 | false | {"Kotlin": 171124, "Go": 37047} | package day08
import GREEN
import LCM
import RESET
import printTimeMillis
import readInput
private fun List<String>.toMap(): Map<String, Pair<String, String>> = drop(1).let {
buildMap {
for (line in it) {
val key = line.split(" = ")[0]
val (left, right) = line.split(" = ")[1].drop(1).dropLast(1)
.split(", ")
put(key, Pair(left, right))
}
}
}
private fun solve(
map: Map<String, Pair<String, String>>,
instructions: String,
start: String,
possibleEnds: Set<String>
): Int {
var current = start
var i = 0
while (!possibleEnds.contains(current)) {
val inst = instructions[i % instructions.length]
current = if (inst == 'L') {
map[current]!!.first
} else {
map[current]!!.second
}
i += 1
}
return i
}
fun part1(input: List<String>): Int {
val instructions = input.first()
val map = input.toMap()
return solve(map, instructions, "AAA", setOf("ZZZ"))
}
fun findLCM(numbers: List<Long>): Long {
var result = numbers[0]
for (i in 1 until numbers.size) {
result = result.LCM(numbers[i])
}
return result
}
fun part2(input: List<String>): Long {
val instructions = input.first()
val map = input.toMap()
val starts = map.keys.filter { it.endsWith('A') }
val ends = map.keys.filter { it.endsWith('Z') }.toSet()
val startToEnd = mutableListOf<Long>()
for (start in starts) {
for (end in ends) {
val steps = solve(map, instructions, start, ends)
startToEnd.add(steps.toLong())
}
}
return findLCM(startToEnd)
}
fun main() {
val testInput = readInput("day08_example.txt")
val testInput2 = readInput("day08_example2.txt")
printTimeMillis { print("part1 example = $GREEN" + part1(testInput) + RESET) }
printTimeMillis { print("part2 example = $GREEN" + part2(testInput2) + RESET) }
val input = readInput("day08.txt")
printTimeMillis { print("part1 input = $GREEN" + part1(input) + RESET) }
printTimeMillis { print("part2 input = $GREEN" + part2(input) + RESET) }
}
| 0 | Kotlin | 0 | 2 | 8ccdcce24cecca6e1d90c500423607d411c9fee2 | 2,173 | advent-of-code | Apache License 2.0 |
src/Day05.kt | dannyrm | 573,100,803 | false | null | import java.util.Stack
typealias MoveInstruction = Triple<Int, Int, Int>
fun main() {
fun part1(input: List<String>): List<String> {
val (stackInput, moveInput) = obtainInputs(input)
val stacks = obtainStacks(stackInput)
parseMoves(moveInput).forEach {
for (i in 0 until it.first) {
val toMove = stacks[it.second-1].pop()
stacks[it.third-1].push(toMove)
}
}
return stacks.map { it.pop() }
}
fun part2(input: List<String>): List<String> {
val (stackInput, moveInput) = obtainInputs(input)
val stacks = obtainStacks(stackInput)
parseMoves(moveInput).forEach { move ->
val toMove = (0 until move.first).map { stacks[move.second-1].pop() }
toMove.reversed().forEach { element ->
stacks[move.third-1].push(element)
}
}
return stacks.map { it.pop() }
}
val input = readInput("Day05")
println(part1(input))
println(part2(input))
}
fun obtainInputs(input: List<String>): Pair<List<String>, List<String>> {
var currentIndex = 0
while (input[currentIndex] != "") {
currentIndex++
}
return Pair(input.subList(0, currentIndex-1), input.subList(currentIndex+1, input.size))
}
fun obtainStacks(stackInput: List<String>): Array<Stack<String>> {
val stacks = Array(9) { Stack<String>() }
stackInput.map { parseStackRow(it) }.reversed().forEach {
it.forEach { pair ->
stacks[pair.second-1].push(pair.first.toString())
}
}
return stacks
}
fun parseStackRow(input: String): List<Pair<Char, Int>> {
val crateIndexes =
input
.mapIndexed { index, c -> if (c == '[') index else -1 }
.filterNot { it == -1 }
val crateContents = crateIndexes.map { input[it+1] }
val cratePositions = crateIndexes.map { (it / 4)+1 }
return crateContents.zip(cratePositions)
}
fun parseMoves(input: List<String>): List<MoveInstruction> {
return input
.map { Regex("move (\\d+) from (\\d+) to (\\d+)").find(it)!!.groupValues }
.map { Triple(it[1].toInt(), it[2].toInt(), it[3].toInt()) }
}
| 0 | Kotlin | 0 | 0 | 9c89b27614acd268d0d620ac62245858b85ba92e | 2,213 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/Day16.kt | N-Silbernagel | 573,145,327 | false | {"Kotlin": 118156} | fun main() {
val input = readFileAsList("Day16")
println(Day16.part1(input))
println(Day16.part2(input))
}
object Day16 {
fun part1(input: List<String>): Int {
val valves = parseValves(input)
val usefulValves = valves.values
.filter { it.flowRate > 0 }
.toSet()
val distances = computeDistances(valves)
return calculateScore(30, valves.getValue("AA"), usefulValves, distances, valves = valves)
}
fun part2(input: List<String>): Int {
val valves = parseValves(input)
val usefulValves = valves.values
.filter { it.flowRate > 0 }
.toSet()
val distances = computeDistances(valves)
return calculateScore(26, valves.getValue("AA"), usefulValves, distances, myTurn = true, valves = valves)
}
private fun calculateScore(
minutes: Int,
current: Valve,
remaining: Set<Valve>,
distances: Map<Valve, Map<Valve, Int>>,
cache: MutableMap<State, Int> = mutableMapOf(),
myTurn: Boolean = false,
valves: Map<String, Valve>
): Int {
val currentScore = minutes * current.flowRate
val currentState = State(current, minutes, remaining)
return currentScore + cache.getOrPut(currentState) {
val maxCurrent = remaining
.filter { next -> distances[current]!![next]!! < minutes }
.takeIf { it.isNotEmpty() }
?.maxOf { next ->
val remainingMinutes = minutes - 1 - distances[current]!![next]!!
calculateScore(remainingMinutes, next, remaining - next, distances, cache, myTurn, valves)
}
?: 0
maxOf(maxCurrent, if (myTurn) calculateScore(26, valves.getValue("AA"), remaining, distances, valves = valves) else 0)
}
}
private fun computeDistances(valves: Map<String, Valve>): Map<Valve, Map<Valve, Int>> {
return valves.values.map { valve ->
computeDistance(valve, valves)
}.associateBy { it.keys.first() }
}
private fun computeDistance(
valve: Valve,
valves: Map<String, Valve>
): MutableMap<Valve, Int> {
val distances = mutableMapOf<Valve, Int>().withDefault { Int.MAX_VALUE }.apply { put(valve, 0) }
val toVisit = mutableListOf(valve)
while (toVisit.isNotEmpty()) {
val current = toVisit.removeFirst()
valves[current.id]!!.tunnelsTo.forEach { neighbour ->
val newDistance = distances[current]!! + 1
if (newDistance < distances.getValue(neighbour)) {
distances[neighbour] = newDistance
toVisit.add(neighbour)
}
}
}
return distances
}
private fun parseValves(input: List<String>): LinkedHashMap<String, Valve> {
val valves = LinkedHashMap<String, Valve>()
for (line in input) {
val id = line.substringAfter("Valve ")
.substringBefore(" has")
val flowRate = line.substringAfter("rate=")
.substringBefore(";")
.toInt()
val valve = Valve(id, flowRate)
valves[id] = valve
}
for (line in input) {
val id = line.substringAfter("Valve ")
.substringBefore(" has")
val tunnelsText = line.substringAfter("valve")
.substringAfter(" ")
val tunnelsToValves = tunnelsText
.split(", ")
.map { valves.getValue(it) }
valves.getValue(id).tunnelsTo = tunnelsToValves
}
return valves
}
private data class State(val current: Valve, val minutes: Int, val opened: Set<Valve>)
data class Valve(
val id: String,
val flowRate: Int,
var tunnelsTo: List<Valve> = listOf(),
var isOpen: Boolean = false
) {
override fun hashCode(): Int {
return id.hashCode()
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as Valve
if (id != other.id) return false
return true
}
override fun toString(): String {
return id
}
}}
| 0 | Kotlin | 0 | 0 | b0d61ba950a4278a69ac1751d33bdc1263233d81 | 4,419 | advent-of-code-2022 | Apache License 2.0 |
src/Day02.kt | dmarcato | 576,511,169 | false | {"Kotlin": 36664} | fun main() {
fun part1(input: List<String>): Int {
return input.sumOf {
val (a, transB) = it.split(" ")
val b = when (transB) {
"X" -> "A"
"Y" -> "B"
"Z" -> "C"
else -> throw RuntimeException()
}
val myScore = when (b) {
"A" -> 1
"B" -> 2
"C" -> 3
else -> 0
}
val victoryScore = when {
a == b -> 3
a == "A" && b == "C" -> 0
a == "B" && b == "A" -> 0
a == "C" && b == "B" -> 0
else -> 6
}
myScore + victoryScore
}
}
fun String.points(): Int = when (this) {
"A" -> 1
"B" -> 2
"C" -> 3
"X" -> 0
"Y" -> 3
"Z" -> 6
else -> throw RuntimeException()
}
val moves = listOf("A", "B", "C")
fun String.loose(): String = moves[(moves.indexOf(this) - 1).mod(3)]
fun String.win(): String = moves[(moves.indexOf(this) + 1).mod(3)]
fun String.op(op: String) = when (op) {
"X" -> loose()
"Y" -> this
"Z" -> win()
else -> throw RuntimeException()
}
fun part2(input: List<String>): Int {
return input.sumOf {
val (a, b) = it.split(" ")
a.op(b).points() + b.points()
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day02_test")
check(part1(testInput) == 15) { "part1 check failed" }
check(part2(testInput) == 12) { "part2 check failed" }
val input = readInput("Day02")
part1(input).println()
part2(input).println()
}
| 0 | Kotlin | 0 | 0 | 6abd8ca89a1acce49ecc0ca8a51acd3969979464 | 1,772 | aoc2022 | Apache License 2.0 |
src/Day04.kt | vjgarciag96 | 572,719,091 | false | {"Kotlin": 44399} | private fun IntRange.encloses(other: IntRange): Boolean {
return first <= other.first && last >= other.last
}
private fun IntRange.overlaps(other: IntRange): Boolean {
return any { other.contains(it) }
}
fun main() {
fun part1(input: List<String>): Int {
return input
.map { pair -> pair.split(",").flatMap { range -> range.split("-").map { it.toInt() } } }
.count { (firstRangeStart, firstRangeEnd, secondRangeStart, secondRangeEnd) ->
val firstRange = firstRangeStart..firstRangeEnd
val secondRange = secondRangeStart..secondRangeEnd
firstRange.encloses(secondRange) || secondRange.encloses(firstRange)
}
}
fun part2(input: List<String>): Int {
return input
.map { pair -> pair.split(",").flatMap { range -> range.split("-").map { it.toInt() } } }
.count { (firstRangeStart, firstRangeEnd, secondRangeStart, secondRangeEnd) ->
val firstRange = firstRangeStart..firstRangeEnd
val secondRange = secondRangeStart..secondRangeEnd
firstRange.overlaps(secondRange)
}
}
val testInput = readInput("Day04_test")
check(part1(testInput) == 2)
check(part2(testInput) == 4)
val input = readInput("Day04")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | ee53877877b21166b8f7dc63c15cc929c8c20430 | 1,379 | advent-of-code-2022 | Apache License 2.0 |
kotlin/src/main/kotlin/year2023/Day17.kt | adrisalas | 725,641,735 | false | {"Kotlin": 130217, "Python": 1548} | package year2023
import year2023.Day17.Direction.*
import java.util.*
fun main() {
val input = readInput("Day17")
Day17.part1(input).println()
Day17.part2(input).println()
}
object Day17 {
fun part1(input: List<String>): Int {
val heatMap = input.map { row ->
row.map { it.digitToInt() }
}
return heatMap.findMinHeatLoss(
minSteps = 1,
maxSteps = 3
)
}
fun part2(input: List<String>): Int {
val heatMap = input.map { row ->
row.map { it.digitToInt() }
}
return heatMap.findMinHeatLoss(
minSteps = 4,
maxSteps = 10
)
}
private enum class Direction { UP, DOWN, LEFT, RIGHT }
private data class Location(val row: Int, val column: Int, val direction: Direction)
private data class LocationWithCost(val location: Location, val heatLost: Int = 0) : Comparable<LocationWithCost> {
val row = location.row
val column = location.column
val direction = location.direction
override fun compareTo(other: LocationWithCost): Int {
return heatLost compareTo other.heatLost
}
}
private fun List<List<Int>>.findMinHeatLoss(minSteps: Int, maxSteps: Int): Int {
val endRow = this.lastIndex
val endColumn = this.first().lastIndex
val visited = mutableMapOf<Location, Int>()
val toVisit = PriorityQueue<LocationWithCost>()
(minSteps..maxSteps).forEach { i ->
val heatLostRight = (1..i).fold(0) { acc, column -> acc + this[0][column] }
toVisit.add(LocationWithCost(Location(0, i, RIGHT), heatLostRight))
val heatLostDown = (1..i).fold(0) { acc, row -> acc + this[row][0] }
toVisit.add(LocationWithCost(Location(i, 0, DOWN), heatLostDown))
}
while (toVisit.isNotEmpty()) {
val current = toVisit.poll()
if (current.row == endRow && current.column == endColumn) {
return current.heatLost
}
if (current.heatLost >= (visited[current.location] ?: Int.MAX_VALUE)) {
continue
}
visited[current.location] = current.heatLost
when (current.direction) {
UP, DOWN -> {
leftMovements(minSteps, maxSteps, current, visited, toVisit)
rightMovements(minSteps, maxSteps, current, endColumn, visited, toVisit)
}
LEFT, RIGHT -> {
upMovements(minSteps, maxSteps, current, visited, toVisit)
downMovements(minSteps, maxSteps, current, endRow, visited, toVisit)
}
}
}
return -1
}
private fun List<List<Int>>.downMovements(
minSteps: Int,
maxSteps: Int,
current: LocationWithCost,
endRow: Int,
visited: MutableMap<Location, Int>,
toVisit: PriorityQueue<LocationWithCost>
) {
(minSteps..maxSteps)
.filter { (current.row + it) <= endRow }
.forEach { steps ->
val heatLost = (1..steps)
.fold(current.heatLost) { acc, i ->
acc + this[current.row + i][current.column]
}
val location = LocationWithCost(
Location(current.row + steps, current.column, DOWN),
heatLost
)
if (!visited.contains(location.location)) {
toVisit.add(location)
}
}
}
private fun List<List<Int>>.upMovements(
minSteps: Int,
maxSteps: Int,
current: LocationWithCost,
visited: MutableMap<Location, Int>,
toVisit: PriorityQueue<LocationWithCost>
) {
(minSteps..maxSteps)
.filter { (current.row - it) >= 0 }
.forEach { steps ->
val heatLost = (1..steps)
.fold(current.heatLost) { acc, i ->
acc + this[current.row - i][current.column]
}
val location = LocationWithCost(
Location(current.row - steps, current.column, UP),
heatLost
)
if (!visited.contains(location.location)) {
toVisit.add(location)
}
}
}
private fun List<List<Int>>.rightMovements(
minSteps: Int,
maxSteps: Int,
current: LocationWithCost,
endColumn: Int,
visited: MutableMap<Location, Int>,
toVisit: PriorityQueue<LocationWithCost>
) {
(minSteps..maxSteps)
.filter { (current.column + it) <= endColumn }
.forEach { steps ->
val heatLost = (1..steps)
.fold(current.heatLost) { acc, i ->
acc + this[current.row][current.column + i]
}
val location = LocationWithCost(
Location(current.row, current.column + steps, RIGHT),
heatLost
)
if (!visited.contains(location.location)) {
toVisit.add(location)
}
}
}
private fun List<List<Int>>.leftMovements(
minSteps: Int,
maxSteps: Int,
current: LocationWithCost,
visited: MutableMap<Location, Int>,
toVisit: PriorityQueue<LocationWithCost>
) {
(minSteps..maxSteps)
.filter { (current.column - it) >= 0 }
.forEach { steps ->
val heatLost = (1..steps)
.fold(current.heatLost) { acc, i ->
acc + this[current.row][current.column - i]
}
val location = LocationWithCost(
Location(current.row, current.column - steps, LEFT),
heatLost
)
if (!visited.contains(location.location)) {
toVisit.add(location)
}
}
}
}
| 0 | Kotlin | 0 | 2 | 6733e3a270781ad0d0c383f7996be9f027c56c0e | 6,192 | advent-of-code | MIT License |
y2016/src/main/kotlin/adventofcode/y2016/Day11.kt | Ruud-Wiegers | 434,225,587 | false | {"Kotlin": 503769} | package adventofcode.y2016
import adventofcode.io.AdventSolution
import adventofcode.util.algorithm.IState
import adventofcode.util.algorithm.aStar
object Day11 : AdventSolution(2016, 11, "Radioisotope Thermoelectric Generators") {
override fun solvePartOne(input: String): String = aStar(FloorPlan(1,
parseConfig(input)))
?.cost
.toString()
override fun solvePartTwo(input: String): String = aStar(FloorPlan(1,
listOf(E(1, 1), E(1, 1)) + parseConfig(input)))
?.cost
.toString()
}
private fun parseConfig(input: String): List<E> {
val chips = mutableMapOf<String, Int>()
val generators = mutableMapOf<String, Int>()
input.lineSequence().forEachIndexed { floor, contents ->
contents.splitToSequence(" a ")
.map { it.substringBefore(' ') }
.forEach {
if ('-' in it)
chips[it.substringBefore('-')] = floor + 1
else generators[it] = floor + 1
}
}
return chips.map { E(it.value, generators[it.key]!!) }
}
private data class E(val chip: Int, val gen: Int) : Comparable<E> {
override fun compareTo(other: E): Int {
val ch = chip.compareTo(other.chip)
return if (ch != 0) ch else gen.compareTo(other.gen)
}
fun moveOne(oldFloor: Int, newFloor: Int): Sequence<E> = sequence {
if (oldFloor == chip) yield(copy(chip = newFloor))
if (oldFloor == gen) yield(copy(gen = newFloor))
}
fun moveBoth(oldFloor: Int, newFloor: Int): Sequence<E> =
if (gen == chip && oldFloor == chip) sequenceOf(copy(chip = newFloor, gen = newFloor))
else emptySequence()
}
private data class FloorPlan(private val elevator: Int, private val elements: List<E>) : IState {
private fun isValid(): Boolean = elevator in 1..4 &&
elements.filterNot { it.chip == it.gen }
.none { element ->
elements.any { other -> element.chip == other.gen }
}
override fun getNeighbors(): Sequence<IState> {
val seqUp = if (elevator in 1..3) getNeighbors(elevator + 1) else emptySequence()
val seqDown = if (elevator in 2..4) getNeighbors(elevator - 1) else emptySequence()
return (seqUp + seqDown).filter { it.isValid() }
}
private fun getNeighbors(newFloor: Int): Sequence<FloorPlan> = sequence {
elements.forEachIndexed { index, elementOne ->
elementOne.moveBoth(elevator, newFloor).forEach { movedPair ->
yield(copy(elevator = newFloor, elements = (elements - elementOne + movedPair).sorted()))
}
elementOne.moveOne(elevator, newFloor).forEach { movedElementOne ->
yield(copy(elevator = newFloor, elements = (elements - elementOne + movedElementOne).sorted()))
elements.filterIndexed { indexTwo, _ -> indexTwo > index }.forEach { elementTwo ->
elementTwo.moveOne(elevator, newFloor).forEach { movedElementTwo ->
yield(copy(elevator = newFloor, elements = (elements - elementOne - elementTwo + movedElementOne + movedElementTwo).sorted()))
}
}
}
}
}
override val isGoal = elements.all { it.chip == 4 && it.gen == 4 }
override val heuristic = elements.sumOf { 8 - it.chip - it.gen } / 2
}
| 0 | Kotlin | 0 | 3 | fc35e6d5feeabdc18c86aba428abcf23d880c450 | 3,006 | advent-of-code | MIT License |
src/jvmTest/kotlin/ai/hypergraph/kaliningraph/rewriting/Isosequences.kt | breandan | 245,074,037 | false | {"Kotlin": 1482924, "Haskell": 744, "OCaml": 200} | package ai.hypergraph.kaliningraph.rewriting
import ai.hypergraph.kaliningraph.types.*
import info.debatty.java.stringsimilarity.Levenshtein
// Experiment: probabilistic subgraph ismorphism as
// substring matching on a random walk trace. E.g.:
//
// GUID: ... 1ef71 258xu 289xy 1ef71 2kfg1 258xu ... \
// | | | | | | |- G1 Trace
// AZID: ... a b c a d b .../
//
// GUID: ... qq371 as3gh mai12 qq371 129vk as3gh ... \
// | | | | | | |- G2 Trace
// AZID: ... q r s q t r .../
//
// Length-5 match: abcadb == qrsqtr \
// |||||| |||||| |- Isomorphic substrings
// mnompn == 123142 /
//
// Looking for the longest common isomorphic subsequence.
// Each index has a length-k canonical form. e.g., k=4
//
// a b c b a d c...
// 1 2 3 2... 1: (1), (1, 2), (1, 2, 3), (1, 2, 3, 2)
// 1 2 1 3... 2: (1), (1, 2), (1, 2, 1), (1, 2, 1, 3)
// 1 2 3 4... 3: (1), (1, 2), (1, 2, 3), (1, 2, 3, 4)
// 1 2 3 4... 4: (1), (1, 2), (1, 2, 3), (1, 2, 3, 4)
//
// Given two graphs, may be possible to treat subgraph
// matching as a longest common subsequence problem on
// a caesar cipher of length k, where k is the window.
//
// TODO: Need a streaming algorithm, i.e. string convolution on the trace.
const val MAX_LEN = 10
fun main() {
val seq = "abcadb".toCharArray().toList()
val sls = seq.prefixSublists()
println(sls)
val enc = sls.map { (lst, idx) -> lst.canonicalize() to idx }
println(enc)
val strA = "abcadbzzzz".also { println(it) }.toList()
val strB = "qrsqtrr".also { println(it) }.toList()
val isomorphicSubstrings = isogramSearch(strA, strB)
println("Longest common isograms up to length $MAX_LEN:")
isomorphicSubstrings.forEach { (a, b) -> println("$a / $b") }
}
/**
* Turns a list into canonical form, e.g.:
* [A B B A B C C D] -> [0 1 1 0 1 2 2 3],
* [W X X W X Y Y Z] -> [0 1 1 0 1 2 2 3]
*/
fun <E> List<E>.canonicalize(): List<Int> =
fold(listOf<Int>() to setOf<E>()) { (l, s), e ->
if (e in s) l + s.indexOf(e) to s
else l + s.size to s + e
}.first
/**
* Indexes all isomorphic subsequences up to [MAX_LEN].
*/
fun <E> List<E>.isogramIndex(): Map<List<Int>, List<Int>> =
prefixSublists().fold(mutableMapOf()) { map, (lst, idx) ->
val key = lst.canonicalize() // Subgraph fingerprint
map[key] = map.getOrDefault(key, listOf()) + idx
map
}
/**
* Takes a random walk [trace] and a [query], and returns a
* list of closest matches according to Levenshtein distance.
*/
fun <E, F> isogramSearch(
trace: List<E>, query: List<F>,
takeTopK: Int = 4,
metric: (List<Int>) -> Int = {
val queryCF = query.canonicalize().joinToString()
val candidate = it.joinToString()
Levenshtein().distance(queryCF, candidate).toInt()
}
): List<Π2<List<E>, List<F>>> {
val traceA = trace.isogramIndex()
val traceB = query.isogramIndex()
val lcs = (traceA.keys intersect traceB.keys).sortedBy(metric)
return lcs.map {
val a = traceA[it]!!.map { idx -> trace.subList(idx, idx + it.size) }
val b = traceB[it]!!.map { idx -> query.subList(idx, idx + it.size) }
a.first() to b.first() // Take first occurrence of n matches
}.take(takeTopK)
}
fun <E> List<E>.sublists(k: Int = MAX_LEN) =
(1 until size + k).map {
subList((it - k).coerceAtLeast(0), it.coerceAtMost(size)) to
(it - k).coerceAtLeast(0)
}
fun <E> List<E>.prefixes() = (1..size).map { subList(0, it) }
fun <E> List<E>.prefixSublists() =
sublists().map { (lst, idx) -> lst.prefixes().map { it to idx } }
.flatten().toSet() | 0 | Kotlin | 8 | 100 | c755dc4858ed2c202c71e12b083ab0518d113714 | 3,689 | galoisenne | Apache License 2.0 |
src/day04/day04.kt | tmikulsk1 | 573,165,106 | false | {"Kotlin": 25281} | package day04
import readInput
/**
* Advent of Code 2022 - Day 4
* @author tmikulsk1
*/
fun main() {
val inputCleanupSections = readInput("day04/input.txt").readLines()
val cleanupSectionsRanges = splitCleanupSectionsInputByRanges(inputCleanupSections)
getPuzzle1TotalContainedInRanges(cleanupSectionsRanges)
getPuzzle2TotalCommonSections(cleanupSectionsRanges)
}
/**
* Puzzle 1: get only pairs that are contained in range
*/
fun getPuzzle1TotalContainedInRanges(cleanupSectionsRanges: List<Pair<List<Int>, List<Int>>>) {
var counter = 0
cleanupSectionsRanges.forEach { section ->
if (section.first.containsOrIsContainedIn(section.second)) {
counter++
}
}
println(counter)
}
/**
* Puzzle 2: get pairs with have common sections
*/
fun getPuzzle2TotalCommonSections(cleanupSectionsRanges: List<Pair<List<Int>, List<Int>>>) {
var counter = 0
cleanupSectionsRanges.forEach { section ->
val intersectValue = section.first.toSet() intersect section.second.toSet()
if (intersectValue.isNotEmpty()) counter++
}
println(counter)
}
fun splitCleanupSectionsInputByRanges(inputCleanupSections: List<String>): List<Pair<List<Int>, List<Int>>> {
return inputCleanupSections
.map { section ->
section.split(",")
}
.map(List<String>::toHashSet)
.map { groupedSectionSet ->
val firstGroup = groupedSectionSet.first().split("-")
val secondGroup = groupedSectionSet.last().split("-")
val firstGroupRange = listOf(
firstGroup.firstInteger()..firstGroup.lastInteger()
).flatten()
val secondGroupRange = listOf(
secondGroup.firstInteger()..secondGroup.lastInteger()
).flatten()
return@map Pair(firstGroupRange, secondGroupRange)
}
}
fun List<Int>.containsOrIsContainedIn(listToCompare: List<Int>): Boolean {
return containsAll(listToCompare) || listToCompare.containsAll(this)
}
fun List<String>.firstInteger() = first().toInt()
fun List<String>.lastInteger() = last().toInt()
| 0 | Kotlin | 0 | 1 | f5ad4e601776de24f9a118a0549ac38c63876dbe | 2,142 | AoC-22 | Apache License 2.0 |
src/Day11.kt | inssein | 573,116,957 | false | {"Kotlin": 47333} | data class Operation(private val input: String) {
private val suffix = input.substringAfter("new = old ")
private val operator = suffix[0]
private val rawAmount = suffix.substring(2)
operator fun invoke(value: Long): Long {
val amount = rawAmount.let {
if (it == "old") value else it.toLong()
}
return when (operator) {
'+' -> value + amount
'*' -> value * amount
else -> error("Invalid operator")
}
}
}
data class Monkey(
val items: MutableList<Long>,
val operation: Operation,
val test: (Long) -> Int,
val denominator: Int,
) {
var inspections: Long = 0
companion object {
fun from(input: List<String>): Monkey {
val items = input[1].substringAfter(" Starting items: ").split(", ").map { it.toLong() }
val operation = Operation(input[2].substringAfter(" Operation: "))
val denominator = input[3].substringAfter(" Test: divisible by ").toInt()
val ifTrue = input[4].substringAfter(" If true: throw to monkey ").toInt()
val ifFalse = input[5].substringAfter(" If false: throw to monkey ").toInt()
val test: (Long) -> Int = { if (it % denominator == 0L) ifTrue else ifFalse }
return Monkey(items.toMutableList(), operation, test, denominator)
}
}
}
fun main() {
fun List<String>.buildMonkeys() =
this.chunked(7).fold(listOf<Monkey>()) { acc, it -> acc.plus(Monkey.from(it)) }
fun List<Monkey>.toBusiness() =
this.map { it.inspections }.sortedDescending().take(2).reduce { it, acc -> it * acc }
fun List<Monkey>.round(decompressor: (Long) -> Long) {
this.forEach { monkey ->
monkey.items.forEach { item ->
val worry = decompressor(monkey.operation(item))
this[monkey.test(worry)].items.add(worry)
monkey.inspections++
}
monkey.items.clear()
}
}
fun part1(input: List<String>): Long {
val monkeys = input.buildMonkeys()
repeat(20) {
monkeys.round { it / 3 }
}
return monkeys.toBusiness()
}
fun part2(input: List<String>): Long {
val monkeys = input.buildMonkeys()
val stuff = monkeys.map { it.denominator }.reduce { acc, it -> acc * it }
repeat(10000) {
monkeys.round { it % stuff }
}
return monkeys.toBusiness()
}
val testInput = readInput("Day11_test")
check(part1(testInput) == 10605L)
check(part2(testInput) == 2713310158L)
val input = readInput("Day11")
println(part1(input)) // 69918
println(part2(input)) // 19573408701
}
| 0 | Kotlin | 0 | 0 | 095d8f8e06230ab713d9ffba4cd13b87469f5cd5 | 2,750 | advent-of-code-2022 | Apache License 2.0 |
src/Utils.kt | kipwoker | 572,884,607 | false | null | import java.io.File
import kotlin.math.max
import kotlin.math.min
fun readInput(name: String) = File("src", "$name.txt")
.readLines()
fun <T> assert(actual: T, expected: T) {
if (actual == expected) {
return
}
throw Exception("Actual $actual Expected $expected")
}
data class Interval(val start: Int, val end: Int) {
companion object {
fun merge(intervals: List<Interval>): List<Interval> {
var sorted = intervals.sortedBy { i -> i.start }
var hasOverlap = true
while (hasOverlap && sorted.size > 1) {
hasOverlap = false
val bucket = sorted.toMutableList<Interval?>()
var i = 0
while (i < bucket.size - 1) {
if (bucket[i] != null && bucket[i + 1] != null && bucket[i]!!.hasOverlap(bucket[i + 1]!!)) {
hasOverlap = true
val merged = bucket[i]!!.merge(bucket[i + 1]!!)
bucket[i] = null
bucket[i + 1] = merged
}
i += 1
}
sorted = bucket.filterNotNull()
}
return sorted
}
}
fun hasFullOverlap(other: Interval): Boolean {
return hasFullOverlap(this, other) || hasFullOverlap(other, this)
}
fun hasOverlap(other: Interval): Boolean {
return hasOverlap(this, other) || hasOverlap(other, this)
}
fun merge(other: Interval): Interval {
return Interval(min(this.start, other.start), max(this.end, other.end))
}
private fun hasFullOverlap(x: Interval, y: Interval): Boolean {
return x.start >= y.start && x.end <= y.end
}
private fun hasOverlap(x: Interval, y: Interval): Boolean {
return x.start >= y.start && x.start <= y.end
}
fun countPoints(excludePoints: Set<Int>? = null): Int {
var count = end - start + 1
if (excludePoints == null) {
return count
}
for (p in excludePoints) {
if (p in start..end) {
--count
}
}
return count
}
fun minStart(x: Int): Interval {
if (x < start) {
return Interval(x, end)
}
return this
}
fun maxEnd(x: Int): Interval {
if (x > end) {
return Interval(start, x)
}
return this
}
fun isInside(t: Int): Boolean {
return t in start..end
}
}
data class Point(val x: Int, val y: Int) {
fun sum(other: Point): Point {
return Point(this.x + other.x, this.y + other.y)
}
}
enum class Direction {
Up,
Down,
Left,
Right
}
object DirectionManager {
private val directions = arrayOf(Direction.Up, Direction.Right, Direction.Down, Direction.Left)
fun turn(current: Direction, target: Direction): Direction {
if (target == Direction.Down || target == Direction.Up) {
throw RuntimeException("Illegal action $current -> $target")
}
val d = if (target == Direction.Left) -1 else 1
val index = (directions.indexOf(current) + d + directions.size) % directions.size
return directions[index]
}
}
enum class Sign {
Eq,
Less,
More
}
enum class ExecutionMode {
Test1,
Test2,
Exec1,
Exec2
}
| 0 | Kotlin | 0 | 0 | d8aeea88d1ab3dc4a07b2ff5b071df0715202af2 | 3,392 | aoc2022 | Apache License 2.0 |
src/Day02.kt | psy667 | 571,468,780 | false | {"Kotlin": 23245} | enum class Fig(val score: Int) {
Rock(1), Paper(2), Scissors(3)
}
enum class Outcome(val score: Int) {
Lose(0), Draw(3), Win(6)
}
fun main() {
val id = "02"
fun String.toFig() = when(this) {
"A", "X" -> Fig.Rock
"B", "Y" -> Fig.Paper
"C", "Z" -> Fig.Scissors
else -> throw Error()
}
fun loserTo(it: Fig) = when(it) {
Fig.Rock -> Fig.Scissors
Fig.Scissors -> Fig.Paper
Fig.Paper -> Fig.Rock
}
fun getOutcome(me: Fig, op: Fig) = when {
me == op -> Outcome.Draw
loserTo(me) == op -> Outcome.Win
else -> Outcome.Lose
}
fun part1(input: List<String>): Int {
return input.sumOf {
val (op, me) = it.split(" ").map(String::toFig)
getOutcome(me, op).score + me.score
}
}
fun String.toOutcome() = when(this) {
"X" -> Outcome.Lose
"Y" -> Outcome.Draw
"Z" -> Outcome.Win
else -> throw Error()
}
fun part2(input: List<String>): Int {
return input
.map { it.split(" ") }.sumOf {
val op = it[0].toFig()
val outcome = it[1].toOutcome()
val me = Fig
.values()
.find { me -> getOutcome(me, op) == outcome }!!
me.score + outcome.score
}
}
val testInput = readInput("Day${id}_test")
check(part1(testInput) == 15)
val input = readInput("Day${id}")
println("==== DAY $id ====")
println("Part 1: ${part1(input)}")
println("Part 2: ${part2(input)}")
}
| 0 | Kotlin | 0 | 0 | 73a795ed5e25bf99593c577cb77f3fcc31883d71 | 1,612 | advent-of-code-2022 | Apache License 2.0 |
src/Day04.kt | dakr0013 | 572,861,855 | false | {"Kotlin": 105418} | import kotlin.test.assertEquals
fun main() {
fun part1(input: List<String>): Int {
return input
.map { pair ->
val ranges =
pair.split(",").map { range -> range.split("-").let { it[0].toInt()..it[1].toInt() } }
ranges[0] to ranges[1]
}
.map {
if (it.first.contains(it.second) || it.second.contains(it.first)) {
1
} else {
0
}
}
.sum()
}
fun part2(input: List<String>): Int {
return input
.map { pair ->
val ranges =
pair.split(",").map { range -> range.split("-").let { it[0].toInt()..it[1].toInt() } }
ranges[0] to ranges[1]
}
.map {
if (it.first.overlaps(it.second)) {
1
} else {
0
}
}
.sum()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day04_test")
assertEquals(2, part1(testInput))
assertEquals(4, part2(testInput))
val input = readInput("Day04")
println(part1(input))
println(part2(input))
}
private fun IntRange.contains(other: IntRange) =
other.first >= this.first && other.last <= this.last
private fun IntRange.overlaps(other: IntRange) =
contains(other.first) || contains(other.last) || other.contains(first) || other.contains(last)
| 0 | Kotlin | 0 | 0 | 6b3adb09f10f10baae36284ac19c29896d9993d9 | 1,397 | aoc2022 | Apache License 2.0 |
2k23/aoc2k23/src/main/kotlin/18.kt | papey | 225,420,936 | false | {"Rust": 88237, "Kotlin": 63321, "Elixir": 54197, "Crystal": 47654, "Go": 44755, "Ruby": 24620, "Python": 23868, "TypeScript": 5612, "Scheme": 117} | package d18
import input.read
import kotlin.math.absoluteValue
fun main() {
println("Part 1: ${part1(read("18.txt"))}")
println("Part 2: ${part2(read("18.txt"))}")
}
fun part1(input: List<String>): Long {
val instructions = input.map { line ->
line.split(" ").let {
val dir = when(it[0]) {
"R" -> Direction.Right
"U" -> Direction.Up
"L" -> Direction.Left
"D" -> Direction.Down
else -> throw IllegalStateException("oops")
}
Instruction(dir, it[1].toLong())
}
}
return area(instructions)
}
fun part2(input: List<String>): Long {
val regex = Regex("""\(#([0-9A-Fa-f]{5})(\d)\)""")
val instructions = input.map { line ->
val values = regex.find(line)!!.groupValues
val quantity = values[1].toLong(16)
val dir = when(values[2]) {
"0" -> Direction.Right
"1" -> Direction.Down
"2" -> Direction.Left
"3" -> Direction.Up
else -> throw IllegalStateException("oops")
}
Instruction(dir, quantity)
}
return area(instructions)
}
fun area(instructions: List<Instruction>): Long =
instructions.fold(State(0, 0, Point(0, 0))) { acc, inst ->
val edge = acc.pos.move(inst)
val area = acc.area + (acc.pos.x * edge.y - edge.x * acc.pos.y)
val perimeter = acc.perimeter + (edge.x - acc.pos.x).absoluteValue + (edge.y - acc.pos.y).absoluteValue
State(area, perimeter, edge)
}.let { (area, perimeter, _) ->
(area.absoluteValue + perimeter) / 2 + 1
}
data class State (val area: Long, val perimeter: Long, val pos: Point)
enum class Direction {
Up,
Down,
Left,
Right;
}
data class Instruction(val dir: Direction, val quantity: Long)
data class Point(val x: Long, val y: Long) {
fun move(inst: Instruction): Point =
when(inst.dir) {
Direction.Up -> Point(x - inst.quantity, y)
Direction.Down -> Point(x + inst.quantity, y)
Direction.Right -> Point(x, y + inst.quantity)
Direction.Left -> Point(x, y - inst.quantity)
}
}
| 0 | Rust | 0 | 3 | cb0ea2fc043ebef75aff6795bf6ce8a350a21aa5 | 2,210 | aoc | The Unlicense |
src/main/kotlin/day10/Day10.kt | cyril265 | 433,772,262 | false | {"Kotlin": 39445, "Java": 4273} | package day10
import readToList
import java.util.*
private val input = readToList("day10.txt")
.map { it.toCharArray() }
fun main() {
println(part1())
println(part2())
}
private fun part1(): Int {
return input.sumOf { line -> calcInvalidLinePoints(line) }
}
private fun part2(): Long {
val scores = mutableListOf<Long>()
input.filter { line -> calcInvalidLinePoints(line) == 0 }
.forEach { line ->
val stack = Stack<Char>()
for (char in line) {
if (isOpenBracket(char)) {
stack.push(char)
} else {
stack.pop()
}
}
if (stack.isNotEmpty()) {
val lineScore = stack
.reversed()
.map { char -> openToCloseMap[char]!! }
.fold(0L) { acc, char -> acc * 5 + p2ScoreMap[char]!! }
scores.add(lineScore)
}
}
return calculateMedian(scores)
}
private fun calcInvalidLinePoints(line: CharArray): Int {
var points = 0
val stack = Stack<Char>()
for (char in line) {
if (isOpenBracket(char)) {
stack.push(char)
} else {
val openBracket = stack.pop()
val expectedClose = openToCloseMap[openBracket]
if (char != expectedClose) {
points += p1ScoreMap[char]!!
}
}
}
return points
}
private fun isOpenBracket(c: Char) = openToCloseMap.keys.contains(c)
private val openToCloseMap = mapOf(
'{' to '}',
'(' to ')',
'[' to ']',
'<' to '>'
)
private val p1ScoreMap = mapOf(
')' to 3,
']' to 57,
'}' to 1197,
'>' to 25137
)
private val p2ScoreMap = mapOf(
')' to 1,
']' to 2,
'}' to 3,
'>' to 4
)
private fun calculateMedian(scores: List<Long>): Long {
val sorted = scores.sorted()
val size = sorted.size
val median = if (size % 2 == 0) {
(sorted[size / 2] + sorted[size / 2 - 1]) / 2.0
} else {
sorted[size / 2].toDouble()
}.toLong()
return median
}
| 0 | Kotlin | 0 | 0 | 1ceda91b8ef57b45ce4ac61541f7bc9d2eb17f7b | 2,133 | aoc2021 | Apache License 2.0 |
src/Day02.kt | Narmo | 573,031,777 | false | {"Kotlin": 34749} | private enum class Shape(val score: Int) {
ROCK(1), PAPER(2), SCISSORS(3);
fun beats(other: Shape): Boolean? = when {
this == other -> null // this means draw
this == PAPER && other == ROCK -> true
this == SCISSORS && other == PAPER -> true
this == ROCK && other == SCISSORS -> true
else -> false
}
fun fromOutcome(outcome: Outcome): Shape = Shape.values().first {
outcome == Outcome.fromBoolean(it.beats(this))
}
companion object {
fun fromString(string: String): Shape = when (string) {
"A", "X" -> ROCK
"B", "Y" -> PAPER
"C", "Z" -> SCISSORS
else -> throw IllegalArgumentException("Invalid shape: $string")
}
}
}
private enum class Outcome(val score: Int) {
WIN(6), DRAW(3), LOSE(0);
companion object {
fun fromString(string: String): Outcome = when (string) {
"X" -> LOSE
"Y" -> DRAW
"Z" -> WIN
else -> throw IllegalArgumentException("Invalid outcome: $string")
}
fun fromBoolean(boolean: Boolean?): Outcome = when (boolean) {
true -> WIN
false -> LOSE
null -> DRAW
}
}
}
fun main() {
fun part1(input: List<String>): Int = input.fold(0) { score, line ->
score + line.split(" ").map { Shape.fromString(it) }.run {
when (second().beats(first())) {
true -> Outcome.WIN.score + second().score
false -> second().score
null -> Outcome.DRAW.score + second().score
}
}
}
fun part2(input: List<String>): Int = input.fold(0) { score, line ->
score + line.split(" ").let { (shape, outcome) ->
Shape.fromString(shape).run {
Outcome.fromString(outcome).run {
this.score + fromOutcome(this).score
}
}
}
}
val testInput = readInput("Day02_test")
check(part1(testInput) == 15)
check(part2(testInput) == 12)
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 335641aa0a964692c31b15a0bedeb1cc5b2318e0 | 1,804 | advent-of-code-2022 | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.