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/main/kotlin/mirecxp/aoc23/day04/Day04.kt
MirecXP
726,044,224
false
{"Kotlin": 42343}
package mirecxp.aoc23.day04 import mirecxp.aoc23.readInput //https://adventofcode.com/2023/day/4 class Day04(private val inputPath: String) { private val lines: List<String> = readInput(inputPath) class Card(val id: Int, val wins: Int) val allCards = mutableMapOf<Int, MutableList<Card>>() fun solve(): String { println("Solving day 4 for ${lines.size} cards [$inputPath]") var sumPoints = 0L //part 1 lines.forEach { line -> line.split(":").apply { val id = get(0).substringAfter("Card ").trim().toInt() val cardSplit = get(1).split(" | ") val winningNumbers = cardSplit[0].toNumList() val numbersToCheck = cardSplit[1].toNumList() val matchedNumbers = numbersToCheck.intersect(winningNumbers) val winCount = matchedNumbers.size val points = when (winCount) { 0 -> 0 else -> 1 shl (winCount - 1) } println("$id : $points points ($winCount wins)") val card = Card(id, winCount) allCards[id] = mutableListOf(card) sumPoints += points } } var cardSum = 0L //part 2 allCards.forEach { cardGroup -> cardGroup.value.forEach { card -> repeat(card.wins) { num -> val i = card.id + num + 1 allCards[i]?.let { group -> group.add(group.first()) } } } } allCards.forEach { cardSum += it.value.size } val solution = "$sumPoints / $cardSum" println(solution) return solution } } fun String.toNumList() = split(" ") .filter { it.isNotEmpty() } .map { it.toLong() } fun main(args: Array<String>) { val testProblem = Day04("test/day04t") check(testProblem.solve() == "13 / 30") val problem = Day04("real/day04a") problem.solve() }
0
Kotlin
0
0
6518fad9de6fb07f28375e46b50e971d99fce912
2,075
AoC-2023
MIT License
y2022/src/main/kotlin/adventofcode/y2022/Day23.kt
Ruud-Wiegers
434,225,587
false
{"Kotlin": 503769}
package adventofcode.y2022 import adventofcode.io.AdventSolution import adventofcode.util.collections.cycle import adventofcode.util.vector.Direction import adventofcode.util.vector.Vec2 object Day23 : AdventSolution(2022, 23, "Unstable Diffusion") { override fun solvePartOne(input: String): Int { val elves = solve(input).elementAt(10) val width = elves.maxOf { it.x } - elves.minOf { it.x } + 1 val height = elves.maxOf { it.y } - elves.minOf { it.y } + 1 return width * height - elves.size } override fun solvePartTwo(input: String): Int = solve(input).zipWithNext().indexOfFirst { it.first == it.second } + 1 private fun solve(input: String) = cycle().scan(parsePositions(input)) { oldPositions, directions -> val new = oldPositions.toMutableSet() oldPositions.groupBy { elf -> propose(elf, oldPositions, directions) } .asSequence() .filter { it.value.size == 1 } .forEach { (k, v) -> new.remove(v.first()) new.add(k) } new } } private fun propose(elf: Vec2, positions: Set<Vec2>, directions: List<Direction>): Vec2 { val new = directions.mapNotNull { val test = when (it) { Direction.UP -> listOf(Vec2(-1, -1), Vec2(0, -1), Vec2(1, -1)) Direction.RIGHT -> listOf(Vec2(1, -1), Vec2(1, 0), Vec2(1, 1)) Direction.DOWN -> listOf(Vec2(-1, 1), Vec2(0, 1), Vec2(1, 1)) Direction.LEFT -> listOf(Vec2(-1, -1), Vec2(-1, 0), Vec2(-1, 1)) } (elf + it.vector).takeIf { test.none { elf + it in positions } } } return if (new.size in 1..3) new.first() else elf } private fun parsePositions(input: String) = input .lineSequence() .flatMapIndexed { y, row -> row.mapIndexedNotNull { x, ch -> Vec2(x, y).takeIf { ch == '#' } } }.toSet() private fun cycle() = listOf(Direction.UP, Direction.DOWN, Direction.LEFT, Direction.RIGHT) .cycle() .windowed(4)
0
Kotlin
0
3
fc35e6d5feeabdc18c86aba428abcf23d880c450
2,068
advent-of-code
MIT License
src/main/kotlin/Day16.kt
lanrete
244,431,253
false
null
data class Interval(val start: Int, val end: Int) { override fun toString() = "$start ~ $end" } object Day16 : Solver() { data class IntervalTreeNode( val start: Int, val end: Int, var sum: Int = 0, var leftChild: IntervalTreeNode? = null, var rightChild: IntervalTreeNode? = null ) data class FFTIntervals(val positiveInterval: List<Interval>, val negativeInterval: List<Interval>) private fun buildTree(start: Int, end: Int, sequence: List<Int>): IntervalTreeNode? { if (start > end) return null if (start == end) return IntervalTreeNode(start = start, end = end, sum = sequence[start]) val root = IntervalTreeNode(start = start, end = end) val mid = start + (end - start) / 2 val left = buildTree(start = start, end = mid, sequence = sequence) val right = buildTree(start = mid + 1, end = end, sequence = sequence) root.leftChild = left root.rightChild = right val leftSum = left?.sum ?: 0 val rightSum = right?.sum ?: 0 root.sum = leftSum + rightSum return root } override val day: Int = 16 override val inputs: List<String> = getInput() private val startSequence = inputs[0].map { it - '0' } private val inputLength = startSequence.size private var root = buildTree(0, end = inputLength - 1, sequence = startSequence)!! private fun getIntervalSum(root: IntervalTreeNode?, start: Int, end: Int): Int { if (root == null) return 0 if (end < root.start || start > root.end) return 0 if (root.start == start && root.end == end) return root.sum val mid = (root.start + root.end) / 2 var leftSum = 0 var rightSum = 0 if (start <= mid) { leftSum = if (mid < end) { getIntervalSum(root.leftChild, start = start, end = mid) } else { getIntervalSum(root.leftChild, start = start, end = end) } } if (mid < end) { rightSum = if (start <= mid) { getIntervalSum(root.rightChild, start = mid + 1, end = end) } else { getIntervalSum(root.rightChild, start = start, end = end) } } return leftSum + rightSum } private fun getIntervals(digit: Int, length: Int): FFTIntervals { val positiveIntervals = ((0 + digit - 1)..length step digit * 4).map { val end = it + digit - 1 if (end < length) Interval(it, it + digit - 1) else Interval(it, length - 1) } val negativeInterval = ((0 + digit * 3 - 1)..length step digit * 4).map { val end = it + digit - 1 if (end < length) Interval(it, it + digit - 1) else Interval(it, length - 1) } return FFTIntervals(positiveIntervals, negativeInterval) } private fun frequencyTransform(length: Int): List<Int> { val newSequence = (0 until length).map { val fftIntervals = getIntervals(it + 1, length) val positiveInterval = fftIntervals.positiveInterval val negativeInterval = fftIntervals.negativeInterval val positiveSum = positiveInterval .map { interval -> getIntervalSum(root, interval.start, interval.end) } .sum() val negativeSum = negativeInterval .map { interval -> getIntervalSum(root, interval.start, interval.end) } .sum() (positiveSum - negativeSum).toString().last() - '0' } root = IntervalTreeNode(0, 1) System.gc() root = buildTree(0, length - 1, newSequence)!! return newSequence } override fun question1(): String { var currentSequence = startSequence repeat(100) { currentSequence = frequencyTransform(inputLength) } return currentSequence.subList(0, 8).joinToString("") } override fun question2(): String { val refinedInput = List(10000) { startSequence }.flatten() val refinedInputLength = refinedInput.size val offset = refinedInput.subList(0, 7).joinToString("").toInt() root = buildTree(0, end = refinedInputLength - 1, sequence = refinedInput)!! var currentSequence = refinedInput repeat(100) { currentSequence = frequencyTransform(refinedInputLength) } return currentSequence.subList(offset, offset + 8).joinToString("") } } fun main() { Day16.solve() }
0
Kotlin
0
1
15125c807abe53230e8d0f0b2ca0e98ea72eb8fd
4,615
AoC2019-Kotlin
MIT License
y2019/src/main/kotlin/adventofcode/y2019/Day24.kt
Ruud-Wiegers
434,225,587
false
{"Kotlin": 503769}
package adventofcode.y2019 import adventofcode.io.AdventSolution import adventofcode.util.collections.firstDuplicate import adventofcode.util.vector.Vec3 fun main() = Day24.solve() object Day24 : AdventSolution(2019, 24, "Planet of Discord") { override fun solvePartOne(input: String) = generateSequence(ConwayGrid(input), ConwayGrid::next) .firstDuplicate() .resourceValue() private data class ConwayGrid(private val grid: List<List<Boolean>>) { constructor(input: String) : this(input.lines().map { it.map { it == '#' } }) fun resourceValue() = grid.flatten().map { if (it) 1L else 0L }.reversed().fold(0L) { acc, it -> acc * 2 + it } fun next() = grid.indices.map { y -> grid[0].indices.map { x -> next(x, y) } }.let(::ConwayGrid) private fun next(x: Int, y: Int): Boolean = if (grid[y][x]) adjacentBugs(x, y) == 1 else adjacentBugs(x, y) in 1..2 private fun adjacentBugs(x: Int, y: Int) = bugCount(x + 1, y) + bugCount(x - 1, y) + bugCount(x, y + 1) + bugCount(x, y - 1) private fun bugCount(x: Int, y: Int) = if (grid.getOrNull(y)?.getOrNull(x) == true) 1 else 0 } override fun solvePartTwo(input: String) = generateSequence(ErisianGrid(toGrid(input)), ErisianGrid::next) .drop(200) .first() .grid .size private fun toGrid(input: String) = sequence { val g = input.lines() for (y in 0 until 5) for (x in 0 until 5) if (g[y][x] == '#') yield(Vec3(x, y, 0)) }.toSet() private data class ErisianGrid(val grid: Set<Vec3>) { val zs: IntRange by lazy { grid.minOf(Vec3::z) - 1..grid.maxOf(Vec3::z) + 1 } fun next() = sequence { for (z in zs) for (y in 0..4) for (x in 0..4) yield(Vec3(x, y, z)) } .filter { next(it) } .toSet() .let { ErisianGrid(it) } private fun next(sq: Vec3): Boolean = sq.neighbors() in if (sq in grid) 1..1 else 1..2 private fun Vec3.neighbors() = left() + right() + up() + down() private fun Vec3.left() = when { x == 2 && y == 2 -> 0 x == 3 && y == 2 -> (0..4).sumOf { countBugs(Vec3(4, it, z + 1)) } x == 0 -> countBugs(Vec3(1, 2, z - 1)) else -> countBugs(copy(x = x - 1)) } private fun Vec3.right() = when { x == 2 && y == 2 -> 0 x == 1 && y == 2 -> (0..4).sumOf { countBugs(Vec3(0, it, z + 1)) } x == 4 -> countBugs(Vec3(3, 2, z - 1)) else -> countBugs(copy(x = x + 1)) } private fun Vec3.up() = when { y == 2 && x == 2 -> 0 y == 3 && x == 2 -> (0..4).sumOf { countBugs(Vec3(it, 4, z + 1)) } y == 0 -> countBugs(Vec3(2, 1, z - 1)) else -> countBugs(copy(y = y - 1)) } private fun Vec3.down() = when { y == 2 && x == 2 -> 0 y == 1 && x == 2 -> (0..4).sumOf { countBugs(Vec3(it, 0, z + 1)) } y == 4 -> countBugs(Vec3(2, 3, z - 1)) else -> countBugs(copy(y = y + 1)) } private fun countBugs(sq: Vec3) = if (sq in grid) 1 else 0 } }
0
Kotlin
0
3
fc35e6d5feeabdc18c86aba428abcf23d880c450
3,535
advent-of-code
MIT License
src/main/kotlin/_2018/Day8.kt
thebrightspark
227,161,060
false
{"Kotlin": 548420}
package _2018 import aocRun import java.util.concurrent.atomic.AtomicInteger fun main() { aocRun(puzzleInput) { return@aocRun sumMetadata(parseTree(it)) } aocRun(puzzleInput) { return@aocRun calcNodeValue(parseTree(it)) } } private fun parseTree(input: String): Node { val iterator = input.split(" ").map { it.toInt() }.iterator() return readNode(iterator, null) } private fun readNode(inputIterator: Iterator<Int>, parent: Node?): Node { val numChildren = inputIterator.next() val numMetadata = inputIterator.next() val node = Node(parent) if (numChildren > 0) repeat(numChildren) { node.children += readNode(inputIterator, node) } if (numMetadata > 0) repeat(numMetadata) { node.metadata += inputIterator.next() } return node } private fun sumMetadata(node: Node): Int { val sum = AtomicInteger(0) sumMetadata(node, sum) return sum.get() } private fun sumMetadata(node: Node, cumulativeSum: AtomicInteger) { cumulativeSum.addAndGet(node.metadata.sum()) node.children.forEach { sumMetadata(it, cumulativeSum) } } private fun calcNodeValue(node: Node): Int = if (node.children.isEmpty()) node.metadata.sum() else node.metadata .mapNotNull { node.children.getOrNull(it - 1) } .map { calcNodeValue(it) } .sum() private data class Node( val parent: Node?, val children: MutableList<Node> = mutableListOf(), val metadata: MutableList<Int> = mutableListOf() ) private const val puzzleInput = "8 11 7 2 4 4 3 6 1 5 0 8 1 6 1 1 5 4 7 3 1 2 3 1 1 1 5 0 9 9 5 2 8 7 5 7 1 4 2 2 1 1 3 1 6 0 8 6 1 8 1 1 5 4 1 3 3 3 1 3 3 1 4 1 2 2 3 3 4 1 9 0 10 1 9 5 2 6 5 6 5 7 1 2 3 1 3 3 2 3 1 1 1 7 0 11 2 5 1 1 8 4 9 1 5 4 7 3 1 3 3 1 1 3 1 7 0 8 5 2 7 8 5 4 1 1 1 1 3 2 1 3 2 3 3 3 2 3 7 1 8 0 9 2 5 4 6 7 2 9 2 1 3 1 3 3 2 1 2 2 1 5 0 9 1 1 6 1 4 2 9 4 3 1 1 2 1 3 1 6 0 9 7 2 9 4 4 5 1 8 6 1 3 1 3 1 1 5 3 3 4 4 3 4 3 7 1 6 0 11 1 3 1 1 1 7 3 8 2 1 6 1 2 1 3 1 1 1 9 0 7 7 2 1 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2 1 6 0 7 5 5 6 5 4 1 8 1 1 2 2 1 2 3 3 5 5 2 3 2 3 5 1 6 0 9 4 6 5 8 4 5 1 1 5 1 3 1 1 3 3 1 7 0 10 3 2 1 9 3 2 3 4 9 1 1 3 1 2 1 1 2 1 8 0 9 9 1 3 1 1 4 4 9 9 3 3 1 3 1 3 2 2 1 3 3 2 2 3 7 1 8 0 6 1 7 2 7 1 5 1 3 3 1 1 3 2 3 1 9 0 9 3 2 4 1 9 1 8 1 9 3 1 3 1 3 3 1 1 1 1 6 0 9 5 5 1 6 4 7 2 8 6 1 2 3 1 1 2 2 4 2 1 4 1 2 3 6 1 9 0 10 1 5 1 3 7 4 6 3 7 2 3 1 1 1 2 1 1 3 2 1 9 0 6 7 4 1 1 1 8 2 2 1 2 3 2 3 1 2 1 8 0 6 8 1 5 2 8 4 1 3 2 2 3 2 1 1 1 2 5 1 4 2 3 4 1 8 0 11 1 5 8 3 4 7 8 5 6 5 8 3 3 3 2 3 1 2 3 1 5 0 6 1 7 9 6 1 1 2 2 1 2 1 1 5 0 11 4 1 4 1 7 4 3 3 2 2 3 1 3 2 1 1 4 2 3 3 4 7 4 3 2 7 5 7 6 10 3 1 4 3 1 4 6 2"
0
Kotlin
0
0
ac62ce8aeaed065f8fbd11e30368bfe5d31b7033
35,641
AdventOfCode
Creative Commons Zero v1.0 Universal
y2021/src/main/kotlin/adventofcode/y2021/Day22.kt
Ruud-Wiegers
434,225,587
false
{"Kotlin": 503769}
package adventofcode.y2021 import adventofcode.io.AdventSolution object Day22 : AdventSolution(2021, 22, "Reactor Reboot") { override fun solvePartOne(input: String) = parse(input).take(20).let(::solve) override fun solvePartTwo(input: String) = parse(input).let(::solve) private fun solve(input: Sequence<Command>) = input .fold(listOf<Cube>()) { cubes, (turnOn, new) -> if (turnOn) addCube(cubes, new) else removeCube(cubes, new) } .sumOf(Cube::size) private fun addCube(cubes: List<Cube>, toAdd: Cube) = cubes + cubes.fold(listOf(toAdd)) { newFragments, existingCube -> newFragments.flatMap { fragment -> fragment.splitBy(existingCube) }.filterNot(existingCube::contains) } private fun removeCube(cubes: List<Cube>, toRemove: Cube) = cubes.flatMap { existingCube -> existingCube.splitBy(toRemove).filterNot(toRemove::contains) } private fun parse(input: String) = input.lineSequence().map { line -> val turnsOn = line.startsWith("on") val numbers = "-?\\d+".toRegex().findAll(line).map { it.value.toInt() } val (xs, ys, zs) = numbers.chunked(2) { it[0]..it[1] }.toList() Command(turnsOn, Cube(xs, ys, zs)) } } private data class Command(val on: Boolean, val cube: Cube) private data class Cube(val xs: IntRange, val ys: IntRange, val zs: IntRange) { fun size() = xs.size() * ys.size() * zs.size() operator fun contains(o: Cube) = o.xs in xs && o.ys in ys && o.zs in zs private infix fun outside(o: Cube) = xs outside o.xs || ys outside o.ys || zs outside o.zs fun splitBy(o: Cube): Sequence<Cube> = splitXBy(o).flatMap { it.splitYBy(o) }.flatMap { it.splitZBy(o) } private fun splitXBy(o: Cube) = splitAxisBy(o, Cube::xs).map { copy(xs = it) } private fun splitYBy(o: Cube) = splitAxisBy(o, Cube::ys).map { copy(ys = it) } private fun splitZBy(o: Cube) = splitAxisBy(o, Cube::zs).map { copy(zs = it) } private inline fun splitAxisBy(o: Cube, selectAxis: Cube.() -> IntRange) = if (outside(o)) sequenceOf(selectAxis()) else selectAxis().splitBy(o.selectAxis()) } private fun IntRange.size() = last - first + 1L private operator fun IntRange.contains(o: IntRange) = o.first in this && o.last in this private infix fun IntRange.outside(o: IntRange) = last < o.first || first > o.last private fun IntRange.splitBy(o: IntRange): Sequence<IntRange> = sequenceOf( first, o.first.takeIf { it in first + 1..last }, (o.last + 1).takeIf { it in first + 1..last }, last + 1 ) .filterNotNull() .windowed(2) { it[0] until it[1] }
0
Kotlin
0
3
fc35e6d5feeabdc18c86aba428abcf23d880c450
2,596
advent-of-code
MIT License
src/Day02.kt
graesj
572,651,121
false
{"Kotlin": 10264}
sealed class Move(val points: Int) object Rock : Move(points = 1) object Paper : Move(points = 2) object Scissor : Move(points = 3) sealed class GameResult(val points: Int) object Victory : GameResult(points = 6) object Draw : GameResult(points = 3) object Loss : GameResult(points = 0) fun charToMove(char: Char): Move { return when (char) { 'A', 'X' -> Rock 'B', 'Y' -> Paper 'C', 'Z' -> Scissor else -> throw RuntimeException("invalid input") } } fun charToDesiredGameResult(char: Char): GameResult { return when (char) { 'X' -> Loss 'Y' -> Draw 'Z' -> Victory else -> throw RuntimeException("invalid input") } } fun game(opponentMove: Move, yourMove: Move): GameResult { if (opponentMove == yourMove) return Draw if (opponentMove == Rock) { return if (yourMove == Paper) Victory else Loss } if (opponentMove == Paper) { return if (yourMove == Scissor) Victory else Loss } return if (yourMove == Rock) Victory else Loss } fun determineMove(opponentMove: Move, desiredGameResult: GameResult): Move { when (desiredGameResult) { Draw -> return opponentMove Victory -> { if (opponentMove == Paper) return Scissor if (opponentMove == Rock) return Paper return Rock } Loss -> { if (opponentMove == Paper) return Rock if (opponentMove == Rock) return Scissor return Paper } } } fun main() { fun part1(input: List<String>): Int { return input.map { val split = it.split(" ") charToMove(split[0].first()) to charToMove(split[1].first()) }.fold(0) { acc, pair: Pair<Move, Move> -> val (opponentMove, yourMove) = pair acc + game(opponentMove, yourMove).points + yourMove.points } } fun part2(input: List<String>): Int { return input.map { val split = it.split(" ") charToMove(split[0].first()) to charToDesiredGameResult(split[1].first()) }.fold(0) { acc, pair: Pair<Move, GameResult> -> val (opponentMove, desiredGameResult) = pair acc + desiredGameResult.points + determineMove(opponentMove, desiredGameResult).points } } // test if implementation meets criteria from the description, like: val testInput = readLines("Day02_test") check(part1(testInput) == 15) val input = readLines("Day02") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
df7f855a14c532f3af7a8dc86bd159e349cf59a6
2,568
aoc-2022
Apache License 2.0
src/main/kotlin/y2023/Day8.kt
juschmitt
725,529,913
false
{"Kotlin": 18866}
package y2023 import utils.Day import kotlin.math.max class Day8 : Day(8, 2023, false) { override fun partOne(): Any { val (directions, map) = inputString.parseDirectionsAndMap() return map.findStepsToEnd(directions.toCharArray()) } override fun partTwo(): Any { val (directions, map) = inputString.parseDirectionsAndMap() return map.keys.filter { it.endsWith('A') } .map { map.findStepsToEndAsGhost(it, directions.toCharArray()) } .findLcm() } } private fun List<Long>.findLcm(): Long { tailrec fun inner(idx: Int, acc: Long): Long { return when { idx == size -> acc else -> inner(idx+1, acc lcm get(idx)) } } return inner(0, first()) } private infix fun Long.lcm(other: Long): Long { val max = max(this, other) tailrec fun inner(lcm: Long): Long = when { lcm == this * other -> lcm lcm % this == 0L && lcm % other == 0L -> lcm else -> inner(lcm + max) } return inner(max) } private fun Map<String, Pair<String, String>>.findStepsToEndAsGhost(startLocation: String, directions: CharArray): Long { tailrec fun inner(location: String, curDir: Int, steps: Long): Long { val newDir = if (curDir + 1 == directions.size) 0 else curDir + 1 val nextLocation = this[location]!!.nextLocation(directions[curDir]) return when { curDir == directions.size - 1 && nextLocation.endsWith('Z') -> steps else -> { inner(nextLocation, newDir, steps + 1) } } } return inner(startLocation, 0, 1) } private fun Map<String, Pair<String, String>>.findStepsToEnd(directions: CharArray): Int { tailrec fun inner(location: String, curDir: Int, steps: Int): Int { val newDir = if (curDir + 1 == directions.size) 0 else curDir + 1 val nextLocation = this[location]!!.nextLocation(directions[curDir]) return when { curDir == directions.size - 1 && nextLocation == "ZZZ" -> steps else -> { inner(nextLocation, newDir, steps + 1) } } } return inner("AAA", 0, 1) } private fun Pair<String, String>.nextLocation(direction: Char): String { return when (direction) { 'L' -> first 'R' -> second else -> error("Not a direction: $direction") } } private fun String.parseDirectionsAndMap(): Pair<String, Map<String, Pair<String, String>>> { val (directions, mapString) = split("\n\n") val map = mapString.split("\n").associate { line -> val (key, destinations) = line.split(" = ") val value = destinations.replace("(", "").replace(")", "").split(", ").zipWithNext().first() key to value } return directions to map }
0
Kotlin
0
0
b1db7b8e9f1037d4c16e6b733145da7ad807b40a
2,814
adventofcode
MIT License
src/Day14.kt
djleeds
572,720,298
false
{"Kotlin": 43505}
import lib.Coordinates import lib.Direction import lib.get enum class Material { AIR, ROCK, SAND } private fun printGrid(grid: List<List<Material>>) { for (y in grid.indices) { println("") for (x in grid[y].indices) { when (grid[y][x]) { Material.AIR -> print(".") Material.ROCK -> print("#") Material.SAND -> print("o") } } } println() } private fun parse(input: List<String>): MutableList<MutableList<Material>> { val coordinates = input.map { line -> line.split(" -> ").map { Coordinates.parse(it) } } val width = coordinates.maxOf { c -> c.maxOf { it.x } } * 2 val height = coordinates.maxOf { c -> c.maxOf { it.y } } + 2 val grid: MutableList<MutableList<Material>> = MutableList(height) { MutableList(width) { Material.AIR } } input.forEach { line -> line.split(" -> ").map { Coordinates.parse(it) }.zipWithNext().forEach { for (c in it.first through it.second) grid[c.y][c.x] = Material.ROCK } } return grid } private fun solve( grid: MutableList<MutableList<Material>>, emitterCoordinates: Coordinates, terminalCondition: (sand: Coordinates, isResting: Boolean) -> Boolean ): Int { var complete = false var sand = emitterCoordinates var sandCount = 0 do { when (Material.AIR) { grid[sand.step(Direction.DOWN)] -> sand = sand.step(Direction.DOWN) grid[sand.step(Direction.DOWN_LEFT)] -> sand = sand.step(Direction.DOWN_LEFT) grid[sand.step(Direction.DOWN_RIGHT)] -> sand = sand.step(Direction.DOWN_RIGHT) else -> { complete = terminalCondition(sand, true) grid[sand.y][sand.x] = Material.SAND sandCount++ sand = emitterCoordinates } } complete = complete || terminalCondition(sand, false) } while (!complete) return sandCount } fun main() { val emitter = Coordinates(500, 0) fun part1(input: List<String>): Int { val grid = parse(input) val abyss = grid.lastIndex return solve(grid, emitter) { sand, _ -> sand.y == abyss }.also { if (debug) printGrid(grid) } } fun part2(input: List<String>): Int { val grid = parse(input).apply { add(MutableList(this[0].size) { Material.ROCK }) } return solve(grid, emitter) { sand, isResting -> isResting && sand == emitter }.also { if (debug) printGrid(grid) } } val testInput = readInput("Day14_test") println(part1(testInput)) println(part2(testInput)) val input = readInput("Day14") println(part1(input)) println(part2(input)) }
0
Kotlin
0
4
98946a517c5ab8cbb337439565f9eb35e0ce1c72
2,765
advent-of-code-in-kotlin-2022
Apache License 2.0
app/src/main/kotlin/com/jamjaws/adventofcode/xxiii/day/Day06.kt
JamJaws
725,792,497
false
{"Kotlin": 30656}
package com.jamjaws.adventofcode.xxiii.day import com.jamjaws.adventofcode.xxiii.readInput class Day06 { fun part1(text: List<String>): Long { val races = text.fold(listOf<Race>()) { acc, line -> line.substringAfter(":") .split(' ') .filter(String::isNotBlank) .map(String::toLong) .let { values -> when (acc.isEmpty()) { true -> acc + values.map { Race(it, 0) } false -> acc.mapIndexed { index, race -> race.copy(distance = values[index]) } } } } return races .map { race -> howManyWaysToBeatRecord(race) } .fold(0) { acc, waysToBeatRecord -> when { (acc == 0) -> waysToBeatRecord else -> acc * waysToBeatRecord } } .toLong() } fun part2(text: List<String>): Int = text.map { line -> line.substringAfter(":") .filter(Char::isDigit) .let(String::toLong) }.let { (time, distance) -> Race(time, distance) } .let(::howManyWaysToBeatRecord) private fun howManyWaysToBeatRecord(race: Race) = (1 until race.time) .map { it * (race.time - it) } .count { it > race.distance } } data class Race(val time: Long, val distance: Long) fun main() { val answer1 = Day06().part1(readInput("Day06")) println(answer1) val answer2 = Day06().part2(readInput("Day06")) println(answer2) }
0
Kotlin
0
0
e2683305d762e3d96500d7268e617891fa397e9b
1,634
advent-of-code-2023
MIT License
src/main/kotlin/pl/mrugacz95/aoc/day18/day18.kt
mrugacz95
317,354,321
false
null
import pl.mrugacz95.aoc.day13.sumByLong import java.lang.RuntimeException import java.util.Stack const val MUL = "*" const val ADD = "+" const val LBR = "(" const val RBR = ")" fun evaluateRPN(expression: List<String>): Long { val stack = Stack<String>() for (term in expression) { when (term) { MUL, ADD -> { val v1 = stack.pop().toLong() val v2 = stack.pop().toLong() when (term) { ADD -> stack.push((v1 + v2).toString()) MUL -> stack.push((v1 * v2).toString()) } } else -> stack.push(term) // number } } return stack.pop().toLong() } fun expressionToRPN( expression: List<String>, precedence: Map<String, Int>, ): List<String> { val result = mutableListOf<String>() val operators = Stack<String>() for (term in expression) { when (term) { LBR -> operators.push(term) RBR -> { while (operators.peek() != LBR) result.add(operators.pop()) operators.pop() } MUL, ADD -> { val currentPrecedence = precedence[term] ?: throw RuntimeException("Precedence for $term not defined") while (operators.isNotEmpty() && operators.peek() != LBR && precedence[operators.peek()]!! <= currentPrecedence ) { result.add(operators.pop()) } operators.add(term) } else -> result.add(term) } } while (!operators.empty()) { result.add(operators.pop()) } return result } fun main() { val equations = {}::class.java.getResource("/day18.in") .readText() .split("\n") .map { it.replace(")", " )") .replace("(", "( ") .split(" ") // split and keep brackets separated } println("Answer part 1 : ${equations.sumByLong { evaluateRPN(expressionToRPN(it, mapOf("+" to 0, "*" to 0))) }}") println("Answer part 2 : ${equations.sumByLong { evaluateRPN(expressionToRPN(it, mapOf("+" to 0, "*" to 1))) }}") }
0
Kotlin
0
1
a2f7674a8f81f16cd693854d9f564b52ce6aaaaf
2,293
advent-of-code-2020
Do What The F*ck You Want To Public License
src/Day13.kt
MatthiasDruwe
571,730,990
false
{"Kotlin": 47864}
import kotlin.math.abs fun eq(item1: MutableList<Any>, item2: MutableList<Any>): Int { repeat(item1.size) { x -> if (x == item2.size) { return -1 } if (item1[x] is MutableList<*> && item2[x] is MutableList<*>) { val result = eq(item1[x] as MutableList<Any>, item2[x] as MutableList<Any>) if (result != 0) { return result } } else if (item1[x] is Int && item2[x] is Int) { if ((item2[x] as Int) - (item1[x] as Int) != 0) { return ((item2[x] as Int) - (item1[x] as Int)) / abs((item2[x] as Int) - (item1[x] as Int)) } else { 0 } } else if (item1[x] is MutableList<*>) { val result = eq(item1[x] as MutableList<Any>, mutableListOf(item2[x])) if (result != 0) { return result } } else if (item2[x] is MutableList<*>) { val result = eq(mutableListOf(item1[x]), item2[x] as MutableList<Any>) if (result != 0) { return result } } } return if (item2.size > item1.size) 1 else 0 } class Comp1 : Comparator<MutableList<Any>> { override fun compare(o1: MutableList<Any>?, o2: MutableList<Any>?): Int { return eq(o1!!, o2!!) } } fun main() { fun part1(input: List<String>): Int { // val pairs = input.splitOnEmptyString().map { Pair(it[0].convertToArray(), it[1].convertToArray()) }.map { // it.first.compareTo(it.second) <= 0 // } // println(pairs) val pairs = input.splitOnEmptyString().map { Pair(it[0].convertToArray(), it[1].convertToArray()) }.map { eq(it.first, it.second) >= 0 } println(pairs) return pairs.mapIndexed { index, value -> if (value) index + 1 else 0 }.sum() } fun part2(input: List<String>): Int { val divider1: MutableList<Any> = mutableListOf(mutableListOf(2)) val divider2: MutableList<Any> = mutableListOf(mutableListOf(6)) val pairs = input.splitOnEmptyString().map { Pair(it[0].convertToArray(), it[1].convertToArray()) } .map { listOf(it.first, it.second) }.flatten().toMutableList() pairs.add(divider1) pairs.add(divider2) pairs.sortWith(Comp1()) pairs.reverse() val index1 = pairs.indexOf(divider1) + 1 val index2 = pairs.indexOf(divider2) + 1 return index1 * index2 } // test if implementation meets criteria from the description, like: val testInput = readInput("Day13_example") check(part1(testInput) == 13) check(part2(testInput) == 140) val input = readInput("Day13") println(part1(input)) println(part2(input)) } fun String.convertToArray(): MutableList<Any> { var array = MutableList<Any>(0) { 0 } val values = this.removePrefix("[").removeSuffix("]") var count = 0 var item = "" values.forEach { if (it == '[') { count++ } else if (it == ']') { count-- } if (it == ',' && count == 0) { if (item.toIntOrNull() != null) { array.add(item.toInt()) item = "" } else if (item != "") { array.add(item.convertToArray()) item = "" } } else { item += it } } if (item.toIntOrNull() != null) { array.add(item.toInt()) item = "" } else if (item != "") { array.add(item.convertToArray()) } return array }
0
Kotlin
0
0
f35f01cea5075cfe7b4a1ead9b6480ffa57b4989
3,626
Advent-of-code-2022
Apache License 2.0
src/year2023/01/Day01.kt
Vladuken
573,128,337
false
{"Kotlin": 327524, "Python": 16475}
package year2023.`01` import readInput import utils.printDebug private const val CURRENT_DAY = "01" private val mapOfValues = mapOf( "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, "1" to 1, "2" to 2, "3" to 3, "4" to 4, "5" to 5, "6" to 6, "7" to 7, "8" to 8, "9" to 9, ) private fun findSumForPart1(input: List<String>): Long { return input.sumOf { val listOfNumbers = it .split("") .mapNotNull { it.toIntOrNull() } val result = listOfNumbers.first().toString() + listOfNumbers.last().toString() printDebug { result } result.toLong() } } private fun findItem(line: String): String { val indexes = mapOfValues.keys.flatMap { val indexOfFirstValue = line.indexOf(it) to mapOfValues[it]!! val indexOfLastValue = line.lastIndexOf(it) to mapOfValues[it]!! listOf(indexOfFirstValue, indexOfLastValue) } .filter { it.first != -1 } .sortedBy { it.first } val firstNumber = indexes.first().second val lastNumber = indexes.last().second val result = "$firstNumber$lastNumber" printDebug { "$line --- $result" } return result } fun main() { fun part1(input: List<String>): Long { return findSumForPart1(input) } fun part2(input: List<String>): Long { return input .map { findItem(it) } .sumOf { it.toLong() } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day${CURRENT_DAY}_test") val input = readInput("Day$CURRENT_DAY") // Part 1 val part1 = part1(input) println(part1) check(part1 == 54634L) // Part 2 val part2Test = part2(testInput) println(part2Test) check(part2Test == 281L) val part2 = part2(input) println(part2) check(part2 == 1L) }
0
Kotlin
0
5
c0f36ec0e2ce5d65c35d408dd50ba2ac96363772
1,987
KotlinAdventOfCode
Apache License 2.0
src/Day07.kt
vladislav-og
573,326,483
false
{"Kotlin": 27072}
fun main() { var dirChildrenConnect = hashMapOf<String, HashSet<String>>() var dirFileSizes = hashMapOf<String, Int>() fun calculateDirTotalSize(dir: String): Int { var children = dirChildrenConnect[dir]!!.toList() var totalSize = 0 while (children.isNotEmpty()) { val nextChildren = arrayListOf<String>() for (child in children) { if (dirChildrenConnect[child]!!.isEmpty()) { totalSize += dirFileSizes[child]!! } else { totalSize += dirFileSizes[child]!! nextChildren.addAll(dirChildrenConnect[child]!!) } } children = nextChildren.toSet().toList() } totalSize += dirFileSizes[dir]!! return totalSize } fun mapDirectoryTree(input: List<String>) { dirChildrenConnect = hashMapOf() dirFileSizes = hashMapOf() var currentActiveCommand = "" val directoryQueue = ArrayDeque<String>() var currentActiveSubDirectory: String for (row in input) { val curDirectoryIdentifier = directoryQueue.joinToString("") if (row.startsWith("$")) { currentActiveCommand = row.substring(2) if (currentActiveCommand.startsWith("cd")) { val dir = currentActiveCommand.split(" ")[1] if (dir == "..") directoryQueue.removeLast() else directoryQueue.addLast(dir) } if (!dirChildrenConnect.keys.contains(curDirectoryIdentifier)) { dirChildrenConnect[curDirectoryIdentifier] = hashSetOf() dirFileSizes[curDirectoryIdentifier] = 0 } } else { if (currentActiveCommand.startsWith("ls")) { val (firstPart, dirNameOrSize) = row.split(" ") if (firstPart == "dir") { currentActiveSubDirectory = curDirectoryIdentifier + dirNameOrSize dirChildrenConnect[curDirectoryIdentifier]!!.add(currentActiveSubDirectory) } else { dirFileSizes[curDirectoryIdentifier] = dirFileSizes[curDirectoryIdentifier]!! + firstPart.toInt() } } } } } fun part1(input: List<String>): Int { mapDirectoryTree(input) var totalSize = 0 for (dir in dirChildrenConnect.keys) { val dirTotalSize = calculateDirTotalSize(dir) if (dirTotalSize <= 100000) { totalSize += dirTotalSize } } return totalSize } fun part2(input: List<String>): Int { mapDirectoryTree(input) val dirSizes = hashMapOf<String, Int>() for (dir in dirChildrenConnect.keys) { val dirTotalSize = calculateDirTotalSize(dir) dirSizes[dir] = dirTotalSize } val spaceNeededToFreeUp = 70000000 - dirSizes["/"]!! val spaceToFreeUp = 30000000 - spaceNeededToFreeUp return dirSizes.values.sorted().first { it >= spaceToFreeUp } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day07_test") println(part1(testInput)) check(part1(testInput) == 95437) println(part2(testInput)) check(part2(testInput) == 24933642) val input = readInput("Day07") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
b230ebcb5705786af4c7867ef5f09ab2262297b6
3,543
advent-of-code-2022
Apache License 2.0
src/Day14.kt
arhor
572,349,244
false
{"Kotlin": 36845}
fun main() { val input = readInput {} println("Part 1: ${solvePuzzle1(input)}") println("Part 2: ${solvePuzzle2(input)}") } private fun solvePuzzle1(input: List<String>): Int { val model = Model.parse(input) val xIndicies = 0..(model.xMax - model.xMin) val yIndicies = 0..model.yMax val startingPoint = Point(500 - model.xMin, 0) var stableUnits = 0 var currentUnit = startingPoint loop@ while (true) { val targetPoints = currentUnit.adjacentPoints() .filter { it.y > currentUnit.y } .sortedBy { it.x } .toList() .let { (left, middle, right) -> listOf(middle, left, right) } for (point in targetPoints) { if (point.x !in xIndicies || point.y !in yIndicies) { break@loop } if (point !in model.data) { currentUnit = point continue@loop } } model.data.add(currentUnit) currentUnit = startingPoint stableUnits++ } return stableUnits } private fun solvePuzzle2(input: List<String>): Int { val model = Model.parse(input) val startingPoint = Point(500 - model.xMin, 0) var stableUnits = 0 var currentUnit = startingPoint loop@ while (true) { val targetPoints = currentUnit.adjacentPoints() .filter { it.y > currentUnit.y } .sortedBy { it.x } .toList() .let { (left, middle, right) -> listOf(middle, left, right) } for (point in targetPoints) { if (point.y < (model.yMax + 2) && point !in model.data) { currentUnit = point continue@loop } } if (currentUnit == startingPoint) { stableUnits++ break@loop } model.data.add(currentUnit) currentUnit = startingPoint stableUnits++ } return stableUnits } private class Model private constructor(input: List<String>) { val data = HashSet<Point>() var xMax = -1 var xMin = -1 var yMax = -1 var yMin = -1 init { val lines = input.flatMap { line -> line.split(" -> ") .map { it.split(",").map(String::toInt).let { (x, y) -> xMin = if (xMin != -1) minOf(xMin, x) else x xMax = if (xMax != -1) maxOf(xMax, x) else x yMin = if (yMin != -1) minOf(yMin, y) else y yMax = if (yMax != -1) maxOf(yMax, y) else y Point(x, y) } } .windowed(2) } for ((alpha, omega) in lines) { when { alpha.x == omega.x -> { for (y in minOf(alpha.y, omega.y)..maxOf(alpha.y, omega.y)) { data.add(Point(alpha.x - xMin, y)) } } alpha.y == omega.y -> { for (x in minOf(alpha.x, omega.x)..maxOf(alpha.x, omega.x)) { data.add(Point(x - xMin, alpha.y)) } } } } } companion object { fun parse(input: List<String>) = Model(input) } }
0
Kotlin
0
0
047d4bdac687fd6719796eb69eab2dd8ebb5ba2f
3,318
aoc-2022-in-kotlin
Apache License 2.0
src/main/kotlin/advent/y2018/day2.kt
IgorPerikov
134,053,571
false
{"Kotlin": 29606}
package advent.y2018 import misc.readAdventInput /** * https://adventofcode.com/2018/day/2 */ fun main(args: Array<String>) { val ids = readAdventInput(2, 2018) calculateChecksum(ids).also { println(it) } commonCharactersOfBoxes(ids).also { println(it) } } private fun calculateChecksum(ids: List<String>): Int { var doubleCount = 0 var tripleCount = 0 ids.forEach { id -> val lettersCounts = collectCharactersToMap(id) lettersCounts.values.count { it == 2 }.let { if (it != 0) doubleCount++ } lettersCounts.values.count { it == 3 }.let { if (it != 0) tripleCount++ } } return doubleCount * tripleCount } private fun collectCharactersToMap(id: String): Map<Char, Int> { val lettersCounts = mutableMapOf<Char, Int>() id.forEach { letter -> lettersCounts.merge(letter, 1) { prev, new -> prev + new } } return lettersCounts } private fun commonCharactersOfBoxes(ids: List<String>): String { val (id1, id2) = findSimilarBoxes(ids) return id1.zip(id2) .filter { chars -> chars.first == chars.second } .joinToString(separator = "") { chars -> chars.first.toString() } } private fun findSimilarBoxes(ids: List<String>): Pair<String, String> { ids.forEachIndexed { i1, id1 -> ids.forEachIndexed { i2, id2 -> if (i1 != i2) { var diffs = 0 var complete = true id1.forEachIndexed inner@{ index, char -> if (id2[index] != char) { if (diffs == 1) { complete = false return@inner } else { diffs++ } } } if (complete) { return Pair(id1, id2) } } } } throw IllegalArgumentException("no similar boxes") }
0
Kotlin
0
0
b30cf179f7b7ae534ee55d432b13859b77bbc4b7
1,964
kotlin-solutions
MIT License
src/Day03.kt
Longtainbin
573,466,419
false
{"Kotlin": 22711}
fun main() { val input = readInput("inputDay03") fun part1(input: List<String>): Int { return input.sumOf { processPart1(it) } } fun part2(input: List<String>): Int { val n = 3 val groups = input.size / n var sum = 0 for (group in 1..groups) { val startIndex = (group - 1) * n sum += processPart2(input[startIndex], input[startIndex + 1], input[startIndex + 2]) } return sum } println(part1(input)) println(part2(input)) } /*** For Part_1 ***/ private fun processPart1(str: String): Int { val N = str.length / 2; val userSet = HashSet<Char>(); var sum = 0 for (i in N until str.length) { userSet.add(str[i]) } for (i in 0 until N) { if (userSet.contains(str[i])) { sum += getPriority(str[i]) userSet.remove(str[i]) } } return sum } /*** For Part_2 ***/ private fun processPart2(str1: String, str2: String, str3: String): Int { val set1 = string2Set(str1) set1.inner(string2Set(str2)) set1.inner(string2Set(str3)) return set1.sumOf { getPriority(it) } } private fun string2Set(str: String): MutableSet<Char> { val set = HashSet<Char>() str.forEach { set.add(it) } return set } fun <T> MutableSet<T>.inner(other: Set<T>) { this.retainAll(other) } /*** common function ***/ private fun getPriority(item: Char): Int { if (item in 'a'..'z') { return item - 'a' + 1; } return item - 'A' + 27 }
0
Kotlin
0
0
48ef88b2e131ba2a5b17ab80a0bf6a641e46891b
1,542
advent-of-code-2022
Apache License 2.0
2021/src/main/kotlin/days/Day4.kt
pgrosslicht
160,153,674
false
null
package days import Day import com.google.common.collect.HashBasedTable class Day4 : Day(4) { override fun partOne(): Int { val values = dataList.take(1).single().split(",") val boards = dataList.drop(2).chunked(6).map { Bingo(it) } for (v in values) { boards.singleOrNull { it.mark(v.toInt()) }?.let { return v.toInt() * it.sumUnmarked() } } return 0 } override fun partTwo(): Int { val values = dataList.take(1).single().split(",") val boards = dataList.drop(2).chunked(6).map { Bingo(it) } val lastBoards: MutableList<Bingo> = mutableListOf() var lastWinningValue: Int = 0 for (v in values) { val winningBoards = boards.filter { it.mark(v.toInt()) } if (winningBoards.isNotEmpty()) lastWinningValue = v.toInt() lastBoards.addAll(winningBoards) } return lastBoards.last().sumUnmarked() * lastWinningValue } class Bingo(private val lines: List<String>) { private val table: HashBasedTable<Int, Int, Cell> = HashBasedTable.create(5, 5) private var won: Boolean = false init { lines.filter { it.isNotEmpty() }.also { check(it.size == 5) }.forEachIndexed { row, s -> s.split(" ").filter { it.isNotEmpty() }.also { check(it.size == 5) } .forEachIndexed { column, x -> table.put(row, column, Cell(x.toInt())) } } } fun mark(value: Int): Boolean { if (won) return false val row = table.rowMap().entries.indexOfFirst { it.value.containsValue(Cell(value)) } if (row == -1) return false val column = table.row(row).entries.indexOfFirst { it.value == Cell(value) } table.get(row, column)!!.marked = true val won = table.row(row).values.all { it.marked } || table.column(column).values.all { it.marked } if (won) this.won = true return won } fun sumUnmarked(): Int = table.values().filter { !it.marked }.sumOf { it.value } } data class Cell(val value: Int, var marked: Boolean = false) } fun main() = Day.mainify(Day4::class)
0
Kotlin
0
0
1f27fd65651e7860db871ede52a139aebd8c82b2
2,211
advent-of-code
MIT License
src/Day03.kt
Moonpepperoni
572,940,230
false
{"Kotlin": 6305}
fun main() { fun String.toRuckSack() : RuckSack { val leftPocket = this.substring(0 until this.length/2).toSet() val rightPocket = this.substring(this.length/2..this.lastIndex).toSet() return RuckSack(leftPocket, rightPocket) } fun RuckSack.getCommonChar() : Char { return (this.first intersect this.second).single() } fun RuckSackGroup.getCommonChar() : Char { return (this[0] intersect this [1] intersect this[2]).single() } fun Char.getScore() : Int { return if (this.isUpperCase()) { this - 'A' + 27 } else { this - 'a' + 1 } } fun part1(input: List<String>): Int { return input.map(String::toRuckSack).map(RuckSack::getCommonChar).sumOf(Char::getScore) } fun part2(input: List<String>): Int { val groups = input.chunked(3) val rucksackGroups = ArrayList<RuckSackGroup>() for (group in groups) { val rucksackGroup = RuckSackGroup() for (rucksack in group) { rucksackGroup.add(rucksack.toSet()) } rucksackGroups.add(rucksackGroup) } return rucksackGroups.map(RuckSackGroup::getCommonChar).sumOf(Char::getScore) } // test if implementation meets criteria from the description, like: val testInput = readInput("Day03_test") check(part1(testInput) == 157) check(part2(testInput) == 70) val input = readInput("Day03") println(part1(input)) println(part2(input)) } typealias RuckSackGroup = ArrayList<Pocket> typealias RuckSack = Pair<Pocket, Pocket> typealias Pocket = Set<Char>
0
Kotlin
0
0
946073042a985a5ad09e16609ec797c075154a21
1,667
moonpepperoni-aoc-2022
Apache License 2.0
src/main/kotlin/day21_dirac_dice/DiracDice.kt
barneyb
425,532,798
false
{"Kotlin": 238776, "Shell": 3825, "Java": 567}
package day21_dirac_dice import histogram.Histogram import histogram.count import histogram.histogramOf import histogram.mutableHistogramOf import kotlin.math.max /** * A simple rules engine is needed: modular arithmetic, a little bookkeeping, * and careful attention to boundary conditions in a two-phase loop. Not simple, * but straightforward, though rather too straightforward this late in the * month. Part two is going to be mind-bending, especially with a quantum * physicist as namesake. * * It's Lanternfish again! Here we need to track counts of game states, a * four-tuple of position and score for each player. For each distinct state, * split the universe 27 ways on player one, check for victory, then the same * for player two, collecting the not-yet-won states up for the next round. */ fun main() { util.solve(504972, ::partOne) util.solve(446968027750017, ::partTwo) } private val split_frequencies = listOf(1L, 3, 6, 7, 6, 3, 1) data class Player(val pos: Long, val score: Long) { fun move(n: Int): Player { val newPos = (pos - 1 + n) % 10 + 1 return Player( newPos, score + newPos ) } fun split(): Histogram<Player> = mutableHistogramOf<Player>().also { hist -> (3..9) .map(this::move) .zip(split_frequencies) .forEach { (p, n) -> hist.count(p, n) } } } data class Die(val sides: Int = 100) { var rollCount: Int = 0 val value get() = (rollCount - 1) % sides + 1 fun roll(): Int { rollCount += 1 return value } } fun partOne(input: String): Long { var (a, b) = input.toPlayers() val die = Die() val loser: Player while (true) { a = a.move(die.roll() + die.roll() + die.roll()) if (a.score >= 1000) { loser = b break } b = b.move(die.roll() + die.roll() + die.roll()) if (b.score >= 1000) { loser = a break } } return loser.score * die.rollCount } private fun String.toPlayers() = lines() .map { it.split(' ')[4].toLong() } .map { Player(it, 0) } data class State(val one: Player, val two: Player) fun partTwo(input: String): Long { val (one, two) = input.toPlayers() var winsOne = 0L var winsTwo = 0L var hist = histogramOf(State(one, two)) while (hist.isNotEmpty()) { val next = mutableHistogramOf<State>() for ((state, count) in hist) { state.one.split().forEach { (o, n) -> if (o.score >= 21) { winsOne += count * n } else { state.two.split().forEach { (t, m) -> if (t.score >= 21) { winsTwo += count * n * m } else { next.count(State(o, t), count * n * m) } } } } } hist = next } return max(winsOne, winsTwo) }
0
Kotlin
0
0
a8d52412772750c5e7d2e2e018f3a82354e8b1c3
3,117
aoc-2021
MIT License
2020/src/year2021/day11/code.kt
eburke56
436,742,568
false
{"Kotlin": 61133}
package year2021.day11 import util.readAllLines private fun countFlashes(grid: List<List<Octopus>>, iteration: Int, maxIterations: Int): Int { if (iteration > maxIterations) return 0 var numFlashed = 0 var justFlashed = initialStep(grid) while (justFlashed.isNotEmpty()) { numFlashed += justFlashed.size justFlashed = getJustFlashed(grid, justFlashed) } return numFlashed + countFlashes(grid, iteration + 1, maxIterations) } private fun findSynced(grid: List<List<Octopus>>, iteration: Int) { var justFlashed = initialStep(grid) while (justFlashed.isNotEmpty()) { justFlashed = getJustFlashed(grid, justFlashed) } if (grid.sumOf { row -> row.count { it.value > 0 } } == 0) { println(iteration) } else { findSynced(grid, iteration + 1) } } private fun initialStep(grid: List<List<Octopus>>): MutableSet<Pair<Int, Int>> { grid.forEach { row -> row.forEach { octopus -> octopus.increment() } } return grid.flatMapIndexed { r, row -> row.mapIndexedNotNull { c, octopus -> if (octopus.value == 0) Pair(r, c) else null } }.toMutableSet() } private fun getJustFlashed( grid: List<List<Octopus>>, justFlashed: MutableSet<Pair<Int, Int>> ): MutableSet<Pair<Int, Int>> { val maxRow = grid.size - 1 val newJustFlashed = mutableSetOf<Pair<Int, Int>>() grid.forEachIndexed { rowIndex, row -> val maxCol = row.size - 1 row.forEachIndexed { colIndex, octopus -> if (octopus.value > 0) { var numAdjacentFlashed = 0 for (r in rowIndex - 1..rowIndex + 1) { for (c in colIndex - 1..colIndex + 1) { if (r == rowIndex && c == colIndex) continue if (r < 0 || r > maxRow) continue if (c < 0 || c > maxCol) continue if (justFlashed.contains(Pair(r, c))) { numAdjacentFlashed += 1 } } } if (octopus.increment(numAdjacentFlashed)) { newJustFlashed.add(Pair(rowIndex, colIndex)) } } } } return newJustFlashed } class Octopus(initialValue: Int) { var value = initialValue private set fun increment(amount: Int = 1): Boolean { value += amount return if (value > 9) { value = 0; true } else false } } fun main() { part1() part2() } private fun part1() { val grid = readAllLines("input.txt").map { line -> line.map { char -> Octopus(char.digitToInt()) } } println(countFlashes(grid, 1, 100)) } private fun part2() { val grid = readAllLines("input.txt").map { line -> line.map { char -> Octopus(char.digitToInt()) } } findSynced(grid, 1) }
0
Kotlin
0
0
24ae0848d3ede32c9c4d8a4bf643bf67325a718e
2,903
adventofcode
MIT License
src/Day02.kt
kmes055
577,555,032
false
{"Kotlin": 35314}
import java.lang.IllegalArgumentException import java.util.Collections.shuffle fun main() { fun calcScore(round: String): Int { val opponent = round.first() - 'A' val player = round.last() - 'A' val outcomeScore = when ((opponent - player).mod(3)) { 0 -> 3 1 -> 0 2 -> 6 else -> 0 } val shapeScore = when (player) { 0 -> 1 1 -> 2 2 -> 3 else -> 0 } return outcomeScore + shapeScore } fun Char.win() = when(this) { 'A', 'B' -> this + 1 'C' -> 'A' else -> 'A' } fun Char.lose() = when(this) { 'B', 'C' -> this - 1 'A' -> 'C' else -> throw IllegalArgumentException("ABC Only") } fun part1(input: List<String>): Int { val permutations = listOf("XYZ", "XZY", "YXZ", "YZX", "ZXY", "ZYX") return permutations.maxOf { permutation -> input.groupBy { it } .mapKeys { it.key.replace(permutation[0], 'A') .replace(permutation[1], 'B') .replace(permutation[2], 'C') } .mapValues { calcScore(it.key) * it.value.size } .values .sum() } } fun part2(input: List<String>): Int { val permutations = listOf("XYZ", "XZY", "YXZ", "YZX", "ZXY", "ZYX") return permutations.maxOf { permutation -> input.groupBy { it } .mapKeys { val opponent = it.key.first() it.key.replace('X', opponent.lose()) .replace('Y', opponent) .replace('Z', opponent.win()) } .mapValues { calcScore(it.key) * it.value.size } .values .sum() } } val input = readInput("Day02") part1(input).println() part2(input).println() }
0
Kotlin
0
0
84c2107fd70305353d953e9d8ba86a1a3d12fe49
2,022
advent-of-code-kotlin
Apache License 2.0
src/Day05.kt
Jessenw
575,278,448
false
{"Kotlin": 13488}
fun main() { fun part1(input: List<String>): String { val stacks: List<ArrayDeque<String>> = buildStacks(input[0].lines()) val moves: List<List<Int>> = buildMoves(input[1].lines()) moves.forEach { for (i in 0 until it[0]) stacks[it[2] - 1].addLast(stacks[it[1] - 1].removeLast()) } return stacks.joinToString("") { it.removeLast() } } fun part2(input: List<String>): String { val stacks: List<ArrayDeque<String>> = buildStacks(input[0].lines()) val moves: List<List<Int>> = buildMoves(input[1].lines()) moves.forEach { val temp = mutableListOf<String>() for (i in 0 until it[0]) { temp.add(stacks[it[1] - 1].removeLast()) } temp.reversed().forEach { t -> stacks[it[2] - 1].addLast(t) } } return stacks.joinToString("") { it.removeLast() } } val testInput = readInputText("Day05_test").split("\n\n") check(part1(testInput) == "CMZ") check(part2(testInput) == "MCD") val input = readInputText("Day05").split("\n\n") println(part1(input)) println(part2(input)) } fun buildStacks(lines: List<String>): List<ArrayDeque<String>> { val stackCount = lines .dropWhile { it.contains("[") } .first() .split(" ") .filter { it.isNotBlank() } .maxOf { it.toInt() } val stacks = MutableList(stackCount) { ArrayDeque<String>() } for (i in 0..stackCount) { lines .dropLast(1) .map { it .chunked(1) .toMutableList() .drop(1) } .forEach { val index = i * 4 if (index <= it.size) { val element = it[index] if (element != " ") { // These are "stacks" but we add as a queue since we read lines top to bottom stacks[i].addFirst(element) } } } } return stacks } fun buildMoves(lines: List<String>) = lines .map { line -> line.split(" ") .filterIndexed { index, _ -> index % 2 != 0 } .map { it.toInt() } }
0
Kotlin
0
0
05c1e9331b38cfdfb32beaf6a9daa3b9ed8220a3
2,393
aoc-22-kotlin
Apache License 2.0
src/Day03.kt
jwalter
573,111,342
false
{"Kotlin": 19975}
fun main() { fun codeScore(code: Int): Int { return if (code >= 98) { code - 96 } else { code - 38 } } fun score(rucksackContents: List<String>): Int { val common = rucksackContents.drop(1).fold(rucksackContents.first()) { acc, s -> s.filter { acc.contains(it) } } val i = common.toSet().map { codeScore(it.code) } return i.sum() } fun part1(input: List<String>): Int { return input .map { it.substring(0, it.length / 2) to it.substring(it.length / 2) } .sumOf { score(it.toList()) } } fun part2(input: List<String>): Int { var first = "" var second = "" val groups = input.mapIndexedNotNull { index, s -> when (index % 3) { 0 -> { first = s null } 1 -> { second = s null } else -> listOf(first, second, s) } }.sumOf { score(it) } return groups } val testInput = readInput("Day03_test") check(part1(testInput) == 157) check(part2(testInput) == 70) val input = readInput("Day03") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
576aeabd297a7d7ee77eca9bb405ec5d2641b441
1,335
adventofcode2022
Apache License 2.0
src/main/kotlin/aoc2023/Day08.kt
davidsheldon
565,946,579
false
{"Kotlin": 161960}
package aoc2023 import utils.InputUtils private enum class Direction{ LEFT, RIGHT; } private fun parseDirection(c: Char) = when(c) { 'L' -> Direction.LEFT 'R' -> Direction.RIGHT else -> throw IllegalArgumentException("Wrong char $c") } data class Position(val index: Int, val loc: String) private class Day08(val instructions: List<Direction>, val maps: Map<String, Pair<String, String>>) { fun move(current: String, dir: Direction): String = when(dir) { Direction.LEFT -> maps[current]!!.first Direction.RIGHT -> maps[current]!!.second } fun loopSize(start: String): Int { return loopFrom(start).count() } private fun loopFrom(start: String): Sequence<Position> { val seen = mutableSetOf<Position>() val positions = positionsFrom(start) val loop = positions.takeWhile { seen.add(it) } return loop } fun locationsLoop(start: String) = loopFrom(start).map { it.loc } private fun positionsFrom(start: String): Sequence<Position> { val positions = sequence { var current = start do { instructions.forEachIndexed { i, dir -> val pos = Position(i, current) yield(pos) current = move(current, dir) } } while (true) } return positions } fun locationsFrom(start: String): Sequence<String> { return positionsFrom(start).map { it.loc } } } private fun parseDay08(input: List<String>): Day08 { val (instructionsList, maps) = blocksOfLines(input).toList() val tree = maps.parsedBy("(\\w+) = \\((\\w+), (\\w+)\\)".toRegex()) { val (label, left, right) = it.destructured label to Pair(left, right) }.toMap() val instructions = instructionsList[0].map { parseDirection(it) } return Day08(instructions, tree) } fun main() { val testInput = """LLR AAA = (BBB, BBB) BBB = (AAA, ZZZ) ZZZ = (ZZZ, ZZZ)""".trimIndent().split("\n") fun part1(input: List<String>): Int { val problem = parseDay08(input) return problem.locationsFrom("AAA") //.onEach { println(it) } .takeWhile { it != "ZZZ" }.count() } fun part2(input: List<String>): Long { val problem = parseDay08(input) val initial = problem.maps.keys.filter { it.endsWith("A") } return initial.map { start -> val loop = problem.locationsLoop(start).toList() val ends = loop.count { it.endsWith("Z") } val index = loop.indexOfFirst { it.endsWith("Z") } println("$start has loop size ${loop.size}") println(" loop has $ends ends and index $index") index.toLong() }.lcm() } // test if implementation meets criteria from the description, like: val testValue = part1(testInput) println(testValue) check(testValue == 6) println(part2(testInput)) val puzzleInput = InputUtils.downloadAndGetLines(2023, 8) val input = puzzleInput.toList() println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
5abc9e479bed21ae58c093c8efbe4d343eee7714
3,171
aoc-2022-kotlin
Apache License 2.0
src/Day16.kt
kenyee
573,186,108
false
{"Kotlin": 57550}
data class Valve( val name: String, val rate: Int, val connections: List<String> ) val valveLookup = mutableMapOf<String, Valve>() fun main() { // ktlint-disable filename val regex = "Valve ([A-Z]+) has flow rate=([0-9]+); tunnel[s]* lead[s]* to valve[s]* ([A-Z, ]+)".toRegex() fun searchMax( valve: Valve, visited: MutableList<String>, currentList: MutableMap<String, Int>, minutesLeft: Int ): Int { if (minutesLeft == 0) return 0 if (visited.contains(valve.name)) return 0 visited.add(valve.name) val maxChild = valve.connections.map { it to searchMax(valveLookup[it]!!, visited, currentList, minutesLeft - 1) }.maxByOrNull { it.second } visited.remove(valve.name) val maxHere = valve.rate * minutesLeft + (maxChild?.second ?: 0) currentList[valve.name] = maxHere return maxHere } fun part1(input: List<String>): Int { // generate graph for (line in input) { val matches = regex.find(line) ?: throw IllegalStateException("Couldn't parse $line") val valve = matches.groupValues[1] val rate = matches.groupValues[2].toInt() val tunnelsTo = matches.groupValues[3].split(", ") valveLookup[valve] = Valve(valve, rate, tunnelsTo) } // get max rate shortest path through graph val visited = mutableListOf<String>() val valveList = mutableMapOf<String, Int>() val max = searchMax(valveLookup["AA"]!!, visited, valveList, minutesLeft = 30) println("max $max for valve list is $valveList ") return 0 } fun part2(input: List<String>): Int { return 0 } // test if implementation meets criteria from the description, like: val testInput = readInput("Day16_test") println("Test max pressure in 30min: ${part1(testInput)}") check(part1(testInput) == 1651) // println("Test #Sand units with floor: ${part2(testInput)}") // check(part2(testInput) == 93) // val input = readInput("Day16_input") // println("#no sensor positions in row 20000: ${part1(input)}") // println("#Sand units with floor: ${part2(input)}") }
0
Kotlin
0
0
814f08b314ae0cbf8e5ae842a8ba82ca2171809d
2,254
KotlinAdventOfCode2022
Apache License 2.0
src/main/kotlin/biz/koziolek/adventofcode/year2023/day04/day4.kt
pkoziol
434,913,366
false
{"Kotlin": 715025, "Shell": 1892}
package biz.koziolek.adventofcode.year2023.day04 import biz.koziolek.adventofcode.findInput import kotlin.math.pow fun main() { val inputFile = findInput(object {}) val scratchCards = parseScratchCards(inputFile.bufferedReader().readLines()) println("Total points: ${scratchCards.sumOf { it.points }}") val finalScratchCards = winMoreScratchCards(scratchCards) println("Total cards after winning more: ${finalScratchCards.sumOf { it.count }}") } data class ScratchCard( val id: Int, val winningNumbers: List<Int>, val myNumbers: List<Int>, val count: Int = 1 ) { val myWinningNumbers: Set<Int> = myNumbers.intersect(winningNumbers) val points: Int get() = if (myWinningNumbers.isNotEmpty()) { 2.0.pow(myWinningNumbers.size - 1).toInt() } else { 0 } } fun parseScratchCards(lines: Iterable<String>): List<ScratchCard> = lines.map { line -> ScratchCard( id = line.split(":", "|")[0] .replace("Card", "") .trim() .toInt(), winningNumbers = line.split(":", "|")[1] .replace(Regex(" +"), " ") .trim() .split(" ") .map { it.trim().toInt() }, myNumbers = line.split(":", "|")[2] .replace(Regex(" +"), " ") .trim() .split(" ") .map { it.trim().toInt() }, ) } fun winMoreScratchCards(scratchCards: List<ScratchCard>): List<ScratchCard> = scratchCards .associateBy { it.id } .let { map -> map.keys.fold(map) { newMap, id -> val currentCard = newMap[id]!! val wonCardIds = (currentCard.id + 1)..(currentCard.id + currentCard.myWinningNumbers.size) val updates = wonCardIds .mapNotNull { newMap[it] } .map { it.copy(count = it.count + currentCard.count) } .associateBy { it.id } newMap + updates } } .values.toList()
0
Kotlin
0
0
1b1c6971bf45b89fd76bbcc503444d0d86617e95
2,123
advent-of-code
MIT License
src/Day03.kt
3n3a-archive
573,389,832
false
{"Kotlin": 41221, "Shell": 534}
fun Day03() { fun preprocess(input: List<String>): List<List<CharArray>> { val charArrays = input .map { it.toCharArray() } .map { val size = it.size listOf( it.copyOfRange(0, (size + 1) / 2), it.copyOfRange((size + 1) / 2, size) ) } return charArrays } fun preprocess2(input: List<String>): List<List<CharArray>> { return input .chunked(3) .map { it.map { it2 -> it2.toCharArray() } } } fun getPriority(char: Char): Int { val charCode = char.code if (charCode in 97..122) { return charCode - 96 } else if (charCode in 65..90) { return charCode - 38 } return -1 } fun part1(input: List<String>): Int { val processed = preprocess(input) var commonItems = mutableListOf<Char>() for (rucksack in processed) { val compartment1 = rucksack[0] val compartment2 = rucksack[1] for (letter in compartment1) { val isAtIndex = compartment2.indexOf(letter) if (isAtIndex != -1) { commonItems.add(compartment2[isAtIndex]) break } } } val commonNumbers = commonItems.map { getPriority(it) } return commonNumbers.sum() } fun part2(input: List<String>): Int { val processed = preprocess2(input) var commonItems = mutableListOf<Char>() for (rucksackGroup in processed) { val rucksack1 = rucksackGroup[0] val rucksack2 = rucksackGroup[1] val rucksack3= rucksackGroup[2] for (letter in rucksack1) { if (rucksack2.contains(letter) && rucksack3.contains(letter)) { commonItems.add(letter) break } } } val commonNumbers = commonItems.map { getPriority(it) } return commonNumbers.sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day03_test") check(part1(testInput) == 157) check(part2(testInput) == 70) val input = readInput("Day03") println("1: " + part1(input)) println("2: " + part2(input)) }
0
Kotlin
0
0
fd25137d2d2df0aa629e56981f18de52b25a2d28
2,410
aoc_kt
Apache License 2.0
src/Day02.kt
adamgaafar
572,629,287
false
{"Kotlin": 12429}
var score = mutableListOf<Int>() var secScore = mutableListOf<Int>() fun main() { fun part1(input: List<String>): Int { for (i in input.indices){ determineWinner(input[i].last(),input[i].first()) } return score.sum() } fun part2(input: List<String>): Int { for (i in input.indices){ determinePlayerOneMove(input[i].first(),input[i].last()) } return secScore.sum() } val input = readInput("Day02") println(part1(input)) println(part2(input)) // test if implementation meets criteria from the description, like: /* val testInput = readInput("Day01_test") check(part1(testInput) == 1)*/ } fun determineWinner(player1: Char, player2:Char):Int{ if(isPlayerOneWInner(player1,player2)){ score.add(determineScore(player1) + 6) }else if (isTie(player1,player2)){ score.add(determineScore(player1) + 3) }else{ score.add(determineScore(player1) + 0) } return score.sum() } fun isPlayerOneWInner(playerOneInput: Char, playerTwoInput: Char): Boolean { return (playerOneInput == 'X' && playerTwoInput == 'C') || (playerOneInput == 'Y' && playerTwoInput == 'A') || (playerOneInput == 'Z' && playerTwoInput == 'B') } fun isTie(playerOneInput: Char, playerTwoInput: Char): Boolean { return (playerOneInput == 'X' && playerTwoInput == 'A') || (playerOneInput == 'Y' && playerTwoInput == 'B') || (playerOneInput == 'Z' && playerTwoInput == 'C') } fun determineScore(i:Char):Int{ return when(i){ 'X' -> 1 'Y' -> 2 'Z' -> 3 else -> 0 } } //part 2 fun determinePlayerOneMove(opponent:Char,strategy:Char): Int { when(strategy){ 'X' -> { var move = when(opponent){ 'A' -> 'Z' 'B' -> 'X' 'C' -> 'Y' else -> 'e' } secScore.add( 0 + determineScore(move)) } 'Y' -> { var move = when(opponent){ 'A' -> 'X' 'B' -> 'Y' 'C' -> 'Z' else -> 'e' } secScore.add( 3 + determineScore(move)) } 'Z' -> { var move = when(opponent){ 'A' -> 'Y' 'B' -> 'Z' 'C' -> 'X' else -> 'e' } secScore.add(6 + determineScore(move)) } else -> 'j' } return secScore.sum() }
0
Kotlin
0
0
5c7c9a2e819618b7f87c5d2c7bb6e6ce415ee41e
2,549
AOCK
Apache License 2.0
src/Day05.kt
undermark5
574,819,802
false
{"Kotlin": 67472}
fun main() { val numberRegex = Regex("\\d+") val crateRegex = Regex("\\[[A-Z]]") fun part1(input: List<String>): String { val stacksText = input.takeWhile { it.isNotBlank() } val steps = input.slice(input.indexOf("")..input.lastIndex).filterNot { it.isBlank() }.map { val numbers = numberRegex.findAll(it, 0).map { it.value.toInt() }.toList() Triple(numbers[0], numbers[1], numbers[2]) } val numStacks = stacksText.last().last().digitToInt() val stacks = MutableList<MutableList<String>>(numStacks) { mutableListOf() } stacksText.map { it.windowed(4, 4, true).map { it.trim() } }.forEach { it.forEachIndexed { index, s -> if (s.isNotBlank() && s.matches(crateRegex)) { stacks[index].add("${s[1]}") } } } steps.forEach { (count, fromOffset, toOffset) -> val from = fromOffset - 1 val to = toOffset - 1 val toMove = stacks[from].take(count) stacks[from] = stacks[from].takeLast(stacks[from].size - count).toMutableList() stacks[to].addAll(0, toMove.reversed()) print("") } return stacks.map { it.firstOrNull() ?: " " }.joinToString(separator = "") } fun part2(input: List<String>): String { val stacksText = input.takeWhile { it.isNotBlank() } val steps = input.slice(input.indexOf("")..input.lastIndex).filterNot { it.isBlank() }.map { val numbers = numberRegex.findAll(it, 0).map { it.value.toInt() }.toList() Triple(numbers[0], numbers[1], numbers[2]) } val numStacks = stacksText.last().last().digitToInt() val stacks = MutableList<MutableList<String>>(numStacks) { mutableListOf() } stacksText.map { it.windowed(4, 4, true).map { it.trim() } }.forEach { it.forEachIndexed { index, s -> if (s.isNotBlank() && s.matches(crateRegex)) { stacks[index].add("${s[1]}") } } } steps.forEach { (count, fromOffset, toOffset) -> val from = fromOffset - 1 val to = toOffset - 1 val toMove = stacks[from].take(count) stacks[from] = stacks[from].takeLast(stacks[from].size - count).toMutableList() stacks[to].addAll(0, toMove) print("") } return stacks.map { it.firstOrNull() ?: " " }.joinToString(separator = "") } // test if implementation meets criteria from the description, like: val testInput = readInput("Day05_test") check(part1(testInput) == "CMZ") check(part2(testInput) == "MCD") val input = readInput("Day05") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
e9cf715b922db05e1929f781dc29cf0c7fb62170
2,817
AoC_2022_Kotlin
Apache License 2.0
src/Day07.kt
ekgame
573,100,811
false
{"Kotlin": 20661}
fun main() { fun String.addIndent(indent: Int) = lines().joinToString("\n") { " ".repeat(indent) + it } abstract class FileSystemEntry(val name: String) { abstract val size: Int } class Directory(name: String, val parent: Directory? = null) : FileSystemEntry(name) { override val size: Int by lazy { content.sumOf { it.size } } val content: MutableList<FileSystemEntry> = mutableListOf() fun createChildDirectory(name: String) = Directory(name, this).also { this.content.add(it) } fun getOrCreateChildDirectory(name: String): Directory = content .filterIsInstance<Directory>() .firstOrNull { it.name == name } ?: createChildDirectory(name) fun flattenDirectories(): List<Directory> = buildList { content.filterIsInstance<Directory>().forEach { add(it) addAll(it.flattenDirectories()) } } override fun toString(): String = buildString { append("- $name (dir)\n") append(content.flatMap { it.toString().lines().map { it.addIndent(2) } }.joinToString("\n")) } } class File(name: String, override val size: Int, val parent: Directory) : FileSystemEntry(name) { override fun toString(): String = "- $name (file, size=$size)" } fun parseFileSystem(input: List<String>): Directory { val rootDirectory = Directory("root") var currentDirectory = rootDirectory var cursor = 0 val hasMoreLines = { cursor < input.size } data class DirectoryEntry(val name: String, val isFile: Boolean, val size: Int) fun parseDirectoryEntries() = sequence { while (hasMoreLines() && !input[cursor].startsWith("$")) { yield(input[cursor++]) } } .map { val (size, name) = it.split(" ") when (size) { "dir" -> DirectoryEntry(name, false, 0) else -> DirectoryEntry(name, true, size.toInt()) } } while (hasMoreLines()) { val command = input[cursor++] when { command.startsWith("$ cd ") -> { currentDirectory = when (val name = command.substring(5)) { "/" -> rootDirectory ".." -> currentDirectory.parent ?: error("going back from root directory") else -> currentDirectory.getOrCreateChildDirectory(name) } } command.startsWith("$ ls") -> { parseDirectoryEntries().forEach { if (it.isFile) { val file = File(it.name, it.size, currentDirectory) currentDirectory.content.add(file) } else { currentDirectory.createChildDirectory(it.name) } } } else -> error("Expected command, but got: $command") } } return rootDirectory } fun part1(input: List<String>): Int = parseFileSystem(input) .flattenDirectories() .filter { it.size <= 100000 } .sumOf { it.size } fun part2(input: List<String>): Int { val root = parseFileSystem(input) return root.flattenDirectories() .sortedBy { it.size } .first { 70_000_000 - root.size + it.size >= 30_000_000 } .size } val testInput = readInput("07.test") check(part1(testInput) == 95437) check(part2(testInput) == 24933642) val input = readInput("07") println(part1(input)) println(part2(input)) }
0
Kotlin
0
2
0c2a68cedfa5a0579292248aba8c73ad779430cd
3,838
advent-of-code-2022
Apache License 2.0
2022/src/day16/day16.kt
Bridouille
433,940,923
false
{"Kotlin": 171124, "Go": 37047}
package day16 import GREEN import RESET import printTimeMillis import readInput data class Valve( val name: String, val flowRate: Int, val links: List<String> = mutableListOf(), var isOpened: Boolean = false, ) { fun shouldOpen() = flowRate > 0 && !isOpened fun open() { isOpened = true } fun close() { isOpened = false } } fun parseInput(input: List<String>): Map<String, Valve> { val ret = mutableMapOf<String, Valve>() input.forEach { val links = it.split("; ")[1].split(" ").drop(4).map { it.replace(",", "").trim() } val valve = it.split("; ")[0].split(" ").let { Valve(it[1], it[4].substringAfter('=').toInt(), links) } ret[valve.name] = valve } return ret } // returns a map of distances between valves {"AA-BB": 1, "DD-HH": 4, "II-CC": 3} fun fillDistances(graph: Map<String, Valve>): Map<String, Int> { val ret = mutableMapOf<String, Int>() val keys = graph.keys.sorted() for (i in 0 until keys.lastIndex) { val valve = graph[keys[i]]!! for (j in i+1..keys.lastIndex) { val start = valve.name val end = graph[keys[j]]!!.name val visited = mutableSetOf<String>() val toVisit = mutableListOf(Pair(start, 0)) while (toVisit.isNotEmpty()) { val curr = toVisit.removeFirst() visited.add(curr.first) if (curr.first == end) { ret["$start-$end"] = curr.second ret["$end-$start"] = curr.second break } val nextOnes = graph[curr.first]!!.links.filter { !visited.contains(it) } toVisit.addAll(nextOnes.map { Pair(it, curr.second + 1) }) } } } return ret } fun getMaxPressure( graph: Map<String, Valve>, distances: Map<String, Int>, currentPos: String, mnLeft: Int, currFlow: Int, total: Int, debugPath: String ): Pair<Int, String>? { if (mnLeft < 0) return null if (mnLeft == 0) return Pair(total, debugPath) val leftToOpen = graph.values.filter { it.shouldOpen() } if (leftToOpen.isEmpty()) return Pair(total + currFlow * mnLeft, debugPath) val totals = mutableListOf<Pair<Int, String>>() for (left in leftToOpen) { val dist = distances["${left.name}-$currentPos"]!! val timeToOpenValve = dist + 1 left.open() val tot = getMaxPressure(graph, distances, left.name, mnLeft - timeToOpenValve, currFlow + left.flowRate, total + (currFlow * timeToOpenValve), "$debugPath -> ${left.name}" ) if (tot != null) totals.add(tot) left.close() } totals.add(Pair(total + currFlow * mnLeft, debugPath)) // The total if we sit here doing nothing return totals.maxByOrNull { it.first } } fun part1(input: List<String>): Int? { val graph = parseInput(input) val distances = fillDistances(graph) return getMaxPressure(graph, distances, "AA",30, 0, 0, "AA")?.first } // https://www.reddit.com/r/adventofcode/comments/znjzjm/2022_day_16_if_a_solution_gives_me_a_star_then/ fun part2(input: List<String>): Int { val graph = parseInput(input) val distances = fillDistances(graph) val me = getMaxPressure(graph, distances, "AA", 26, 0, 0, "AA")!! for (name in me.second.split(" -> ")) { graph[name]!!.open() } val elephant = getMaxPressure(graph, distances, "AA", 26, 0, 0, "AA")!! return me.first + elephant.first } fun main() { val testInput = readInput("day16_example.txt") printTimeMillis { print("part1 example = $GREEN" + part1(testInput) + RESET) } printTimeMillis { print("part2 example = $GREEN" + part2(testInput) + RESET) } // 1707 val input = readInput("day16.txt") printTimeMillis { print("part1 input = $GREEN" + part1(input) + RESET) } printTimeMillis { print("part2 input = $GREEN" + part2(input) + RESET) } }
0
Kotlin
0
2
8ccdcce24cecca6e1d90c500423607d411c9fee2
4,032
advent-of-code
Apache License 2.0
src/Day05.kt
dcbertelsen
573,210,061
false
{"Kotlin": 29052}
import java.io.File fun main() { fun dataToParts(input: String): Pair<String, String> { val parts = input.split("\n\n") return parts[0] to parts[1] } fun initStacks(input: String): Map<Int, MutableList<Char>>{ val lines = input.split("\n").reversed() val stacks = lines[0].filter { it != ' ' }.map { c -> c.digitToInt() to mutableListOf<Char>() }.toMap() lines.drop(1).forEach { line -> line.chunked(4).forEachIndexed { i, s -> if (s[1] != ' ') stacks[i+1]?.add(s[1]) } } return stacks } fun readMoves(input: String): List<Triple<Int, Int, Int>> { return input.lines().map { line -> line.split(" ")} .map { Triple(it[1].toInt(), it[3].toInt(), it[5].toInt())} } fun part1(input: String): String { val (stackData, moveData) = dataToParts(input) val stacks = initStacks(stackData) val moves = readMoves(moveData) moves.forEach { move -> repeat (move.first) { stacks[move.third]?.add(stacks[move.second]?.removeLast() ?: ' ') } } return stacks.map { it.value.last() }.joinToString("") } fun part2(input: String): String { val (stackData, moveData) = dataToParts(input) val stacks = initStacks(stackData) val moves = readMoves(moveData) moves.forEach { move -> val crates = stacks[move.second]?.takeLast(move.first) ?: listOf() repeat(move.first) { stacks[move.second]?.removeLast() } stacks[move.third]?.addAll(crates) } return stacks.map { it.value.last() }.joinToString("") } val testInput = listOf<String>( " [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" ).joinToString("\n") // test if implementation meets criteria from the description, like: val test = part1(testInput) println(test) check(test == "CMZ") // check(part2(testInput) == 42) val input = File("./src/resources/Day05.txt").readText() println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
9d22341bd031ffbfb82e7349c5684bc461b3c5f7
2,282
advent-of-code-2022-kotlin
Apache License 2.0
src/Day04.kt
arturkowalczyk300
573,084,149
false
{"Kotlin": 31119}
fun main() { fun part1(input: List<String>): Int { //divide lines to ranges per elf var countRangeFullyContainsAnotherRange = 0 input.forEach { line -> val ranges = line.split(',') val rangeStringElf1 = ranges[0].split('-') val rangeStringElf2 = ranges[1].split('-') val rangeElf1 = IntRange(rangeStringElf1[0].toInt(), rangeStringElf1[1].toInt()) val rangeElf2 = IntRange(rangeStringElf2[0].toInt(), rangeStringElf2[1].toInt()) if (rangeElf1.toList().containsAll(rangeElf2.toList()) || rangeElf2.toList().containsAll(rangeElf1.toList()) ) countRangeFullyContainsAnotherRange++ } return countRangeFullyContainsAnotherRange } fun part2(input: List<String>): Int { //divide lines to ranges per elf var countRangeContainsPartOfAnotherRange = 0 input.forEach { line -> val ranges = line.split(',') val rangeStringElf1 = ranges[0].split('-') val rangeStringElf2 = ranges[1].split('-') val rangeElf1 = IntRange(rangeStringElf1[0].toInt(), rangeStringElf1[1].toInt()) val rangeElf2 = IntRange(rangeStringElf2[0].toInt(), rangeStringElf2[1].toInt()) if (rangeElf1.toList().intersect(rangeElf2.toList()).isNotEmpty()) countRangeContainsPartOfAnotherRange++ } return countRangeContainsPartOfAnotherRange } // test if implementation meets criteria from the description, like: val testInput = readInput("Day04_test") check(part1(testInput) == 2) val input = readInput("Day04") println(part1(input)) //second part check(part2(testInput) == 4) println(part2(input)) }
0
Kotlin
0
0
69a51e6f0437f5bc2cdf909919c26276317b396d
1,794
aoc-2022-in-kotlin
Apache License 2.0
src/day12/Code.kt
ldickmanns
572,675,185
false
{"Kotlin": 48227}
package day12 import readInput typealias Grid = Array<IntArray> val Grid.nRows get() = size val Grid.nColumns get() = first().size operator fun Grid.get(coordinates: Coordinates) = this[coordinates.y][coordinates.x] operator fun Grid.set(coordinates: Coordinates, int: Int) { this[coordinates.y][coordinates.x] = int } typealias Coordinates = Pair<Int, Int> val Coordinates.x get() = first val Coordinates.y get() = second val Coordinates.up get() = Coordinates(x, y + 1) val Coordinates.right get() = Coordinates(x + 1, y) val Coordinates.down get() = Coordinates(x, y - 1) val Coordinates.left get() = Coordinates(x - 1, y) private infix fun Coordinates.inside(grid: Grid) = x >= 0 && x < grid.nColumns && y >= 0 && y < grid.nRows fun main() { val input = readInput("day12/input") // val input = readInput("day12/input_test") val heightMap = transformToHeightMap(input) println(part1(heightMap)) println(part2(heightMap)) } private fun transformToHeightMap( input: List<String> ): Grid = input.map { row -> row.map { it.code }.toIntArray() }.toTypedArray() fun part1(grid: Grid): Int { val startingPoint = findLetter(letter = 'S', grid = grid) return computeDistance(grid = grid, startingPoint = startingPoint) } private fun computeDistance(grid: Grid, startingPoint: Coordinates): Int { val distances = Array(grid.nRows) { IntArray(grid.nColumns) { Int.MAX_VALUE } } distances[startingPoint] = 0 dijkstra( currentPoint = startingPoint, grid = grid, distances = distances, ) val targetPoint = findLetter(letter = 'E', grid = grid) return distances[targetPoint] } private fun findLetter(letter: Char, grid: Grid): Coordinates { grid.forEachIndexed { rowIndex, row -> row.forEachIndexed { columnIndex, code -> if (code == letter.code) return Coordinates(columnIndex, rowIndex) } } error("Letter not found") } private fun dijkstra( currentPoint: Coordinates, currentCode: Int = 'a'.code, grid: Grid, steps: Int = 0, distances: Grid, ): Unit = with(currentPoint) { val directions = mutableListOf<Coordinates>() // up val up = currentPoint.up if (up inside grid) directions.add(up) // right val right = currentPoint.right if (right inside grid) directions.add(Coordinates(x + 1, y)) // down val down = currentPoint.down if (down inside grid) directions.add(down) // left val left = currentPoint.left if (left inside grid) directions.add(left) val nextSteps = steps + 1 directions.forEach { destinationCoordinates -> val destinationCode = grid[destinationCoordinates] if (destinationCode == 'E'.code && currentCode == 'z'.code) { distances[destinationCoordinates] = nextSteps return } if (destinationCode > currentCode + 1 || destinationCode == 'E'.code) return@forEach if (distances[destinationCoordinates] > nextSteps) { distances[destinationCoordinates] = nextSteps dijkstra( currentPoint = destinationCoordinates, currentCode = destinationCode, grid = grid, steps = nextSteps, distances = distances, ) } } } fun part2(grid: Grid): Int { val startingPoint = findLetter(letter = 'S', grid = grid) grid[startingPoint] = 'a'.code val startingPoints = findLetters('a', grid = grid) var shortestDistance = Int.MAX_VALUE startingPoints.forEach { potentialStartingPoint -> val distance = computeDistance(grid = grid, startingPoint = potentialStartingPoint) if (distance < shortestDistance) shortestDistance = distance } return shortestDistance } private fun findLetters(letter: Char, grid: Grid): List<Coordinates> { val coordinates = mutableListOf<Coordinates>() grid.forEachIndexed { rowIndex, row -> row.forEachIndexed { columnIndex, code -> if (code == letter.code) coordinates.add(Coordinates(columnIndex, rowIndex)) } } return coordinates }
0
Kotlin
0
0
2654ca36ee6e5442a4235868db8174a2b0ac2523
4,158
aoc-kotlin-2022
Apache License 2.0
src/Day05.kt
Cryosleeper
572,977,188
false
{"Kotlin": 43613}
import java.util.Deque import java.util.LinkedList fun main() { fun part1(input: List<String>): String { val (stacks, moves) = input.parseInput() for (move in moves) { for (x in 0 until move.number) { stacks[move.to].addFirst(stacks[move.from].pop()) } } return stacks.map { it.peek() }.joinToString("") } fun part2(input: List<String>): String { val (stacks, moves) = input.parseInput() val buffer = LinkedList<Char>() for (move in moves) { (0 until move.number).forEach { _ -> buffer.addFirst(stacks[move.from].pop()) } (0 until move.number).forEach { _ -> stacks[move.to].addFirst(buffer.pop()) } } return stacks.map { it.peek() }.joinToString("") } // test if implementation meets criteria from the description, like: val testInput = readInput("Day05_test") check(part1(testInput) == "CMZ") check(part2(testInput) == "MCD") val input = readInput("Day05") println(part1(input)) println(part2(input)) } data class Move(val from: Int, val to: Int, val number: Int) fun List<String>.parseInput(): Pair<List<Deque<Char>>, List<Move>> { val inputDividerIndex = indexOf("") val initialStacks = subList(0, inputDividerIndex) val initialMoves = subList(inputDividerIndex + 1, size) val stacks = initialStacks.toQueues() val moves = initialMoves.toMoves() return Pair(stacks, moves) } private fun List<String>.toMoves(): List<Move> { val result = mutableListOf<Move>() val regex = "\\d+".toRegex() for (line in this) { regex.findAll(line).toList().apply { result.add( Move( from = this[1].value.toInt() - 1, to = this[2].value.toInt() - 1, number = this[0].value.toInt() ) ) } } return result } private fun List<String>.toQueues(): List<Deque<Char>> { val input = reversed() val stackNumber = "\\d+".toRegex().findAll(input[0]).count() val stacks = (0 until stackNumber).map { LinkedList<Char>() } val regex = "[A-Z]+".toRegex() for (line in input.subList(1, input.size)) { regex.findAll(line).forEach { stacks[it.range.first / 4].push(it.value[0]) } } return stacks }
0
Kotlin
0
0
a638356cda864b9e1799d72fa07d3482a5f2128e
2,445
aoc-2022
Apache License 2.0
src/day23/Day23.kt
daniilsjb
726,047,752
false
{"Kotlin": 66638, "Python": 1161}
package day23 import java.io.File import kotlin.math.max fun main() { val data = parse("src/day23/Day23.txt") println("🎄 Day 23 🎄") println() println("[Part 1]") println("Answer: ${part1(data)}") println() println("[Part 2]") println("Answer: ${part2(data)}") } private fun parse(path: String): List<List<Char>> = File(path) .readLines() .map(String::toList) private val directions = mapOf( '.' to listOf((1 to 0), (-1 to 0), (0 to 1), (0 to -1)), '>' to listOf((1 to 0)), '<' to listOf((-1 to 0)), 'v' to listOf((0 to 1)), '^' to listOf((0 to -1)), ) private data class Vertex( val x: Int, val y: Int, ) private fun dfs( graph: Map<Vertex,Map<Vertex, Int>>, source: Vertex, target: Vertex, visited: Set<Vertex> = setOf(), ): Int { if (source == target) { return 0 } var distance = Int.MIN_VALUE for ((adjacent, weight) in graph.getValue(source)) { if (adjacent !in visited) { distance = max(distance, weight + dfs(graph, adjacent, target, visited + adjacent)) } } return distance } private fun solve(grid: List<List<Char>>): Int { val sz = grid.size val source = Vertex(1, 0) val target = Vertex(sz - 2, sz - 1) val vertices = mutableListOf(source, target) for ((y, row) in grid.withIndex()) { for ((x, col) in row.withIndex()) { if (col == '#') { continue } val neighbors = listOfNotNull( grid.getOrNull(y)?.getOrNull(x - 1), grid.getOrNull(y)?.getOrNull(x + 1), grid.getOrNull(y - 1)?.getOrNull(x), grid.getOrNull(y + 1)?.getOrNull(x), ) if (neighbors.count { it == '#' } <= 1) { vertices += Vertex(x, y) } } } val graph = vertices.associateWith { mutableMapOf<Vertex, Int>() } for (origin in vertices) { val options = ArrayDeque<Pair<Vertex, Int>>().apply { add(origin to 0) } val visited = mutableSetOf(origin) while (options.isNotEmpty()) { val (vertex, n) = options.removeFirst() val (vx, vy) = vertex if (n != 0 && vertex in vertices) { graph.getValue(origin)[vertex] = n continue } for ((dx, dy) in directions.getValue(grid[vy][vx])) { val nx = vx + dx val ny = vy + dy if (nx !in 0..<sz || ny !in 0..<sz) { continue } if (grid[ny][nx] == '#') { continue } if (Vertex(nx, ny) in visited) { continue } options += Vertex(nx, ny) to (n + 1) visited += Vertex(nx, ny) } } } return dfs(graph, source, target) } private fun part1(data: List<List<Char>>): Int = solve(data) private fun part2(data: List<List<Char>>): Int = solve(data.map { it.map { c -> if (c in "<^v>") '.' else c } })
0
Kotlin
0
0
46a837603e739b8646a1f2e7966543e552eb0e20
3,293
advent-of-code-2023
MIT License
src/Day11.kt
kipwoker
572,884,607
false
null
import kotlin.math.pow data class Modifier(val op: Char, val value: Int) data class Condition(val divisibleBy: Int, val ifTrue: Int, val ifFalse: Int) data class Monkey( val index: Int, val queue: MutableList<Long>, val modifier: Modifier, val condition: Condition, var inspectionCount: Long ) fun main() { fun parse(input: List<String>): List<Monkey> { val chunks = input.chunked(7) return chunks.map { it -> val index = it[0].toInt() val items = it[1].split(',').map { x -> x.toLong() }.toMutableList() val modifierParts = it[2].split(' ') val modifier = Modifier(modifierParts[0][0], modifierParts[1].toInt()) val divisibleBy = it[3].toInt() val ifTrue = it[4].toInt() val ifFalse = it[5].toInt() val condition = Condition(divisibleBy, ifTrue, ifFalse) Monkey(index, items, modifier, condition, 0) } } fun applyModifier(value: Long, modifier: Modifier): Long { return when (modifier.op) { '^' -> value.toDouble().pow(modifier.value.toDouble()).toLong() '+' -> value + modifier.value '*' -> value * modifier.value else -> throw RuntimeException("Unknown modifier $modifier") } } fun applyCondition(value: Long, condition: Condition): Int { return if (value % condition.divisibleBy == 0L) condition.ifTrue else condition.ifFalse } fun printState(monkeys: List<Monkey>) { for (monkey in monkeys) { println("Monkey ${monkey.index}: ${monkey.queue}") } } fun printCounts(monkeys: List<Monkey>) { for (monkey in monkeys) { println("Monkey ${monkey.index}: ${monkey.inspectionCount}") } } fun play(monkeys: List<Monkey>, iterationsCount: Int, worryReducer: (v: Long) -> Long) { val overflowBreaker = monkeys.map { it.condition.divisibleBy }.reduce { acc, i -> acc * i } for (i in 1..iterationsCount) { for (monkey in monkeys) { for (item in monkey.queue) { val worryLevel = applyModifier(item, monkey.modifier) val newLevel = worryReducer(worryLevel) % overflowBreaker val newIndex = applyCondition(newLevel, monkey.condition) monkeys[newIndex].queue.add(newLevel) ++monkey.inspectionCount } monkey.queue.clear() } if (i % 20 == 0){ println("Iteration $i") printCounts(monkeys) println() } } } fun calculateResult(monkeys: List<Monkey>): Long { val ordered = monkeys.sortedBy { -it.inspectionCount } return ordered[0].inspectionCount * ordered[1].inspectionCount } fun part1(input: List<String>): Long { val monkeys = parse(input) play(monkeys, 20) { x -> x / 3 } return calculateResult(monkeys) } fun part2(input: List<String>): Long { val monkeys = parse(input) play(monkeys, 10000) { x -> x } return calculateResult(monkeys) } val testInput = readInput("Day11_test") assert(part1(testInput), 10605L) assert(part2(testInput), 2713310158L) val input = readInput("Day11") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
d8aeea88d1ab3dc4a07b2ff5b071df0715202af2
3,436
aoc2022
Apache License 2.0
src/Day02.kt
rod41732
728,131,475
false
{"Kotlin": 26028}
import kotlin.math.max fun main() { fun parseShow(show: String): List<Int> { val counts = mutableListOf(0, 0, 0) val colors = show.split(',').map { it.trim() } colors.forEach { val (num, name) = it.split(' ') val numInt = num.toInt() when (name) { "red" -> counts[0] = numInt "green" -> counts[1] = numInt "blue" -> counts[2] = numInt else -> throw Exception("Unreachable!") } } return counts } fun part1(input: List<String>): Int { var total = 0 input.forEachIndexed { idx, it -> val shows = it.substringAfter(':').split(";") val possible = !shows.any { val counts = parseShow(it) counts[0] > 12 || counts[1] > 13 || counts[2] > 14 } if (possible) { total += idx + 1 } } return total } fun part2(input: List<String>): Int { var total = 0 input.forEachIndexed { idx, it -> val shows = it.substringAfter(':').split(";") val counts = mutableListOf(0, 0, 0) shows.forEach { val colors = it.split(',').map { it.trim() } colors.forEach { val (num, name) = it.split(' ') val numInt = num.toInt() when (name) { "red" -> counts[0] = max(counts[0], numInt) "green" -> counts[1] = max(counts[1], numInt) "blue" -> counts[2] = max(counts[2], numInt) else -> throw Exception("Unreachable!") } } } total += counts[0] * counts[1] * counts[2] } return total } // test if implementation meets criteria from the description, like: val testInput = readInput("Day02_test") assertEqual(part1(testInput), 8) assertEqual(part2(testInput) , 2286) val input = readInput("Day02") part1(input).println() part2(input).println() }
0
Kotlin
0
0
05a308a539c8a3f2683b11a3a0d97a7a78c4ffac
2,170
aoc-23
Apache License 2.0
src/Day15.kt
schoi80
726,076,340
false
{"Kotlin": 83778}
fun Char.convert(curr: Long = 0): Long { return (curr + this.code) * 17 % 256 } fun String.convert(): Long { return fold(0L) { acc, c -> c.convert(acc) } } data class Box( val set: MutableSet<String>, val list: MutableList<String>, val label: MutableMap<String, Int> ) { fun remove(lens: String) { if (set.contains(lens)) { set.remove(lens) list.remove(lens) label.remove(lens) } } fun add(lens: String, fl: Int) { label[lens] = fl if (!set.contains(lens)) { set.add(lens) list.add(lens) } } fun calc(): Long { return list.mapIndexed { index, s -> (index + 1L) * label[s]!! }.sum() } } fun main() { fun part1(input: List<String>): Long { return input.sumOf { it.split(",").sumOf { it.fold(0L) { acc, c -> c.convert(acc) } } } } fun part2(input: List<String>): Long { val boxes = Array<Box>(256) { Box(mutableSetOf(), mutableListOf(), mutableMapOf()) } input[0].split(",").forEach { val tokens = it.split("=") if (tokens.size == 2) { val lens = tokens[0] val fl = tokens[1].toInt() val index = lens.convert().toInt() boxes[index].add(lens, fl) } else { val lens = it.take(it.length - 1) val index = lens.convert().toInt() boxes[index].remove(lens) } } return boxes.mapIndexed { i, box -> (i + 1) * box.calc() }.sum() } val input = readInput("Day15") part1(input).println() part2(input).println() }
0
Kotlin
0
0
ee9fb20d0ed2471496185b6f5f2ee665803b7393
1,753
aoc-2023
Apache License 2.0
src/main/kotlin/fijb/leetcode/algorithms/A5LongestPalindromicSubstring.kt
fi-jb
552,324,917
false
{"Kotlin": 22836}
package fijb.leetcode.algorithms // https://leetcode.com/problems/longest-palindromic-substring/ object A5LongestPalindromicSubstring { fun longestPalindrome(s: String): String { var max = Pair(0, 0) for (i in s.indices) max = maxPairOf(max, maxPairOf(getOddPair(s, i), getEvenPair(s, i))) return s.substring(max.first, max.second) } // "aba" for example private fun getOddPair(s: String, point: Int): Pair<Int, Int> { var i = 0 while (point - i - 1 >= 0 && point + i + 1 <= s.length - 1 && s[point - i - 1] == s[point + i + 1]) i ++ return Pair(maxOf(0, point - i), minOf(s.length, point + i) + 1) } // "abba" for example private fun getEvenPair(s: String, point: Int): Pair<Int, Int> { var i = 0 if (point + 1 > s.length - 1 || s[point] != s[point + 1]) return Pair(0, 0) while (point - i - 1 >= 0 && point + i + 2 <= s.length - 1 && s[point - i - 1] == s[point + i + 2]) i ++ return Pair(maxOf(0, point - i), minOf(s.length, point + i + 1) + 1) } private fun maxPairOf(p1: Pair<Int, Int>, p2: Pair<Int, Int>) = if (p1.second - p1.first >= p2.second - p2.first) p1 else p2 }
0
Kotlin
0
0
f0d59da5bcffaa7a008fe6b83853306d40ac4b90
1,205
leetcode
MIT License
src/Day03.kt
uzorov
576,933,382
false
{"Kotlin": 6068}
import java.io.File fun main() { fun parseInput(input: String): List<String> { return input.split("\n").map { it } } fun getCodeNumber(i: Char): Int { return if (i.code > 96) i.code - 96 else i.code - 38 } fun compareAndReturnNextSum(sortedstringsPart1: String, sortedstringsPart2: String): Int { for (i in sortedstringsPart1) { for (j in sortedstringsPart2) { if (i == j) return getCodeNumber(i) } } return -999999 } fun part1(input: String): Int { val sortedStrings_first_part = parseInput(input).map { it.substring(it.length / 2) } val sortedStrings_second_part = parseInput(input).map { it.substring(0, it.length / 2) } var sum = 0 for (i in sortedStrings_first_part.indices) { sum += compareAndReturnNextSum(sortedStrings_first_part[i], sortedStrings_second_part[i]) } return sum } fun compareAndReturnNextSumForManyEls(s: String, s1: String, s2: String): Int { s.forEach { if ((s1.indexOf(it) != -1) and (s2.indexOf(it) != -1)) { return getCodeNumber(it) } } return -9999999 } fun part2(input: String): Int { val listOfElvesItems: List<String> = parseInput(input) var sum = 0 for (i in listOfElvesItems.indices step 3) { sum += compareAndReturnNextSumForManyEls(listOfElvesItems[i], listOfElvesItems[i+1], listOfElvesItems[i+2]) } return sum } // fun part2(input: List<String>): Int { // return //} // test if implementation meets criteria from the description, like: //val testInput = readInput("Day01_test") //check(part1(testInput) == 1) val input = File("src/day3input.txt").readText() part2(input).println() } //part2(input).println()
0
Kotlin
0
0
be4ec026f6114f2fa7ae7ebd9b55af9215de8e7b
2,041
aoc-2022-in-kotlin
Apache License 2.0
src/adventofcode/day08/Day08.kt
bstoney
574,187,310
false
{"Kotlin": 27851}
package adventofcode.day08 import adventofcode.AdventOfCodeSolution import adventofcode.peek fun main() { Solution.solve() } object Solution : AdventOfCodeSolution<Int>() { override fun solve() { solve(8, 21, 8) } override fun part1(input: List<String>): Int { return getTrees(input).count { it.visibility == TreeVisibility.Visible } } override fun part2(input: List<String>): Int? { return getTrees(input).maxOfOrNull { it.scenicScore } } private fun getTrees(input: List<String>): List<Tree> { val trees = input.mapIndexed { r, row -> row.map { char -> char.code - 0x30 } .mapIndexed { c, height -> UnexploredTree(r, c, height) } } val maxR = trees.lastIndex val maxC = trees[0].lastIndex return trees.flatten() .map { tree -> with(tree) { val treeNorth = (r - 1 downTo 0).map { trees[it][c] }.find { isBlockedBy(it) } ?: Edge(0, c) val treeSouth = (r + 1..maxR).map { trees[it][c] }.find { isBlockedBy(it) } ?: Edge(maxR, c) val treeWest = (c - 1 downTo 0).map { trees[r][it] }.find { isBlockedBy(it) } ?: Edge(r, 0) val treeEast = (c + 1..maxC).map { trees[r][it] }.find { isBlockedBy(it) } ?: Edge(r, maxC) tree.viewTo(treeNorth, treeEast, treeSouth, treeWest) } } .peek { debug("tree ${it.r},${it.c} ${it.height} is ${it.visibility}") } .toList() } enum class TreeVisibility { Visible, Hidden, Unknown, } interface GridLocation { val r: Int val c: Int } data class Edge(override val r: Int, override val c: Int) : GridLocation interface Tree : GridLocation { val height: Int val visibility: TreeVisibility val scenicScore: Int fun isBlockedBy(other: Tree): Boolean { if (other.height >= height) { debug("tree: $r,$c $height") debug("blocked by: ${other.r},${other.c} ${other.height}") return true } return false } } data class UnexploredTree(override val r: Int, override val c: Int, override val height: Int) : Tree { override val visibility = TreeVisibility.Unknown override val scenicScore: Int get() = throw IllegalStateException("Unexplored") fun viewTo(n: GridLocation, e: GridLocation, s: GridLocation, w: GridLocation) = ExploredTree(r, c, height, ViewTo(n, e, s, w)) } data class ExploredTree( override val r: Int, override val c: Int, override val height: Int, val view: ViewTo ) : Tree { override val visibility: TreeVisibility by lazy { if (view.any { it is Edge }) { TreeVisibility.Visible } else { TreeVisibility.Hidden } } override val scenicScore: Int by lazy { val viewNorth = r - view.n.r val viewEast = view.e.c - c val viewSouth = view.s.r - r val viewWest = c - view.w.c viewNorth * viewEast * viewSouth * viewWest } } data class ViewTo(val n: GridLocation, val e: GridLocation, val s: GridLocation, val w: GridLocation) : Iterable<GridLocation> { override fun iterator(): Iterator<GridLocation> = listOf(n, e, s, w).iterator() } }
0
Kotlin
0
0
81ac98b533f5057fdf59f08940add73c8d5df190
3,564
fantastic-chainsaw
Apache License 2.0
src/year2021/day2/Day02.kt
tiagoabrito
573,609,974
false
{"Kotlin": 73752}
package year2021.day2 import readInput fun main() { fun aaa(a: List<String>?): Int { return (a ?: emptyList()).map { it.split(" ") }.map { when (it[0]) { "up" -> -1 else -> 1 } * it[1].toInt() }.sum() } fun part1(input: List<String>): Int { val groupBy = input.groupBy(keySelector = { it.first() == 'f' }) return aaa(groupBy[true]) * aaa(groupBy[false]) } data class Position(val x: Int=0, val y: Int=0, val aim: Int=0) fun asPosition(it: List<String>) = when (it[0]) { "up" -> Position(aim = -1 * it[1].toInt()) "down" -> Position(aim = it[1].toInt()) else -> Position(x = it[1].toInt()) } fun part2(input: List<String>): Int { val map = input.map { a -> asPosition(a.split(" ")) } return map .reduce { acc, b -> Position(acc.x + b.x, acc.y + acc.aim*b.x, acc.aim + b.aim) } .let { it.x * it.y } } // test if implementation meets criteria from the description, like: val testInput = readInput("year2021/Day02_test") check(part1(testInput) == 150) val input = readInput("year2021/Day02") println(part1(input)) check(part2(testInput) == 900) println(part2(input)) }
0
Kotlin
0
0
1f9becde3cbf5dcb345659a23cf9ff52718bbaf9
1,292
adventOfCode
Apache License 2.0
src/Day09.kt
jstapels
572,982,488
false
{"Kotlin": 74335}
import kotlin.math.absoluteValue // fun dumpKnots(knots: List<Pos>, locs: Set<Pos>): String { // val dump = StringBuilder() // val maxX = 20//knots.maxOf { it.x } // val maxY = 20//knots.maxOf { it.y } // (maxY downTo 0).forEach { y -> // (0..maxX).map { Pos(it, y) } // .forEach { // knots.withIndex() // .firstOrNull { (i, v) -> v == it } // ?.let { (i, _) -> dump.append(i) } // ?: dump.append(if (it in locs) "#" else ".") // } // dump.append("\n") // } // return dump.toString() // } fun main() { data class Cmd(val dir: String, val len: Int) data class Coord(val x: Int, val y: Int) { fun move(cmd: Cmd) = when (cmd.dir) { "U" -> Coord(x, y + cmd.len) "D" -> Coord(x, y - cmd.len) "L" -> Coord(x - cmd.len, y) "R" -> Coord(x + cmd.len, y) else -> throw IllegalArgumentException("Unrecognized cmd: $cmd") } fun tail(head: Coord): Coord { if (distance(head) <= 1) return this val dx = (head.x - x).coerceIn(-1, 1) val dy = (head.y - y).coerceIn(-1, 1) return Coord(x + dx, y + dy) } fun distance(coord: Coord) = maxOf((x - coord.x).absoluteValue, (y - coord.y).absoluteValue) } fun parseInput(input: List<String>) = input.map { it.split(" ") } .map { (d, l) -> Cmd(d, l.toInt()) } fun follow(cmds: List<Cmd>, size:Int): Int { val knots = MutableList(size) { _ -> Coord(0, 0) } val locs = mutableSetOf(Coord(0, 0)) cmds.flatMap { c -> (1..c.len).map { Cmd(c.dir, 1) } } .forEach { cmd -> knots.indices .forEach { i -> when (i) { 0 -> knots[0] = knots[0].move(cmd) else -> { knots[i] = knots[i].tail(knots[i - 1]) if (i + 1 == size) locs.add(knots[i]) } } } } return locs.size } fun part1(input: List<String>): Int { return follow(parseInput(input), 2) } fun part2(input: List<String>): Int { return follow(parseInput(input), 10) } // test if implementation meets criteria from the description, like: val testInput = readInput("Day09_test") checkThat(part1(testInput), 13) checkThat(part2(testInput), 1) val testInput2 = readInput("Day09_test2") checkThat(part2(testInput2), 36) val input = readInput("Day09") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
0d71521039231c996e2c4e2d410960d34270e876
2,805
aoc22
Apache License 2.0
src/main/kotlin/net/navatwo/adventofcode2023/day6/Day6Solution.kt
Nava2
726,034,626
false
{"Kotlin": 100705, "Python": 2640, "Shell": 28}
package net.navatwo.adventofcode2023.day6 import net.navatwo.adventofcode2023.framework.ComputedResult import net.navatwo.adventofcode2023.framework.Solution import kotlin.math.ceil import kotlin.math.floor sealed class Day6Solution : Solution<Day6Solution.Races> { data object Part1 : Day6Solution() { override fun solve(input: Races): ComputedResult { val races = input.times.asSequence() .zip(input.records.asSequence()) { time, distance -> TimeMs(time.toLong()) to DistanceMM(distance.toLong()) } val winnersPerRace = races.map { (time, record) -> computeNumberOfWinners(time, record) } val multiple = winnersPerRace.fold(1L, Long::times) return ComputedResult.Simple(multiple) } } data object Part2 : Day6Solution() { override fun solve(input: Races): ComputedResult { val time = input.times.fold(StringBuilder(), StringBuilder::append).toString().toLong() val record = input.records.fold(StringBuilder(), StringBuilder::append).toString().toLong() val result = computeNumberOfWinners(TimeMs(time), DistanceMM(record)) return ComputedResult.Simple(result) } } protected fun computeNumberOfWinners(time: TimeMs, record: DistanceMM): Long { // r = record // d = distance past record // t = max time // h = hold time // // (r + d) = (t - h) * h // (r + d) = -h^2 + t * h // // solving this equation for d = 0, then using the spaces between the roots computes the number // of values that are winners. // d = -h^2 + t * h - r val (first, last) = findRoots(-1, time.value, -record.value) // need to round first *down* and last *up* to get the correct value as the result could // be a decimal value for each root return floor(last).toLong() - ceil(first).toLong() + 1 } /** * Find the roots of the quadratic equation. */ private fun findRoots(a: Long, b: Long, c: Long): Pair<Double, Double> { val sqrt = Math.sqrt((b * b - 4 * a * c).toDouble()) val root1 = (-b + sqrt) / (2 * a) val root2 = (-b - sqrt) / (2 * a) return minOf(root1, root2) to maxOf(root1, root2) } override fun parse(lines: Sequence<String>): Races { val (times, distances) = lines .map { line -> line.substringAfter(':') .splitToSequence(' ') .filter { it.isNotBlank() } .map { it.trim() } .toList() } .toList() return Races(times, distances) } @JvmInline value class TimeMs(val value: Long) @JvmInline value class DistanceMM(val value: Long) data class Races(val times: List<String>, val records: List<String>) { init { check(times.size == records.size) } } }
0
Kotlin
0
0
4b45e663120ad7beabdd1a0f304023cc0b236255
2,738
advent-of-code-2023
MIT License
src/main/kotlin/aoc2022/Day08.kt
davidsheldon
565,946,579
false
{"Kotlin": 161960}
package aoc2022 import utils.InputUtils fun main() { val testInput = """30373 25512 65332 33549 35390""".split("\n") fun countTrue(it: BooleanArray) = it.count { b -> b } fun extracted(values: Iterable<IndexedValue<Char>>): Sequence<Int> { return sequence { var max: Char = 0.toChar() for ((x, c) in values) { if (c > max) { max = c; yield(x) } } } } fun columns(input: List<String>): List<IndexedValue<List<Char>>> = input[0].indices.map { index -> IndexedValue(index, input.map { it[index] }) } fun List<Char>.countUntilFirst(target: Char): Int { forEachIndexed { i, c -> if (c >= target) return i + 1 } return size } fun scenicScore( input: List<String>, y: Int, x: Int, width: Int, height: Int ): Int { val house = input[y][x] val line1 = (x + 1 until width).map { input[y][it] }.countUntilFirst(house) val line2 = (0 until x).reversed().map { input[y][it] }.countUntilFirst(house) val line3 = (y + 1 until height).map { input[it][x] }.countUntilFirst(house) val line4 = (0 until y).reversed().map { input[it][x] }.countUntilFirst(house) val score = line1 * line2 * line3 * line4 return score } fun part1(input: List<String>): Int { val visible = Array(input.size) { i -> BooleanArray(input[i].length) } for ((y, row) in input.withIndex()) { extracted(row.withIndex()).forEach { visible[y][it] = true } extracted(row.withIndex().reversed()).forEach { visible[y][it] = true } } for ((x, col) in columns(input)) { extracted(col.withIndex()).forEach { visible[it][x] = true } extracted(col.withIndex().reversed()).forEach { visible[it][x] = true } } println(visible.joinToString("\n") { row -> row.map { if (it) '1' else '.' }.toCharArray().concatToString() }) return visible.sumOf(::countTrue) } fun part2(input: List<String>): Int { val width = input[0].length val height = input.size return sequence { for (x in 1 until width - 1) { for (y in 1 until height - 1) { val score = scenicScore(input, y, x, width, height) yield(score) } } }.max() } // test if implementation meets criteria from the description, like: val testValue = part1(testInput) println(testValue) check(testValue == 21) val puzzleInput = InputUtils.downloadAndGetLines(2022, 8).toList() println(part1(puzzleInput)) println(part2(puzzleInput)) }
0
Kotlin
0
0
5abc9e479bed21ae58c093c8efbe4d343eee7714
2,776
aoc-2022-kotlin
Apache License 2.0
src/Day09.kt
azat-ismagilov
573,217,326
false
{"Kotlin": 75114}
import java.lang.RuntimeException import kotlin.math.* object Day09 { data class Position(val x: Int = 0, val y: Int = 0) { fun distance(other: Position) = max(abs(x - other.x), abs(y - other.y)) fun differenceVector(other: Position) = Position((other.x - x).sign, (other.y - y).sign) operator fun plus(other: Position) = Position(x + other.x, y + other.y) } sealed interface Move { val steps: Int } class MoveUp(override val steps: Int) : Move class MoveDown(override val steps: Int) : Move class MoveLeft(override val steps: Int) : Move class MoveRight(override val steps: Int) : Move class Rope(countTails: Int = 2) { private var positions = MutableList(countTails) { Position() } private val visitedTailInternal = mutableListOf<Position>() val visitedTail get() = visitedTailInternal.toList() private fun adjustTails() { for (index in 1 until positions.size) if (positions[index].distance(positions[index - 1]) > 1) positions[index] += positions[index].differenceVector(positions[index - 1]) visitedTailInternal.add(positions.last()) } private fun processMove(move: Move): Rope { repeat(move.steps) { positions[0] = when (move) { is MoveUp -> positions[0].copy(y = positions[0].y - 1) is MoveDown -> positions[0].copy(y = positions[0].y + 1) is MoveLeft -> positions[0].copy(x = positions[0].x - 1) is MoveRight -> positions[0].copy(x = positions[0].x + 1) } adjustTails() } return this } fun processMoves(moves: Iterable<Move>): Rope { moves.forEach { processMove(it) } return this } } fun part1(input: List<String>): Int = Rope() .processMoves(input.toMoves()).visitedTail.toSet().size fun part2(input: List<String>): Int = Rope(10) .processMoves(input.toMoves()).visitedTail.toSet().size private fun List<String>.toMoves() = this.map { val split = it.split(' ') val steps = split[1].toInt() when (split[0]) { "U" -> MoveUp(steps) "D" -> MoveDown(steps) "L" -> MoveLeft(steps) "R" -> MoveRight(steps) else -> throw RuntimeException() } } } fun main() { // test if implementation meets criteria from the description, like: val testInput = readInput("Day09_test") check(Day09.part1(testInput) == 13) val testInput2 = readInput("Day09_test2") check(Day09.part2(testInput2) == 36) val input = readInput("Day09") println(Day09.part1(input)) println(Day09.part2(input)) }
0
Kotlin
0
0
abdd1b8d93b8afb3372cfed23547ec5a8b8298aa
2,835
advent-of-code-kotlin-2022
Apache License 2.0
src/day23/result.kt
davidcurrie
437,645,413
false
{"Kotlin": 37294}
package day23 import java.io.File import java.util.* import kotlin.math.abs fun main() { println(solve("src/day23/input.txt")) println(solve("src/day23/input-part2.txt")) } enum class Amphipod(val stepEnergy: Int) { A(1), B(10), C(100), D(1000) } data class Room(val natives: Amphipod, val size: Int, val entry: Int, val inhabitants: List<Amphipod>) { fun allHome() = full() && allNatives() fun full() = inhabitants.size == size fun allNatives() = inhabitants.all { it == natives } fun exit(): Pair<Amphipod, Room>? { if (allNatives()) return null if (inhabitants.isEmpty()) return null return Pair(inhabitants.first(), copy(inhabitants = inhabitants.subList(1, inhabitants.size))) } fun entry(a: Amphipod?): Room? { if (a != natives) return null if (!allNatives()) return null return copy(inhabitants = listOf(a) + inhabitants) } } data class Burrow(val hallway: List<Amphipod?>, val rooms: List<Room>, val energy: Int = 0) { fun allHome() = rooms.all { it.allHome() } fun hallwayClear(from: Int, to: Int) = (if (from < to) (from+1..to) else (to until from)).all { hallway[it] == null } fun entries() = rooms.map { it.entry } fun hallwayStops() = hallway.indices.filterNot { it in entries() } fun moves(): List<Burrow> { val roomExits = rooms.withIndex().map { (roomIndex, room) -> val exit = room.exit() if (exit == null) { emptyList() } else { hallwayStops().filter { hallwayClear(room.entry, it) }.map { to -> val newHallway = hallway.mapIndexed { index, amphipod -> if (index == to) exit.first else amphipod } val newRooms = rooms.mapIndexed { index, room -> if (index == roomIndex) exit.second else room } val steps = 1 + abs(to - room.entry) + (room.size - room.inhabitants.size) val energyUse = steps * exit.first.stepEnergy Burrow(newHallway, newRooms, energy + energyUse) } } }.flatten() val roomEntries = hallway.mapIndexed { from, amphipod -> rooms.mapIndexedNotNull { roomIndex, room -> val newRoom = room.entry(amphipod) if (newRoom != null && hallwayClear(from, room.entry)) { val newHallway = hallway.mapIndexed { index, amphipod -> if (index == from) null else amphipod } val newRooms = rooms.mapIndexed { index, room -> if (index == roomIndex) newRoom else room } val steps = abs(from - room.entry) + (room.size - room.inhabitants.size) val energyUse = steps * amphipod!!.stepEnergy Burrow(newHallway, newRooms, energy + energyUse) } else { null } } }.flatten() return roomEntries + roomExits } fun print() { println("Energy: $energy") println(hallway.map { amphipod -> amphipod?.name ?: "." }.joinToString("") { it }) (0 until rooms[0].size).forEach { row -> println(hallway.indices.map { index -> rooms.firstOrNull { room -> room.entry == index } } .map { room -> if (room == null) " " else (row + room.inhabitants.size - room.size).let { if (it >= 0) room.inhabitants[it].name else "." } } .joinToString("") { it }) } } } fun solve(filename: String): Int? { val queue = PriorityQueue<List<Burrow>>(Comparator.comparingInt { it.last().energy }) queue.add(listOf(parse(filename))) val visited = mutableMapOf<Pair<List<Amphipod?>, List<Room>>, Int>() while (queue.isNotEmpty()) { val burrows = queue.poll() val burrow = burrows.last() val signature = Pair(burrow.hallway, burrow.rooms) val previousBestEnergy = visited[signature] if ((previousBestEnergy != null) && (previousBestEnergy <= burrow.energy)) { continue } visited[signature] = burrow.energy if (burrow.allHome()) { burrows.forEach { it.print() } return burrow.energy } queue.addAll(burrow.moves().map { burrows + it }) } return null } fun parse(filename: String): Burrow { val lines = File(filename).readLines() val hallway = lines[1].drop(1).dropLast(1).map { if (it == '.') null else Amphipod.valueOf(it.toString()) } val roomLines = lines.drop(2).dropLast(1) val rooms = (0..3).map { room -> val natives = Amphipod.values()[room] val inhabitants = roomLines.mapNotNull { if (it[3 + (room * 2)] == '.') null else Amphipod.valueOf(it[3 + (room * 2)].toString()) } Room(natives, roomLines.size, 2 + (room * 2), inhabitants) } return Burrow(hallway, rooms) }
0
Kotlin
0
0
dd37372420dc4b80066efd7250dd3711bc677f4c
4,914
advent-of-code-2021
MIT License
src/Day09.kt
shepard8
573,449,602
false
{"Kotlin": 73637}
import kotlin.math.abs open class Node { protected var x = 0 protected var y = 0 fun move(dx: Int, dy: Int) { x += dx y += dy } open fun follow(other: Node) { val dx = abs(other.x - x) val dy = abs(other.y - y) if (dx > 1 && dy > 1) { x = (x + other.x) / 2 y = (y + other.y) / 2 } else if (dx > 1) { x = (x + other.x) / 2 y = other.y } else if (dy > 1) { y = (y + other.y) / 2 x = other.x } } } class CountingNode: Node() { private val visitedPositions = mutableSetOf(Pair(0, 0)) override fun follow(other: Node) { super.follow(other) visitedPositions.add(Pair(x, y)) } fun numberOfVisitedPositions() = visitedPositions.count() } fun unitVector(direction: String): Pair<Int, Int> = when (direction) { "U" -> Pair(0, 1) "D" -> Pair(0, -1) "L" -> Pair(-1, 0) "R" -> Pair(1, 0) else -> throw IllegalArgumentException() } fun part1(input: List<String>): Int { val head = Node() val tail = CountingNode() input.forEach { line -> val (direction, count) = line.split(" ") val (dx, dy) = unitVector(direction) for (i in 1..count.toInt()) { head.move(dx, dy) tail.follow(head) } } return tail.numberOfVisitedPositions() } fun part2(input: List<String>): Int { val nodes = (1..9).map { Node() } + CountingNode() input.forEach { line -> val (direction, count) = line.split(" ") val (dx, dy) = unitVector(direction) for (i in 1..count.toInt()) { nodes[0].move(dx, dy) (1..9).forEach { nodes[it].follow(nodes[it - 1]) } } } return nodes.filterIsInstance<CountingNode>().first().numberOfVisitedPositions() } fun main() { val input = readInput("Day09") println(part1(input)) println(part2(input)) }
0
Kotlin
0
1
81382d722718efcffdda9b76df1a4ea4e1491b3c
2,015
aoc2022-kotlin
Apache License 2.0
src/Day9.kt
michaelYuenAE
573,094,416
false
{"Kotlin": 74685}
import kotlin.math.abs import kotlin.math.sign class Day9(private val input: List<String>) { private val motions = input.map { it.substringBefore(" ") to it.substringAfter(" ").toInt() } private val directions = mapOf( "R" to Point(1, 0), "U" to Point(0, 1), "L" to Point(-1, 0), "D" to Point(0, -1), ) fun solvePart1() = visitedTailPositions(numberOfKnots = 2) fun solvePart2() = visitedTailPositions(numberOfKnots = 10) private fun visitedTailPositions(numberOfKnots: Int): Int { val knots = MutableList(numberOfKnots) { Point(0, 0) } val visited = mutableSetOf<Point>() motions.forEach { (dir, steps) -> repeat(steps) { knots[0] = knots[0] + directions.getValue(dir) knots.indices.windowed(2) { (head, tail) -> if (!knots[tail].isNeighbourOf(knots[head])) { knots[tail] = knots[tail] movedTo knots[head] } } visited.add(knots.last()) } } return visited.size } private data class Point(val x: Int, val y: Int) { operator fun plus(other: Point) = Point(other.x + x, other.y + y) infix fun movedTo(other: Point) = this + Point((other.x - x).sign, (other.y - y).sign) fun isNeighbourOf(other: Point) = abs(other.x - x) < 2 && abs(other.y - y) < 2 } } fun main() { val day = "day9_input" println(Day9(readInput(day)).solvePart2()) }
0
Kotlin
0
0
ee521263dee60dd3462bea9302476c456bfebdf8
1,539
advent22
Apache License 2.0
src/Day09.kt
mrugacz95
572,881,300
false
{"Kotlin": 102751}
import kotlin.math.abs operator fun Pair<Int, Int>.plus(other: Pair<Int, Int>): Pair<Int, Int> { return Pair(this.first + other.first, this.second + other.second) } fun Pair<Int, Int>.adjacent(other: Pair<Int, Int>): Boolean { return abs(this.first - other.first) <= 1 && abs(this.second - other.second) <= 1 } fun main() { fun List<String>.parse(): List<Pair<Char, Int>> { return map { val (a, b) = it.split(' ') val dist = b.toInt() Pair(a.first(), dist) } } fun directionToPair(d: Char): Pair<Int, Int> { val dist = 1 return when (d) { 'R' -> Pair(0, dist) 'L' -> Pair(0, -dist) 'D' -> Pair(dist, 0) 'U' -> Pair(-dist, 0) else -> throw Exception("cant parse") } } fun part1(input: List<String>): Int { var headPos = Pair(0, 0) var tailPos = Pair(0, 0) val tailPositions = mutableSetOf<Pair<Int, Int>>() tailPositions.add(tailPos) input.parse().map { (d, l) -> val dir = directionToPair(d) for (i in 0 until l) { headPos += dir if (!headPos.adjacent(tailPos)) { if (headPos.first > tailPos.first) { tailPos += Pair(1, 0) } if (headPos.second > tailPos.second) { tailPos += Pair(0, 1) } if (headPos.first < tailPos.first) { tailPos += Pair(-1, 0) } if (headPos.second < tailPos.second) { tailPos += Pair(0, -1) } } tailPositions.add(tailPos) } } return tailPositions.size } fun part2(input: List<String>): Int { val ropePos = MutableList(10) { Pair(0, 0) } val tailPositions = mutableSetOf<Pair<Int, Int>>() tailPositions.add(ropePos.last()) input.parse().map { (d, l) -> val dir = directionToPair(d) for (i in 0 until l) { ropePos[0] += dir for (ropePartIdx in ropePos.indices) { if (ropePartIdx == 0) continue val prevPos = ropePos[ropePartIdx - 1] val ropePart = ropePos[ropePartIdx] var newRopePart = ropePart if (!prevPos.adjacent(ropePart)) { if (prevPos.first > ropePart.first) { newRopePart += Pair(1, 0) } if (prevPos.second > ropePart.second) { newRopePart += Pair(0, 1) } if (prevPos.first < ropePart.first) { newRopePart += Pair(-1, 0) } if (prevPos.second < ropePart.second) { newRopePart += Pair(0, -1) } } ropePos[ropePartIdx] = newRopePart } tailPositions.add(ropePos.last()) } } return tailPositions.size } val testInput1 = readInput("Day09_test1") val testInput2 = readInput("Day09_test2") val input = readInput("Day09") assert(part1(testInput1), 13) println(part1(input)) assert(part2(testInput2), 36) println(part2(input)) } // Time: 00:50
0
Kotlin
0
0
29aa4f978f6507b182cb6697a0a2896292c83584
3,588
advent-of-code-2022
Apache License 2.0
src/main/kotlin/solutions/day13/Day13.kt
Dr-Horv
570,666,285
false
{"Kotlin": 115643}
package solutions.day13 import solutions.Solver sealed class Package class ListPackage(val list: List<Package>) : Package() { override fun toString(): String = "[${list.joinToString(",")}]" companion object } fun ListPackage.Companion.of(p: IntegerPackage): Package = ListPackage(listOf(p)) class IntegerPackage(val value: Int) : Package() { override fun toString(): String = this.value.toString() } class Day13 : Solver { private fun parse(s: String): Package { val cs = s.toMutableList().subList(1, s.length) return parseHelp(cs) } private fun parseHelp(cs: MutableList<Char>): Package { val listPackages = mutableListOf<Package>() while (cs.isNotEmpty()) { when (cs.first()) { '[' -> { cs.removeFirst() val lp = parseHelp(cs) listPackages.add(lp) } ']' -> { cs.removeFirst() return ListPackage(list = listPackages) } ',' -> { cs.removeFirst() } else -> { var nbrs = "" while (cs.first().isDigit()) { nbrs += cs.removeFirst() } listPackages.add(IntegerPackage(value = nbrs.toInt())) } } } return ListPackage(list = listPackages) } override fun solve(input: List<String>, partTwo: Boolean): String { val packages = input.map { it.trim() } .filter { it.isNotBlank() } .map { parse(it) } return if (!partTwo) { var pairIndex = 1 val orderedIndices = mutableListOf<Int>() val iterator = packages.iterator() while (iterator.hasNext()) { if (comparePackage(iterator.next(), iterator.next()) < 0) { orderedIndices.add(pairIndex) } pairIndex++ } orderedIndices.sum().toString() } else { val divider1 = parse("[[2]]") val divider2 = parse("[[6]]") val packagesWithDividers = packages + listOf(divider1, divider2) val sorted = packagesWithDividers.sortedWith { a, b -> comparePackage(a, b) } ((sorted.indexOf(divider1) + 1) * (sorted.indexOf(divider2) + 1)).toString() } } private fun comparePackage(p1: Package, p2: Package): Int = when { p1 is IntegerPackage && p2 is IntegerPackage -> compareIntegerPackages(p1, p2) p1 is ListPackage && p2 is ListPackage -> compareListPackages(p1, p2) p1 is IntegerPackage && p2 is ListPackage -> comparePackage( ListPackage.of(p1), p2 ) p1 is ListPackage && p2 is IntegerPackage -> comparePackage( p1, ListPackage.of(p2) ) else -> throw Error("Unsupported compare: $p1 and $p2") } private fun compareListPackages(p1: ListPackage, p2: ListPackage): Int { val l1 = p1.list.listIterator() val l2 = p2.list.listIterator() while (l1.hasNext() && l2.hasNext()) { val comparison = comparePackage(l1.next(), l2.next()) if (comparison != 0) { return comparison } } return when { l1.hasNext().not() && l2.hasNext() -> -1 l1.hasNext().not() && l2.hasNext().not() -> 0 l1.hasNext() && l2.hasNext().not() -> 1 else -> throw Error("Unexpected") } } private fun compareIntegerPackages(p1: IntegerPackage, p2: IntegerPackage): Int = when { p1.value < p2.value -> -1 p1.value == p2.value -> 0 else -> 1 } }
0
Kotlin
0
2
6c9b24de2fe2a36346cb4c311c7a5e80bf505f9e
3,836
Advent-of-Code-2022
MIT License
src/Day03.kt
StephenVinouze
572,377,941
false
{"Kotlin": 55719}
fun main() { fun itemPriority(item: Char): Int { // char ascii code starts at 65 for uppercase letters and 97 for lowercases // Shifting uppercases for additional 26 to count after lowercases letters val offset = if (Character.isUpperCase(item)) 65 - 26 else 97 return item.code - offset + 1 } fun part1(input: List<String>): Int = input .map { val items = it.toCharArray().toList() val compartments = items.chunked(items.size / 2) val firstCompartment = compartments.first() val secondCompartment = compartments.last() firstCompartment.intersect(secondCompartment.toSet()) } .sumOf { identicalItems -> identicalItems.sumOf { item -> itemPriority(item) } } fun part2(input: List<String>): Int = input .chunked(3) .map { it.map { rucksack -> rucksack.toCharArray().toList() } } .sortedByDescending { it.size } .sumOf { groupRucksack -> val biggerRucksack = groupRucksack[0] val mediumRucksack = groupRucksack[1] val smallerRucksack = groupRucksack[2] var groupItem: Char? = null for (i in 0..biggerRucksack.lastIndex) { val item = biggerRucksack[i] if (mediumRucksack.contains(item) && smallerRucksack.contains(item)) { groupItem = item break } } if (groupItem == null) throw IllegalStateException("Must have common item") itemPriority(groupItem) } val testInput = readInput("Day03_test") check(part1(testInput) == 157) check(part2(testInput) == 70) val input = readInput("Day03") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
11b9c8816ded366aed1a5282a0eb30af20fff0c5
1,996
AdventOfCode2022
Apache License 2.0
src/Day12.kt
iam-afk
572,941,009
false
{"Kotlin": 33272}
fun main() { fun List<ByteArray>.steps(start: List<ByteArray>.() -> Sequence<Pair<Int, Int>>): Int? { val queue = ArrayDeque<Triple<Int, Int, Int>>() val visited = Array(this.size) { BooleanArray(this[it].size) } for ((i, j) in this.start()) { queue.add(Triple(i, j, 0)) visited[i][j] = true this[i][j] = 'a'.code.toByte() } val (ei, ej) = this.withIndex() .map { (i, row) -> i to row.indexOf('E'.code.toByte()) } .find { (_, j) -> j != -1 } ?: error("location of E not found") this[ei][ej] = 'z'.code.toByte() while (!queue.isEmpty()) { val (i, j, k) = queue.removeFirst() for ((di, dj) in arrayOf(1 to 0, -1 to 0, 0 to 1, 0 to -1)) { val ni = i + di val nj = j + dj if (ni in this.indices && nj in this[ni].indices && !visited[ni][nj] && this[i][j] + 1 >= this[ni][nj]) { if (ni == ei && nj == ej) return k + 1 queue.add(Triple(ni, nj, k + 1)) visited[ni][nj] = true } } } return null } fun part1(input: List<String>): Int? = input.map { it.toByteArray() }.steps { sequence { for (i in this@steps.indices) { for (j in this@steps.indices) { if (this@steps[i][j] == 'S'.code.toByte()) { yield(i to j) } } } } } fun part2(input: List<String>): Int? = input.map { it.toByteArray() }.steps { sequence { for (i in this@steps.indices) { for (j in this@steps.indices) { if (this@steps[i][j] == 'S'.code.toByte() || this@steps[i][j] == 'a'.code.toByte()) { yield(i to j) } } } } } // test if implementation meets criteria from the description, like: 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
b30c48f7941eedd4a820d8e1ee5f83598789667b
2,253
aockt
Apache License 2.0
src/main/kotlin/Day10.kt
akowal
434,506,777
false
{"Kotlin": 30540}
fun main() { println(Day10.solvePart1()) println(Day10.solvePart2()) } object Day10 { private val input = readInput("day10") private val closing = mapOf( '(' to ')', '[' to ']', '{' to '}', '<' to '>' ) private val errorScores = mapOf( ')' to 3, ']' to 57, '}' to 1197, '>' to 25137 ) private val autocompleteScores = mapOf( ')' to 1, ']' to 2, '}' to 3, '>' to 4 ) fun solvePart1() = input.sumOf { errorScore(it) } fun solvePart2() = input.filter { errorScore(it) == 0 } .map { autocompleteScore(it) } .sorted() .let { it[it.size / 2] } private fun errorScore(s: String): Int { val expect = ArrayDeque<Char>() for (c in s) { when (c) { '(', '[', '{', '<' -> expect.addLast(closing[c]!!) ')', ']', '}', '>' -> c == expect.removeLast() || return errorScores[c]!! } } return 0 } private fun autocompleteScore(s: String): Long { val expect = ArrayDeque<Char>() for (c in s) { when (c) { '(', '[', '{', '<' -> expect.addLast(closing[c]!!) ')', ']', '}', '>' -> c == expect.removeLast() || error("oops") } } return expect.reversed().fold(0L) { acc, c -> acc * 5 + autocompleteScores[c]!! } } }
0
Kotlin
0
0
08d4a07db82d2b6bac90affb52c639d0857dacd7
1,450
advent-of-kode-2021
Creative Commons Zero v1.0 Universal
src/Day9_Michael.kt
michaelYuenAE
573,094,416
false
{"Kotlin": 74685}
import kotlin.math.abs import kotlin.math.sign class Day9_Michael(private val input: List<String>) { private val motions = input.map { it.substringBefore(" ") to it.substringAfter(" ").toInt() } private val directions = mapOf( "U" to Point(0,1), "D" to Point(0,-1), "L" to Point(-1, 0), "R" to Point(1,0) ) fun solvePart1() = visitedTailPositions(numberOfKnots = 2) fun solvePart2() = visitedTailPositions(numberOfKnots = 10) private fun visitedTailPositions(numberOfKnots: Int): Int { val knots = MutableList(numberOfKnots) { Point(0, 0)} val visited = mutableSetOf<Point>() motions.forEach { (direction, times) -> repeat(times) { knots.indices.windowed(2) {(head, tail) -> knots[head] = knots[head].move(directions.getValue(direction)) if(!knots[tail].isNeighbourOf(knots[head])) { knots[tail] = knots[tail].movedTo(knots[head]) } visited.add(knots[tail]) } } } return visited.size } private data class Point(val x: Int, val y: Int) { fun move(other: Point): Point = Point(this.x + other.x, this.y + other.y) infix fun movedTo(other: Point) = this.move(Point((other.x - x).sign, (other.y - y).sign)) fun isNeighbourOf(other: Point) = abs(other.x - x) <2 && abs(other.y - y)<2 } } fun main() { val day = "day9_input" println(Day9_Michael(readInput(day)).solvePart1()) }
0
Kotlin
0
0
ee521263dee60dd3462bea9302476c456bfebdf8
1,586
advent22
Apache License 2.0
src/Day06.kt
martintomac
726,272,603
false
{"Kotlin": 19489}
fun main() { fun findLargerDistanceConfigurations(time: Long, record: Long) = (1..<time).asSequence() .map { it to it * (time - it) } .dropWhile { it.second <= record } .takeWhile { it.second > record } .toList() fun part1(lines: List<String>): Int { val times = lines[0].split(":")[1].trim().split(" +".toRegex()).map { it.toLong() } val records = lines[1].split(":")[1].trim().split(" +".toRegex()).map { it.toLong() } return times.zip(records) .map { (time, record) -> findLargerDistanceConfigurations(time, record).count() } .reduce { acc, i -> acc * i } } fun part2(lines: List<String>): Int { val time = lines[0].split(":")[1].replace(" ", "").toLong() val record = lines[1].split(":")[1].replace(" ", "").toLong() return findLargerDistanceConfigurations(time, record).count() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day06_test") part1(testInput).println() part2(testInput).println() val input = readInput("Day06") part1(input).println() part2(input).println() }
0
Kotlin
0
0
dc97b23f8461ceb9eb5a53d33986fb1e26469964
1,186
advent-of-code-2023
Apache License 2.0
src/year2022/day18/Solution.kt
TheSunshinator
572,121,335
false
{"Kotlin": 144661}
package year2022.day18 import io.kotest.matchers.shouldBe import utils.Point3d import utils.cartesianProduct import utils.manhattanDistanceTo import utils.minMaxOf import utils.neighbors import utils.readInput fun main() { val testInput = readInput("18", "test_input").mapTo(mutableSetOf(), String::toPoint) val realInput = readInput("18", "input").mapTo(mutableSetOf(), String::toPoint) countFaces(testInput) .also(::println) shouldBe 64 countFaces(realInput) .let(::println) filledDroplet(testInput) .let(::countFaces) .also(::println) shouldBe 58 filledDroplet(realInput) .let(::countFaces) .also(::println) } private fun String.toPoint(): Point3d { return splitToSequence(',') .mapTo(mutableListOf(), String::toInt) .let { (x, y, z) -> Point3d(x, y, z) } } private fun countFaces(input: Iterable<Point3d>): Int { return groupings.zip(sortings) .flatMap { (grouping, sorting) -> val firstSelector = grouping.first val secondSelector = grouping.second input.groupBy { it.firstSelector() to it.secondSelector() } .values .map { it.sortedWith(sorting).zipWithNext() } } .sumOf { row -> row.count { (first, second) -> first.manhattanDistanceTo(second) > 1 }.let { 2 * (it + 1) } } } private val groupings: Sequence<Pair<Point3d.() -> Int, Point3d.() -> Int>> = sequenceOf( Point3d::x to Point3d::y, Point3d::x to Point3d::z, Point3d::y to Point3d::z, ) private val sortings = sequenceOf( compareBy(Point3d::z), compareBy(Point3d::y), compareBy(Point3d::x), ) private fun filledDroplet(input: Set<Point3d>): Set<Point3d> { val xRange = input.minMaxOf { it.x }.let { (it.first - 1)..(it.second + 1) } val yRange = input.minMaxOf { it.y }.let { (it.first - 1)..(it.second + 1) } val zRange = input.minMaxOf { it.z }.let { (it.first - 1)..(it.second + 1) } val candidates = (xRange cartesianProduct yRange cartesianProduct zRange.asSequence()) .mapTo(mutableSetOf()) { (point2d, z) -> Point3d(point2d.x, point2d.y, z) } return generateSequence(setOf(Point3d(0, 0, 0))) { points -> points.flatMapTo(mutableSetOf()) { it.neighbors(includeThis = true) } .minus(input) .intersect(candidates) .takeUnless { it.size == points.size } } .flatten() .toSet() .let(candidates::minus) }
0
Kotlin
0
0
d050e86fa5591447f4dd38816877b475fba512d0
2,570
Advent-of-Code
Apache License 2.0
src/main/kotlin/dev/bogwalk/batch6/Problem70.kt
bog-walk
381,459,475
false
null
package dev.bogwalk.batch6 import dev.bogwalk.util.combinatorics.permutationID import dev.bogwalk.util.maths.primeNumbers /** * Problem 70: Totient Permutation * * https://projecteuler.net/problem=70 * * Goal: Find the value of n, with 1 < n < N, for which Phi(n) is a permutation of n and the * ratio n/Phi(n) produces a minimum. * * Constraints: 100 <= N <= 1e7 * * Euler's Totient Function: Phi(n) is used to determine the count of positive integers < n that are * relatively prime to n. The number 1 is considered co-prime to every positive number, so * Phi(1) = 1. Phi(87109) = 79180, which is a permutation. * * e.g.: N = 100 * result = 21 -> Phi(21) = 12 & 21/Phi(21) = 1.75 */ class TotientPermutation { /** * Solution based on Euler's product formula: * * Phi(n) = nPi(1 - (1/p)), with p being distinct prime factors of n. * * If the ratio n / Phi(n) is the required result, this becomes: * * n/Phi(n) = n / (nPi(1 - (1/p))) * n/Phi(n) = Pi(p / (p - 1)) * * If this ratio must be minimised then the result of Phi(n) needs to be maximised, which is * done by finding n with the fewest but largest distinct prime factors. If these prime * factors are narrowed down to only 2 & are both as close to sqrt([limit]) as possible, then * Phi's formula becomes: * * Phi(n) = n(1 - (1/p_1))(1 - (1/p_2)), with n = p_1p_2 it becomes: * * Phi(n) = p_1p_2(1 - (1/p_1))(1 - (1/p_2)) * * Phi(n) = (p_1p_2 - (p_1p_2/p_1))(1 - (1/p_2)) * * Phi(n) = (p_1p_2 - p_2)(1 - (1/p_2)) * * Phi(n) = p_1p_2 - p_1 - p_2 + 1 = (p_1 - 1)(p_2 - 1) * * This solution finds all valid n except for one, 2817 = {3^2, 313^1}, as it is a product of * 3 prime factors. This n is captured in the alternative solution below, without adding a * special case clause, but is a slower solution. * * SPEED (BETTER) 690.93ms for N = 1e7 */ fun totientPermutation(limit: Int): Int { if (limit in 2818..2991) return 2817 val primes = primeNumbers(limit) val numOfPrimes = primes.size var minPerm = 1 to Double.MAX_VALUE for (i in 0 until numOfPrimes - 1) { val p1 = primes[i] for (j in i + 1 until numOfPrimes) { val p2 = primes[j] if (1L * p1 * p2 >= limit) break val n = p1 * p2 val phi = (p1 - 1) * (p2 - 1) val ratio = 1.0 * n / phi if ( ratio < minPerm.second && permutationID(n.toLong()) == permutationID(phi.toLong()) ) { minPerm = n to ratio } } } return minPerm.first } /** * Solution finds totient of every n under [limit] by iterating over prime numbers instead of * using a helper prime factorisation method. This iteration is broken early & returns null if * the increasingly reducing totient count becomes too small to satisfy the current minimum * ratio. * * SPEED (WORSE) 2.99s for N = 1e7 */ fun totientPermutationRobust(limit: Int): Int { val primes = primeNumbers(limit) var minPerm = 2 to Double.MAX_VALUE /** * Only returns a value of Phi(n) if n/Phi(n) will create a value that challenges the * current minimum ratio stored. * * Based on Euler's product formula: * * Phi(n) = nPi(1 - (1/p)), that repeatedly subtracts found prime factors from n. */ fun maximisedTotient(n: Int): Int? { var count = n var reduced = n for (p in primes) { if (p * p > reduced) break if (reduced % p != 0) continue do { reduced /= p } while (reduced % p == 0) // equivalent to count = count * (1 - (1/p)) count -= count / p if (count * minPerm.second < n) return null } return if (reduced > 1) count - (count / reduced) else count } for (n in 3 until limit) { val phi = maximisedTotient(n) val ratio = phi?.let { 1.0 * n / it } ?: continue if ( ratio < minPerm.second && permutationID(n.toLong()) == permutationID(phi.toLong()) ) { minPerm = n to ratio } } return minPerm.first } }
0
Kotlin
0
0
62b33367e3d1e15f7ea872d151c3512f8c606ce7
4,632
project-euler-kotlin
MIT License
src/Day15.kt
floblaf
572,892,347
false
{"Kotlin": 28107}
import kotlin.math.abs fun main() { data class Sensor( val x: Int, val y: Int, val distanceScanned: Int ) data class Beacon( val x: Int, val y: Int ) val sensors = mutableListOf<Sensor>() val beacons = mutableListOf<Beacon>() readInput("Day15") .map { val match = Regex("Sensor at x=(-?\\d+), y=(-?\\d+): closest beacon is at x=(-?\\d+), y=(-?\\d+)").find(it)!! val (xSensor, ySensor, xBeacon, yBeacon) = match.destructured beacons.add(Beacon(x = xBeacon.toInt(), y = yBeacon.toInt())) sensors.add( Sensor( x = xSensor.toInt(), y = ySensor.toInt(), distanceScanned = abs(xBeacon.toInt() - xSensor.toInt()) + abs(yBeacon.toInt() - ySensor.toInt()) ) ) } val uniqueBeacons = beacons.distinct() fun getNonBeaconRanges(y: Int): List<IntRange> { val result = sensors .mapNotNull { val remain = it.distanceScanned - abs(it.y - y) if (remain > 0) { it.x - remain..it.x + remain } else { null } } .sortedBy { it.first } val filtered = mutableListOf<IntRange>() result.forEach { current -> var added = false filtered.forEach inside@{ if (it.contains(current.first) && it.contains(current.last)) { added = true return@inside } if (it.contains(current.first)) { filtered.remove(it) filtered.add(it.first..current.last) added = true return@inside } if (it.contains(current.last)) { filtered.remove(it) filtered.add(current.first..it.last) added = true return@inside } } if (!added) { filtered.add(current) } } return filtered } fun part1(): Int { val y = 2000000 return getNonBeaconRanges(2_000_000).let { nonRanges -> nonRanges.sumOf { it.last - it.first + 1 } - uniqueBeacons.count { beacon -> beacon.y == y && nonRanges.any { it.contains(beacon.x) } } } } fun part2(): Long { val y = (0..4_000_000).first { getNonBeaconRanges(it).size >= 2 } val x = getNonBeaconRanges(y).first().last + 1 return x.toLong() * 4_000_000L + y.toLong() } println(part1()) println(part2()) }
0
Kotlin
0
0
a541b14e8cb401390ebdf575a057e19c6caa7c2a
2,818
advent-of-code-2022
Apache License 2.0
src/Day15.kt
maewCP
579,203,172
false
{"Kotlin": 59412}
import kotlin.math.abs fun main() { val testingPoints = mutableListOf<Pair<Int, Int>>() val data = mutableMapOf<Pair<Int, Int>, Pair<Int, Int>>() val distances = mutableMapOf<Pair<Int, Int>, Int>() fun getDistance(a: Pair<Int, Int>, b: Pair<Int, Int>): Int { return abs(a.first - b.first) + abs(a.second - b.second) } fun findTestingPoints(a: Pair<Int, Int>, b: Pair<Int, Int>, xFrom: Int, xTo: Int, yFrom: Int, yTo: Int) { val xAddition = if (a.first < b.first) 1 else -1 val yAddition = if (a.second < b.second) 1 else -1 var x = a.first var y = a.second while (x != b.first && y != b.second) { if (x in (xFrom..xTo) && y in (yFrom..yTo)) { testingPoints.add(Pair(x, y)) } x += xAddition y += yAddition } } fun getXRange(sensor: Pair<Int, Int>, distance: Int, y: Int): IntRange? { val ray = distance * if (sensor.second > y) -1 else 1 if (abs(ray) < abs(sensor.second - y)) return null val diffY = abs(sensor.second + ray - y) return (sensor.first - diffY..sensor.first + diffY) } fun prepareInput(input: List<String>) { val regex = "Sensor at x=(-?\\d+), y=(-?\\d+): closest beacon is at x=(-?\\d+), y=(-?\\d+)".toRegex() data.clear() distances.clear() input.forEach { line -> val groups = regex.find(line)!!.destructured.toList().map { it.toInt() } val sensor = Pair(groups[0], groups[1]) val beacon = Pair(groups[2], groups[3]) data[sensor] = beacon } // find distance data.forEach { (sensor, beacon) -> distances[sensor] = getDistance(sensor, beacon) } } fun part1(input: List<String>, y: Int): Int { prepareInput(input) val xs = mutableSetOf<Int>() data.forEach { (sensor, _) -> val xRange = getXRange(sensor, distances[sensor]!!, y) if (xRange != null) xs.addAll(xRange.toSet()) } listOf(data.keys, data.values).map { points -> xs.removeAll(points.filter { it.second == y }.map { it.first }.toSet()) } return xs.size } fun part2(input: List<String>, xFrom: Int, xTo: Int, yFrom: Int, yTo: Int): Long { prepareInput(input) data.forEach { (sensor, _) -> val left = Pair(sensor.first - distances[sensor]!! - 1, sensor.second) val top = Pair(sensor.first, sensor.second - distances[sensor]!! - 1) val right = Pair(sensor.first + distances[sensor]!! + 1, sensor.second) val bottom = Pair(sensor.first, sensor.second + distances[sensor]!! + 1) findTestingPoints(left, top, xFrom, xTo, yFrom, yTo) findTestingPoints(top, right, xFrom, xTo, yFrom, yTo) findTestingPoints(right, bottom, xFrom, xTo, yFrom, yTo) findTestingPoints(bottom, left, xFrom, xTo, yFrom, yTo) testingPoints.forEach { point -> var detected = false run breakOSensor@{ distances.forEach { (oSensor, distance) -> if (getDistance(oSensor, point) <= distance) { detected = true return@breakOSensor } } } if (!detected && point !in data.keys && point !in data.values) { return(point.first * 4000000L + point.second) } } testingPoints.clear() } // // data.forEach { (sensor, beacon) -> // if (sensor.second == y) xRanges.remove(sensor.first) // if (beacon.second == y) xRanges.remove(beacon.first) // } // println(xRanges.sorted()) // println(xRanges.size) return -1 } // test if implementation meets criteria from the description, like: val testInput = readInput("Day15_test") check(part1(testInput, 10) == 26) check(part2(testInput, 0, 20, 0, 20) == 56000011L) val input = readInput("Day15") part1(input, 2000000).println() part2(input, 0, 4000000, 0, 4000000).println() }
0
Kotlin
0
0
8924a6d913e2c15876c52acd2e1dc986cd162693
4,229
advent-of-code-2022-kotlin
Apache License 2.0
src/Day07.kt
arnoutvw
572,860,930
false
{"Kotlin": 33036}
import kotlin.collections.ArrayList fun main() { data class Dir(val prevDir: Dir?, val subdirs : ArrayList<Dir>, var size: Int, val name: String) { fun calculateSize() :Int { return subdirs.sumOf { it.calculateSize() } + size } fun getSubDir(name: String) :Dir? { return subdirs.firstOrNull { it.name == name } } override fun toString(): String { return "Dir(subdirs=$subdirs, size=$size, name='$name')" } } fun checkSmallDir(dir: Dir, size: Int): Int { var sizeSmallDirs = size if (dir.calculateSize() <= 100000) { sizeSmallDirs += dir.calculateSize(); } for(subDir in dir.subdirs) { sizeSmallDirs += checkSmallDir(subDir, 0) } return sizeSmallDirs; } fun populateDirs(input: List<String>, currentDir: Dir) { var currentDir1 = currentDir input.forEach { if (it == "$ cd /" || it.startsWith("$ ls")) { //SKIP } else if (it.startsWith("$ cd")) { val dirname = it.substring(5) if (dirname == "..") { currentDir1 = currentDir1.prevDir!! } else { var subDir = currentDir1.getSubDir(dirname) if (subDir == null) { subDir = Dir(currentDir1, ArrayList(), 0, dirname) currentDir1.subdirs.add(subDir) } currentDir1 = subDir } } else { if (it.startsWith("dir")) { currentDir1.subdirs.add(Dir(currentDir1, ArrayList(), 0, it.substring(4))) } else { val split = it.split(" ") currentDir1.size += split.get(0).toInt() } } } } fun part1(input: List<String>): Int { val currentDir = Dir(null, ArrayList<Dir>(), 0, "/") populateDirs(input, currentDir) return checkSmallDir(currentDir, 0) } fun addDirsToList(dirs: ArrayList<Dir>, startDir: Dir) { dirs.add(startDir) for(subDir in startDir.subdirs) { addDirsToList(dirs, subDir) } } fun part2(input: List<String>): Int { val currentDir = Dir(null, ArrayList<Dir>(), 0, "/") populateDirs(input, currentDir) val minFreeup = 30000000 - (70000000 - currentDir.calculateSize()) val dirs = ArrayList<Dir>() addDirsToList(dirs, currentDir) return dirs.filter { it.calculateSize() >= minFreeup }.minByOrNull { it.calculateSize() }!!.calculateSize() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day07_test") println("Test") println(part1(testInput)) println(part2(testInput)) check(part1(testInput) == 95437) check(part2(testInput) == 24933642) println("Waarde") val input = readInput("Day07") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
0cee3a9249fcfbe358bffdf86756bf9b5c16bfe4
3,094
aoc-2022-in-kotlin
Apache License 2.0
src/main/kotlin/com/ryanmoelter/advent/day05/Stacks.kt
ryanmoelter
573,615,605
false
{"Kotlin": 84397}
package com.ryanmoelter.advent.day05 fun main() { println(findTopsMovingMultiple(day05Stacks, day05Instructions)) } fun findTopsMovingMultiple(stacksInput: String, instructionsInput: String): String { val stacks = parseStacks(stacksInput) val instructions = parseInstructions(instructionsInput) instructions.forEach { instruction -> stacks.moveMultiple(instruction) } return stacks.getTops() } fun findTopsMovingOne(stacksInput: String, instructionsInput: String): String { val stacks = parseStacks(stacksInput) val instructions = parseInstructions(instructionsInput) instructions.forEach { instruction -> stacks.move(instruction) } return stacks.getTops() } fun parseStacks(stacksString: String): Stacks { val stackDescriptions = stacksString.lines() .reversed() .filter { it.isNotBlank() } val namesLine = stackDescriptions.first() val contentsLines = stackDescriptions .subList(1, stackDescriptions.size) val numStacks = namesLine.filter { !it.isWhitespace() }.length val stacks = Stacks(buildList { repeat(numStacks) { add(ArrayDeque()) } }) contentsLines.forEach { line -> val startingIndex = 1 repeat(numStacks) { index -> val currentValue = line[startingIndex + (index * 4)] if (currentValue.isLetter()) { stacks.add(currentValue, index) } } } return stacks } fun parseInstructions(instructionString: String): List<Instruction> = instructionString.lines() .filter { it.isNotBlank() } .map { line -> line.filter { !it.isLetter() }.trim() } .map { line -> line.split(' ').filter { it.isNotBlank() } } .map { (number, from, to) -> Instruction(number.toInt(), from.toInt(), to.toInt()) } data class Stacks(val stacks: List<ArrayDeque<Char>>) { fun getTops() = stacks.fold("") { acc, chars -> acc + chars.last() }.also { println(this) } fun add(value: Char, to: Int) { stacks[to] += value } fun moveMultiple(instruction: Instruction) { stacks[instruction.to - 1].addAll(stacks[instruction.from - 1].takeLast(instruction.number)) repeat(instruction.number) { stacks[instruction.from - 1].removeLast() } } fun move(instruction: Instruction) { repeat(instruction.number) { stacks[instruction.to - 1].add(stacks[instruction.from - 1].removeLast()) } } } data class Instruction(val number: Int, val from: Int, val to: Int)
0
Kotlin
0
0
aba1b98a1753fa3f217b70bf55b1f2ff3f69b769
2,403
advent-of-code-2022
Apache License 2.0
src/day/_3/Day03.kt
Tchorzyksen37
572,924,533
false
{"Kotlin": 42709}
package day._3 import readInput import java.util.stream.Collectors fun main() { fun stringToCharacterList(str: String): List<String> { return str.chars().mapToObj(Character::toString).collect(Collectors.toList()) } fun mapElementToIntValue(element: String): Int { return if (element[0].isLowerCase()) (element.codePointAt(0) - 96) else (element.codePointAt(0) - 38) } fun part1(input: List<String>): Int { var theSumOfPriorities = 0 for (str in input) { val firstElementCompartmentOne = stringToCharacterList(str.subSequence(0, str.length / 2).toString()) val firstElementCompartmentTwo = stringToCharacterList(str.subSequence(str.length / 2, str.length).toString()) val duplicate = firstElementCompartmentOne.stream().filter { ch -> firstElementCompartmentTwo.contains(ch) }.findFirst() if (duplicate.isPresent) { theSumOfPriorities += mapElementToIntValue(duplicate.get()) } } return theSumOfPriorities } fun mapToGroups(input: List<String>): List<List<String>> { val groups = mutableListOf<List<String>>() var group = mutableListOf<String>() for ((index, value) in input.withIndex()) { group.add(value) if (index % 3 == 2) { groups.add(group) group = mutableListOf() } } return groups } fun part2(input: List<String>): Int { val groups = mapToGroups(input) var badgesSum = 0 for (group in groups) { val firstCrewMember = stringToCharacterList(group[0]) val secondCrewMember = stringToCharacterList(group[1]) val thirdCrewMember = stringToCharacterList(group[2]) val duplicate = firstCrewMember.stream().filter { ch -> secondCrewMember.contains(ch) }.filter { ch -> thirdCrewMember.contains(ch) }.findFirst() if (duplicate.isPresent) { badgesSum += mapElementToIntValue(duplicate.get()) } } return badgesSum } val testInput = readInput("day/_3/Day03_test") check(part1(testInput) == 157) check(part2(testInput) == 70) val input = readInput("day/_3/Day03") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
27d4f1a6efee1c79d8ae601872cd3fa91145a3bd
2,026
advent-of-code-2022
Apache License 2.0
src/Day09.kt
astrofyz
572,802,282
false
{"Kotlin": 124466}
fun main() { fun abs(a: Int, b: Int): Int{ return maxOf(a, b) - minOf(a, b) } fun sign(a: Int): Int{ if (a > 0) return 1 else if (a < 0) return -1 return 0 } fun Pair<Int, Int>.move(moveDir: String):Pair<Int, Int>{ return when (moveDir){ "R" -> Pair(this.first, this.second+1) "L" -> Pair(this.first, this.second-1) "U" -> Pair(this.first+1, this.second) "D" -> Pair(this.first-1, this.second) else -> this } } fun Pair<Int, Int>.adjustTail(head: Pair<Int, Int>): Pair<Int, Int>{ return when(Pair(abs(head.first, this.first), abs(head.second, this.second))){ Pair(0, 1), Pair(1, 0), Pair(1, 1), Pair(0, 0) -> this else -> Pair(this.first+sign(head.first-this.first), this.second+sign(head.second - this.second)) } } fun part1(input: List<String>): Int { var headPos = Pair(0, 0) var tailPos = Pair(0, 0) val tailVisited = mutableSetOf(tailPos) for (step in input){ repeat(step.split(" ")[1].toInt()){ headPos = headPos.move(step.split(" ")[0]) tailPos = tailPos.adjustTail(headPos) tailVisited.add(tailPos) } } return tailVisited.size } fun part2(input: List<String>): Int { val knotsPos = MutableList(10) { Pair(0, 0) } val tailVisited = mutableSetOf(knotsPos[8]) for (step in input) { val (directionOfStep, numberOfRepetition) = step.split(" ") repeat(numberOfRepetition.toInt()) { knotsPos[0] = knotsPos[0].move(directionOfStep) for (i in 1 .. 9){ knotsPos[i] = knotsPos[i].adjustTail(knotsPos[i-1]) } tailVisited.add(knotsPos[9]) } } return tailVisited.size } // test if implementation meets criteria from the description, like: val testInput = readInput("Day09_test") check(part1(testInput) == 13) val input = readInput("Day09") println(part1(input)) part2(testInput) val testInput2 = readInput("Day09_test2") check(part2(testInput2) == 36) println(part2(input)) }
0
Kotlin
0
0
a0bc190b391585ce3bb6fe2ba092fa1f437491a6
2,307
aoc22
Apache License 2.0
src/day3/Day03.kt
JoeSkedulo
573,328,678
false
{"Kotlin": 69788}
package day3 import readInput fun main() { val alphabet = ('a'..'z').toMutableList() + ('A'..'Z').toMutableList() fun sacks(input: List<String>) : List<Rucksack> { return input.map { line -> Rucksack( one = line.substring(0, line.length / 2), two = line.substring(line.length / 2, line.length) ) } } fun sacksPartTwo(input: List<String>) : List<List<String>> { return buildList { val sacks = input.toMutableList() do { add(sacks.take(3)) repeat(3) { sacks.removeFirst() } } while (sacks.isNotEmpty()) }.toList() } fun part1(input: List<String>): Int { return sacks(input).sumOf { (one, two) -> val difference = one.toSet().intersect(two.toList().toSet()).first() alphabet.indexOf(difference) + 1 } } fun part2(input: List<String>): Int { return sacksPartTwo(input) .map { group -> alphabet.toMutableList().apply { group.forEach { sack -> alphabet.subtract(sack.toList().toSet()) .forEach { item -> this.remove(item) } } }.first() }.sumOf { common -> alphabet.indexOf(common) + 1 } } val input = readInput("day3/Day03") println(part1(input)) println(part2(input)) } data class Rucksack( val one: String, val two: String )
0
Kotlin
0
0
bd8f4058cef195804c7a057473998bf80b88b781
1,574
advent-of-code
Apache License 2.0
src/Day04.kt
gsalinaslopez
572,839,981
false
{"Kotlin": 21439}
fun main() { fun getRanges(input: List<String>): List<Pair<IntRange, IntRange>> = input .map { entry -> val sections = entry.split(",") val firstSection = sections.first().split("-").map { it.toInt() } val secondSection = sections.last().split("-").map { it.toInt() } val firstRange = firstSection.first()..firstSection.last() val secondRange = secondSection.first()..secondSection.last() Pair(firstRange, secondRange) } fun part1(input: List<String>): Int = getRanges(input) .sumOf { entry -> val (firstRange, secondRange) = entry if (firstRange.first() in secondRange && firstRange.last() in secondRange || secondRange.first() in firstRange && secondRange.last() in firstRange ) { Integer.valueOf(1) } else { Integer.valueOf(0) } } fun part2(input: List<String>): Int = getRanges(input) .sumOf { entry -> val (firstRange, secondRange) = entry if (firstRange.first() in secondRange || firstRange.last() in secondRange || secondRange.first() in firstRange || secondRange.last() in firstRange ) { Integer.valueOf(1) } else { Integer.valueOf(0) } } // 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)) }
0
Kotlin
0
0
041c7c3716bfdfdf4cc89975937fa297ea061830
1,672
aoc-2022-in-kotlin
Apache License 2.0
src/Day13.kt
RobvanderMost-TomTom
572,005,233
false
{"Kotlin": 47682}
import org.json.JSONArray fun main() { fun isInOrder(left:JSONArray, right: JSONArray): Order { for (i in 0 until left.length()) { if (i >= right.length()) { return Order.OutOfOrder } val leftArray = left.optJSONArray(i) val rightArray = right.optJSONArray(i) val result = if (leftArray == null && rightArray == null) { val leftValue = left.getInt(i) val rightValue = right.getInt(i) if (leftValue < rightValue) { Order.InOrder } else if (leftValue > rightValue) { Order.OutOfOrder } else { Order.Inconclusive } } else if (leftArray == null) { val leftValue = left.getInt(i) isInOrder(JSONArray(listOf(leftValue)), rightArray) } else if (rightArray == null) { val rightValue = right.getInt(i) isInOrder(leftArray, JSONArray(listOf(rightValue))) } else { isInOrder(leftArray, rightArray) } if (result != Order.Inconclusive) { return result } } if (left.length() < right.length()) { return Order.InOrder } return Order.Inconclusive } fun isInOrder(left:String, right: String): Order = isInOrder(JSONArray(left), JSONArray(right)) fun part1(input: List<String>): Int { return input.chunked(3) .onEach { check(it.size >= 2) } .mapIndexedNotNull { index, pair -> if (isInOrder(pair[0], pair[1]) == Order.InOrder) { println("In order: ${index + 1}") index + 1 } else { println("Out of order: ${index + 1}") null } } .sum() } fun part2(input: List<String>): Int { val sortedPackets = input .asSequence() .filter { it.isNotEmpty() } .plus("[[2]]") .plus("[[6]]") .sortedWith { o1, o2 -> if (isInOrder(o1, o2) == Order.InOrder) { -1 } else { 1 } } .onEach { println(it) } .toList() return (sortedPackets.indexOf("[[2]]") + 1) * (sortedPackets.indexOf("[[6]]") + 1) } // test if implementation meets criteria from the description, like: val testInput = readInput("Day13_test") check(part1(testInput) == 13) check(part2(testInput) == 140) check(isInOrder("[[6]]", "[6,1,4,0,3]") == Order.InOrder) val input = readInput("Day13") check(part1(input) == 5350) val answer2 = part2(input) check(answer2 != 20085) println(answer2) }
5
Kotlin
0
0
b7143bceddae5744d24590e2fe330f4e4ba6d81c
2,954
advent-of-code-2022
Apache License 2.0
src/main/kotlin/co/csadev/advent2021/Day20.kt
gtcompscientist
577,439,489
false
{"Kotlin": 252918}
/** * Copyright (c) 2021 by <NAME> * Advent of Code 2021, Day 20 * Problem Description: http://adventofcode.com/2021/day/20 */ package co.csadev.advent2021 import co.csadev.adventOfCode.BaseDay import co.csadev.adventOfCode.Point2D import co.csadev.adventOfCode.Resources.resourceAsText import kotlin.system.measureTimeMillis class Day20(override val input: String = resourceAsText("21day20.txt")) : BaseDay<String, Int, Int> { private val enhancement = input.split("\n\n").first().map { it == '#' } private val image = input.split("\n\n")[1].lines().flatMapIndexed { y, s -> s.mapIndexed { x, c -> Point2D(x, y) to (if (c == '#') 1 else 0) } }.toMap() private fun Map<Point2D, Int>.enhance(default: Int = if (enhancement[0]) 1 else 0): Map<Point2D, Int> { return mapValues { val mapped = it.key.neighborsInc.toSortedSet().map { n -> getOrDefault(n, default) } val joined = mapped.joinToString("") val bin = joined.toInt(2) if (enhancement[bin]) 1 else 0 } } private fun Map<Point2D, Int>.print(): Map<Point2D, Int> { val min = Point2D(keys.minOf { it.x } - 1, keys.minOf { it.y } - 1) val max = Point2D(keys.maxOf { it.x } + 1, keys.maxOf { it.y } + 1) (min.y..max.y).forEach { y -> println((min.x..max.x).joinToString("") { x -> if (this[Point2D(x, y)] == 1) "#" else "." }) } return this } private fun Map<Point2D, Int>.enlarge(repeat: Int): Map<Point2D, Int> { val min = Point2D(keys.minOf { it.x } - (repeat * 2), keys.minOf { it.y } - (repeat * 2)) val max = Point2D(keys.maxOf { it.x } + (repeat * 2), keys.maxOf { it.y } + (repeat * 2)) return toMutableMap().apply { (min.y..max.y).forEach { y -> (min.x..max.x).forEach { x -> val p = Point2D(x, y) this[p] = this.getOrDefault(p, 0) } } }.toSortedMap() } private fun Map<Point2D, Int>.trim(edgeSize: Int): Map<Point2D, Int> { val min = Point2D(keys.minOf { it.x }, keys.minOf { it.y }) val max = Point2D(keys.maxOf { it.x }, keys.maxOf { it.y }) return filterKeys { it.x in min.x + edgeSize..max.x - edgeSize && it.y in min.y + edgeSize..max.y - edgeSize } } override fun solvePart1() = image.enlarge(2) .enhance().enhance() .trim(2).print().values.sum() override fun solvePart2(): Int { var enhanced = image.enlarge(100) repeat(50) { i -> measureTimeMillis { enhanced = enhanced.enhance(default = if (enhancement[0]) 1 else 0) // .print() }.also { println("Enhance x$i -> $it ms") } } return enhanced.trim(100).print().values.sum() } }
0
Kotlin
0
1
43cbaac4e8b0a53e8aaae0f67dfc4395080e1383
2,871
advent-of-kotlin
Apache License 2.0
src/Day07.kt
aneroid
572,802,061
false
{"Kotlin": 27313}
class Day07(input: List<String>) { private val allPaths = parseInput(input) private fun parseInput(input: List<String>): Map<String, Int> = buildMap { var index = 0 var currDir = "" while (index < input.size) { val line = input[index++] when (line.take(4)) { "$ cd" -> currDir = changedDir(currDir, line.drop(5)) "$ ls" -> index += listDir(input.drop(index)) .map { this[changedDir(currDir, it.second)] = it.first }.size else -> throw IllegalArgumentException("Invalid command: $line") } } } private fun listDir(input: List<String>): List<Pair<Int, String>> = input .takeWhile { !it.startsWith("$") } .map { (it.substringBefore(" ").toIntOrNull() ?: 0) to it.substringAfter(" ") } private fun changedDir(currDir: String, dirName: String): String = when (dirName) { "/" -> "/" ".." -> currDir.substringBeforeLast("/") else -> if (currDir != "/") "$currDir/$dirName" else "/$dirName" } fun totalSizeOfDir(dirName: String): Int { return allPaths .filterKeys { it.startsWith("$dirName/") || dirName == "/" } .values .sum() } fun partOne(): Int = allPaths .map { totalSizeOfDir(it.key) } .filter { it <= 100_000 } .sum() fun partTwo(): Int { val total = 70_000_000 val required = 30_000_000 val unused = total - totalSizeOfDir("/") return allPaths .map { totalSizeOfDir(it.key) } .filter { it + unused >= required } .min() } } fun main() { val testInput = readInput("Day07_test") val input = readInput("Day07") println("part One:") val day07Test = Day07(testInput) assertThat( listOf("/a/e", "/a", "/d", "/").map { day07Test.totalSizeOfDir(it) } ).isEqualTo(listOf(584, 94853, 24933642, 48381165)) assertThat(day07Test.partOne()).isEqualTo(95437) println("actual: ${Day07(input).partOne()}\n") println("part Two:") assertThat(Day07(testInput).partTwo()).isEqualTo(24933642) // uncomment when ready println("actual: ${Day07(input).partTwo()}\n") // uncomment when ready }
0
Kotlin
0
0
cf4b2d8903e2fd5a4585d7dabbc379776c3b5fbd
2,454
advent-of-code-2022-kotlin
Apache License 2.0
app/src/main/java/online/vapcom/codewars/strings/StringsKatas.kt
vapcomm
503,057,535
false
{"Kotlin": 142486}
package online.vapcom.codewars.strings /** * Two to One * https://www.codewars.com/kata/5656b6906de340bd1b0000ac/train/kotlin */ fun longest(s1: String, s2: String): String { val set = (s1 + s2).toSortedSet() val sb = StringBuilder(set.size) set.forEach { sb.append(it) } return sb.toString() } /** * Get the Middle Character * https://www.codewars.com/kata/56747fd5cb988479af000028/train/kotlin */ fun getMiddle(word: String): String { return if (word.isEmpty()) "" else { val half = word.length / 2 if (word.length % 2 == 0) { word.substring(half - 1, half + 1) } else { word.substring(half, half + 1) } } } /** * Find the missing letter * https://www.codewars.com/kata/5839edaa6754d6fec10000a2/train/kotlin * * 'a', 'b', 'c', 'd', 'f' */ fun findMissingLetter(array: CharArray): Char { if (array.size < 2) throw IllegalArgumentException("array size should be at least 2") for(i in 0 .. array.size - 2) { if (array[i + 1] - array[i] > 1) return array[i] + 1 } // not found, we assume that a character is missing before the first return array[0] - 1 } /** * Encrypt this! * https://www.codewars.com/kata/5848565e273af816fb000449/train/kotlin * The first letter must be converted to its ASCII code. * The second letter must be switched with the last letter */ fun encryptThis(text: String): String { if (text.isBlank()) return "" return text.split(" ").map { plain -> when (plain.length) { 1 -> plain[0].code.toString() 2 -> "${plain[0].code}${plain[1]}" else -> "${plain[0].code}${plain[plain.length - 1]}${plain.substring(2, plain.length - 1)}${plain[1]}" } }.joinToString(" ") } /** * Character with longest consecutive repetition * https://www.codewars.com/kata/586d6cefbcc21eed7a001155/train/kotlin * "bbbaaabaaaa", Pair('a',4) */ fun longestRepetition(s: String): Pair<Char?,Int> { if (s.isEmpty()) return Pair(null, 0) var currentChar = s[0] var count = 1 var maxChar = currentChar var maxCount = 1 for (i in 1 until s.length) { if (currentChar == s[i]) { // sequence continues count++ } else { // new sequence if (count > maxCount) { maxChar = currentChar maxCount = count } currentChar = s[i] count = 1 } } return if (count > maxCount) Pair(currentChar, count) else Pair(maxChar, maxCount) } /** * Strip Comments * https://www.codewars.com/kata/51c8e37cee245da6b40000bd/train/kotlin * *NOTE: for speed and lower memory consumption it's better to use state machine to process whole string in one pass. */ fun stripComments(input: String, markers: CharArray): String { return input.split("\n").joinToString("\n") { str -> var candidate = str for (m in markers) { val substr = str.substringBefore(m) if (substr.length < candidate.length) candidate = substr } candidate.trimEnd() } } /** * The observed PIN * * https://www.codewars.com/kata/5263c6999e0f40dee200059d/train/kotlin * ┌───┬───┬───┐ * │ 1 │ 2 │ 3 │ * ├───┼───┼───┤ * │ 4 │ 5 │ 6 │ * ├───┼───┼───┤ * │ 7 │ 8 │ 9 │ * └───┼───┼───┘ * │ 0 │ * └───┘ */ fun getPINs(observed: String): List<String> { if (observed.isBlank()) return emptyList() val variants: Array<CharArray> = arrayOf( charArrayOf('0', '8'), charArrayOf('1', '2', '4'), charArrayOf('2', '3', '5', '1'), charArrayOf('3', '6', '2'), charArrayOf('4', '1', '5', '7'), charArrayOf('5', '2', '6', '8', '4'), charArrayOf('6', '9', '5', '3'), charArrayOf('7', '4', '8'), charArrayOf('8', '5', '9', '0', '7'), charArrayOf('9', '6', '8'), ) val combinations: Array<CharArray> = Array(observed.length) { CharArray(0) } observed.forEachIndexed { index, ch -> if (ch.isDigit()) combinations[index] = variants[ch.code - '0'.code] else return emptyList() } val counts = IntArray(observed.length) val chars = CharArray(observed.length) val result = mutableListOf<String>() do { // make current code combination for (i in chars.indices) { chars[i] = combinations[i][counts[i]] } result.add(String(chars)) // update combination var overflow = false for (i in counts.indices.reversed()) { counts[i]++ if (counts[i] >= combinations[i].size) { counts[i] = 0 overflow = true } else { overflow = false break } } } while (!overflow) return result }
0
Kotlin
0
0
97b50e8e25211f43ccd49bcee2395c4bc942a37a
5,067
codewars
MIT License
app/src/main/kotlin/day07/Day07.kt
KingOfDog
433,706,881
false
{"Kotlin": 76907}
package day07 import common.InputRepo import common.readSessionCookie import common.solve import kotlin.math.abs import kotlin.math.ceil import kotlin.math.floor import kotlin.math.roundToInt fun main(args: Array<String>) { val day = 7 val input = InputRepo(args.readSessionCookie()).get(day = day) solve(day, input, ::solveDay07Part1, ::solveDay07Part2) } fun solveDay07Part1(input: List<String>): Int { val initialPositions = parseInput(input) val targetPosition = initialPositions.median() return initialPositions.sumOf { abs(targetPosition - it) } } fun solveDay07Part2(input: List<String>): Int { val initialPositions = parseInput(input) val average = initialPositions.average().roundToInt() val targetPositions = listOf(average - 1, average, average + 1) return targetPositions.calculateCosts(initialPositions).minOf { it } } fun solveDay07Part2BruteForce(input: List<String>): Int { val initialPositions = parseInput(input) val possiblePositions = (initialPositions.minOrNull()!!..initialPositions.maxOrNull()!!).toList() return possiblePositions.calculateCosts(initialPositions).minOf { it } } private fun List<Int>.calculateCosts( initialPositions: List<Int> ): List<Int> = map { targetPosition -> initialPositions.sumOf { fuelCost(abs(targetPosition - it)) } } private fun parseInput(input: List<String>): List<Int> { val initialPositions = input.first().split(",").map { it.toInt() } return initialPositions } fun List<Int>.median(): Int { val sorted = sorted() val middle = size / 2.0 return if (middle % 1 == 0.0) { sorted[middle.toInt()] } else { (sorted[floor(middle).toInt()] + sorted[ceil(middle).toInt()]) / 2 } } fun fuelCost(distance: Int): Int { if (distance == 0) return 0 return fuelCost(distance - 1) + distance }
0
Kotlin
0
0
576e5599ada224e5cf21ccf20757673ca6f8310a
1,857
advent-of-code-kt
Apache License 2.0
src/Day04.kt
rifkinni
573,123,064
false
{"Kotlin": 33155, "Shell": 125}
class PairRange(private val range1: Set<Int>, private val range2: Set<Int>) { fun fullyContains(): Boolean { return if (range1.size > range2.size) { range1.containsAll(range2) } else { range2.containsAll(range1) } } fun containsAny(): Boolean { return range1.intersect(range2).isNotEmpty() } companion object { fun parseSets(input: String): Pair<Set<Int>, Set<Int>> { val pair = input.split(",") val set1 = parseSet(pair[0]) val set2 = parseSet(pair[1]) return Pair(set1, set2) } private fun parseSet(input: String): Set<Int> { val splitString = input.split("-") return (Integer.parseInt(splitString[0])..Integer.parseInt(splitString[1])).toSet() } } } fun main() { fun part1(input: List<String>): Int { return input.count { val sets = PairRange.parseSets(it) PairRange(sets.first, sets.second).fullyContains() } } fun part2(input: List<String>): Int { return input.count { val sets = PairRange.parseSets(it) PairRange(sets.first, sets.second).containsAny() } } // 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)) }
0
Kotlin
0
0
c2f8ca8447c9663c0ce3efbec8e57070d90a8996
1,525
2022-advent
Apache License 2.0
src/Day12.kt
maciekbartczak
573,160,363
false
{"Kotlin": 41932}
import java.util.LinkedList import java.util.Queue fun main() { fun part1(input: List<String>): Int { val grid = makeGrid(input) val startingPosition = grid.findRootNode() val endPosition = bfs(grid, startingPosition)!! return endPosition.distance } fun part2(input: List<String>): Int { val grid = makeGrid(input) return grid.findRootNodes() .mapNotNull { bfs(grid, it) } .minOf { it.distance } } val testInput = readInput("Day12_test") check(part1(testInput) == 31) check(part2(testInput) == 29) val input = readInput("Day12") println(part1(input)) println(part2(input)) } private class Node( val pos: Pair<Int, Int>, val distance: Int, val value: Char, ) private fun makeGrid(input: List<String>): List<List<Char>> { return input.map { it.toList() } } private fun List<List<Char>>.findRootNode(): Pair<Int, Int> { for (y in this.indices) { for (x in this[y].indices) { if (this[y][x] == 'S') { return x to y } } } return -1 to -1 } private fun List<List<Char>>.findRootNodes(): List<Pair<Int, Int>> { val positions = mutableListOf<Pair<Int, Int>>() for (y in this.indices) { for (x in this[y].indices) { val char = this[y][x] if (char.normalize() == 'a') { positions.add(x to y) } } } return positions } private fun bfs(grid: List<List<Char>>, startingPosition: Pair<Int, Int>): Node? { val startingNode = Node( startingPosition, 0, grid[startingPosition.second][startingPosition.first] ) val queue: Queue<Node> = LinkedList() val visited = mutableSetOf(startingPosition) queue.add(startingNode) while (queue.isNotEmpty()) { val currentNode = queue.remove() if (currentNode.value == 'E') { return currentNode } val neighbours = grid.getNeighbours(currentNode.pos) neighbours.forEach { if (it !in visited) { visited.add(it) queue.add( Node( it, currentNode.distance + 1, grid[it.second][it.first] ) ) } } } return null } private fun List<List<Char>>.getNeighbours(pos: Pair<Int, Int>): List<Pair<Int, Int>> { val neighbours = mutableListOf<Pair<Int, Int>>() directions.forEach { val neighbour = pos.offsetBy(it) if (this.isPositionWithinBounds(neighbour) && this.getHeightDifference(neighbour, pos) <= 1) { neighbours.add(neighbour) } } return neighbours } private fun List<List<Char>>.isPositionWithinBounds(pos: Pair<Int, Int>): Boolean { val x = pos.first val y = pos.second return y in this.indices && x in this[0].indices } private fun List<List<Char>>.getHeightDifference(first: Pair<Int, Int>, second: Pair<Int, Int>): Int { val firstChar = this[first.second][first.first] val secondChar = this[second.second][second.first] return firstChar.normalize().code - secondChar.normalize().code } private fun Char.normalize(): Char { return when(this) { 'S' -> 'a' 'E' -> 'z' else -> this } } val directions = listOf( 1 to 0, -1 to 0, 0 to 1, 0 to -1, )
0
Kotlin
0
0
53c83d9eb49d126e91f3768140476a52ba4cd4f8
3,477
advent-of-code-2022
Apache License 2.0
app/src/main/kotlin/com/jamjaws/adventofcode/xxiii/day/Day07.kt
JamJaws
725,792,497
false
{"Kotlin": 30656}
package com.jamjaws.adventofcode.xxiii.day import com.jamjaws.adventofcode.xxiii.readInput class Day07 { companion object { private val CARD_OPTIONS = listOf('A', 'K', 'Q', 'J', 'T', '9', '8', '7', '6', '5', '4', '3', '2') private val CARD_OPTIONS_JOKER = listOf('A', 'K', 'Q', 'T', '9', '8', '7', '6', '5', '4', '3', '2', 'J') } fun part1(text: List<String>): Int = text.asSequence() .map { parseHand(it, ::getHandType) } .sortedWith(getHandComparator(CARD_OPTIONS)) .map(Hand::bid) .mapIndexed { index, bid -> bid * (text.size - index) } .sum() fun part2(text: List<String>): Int = text.asSequence() .map { parseHand(it, ::getHandTypeWithJoker) } .sortedWith(getHandComparator(CARD_OPTIONS_JOKER)) .map(Hand::bid) .mapIndexed { index, bid -> bid * (text.size - index) } .sum() private fun parseHand(line: String, getHandType: (String) -> HandType): Hand { val (cards, bid) = line.split(' ') return Hand(cards, getHandType(cards), bid.toInt()) } private fun getHandType(cards: String): HandType { val distinctCards = cards.toSet() return when { distinctCards.size == 1 -> HandType.FiveOfAKind distinctCards.size == 2 && distinctCards.any { distinctCard -> cards.count { it == distinctCard } == 4 } -> HandType.FourOfAKind distinctCards.size == 2 && distinctCards.any { distinctCard -> cards.count { it == distinctCard } == 3 } -> HandType.FullHouse distinctCards.size == 3 && distinctCards.any { distinctCard -> cards.count { it == distinctCard } == 3 } -> HandType.ThreeOfAKind distinctCards.size == 3 && distinctCards.any { distinctCard -> cards.count { it == distinctCard } == 2 } -> HandType.TwoPair distinctCards.size == 4 -> HandType.OnePair else -> HandType.HighCard } } private fun getHandTypeWithJoker(cards: String): HandType { val distinctCardsMinusJ = cards.toSet() - 'J' val jokerCount = cards.count { it == 'J' } return when { distinctCardsMinusJ.size in 0..1 -> HandType.FiveOfAKind distinctCardsMinusJ.size == 2 && distinctCardsMinusJ.any { distinctCard -> jokerCount + cards.count { it == distinctCard } == 4 } -> HandType.FourOfAKind distinctCardsMinusJ.size == 2 && distinctCardsMinusJ.any { distinctCard -> jokerCount + cards.count { it == distinctCard } == 3 } -> HandType.FullHouse distinctCardsMinusJ.size == 3 && distinctCardsMinusJ.any { distinctCard -> jokerCount + cards.count { it == distinctCard } == 3 } -> HandType.ThreeOfAKind distinctCardsMinusJ.size == 3 && distinctCardsMinusJ.any { distinctCard -> jokerCount + cards.count { it == distinctCard } == 2 } -> HandType.TwoPair distinctCardsMinusJ.size == 4 -> HandType.OnePair else -> HandType.HighCard } } private fun getHandComparator(cardOptionsSorted: List<Char>) = compareBy<Hand> { it.type.ordinal } .thenBy { cardOptionsSorted.indexOf(it.cards.first()) } .thenBy { cardOptionsSorted.indexOf(it.cards[1]) } .thenBy { cardOptionsSorted.indexOf(it.cards[2]) } .thenBy { cardOptionsSorted.indexOf(it.cards[3]) } .thenBy { cardOptionsSorted.indexOf(it.cards[4]) } } enum class HandType { FiveOfAKind, FourOfAKind, FullHouse, ThreeOfAKind, TwoPair, OnePair, HighCard, } data class Hand(val cards: String, val type: HandType, val bid: Int) fun main() { val answer1 = Day07().part1(readInput("Day07")) println(answer1) val answer2 = Day07().part2(readInput("Day07")) println(answer2) }
0
Kotlin
0
0
e2683305d762e3d96500d7268e617891fa397e9b
3,802
advent-of-code-2023
MIT License
src/main/kotlin/de/nosswald/aoc/days/Day03.kt
7rebux
722,943,964
false
{"Kotlin": 34890}
package de.nosswald.aoc.days import de.nosswald.aoc.Day // https://adventofcode.com/2023/day/3 object Day03 : Day<Int>(3, "Gear Ratios") { private data class Point(val x: Int, val y: Int) override fun partOne(input: List<String>): Int { return combined(input, { it.isSymbol() }, List<Int>::sum) } override fun partTwo(input: List<String>): Int { return combined(input, { c -> c == '*' }, { nums -> if (nums.size == 2) nums.reduce(Int::times) else 0 }) } private fun combined( input: List<String>, isSymbolValid: (Char) -> Boolean, formula: (List<Int>) -> Int): Int { val checked = mutableSetOf<Point>() return input.mapIndexed { y, line -> line .withIndex() .filter { isSymbolValid(it.value) } .map { findAdjacentNumbers(input, Point(it.index, y), checked) } .sumOf { formula(it) } }.sum() } private fun Char.isSymbol(): Boolean { return !(this == '.' || this.isDigit()) } private fun Point.getNeighbors(): List<Point> { val directions = listOf(-1, 0, 1) return directions .flatMap { dX -> directions.map { dY -> Point(x + dX, y + dY) } } .filter { it != this } } private fun findAdjacentNumbers(input: List<String>, point: Point, checked: MutableSet<Point>): List<Int> { return point.getNeighbors() .filter { p -> p.y in input.indices && p.x in input[p.y].indices && input[p.y][p.x].isDigit() } .mapNotNull { p -> if (checked.contains(p)) null else input[p.y].findNumberAt(p, checked) } } private fun String.findNumberAt(point: Point, checked: MutableSet<Point>): Int { val firstIndex = generateSequence(point.x, Int::dec) .takeWhile { it >= 0 && this[it].isDigit() } .last() val lastIndex = generateSequence(point.x, Int::inc) .takeWhile { it < this.length && this[it].isDigit() } .last() val indices = firstIndex..lastIndex // Prevent duplicate numbers checked.addAll(indices.map { Point(it, point.y) }) return indices .map(this::get) .joinToString("") .toInt() } override val partOneTestExamples: Map<List<String>, Int> = mapOf( listOf( "467..114..", "...*......", "..35..633.", "......#...", "617*......", ".....+.58.", "..592.....", "......755.", "...$.*....", ".664.598..", ) to 4361 ) override val partTwoTestExamples: Map<List<String>, Int> = mapOf( listOf( "467..114..", "...*......", "..35..633.", "......#...", "617*......", ".....+.58.", "..592.....", "......755.", "...$.*....", ".664.598..", ) to 467835 ) }
0
Kotlin
0
1
398fb9873cceecb2496c79c7adf792bb41ea85d7
3,150
advent-of-code-2023
MIT License
src/Day10.kt
razvn
573,166,955
false
{"Kotlin": 27208}
import java.lang.Exception fun main() { val day = "Day10" fun part1(input: List<String>): Int { val values = loadValues(input) val keep = valuesToKeep(values, 20, 60, 100, 140, 180, 220) // println(keep) return keep.map { (k, v) -> k * v }.sum() } fun part2(input: List<String>): Int { val nbChars = 40 val fillChar = "." val mapValues = loadValues(input) var x: Int var sprite: String var line = "" val lines = (1..240).mapNotNull { cycle -> x = mapValues.xValue(cycle) val spritePrefix = if (x < 1) "" else fillChar.repeat(x - 1) val fillPostfix = fillChar.repeat(nbChars) sprite = ("$spritePrefix###$fillPostfix").take(nbChars) val idx = (cycle - 1) % nbChars val draw = sprite[idx] line += draw // println("Cycle: \t$cycle \t| \tx: \t$x \t| \tidx: \t$idx \t| \tdraw: \t'$draw' \t| \tsprite: \t'$sprite' \t| \tcurrent: \t'$s'") if (cycle % nbChars == 0) { val fullLine = line line = "" fullLine } else null } lines.forEach { println(it.replace(fillChar, " ")) } return 0 } // test if implementation meets criteria from the description, like: val testInput = readInput("${day}_test") // println(part1(testInput)) println(part2(testInput)) check(part1(testInput) == 13140) // check(part2(testInput) == 36) val input = readInput(day) println(part1(input)) println(part2(input)) } private fun loadValues(input: List<String>): Map<Int, Int> { var x = 1 var cycle = 1 return mapOf(1 to 1) + input.map { when { it == "noop" -> cycle++ it.startsWith("add") -> { val cmd = it.split(" ") x += cmd[1].toInt() cycle += 2 } } cycle to x }.toMap() } private fun valuesToKeep(map: Map<Int, Int>, vararg cycle: Int): Map<Int, Int> { return cycle.associateWith { // println("Getting: $it - ${map[it]} - ${map[it - 1]} - ${map[it - 2]}") val response = map[it] ?: map[it - 1] response ?: throw Exception("Both $it and $it - 1 are null - can't be true") } } private fun Map<Int, Int>.xValue(idx: Int) = this[idx] ?: this[idx - 1] ?: throw Exception("There should be a value for '$idx'")
0
Kotlin
0
0
73d1117b49111e5044273767a120142b5797a67b
2,473
aoc-2022-kotlin
Apache License 2.0
src/Day15.kt
HaydenMeloche
572,788,925
false
{"Kotlin": 25699}
fun manhattanDistance(x1: Int, y1: Int, x2: Int, y2: Int) = kotlin.math.abs(x1 - x2) + kotlin.math.abs(y1 - y2) data class Point(val x: Int, val y: Int) data class Sensor(val loc: Point, val beacon: Point) { val distance = manhattanDistance(loc.x, loc.y, beacon.x, beacon.y) fun inRange(x: Int, y: Int) = manhattanDistance(loc.x, loc.y, x, y) <= distance fun isBeacon(x: Int, y: Int) = beacon.x == x && beacon.y == y fun noBeacon(x: Int, y: Int) = inRange(x, y) && !isBeacon(x, y) } class SensorGrid(val sensors: List<Sensor>) { val xMin = sensors.minOf { it.loc.x - it.distance } val xMax = sensors.maxOf { it.loc.x + it.distance } fun scanDepth(depth: Int) = (xMin..xMax).count { x -> sensors.any { it.noBeacon(x, depth) } } fun scan(maxRange: Int): Point? { for (x in 0..maxRange) { var y = 0 while (y <= maxRange) { val sensor = sensors.find { it.inRange(x, y) } if (sensor == null) return Point(x, y) y = sensor.loc.y + sensor.distance - kotlin.math.abs(x - sensor.loc.x) + 1 } } return null } } fun main() { val pattern = Regex(".*x=(-?\\d+), y=(-?\\d+).*x=(-?\\d+), y=(-?\\d+)") val lines = readInput("Day15") val sensors = lines.map { line -> val (x1, y1, x2, y2) = pattern.find(line)!!.destructured Sensor(Point(x1.toInt(), y1.toInt()), Point(x2.toInt(), y2.toInt())) } val sensorGrid = SensorGrid(sensors) println("answer one: ${sensorGrid.scanDepth(2000000)}") println("answer two: ${sensorGrid.scan(4000000)?.let { it.x.toLong() * 4000000L + it.y.toLong() }}") }
0
Kotlin
0
1
1a7e13cb525bb19cc9ff4eba40d03669dc301fb9
1,669
advent-of-code-kotlin-2022
Apache License 2.0
src/day18/Day18.kt
EndzeitBegins
573,569,126
false
{"Kotlin": 111428}
package day18 import readInput import readTestInput private data class Coordinate(val x: Int, val y: Int, val z: Int) private typealias LavaCube = Coordinate private typealias LavaDroplet = Set<LavaCube> private fun List<String>.toLavaDroplet(): LavaDroplet = this .map { line -> val (x, y, z) = line.split(",") LavaCube(x.toInt(), y.toInt(), z.toInt()) } .toSet() private val Coordinate.sides: List<Coordinate> get() = listOf( Coordinate(x = x - 1, y = y, z = z), Coordinate(x = x + 1, y = y, z = z), Coordinate(x = x, y = y - 1, z = z), Coordinate(x = x, y = y + 1, z = z), Coordinate(x = x, y = y, z = z - 1), Coordinate(x = x, y = y, z = z + 1), ) private fun LavaCube.findVisibleSides(lavaDroplet: LavaDroplet): List<Coordinate> = sides.filterNot { sideCube -> sideCube in lavaDroplet } private fun part1(input: List<String>): Int { val lavaDroplet = input.toLavaDroplet() val lavaDropletOutsideSurfaceArea = lavaDroplet .flatMap { lavaCube -> lavaCube.findVisibleSides(lavaDroplet) } return lavaDropletOutsideSurfaceArea.size } private fun part2(input: List<String>): Int { val lavaDroplet = input.toLavaDroplet() val visibleSides = lavaDroplet .flatMap { lavaCube -> lavaCube.findVisibleSides(lavaDroplet) } val minX = lavaDroplet.minOf { it.x } - 1 val minY = lavaDroplet.minOf { it.y } - 1 val minZ = lavaDroplet.minOf { it.z } - 1 val maxX = lavaDroplet.maxOf { it.x } + 1 val maxY = lavaDroplet.maxOf { it.y } + 1 val maxZ = lavaDroplet.maxOf { it.z } + 1 val spaceAroundLavaDroplet = mutableListOf<Coordinate>() val workingQueue = mutableListOf(Coordinate(x = minX, y = minY, z = minZ)) while (workingQueue.isNotEmpty()) { val active = workingQueue.removeFirst() spaceAroundLavaDroplet.add(active) val candidates = active.sides .asSequence() .filterNot { it.x < minX || it.x > maxX } .filterNot { it.y < minY || it.y > maxY } .filterNot { it.z < minZ || it.z > maxZ } .filterNot { it in workingQueue } .filterNot { it in spaceAroundLavaDroplet } .filterNot { it in lavaDroplet } for (candidate in candidates) { workingQueue.add(candidate) } } val lavaDropletOutsideSurfaceArea = visibleSides.filter { it in spaceAroundLavaDroplet } return lavaDropletOutsideSurfaceArea.size } fun main() { // test if implementation meets criteria from the description, like: val testInput = readTestInput("Day18") check(part1(testInput) == 64) check(part2(testInput) == 58) val input = readInput("Day18") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
ebebdf13cfe58ae3e01c52686f2a715ace069dab
2,802
advent-of-code-kotlin-2022
Apache License 2.0
advent-of-code-2023/src/main/kotlin/Day19.kt
jomartigcal
433,713,130
false
{"Kotlin": 72459}
// Day 19: Aplenty // https://adventofcode.com/2023/day/19 import java.io.File private const val COLON = ":" private const val GREATER_THAN = ">" private const val LESS_THAN = "<" data class Workflow(val name: String, val rules: List<String>) data class Part(val x: Int, val m: Int, val a: Int, val s: Int) { fun getValue(category: String): Int { return when (category) { "x" -> x "m" -> m "a" -> a "s" -> s else -> 0 } } } fun main() { val lines = File("src/main/resources/Day19.txt").readLines() val workflowList = lines.takeWhile { it.isNotEmpty() } val workFlows = workflowList.map { workflow -> val rules = workflow.substringAfter("{").substringBefore("}") Workflow( workflow.substringBefore("{"), rules.split(",") ) } val regex = """\{x=(\d*),m=(\d*),a=(\d*),s=(\d*)}""".toRegex() val partList = lines.drop(workflowList.size + 1).takeWhile { it.isNotEmpty() } val parts = partList.mapNotNull { regex.matchEntire(it)?.destructured?.let { xmas -> val (x, m, a, s) = xmas Part(x = x.toInt(), m = m.toInt(), a = a.toInt(), s = s.toInt()) } } val sumOfAcceptedParts = parts.sumOf { part -> if (sortThroughParts(part, workFlows)) { part.x + part.m + part.a + part.s } else { 0 } } println(sumOfAcceptedParts) } private fun sortThroughParts(part: Part, workflows: List<Workflow>): Boolean { var workflow = workflows.find { it.name == "in" } ?: return false while (true) { val rules = workflow.rules for (index in rules.indices) { val rule = rules[index] if (isPartAccepted(rule)) { return true } else if (isPartRejected(rule)) { return false } else if (rule.contains(LESS_THAN) || rule.contains(GREATER_THAN)) { val symbol = if (rule.contains(LESS_THAN)) LESS_THAN else GREATER_THAN val left = part.getValue(rule.substringBefore(symbol)) val right = rule.substringAfter(symbol).substringBefore(COLON).toInt() val result = rule.substringAfter(COLON) if (symbol == LESS_THAN && left < right || symbol == GREATER_THAN && left > right) { if (isPartAccepted(result)) { return true } else if (isPartRejected(result)) { return false } else { workflow = workflows.find { it.name == result } ?: return false break } } } else { workflow = workflows.find { it.name == rule } ?: return false break } } } } private fun isPartAccepted(value: String) = value == "A" private fun isPartRejected(value: String) = value == "R"
0
Kotlin
0
0
6b0c4e61dc9df388383a894f5942c0b1fe41813f
3,026
advent-of-code
Apache License 2.0
src/main/kotlin/com/github/ferinagy/adventOfCode/aoc2021/2021-19.kt
ferinagy
432,170,488
false
{"Kotlin": 787586}
package com.github.ferinagy.adventOfCode.aoc2021 import com.github.ferinagy.adventOfCode.Coord3D import com.github.ferinagy.adventOfCode.println import com.github.ferinagy.adventOfCode.readInputText import com.github.ferinagy.adventOfCode.transpose import kotlin.math.abs fun main() { val input = readInputText(2021, "19-input") val testInput1 = readInputText(2021, "19-test1") println("Test part 1 and 2:") val (test1, test2) = solve(testInput1) test1.println() test2.println() println() println("Real part 1 and 2:") val (real1, real2) = solve(input) real1.println() real2.println() } private fun solve(input: String): Pair<Int, Int> { val rawScanners = parse(input) val scanners = rawScanners.map { (name, allBeacons) -> val beacons = allBeacons.map { current -> allBeacons.filter { it != current } .map { current.relativePosition(it) } .map { it.possiblePositions() } .transpose() .map { it.toSet() } .let { UnplacedBeacon(current.possiblePositions(), it) } } UnplacedScanner(name, beacons) } val fixed = mutableListOf(scanners.first().place(Coord3D(0, 0, 0), 0)) val toPlace = scanners.drop(1).toMutableList() outer@ while (toPlace.isNotEmpty()) { val current = toPlace.removeFirst() for (currentBeacon in current.beacons.drop(11)) { for (fixedScanner in fixed) { for (fixedBeacon in fixedScanner.beacons.drop(11)) { val possibleScanners = currentBeacon.getPossibleScanners(fixedBeacon) if (possibleScanners.isEmpty()) continue val (position, rotation) = possibleScanners.single() val placedScanner = current.place(position, rotation) val verified = verifyScanner(placedScanner, fixed) if (verified) { fixed.add(placedScanner) continue@outer } } } } toPlace.add(current) } val beacons = fixed.flatMap { it.beacons }.map { it.position }.toSet() val dist = fixed.maxOf { s1 -> fixed.maxOf { s2 -> s1.position.relativePosition(s2.position).manhattanDist } } return beacons.size to dist } private fun PlacedScanner.isInRange(beacon: PlacedBeacon) = abs(position.x - beacon.position.x) <= 1000 && abs(position.y - beacon.position.y) <= 1000 && abs(position.z - beacon.position.z) <= 1000 private fun verifyScanner(scanner: PlacedScanner, placedScanners: List<PlacedScanner>): Boolean { return placedScanners.all { otherScanner -> val othersInRange = otherScanner.beacons.filter { scanner.isInRange(it) }.map { it.position }.toSet() val inRangeOfOther = scanner.beacons.filter { otherScanner.isInRange(it) }.map { it.position }.toSet() (othersInRange - inRangeOfOther).isEmpty() && (inRangeOfOther - othersInRange).isEmpty() } } private fun parse(input: String): List<Pair<String, List<Coord3D>>> { val scanners = input.split("\n\n").map { scanner -> val lines = scanner.lines() lines.first() to lines.drop(1).map { Coord3D.parse(it) } } return scanners } private data class PlacedScanner(val name: String, val position: Coord3D, val beacons: List<PlacedBeacon>) private data class UnplacedScanner(val name: String, val beacons: List<UnplacedBeacon>) private fun UnplacedScanner.place(position: Coord3D, rotation: Int): PlacedScanner { val placedBeacons = beacons.map { val relative = it.positions[rotation] val final = position + relative PlacedBeacon(final, it.relativePositions[rotation]) } return PlacedScanner(name, position, placedBeacons) } private data class UnplacedBeacon(val positions: List<Coord3D>, val relativePositions: List<Set<Coord3D>>) private fun UnplacedBeacon.getPossibleScanners(other: PlacedBeacon): List<Pair<Coord3D, Int>> { return relativePositions.mapIndexedNotNull { rotation, beacon -> val common = other.relativePositions.intersect(beacon).size if (common < 11) null else { positions[rotation].relativePosition(other.position) to rotation } } } private data class PlacedBeacon(val position: Coord3D, val relativePositions: Set<Coord3D>) fun Coord3D.relativePosition(other: Coord3D) = Coord3D(other.x - x, other.y - y, other.z - z) fun Coord3D.possiblePositions(): List<Coord3D> { val original = this return listOf( original.copy(x = x, y = y, z = z), original.copy(x = x, y = z, z = -y), original.copy(x = x, y = -y, z = -z), original.copy(x = x, y = -z, z = y), original.copy(x = -x, y = -z, z = -y), original.copy(x = -x, y = -y, z = z), original.copy(x = -x, y = z, z = y), original.copy(x = -x, y = y, z = -z), original.copy(x = y, y = x, z = -z), original.copy(x = y, y = -z, z = -x), original.copy(x = y, y = -x, z = z), original.copy(x = y, y = z, z = x), original.copy(x = -y, y = z, z = -x), original.copy(x = -y, y = -x, z = -z), original.copy(x = -y, y = -z, z = x), original.copy(x = -y, y = x, z = z), original.copy(x = z, y = -y, z = x), original.copy(x = z, y = x, z = y), original.copy(x = z, y = y, z = -x), original.copy(x = z, y = -x, z = -y), original.copy(x = -z, y = -x, z = y), original.copy(x = -z, y = y, z = x), original.copy(x = -z, y = x, z = -y), original.copy(x = -z, y = -y, z = -x), ) }
0
Kotlin
0
1
f4890c25841c78784b308db0c814d88cf2de384b
5,749
advent-of-code
MIT License
mantono-kotlin/src/main/kotlin/com/mantono/aoc/day03/Day3.kt
joelfak
433,981,631
true
{"Python": 234827, "Rust": 135681, "C#": 107607, "C++": 97151, "F#": 68551, "Haskell": 36120, "Nim": 30557, "Kotlin": 14600, "REXX": 13854, "OCaml": 12448, "Go": 11995, "C": 9751, "Swift": 8043, "JavaScript": 1750, "PowerShell": 866, "CMake": 851, "AppleScript": 493, "Shell": 255}
package com.mantono.aoc.day03 import com.mantono.aoc.AoC import com.mantono.aoc.Part import java.lang.Integer.max import java.lang.Integer.min import kotlin.math.abs private val startPosition = Position(0, 0) private typealias Path = List<Position> private typealias MutablePath = MutableList<Position> @AoC(3, Part.A) fun findDistanceToClosestIntersection(input: String): Int { val (positionsCable0: Path, positionsCable1: Path) = positionsForPathFromInput(input) val overlaps: Set<Position> = positionsCable0.toSet().intersect(positionsCable1.toSet()) return overlaps .asSequence() .filterNot { it == startPosition } .map { it.manhattanDistance(startPosition) } .sorted() .first() } @AoC(3, Part.B) fun findDistanceToFirstIntersection(input: String): Int { val (positionsCable0: Path, positionsCable1: Path) = positionsForPathFromInput(input) val overlaps: Set<Position> = positionsCable0.toSet().intersect(positionsCable1.toSet()) return overlaps.asSequence() .filterNot { it == startPosition } .map { intersection: Position -> val path0Intersection: Path = positionsCable0.takeWhile { it != intersection } + intersection val path1Intersection: Path = positionsCable1.takeWhile { it != intersection } + intersection val distance0: Int = distanceForPath(path0Intersection) val distance1: Int = distanceForPath(path1Intersection) distance0 + distance1 } .sorted() .first() } fun positionsForPathFromInput(input: String): Pair<Path, Path> { val inputs: List<String> = input.split("\n") val firstCable: List<Vector> = pathDirectionsToPath(inputs[0]) val secondCable: List<Vector> = pathDirectionsToPath(inputs[1]) return positionsFromPath(firstCable) to positionsFromPath(secondCable) } fun distanceForPath(path: Path): Int = path .zipWithNext { p0: Position, p1: Position -> p0.manhattanDistance(p1) } .sum() fun pathDirectionsToPath(pathDirections: String): List<Vector> = pathDirections .split(",") .asSequence() .filterNot { it.isBlank() } .map { Vector.parseFrom(it) } .toList() data class Vector(val direction: Direction, val distance: Int) { companion object { fun parseFrom(input: String): Vector { val direction = Direction.fromString(input[0]) val distance = input.drop(1).toInt() return Vector(direction, distance) } } } data class Position(val x: Int, val y: Int) { fun walk(path: Vector): Position { return when(path.direction) { Direction.Up -> this.copy(y = y + path.distance) Direction.Right -> this.copy(x = x + path.distance) Direction.Down -> this.copy(y = y - path.distance) Direction.Left -> this.copy(x = x - path.distance) } } fun manhattanDistance(other: Position): Int { val yDistance: Int = abs(this.y - other.y) val xDistance: Int = abs(this.x - other.x) return yDistance + xDistance } } fun positionsFromPath(fullPath: List<Vector>): Path { val visited: MutablePath = ArrayList(fullPath.size*2) val finalDestination: Position = fullPath.asSequence() .fold(startPosition) { pos: Position, path: Vector -> visited.add(pos) pos.walk(path) } visited.add(finalDestination) return visited.asSequence() .zipWithNext(::positionsBetween) .flatten() .distinct() .toList() } fun positionsBetween(pos0: Position, pos1: Position): Path { require(pos0.x == pos1.x || pos0.y == pos1.y) { "Trying compare two positions that are not in a straight line to each other" } return if(pos0.x == pos1.x) { val line: IntProgression = if(pos0.y <= pos1.y) { min(pos0.y, pos1.y) .. max(pos0.y, pos1.y) } else { max(pos0.y, pos1.y) downTo min(pos0.y, pos1.y) } line.map { Position(pos0.x, it) } } else { val line: IntProgression = if(pos0.x <= pos1.x) { min(pos0.x, pos1.x) .. max(pos0.x, pos1.x) } else { max(pos0.x, pos1.x) downTo min(pos0.x, pos1.x) } line.map { Position(it, pos0.y) } } } enum class Direction { Up, Right, Down, Left; companion object { fun fromString(input: Char): Direction = values() .asSequence() .first { it.name.startsWith(input) } } }
0
Python
0
0
d5031078c53c181835b4bf86458b360542f0122e
4,548
advent_of_code_2019
Apache License 2.0
src/Day19.kt
illarionov
572,508,428
false
{"Kotlin": 108577}
import kotlin.system.measureTimeMillis fun main() { val testInput = readInput("Day19_test") .map(String::parseBlueprint) val input = readInput("Day19") .map(String::parseBlueprint) part1(testInput).also { println("Part 1, test input: $it") check(it == 33) } part1(input).also { println("Part 1, real input: $it") check(it == 1487) } part2(testInput).also { println("Part 2, test input: $it") check(it == 56 * 62) } part2(input).also { println("Part 2, real input: $it") check(it == 13440) // 16*40*21 } } private data class Blueprint( val id: Int, val oreRobotCost: RobotCost, val clayRobotCost: RobotCost, val obsidianRobotCost: RobotCost, val geodeRobotCost: RobotCost ) private data class RobotCost( val ore: Int = 0, val clay: Int = 0, val obsidian: Int = 0 ) { fun canBuildRobot(ore: Int, clay: Int, obsidian: Int): Boolean { return (obsidian >= this.obsidian && clay >= this.clay && ore >= this.ore) } } private 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.""" ) private fun String.parseBlueprint(): Blueprint { val blueprint = blueprintRegex.matchEntire(this) ?.groupValues ?.drop(1) ?.map(String::toInt) ?: error("Can not parse blueprint `$this`") return Blueprint( id = blueprint[0], oreRobotCost = RobotCost(blueprint[1], 0, 0), clayRobotCost = RobotCost(blueprint[2], 0, 0), obsidianRobotCost = RobotCost(blueprint[3], blueprint[4], 0), geodeRobotCost = RobotCost(blueprint[5], 0, blueprint[6]), ) } private fun part1(input: List<Blueprint>): Int { return input.sumOf { b -> val maxGeodes = b.getMaxOpenedGeodes(24) val level = maxGeodes * b.id println("Blueprint: ${b.id}, max geodes: ${maxGeodes}, level: ${level}") level } } private fun part2(input: List<Blueprint>): Int { return input.take(3).map { b -> val maxGeodes = b.getMaxOpenedGeodes(32) println("Blueprint: ${b.id}, max geodes: ${maxGeodes}") maxGeodes }.reduce(Int::times) } private fun Blueprint.getMaxOpenedGeodes(minutes: Int): Int { data class State( val minute: Int = 0, val oreRobots: Int = 1, val clayRobots: Int = 0, val obsidianRobots: Int = 0, val geodeRobots: Int = 0, val ore: Int = 0, val clay: Int = 0, val obsidian: Int = 0, val geode: Int = 0 ) val cache: MutableMap<Int, State> = mutableMapOf() val queue: ArrayDeque<State> = ArrayDeque() queue.add(State(minute = 0, oreRobots = 1, ore = 0)) val maxOreRobots = maxOf( this.oreRobotCost.ore, this.obsidianRobotCost.ore, this.clayRobotCost.ore, this.geodeRobotCost.ore ) val maxClayRobots = maxOf( this.oreRobotCost.clay, this.obsidianRobotCost.clay, this.clayRobotCost.clay, this.geodeRobotCost.clay ) val maxObsidianRobots = maxOf( this.oreRobotCost.obsidian, this.clayRobotCost.obsidian, this.geodeRobotCost.obsidian ) fun queueIfEligible(state: State): Boolean { cache[state.minute - 1]?.let { old -> if (old.geode > state.geode) { return false } } cache[state.minute] = state queue.addLast(state) return true } var maxGeodes = 0 while (!queue.isEmpty()) { val state = queue.removeLast() val minute = state.minute + 1 if (minute > minutes) continue val newOre = state.ore + state.oreRobots val newClay = state.clay + state.clayRobots val newObsidian = state.obsidian + state.obsidianRobots val newGeode = state.geode + state.geodeRobots val estimateBestCase = run { val timeLeft = maxOf(minutes - state.minute, 0) state.geode + timeLeft * state.geodeRobots + (timeLeft * (timeLeft - 1) / 2) } if (estimateBestCase < maxGeodes) { continue } maxGeodes = maxOf(maxGeodes, newGeode) if (this.geodeRobotCost.canBuildRobot(state.ore, state.clay, state.obsidian)) { val newStateWithGeode = state.copy( minute = minute, ore = newOre - this.geodeRobotCost.ore, clay = newClay - this.geodeRobotCost.clay, obsidian = newObsidian - this.geodeRobotCost.obsidian, geode = newGeode, geodeRobots = state.geodeRobots + 1 ) queueIfEligible(newStateWithGeode) continue } val canBuildOreRobot = this.oreRobotCost.canBuildRobot(state.ore, state.clay, state.obsidian) val canBuildClayRobot = this.clayRobotCost.canBuildRobot(state.ore, state.clay, state.obsidian) val canBuildObsidianRobot = this.obsidianRobotCost.canBuildRobot(state.ore, state.clay, state.obsidian) if (canBuildOreRobot && state.oreRobots < maxOreRobots) { val newStateWithOre = state.copy( minute = minute, ore = newOre - this.oreRobotCost.ore, clay = newClay - this.oreRobotCost.clay, obsidian = newObsidian - this.oreRobotCost.obsidian, geode = newGeode, oreRobots = state.oreRobots + 1 ) queueIfEligible(newStateWithOre) } if (canBuildClayRobot && state.clayRobots < maxClayRobots ) { val newStateWithClay = state.copy( minute = minute, ore = newOre - this.clayRobotCost.ore, clay = newClay - this.clayRobotCost.clay, obsidian = newObsidian - this.clayRobotCost.obsidian, geode = newGeode, clayRobots = state.clayRobots + 1 ) queueIfEligible(newStateWithClay) } if (canBuildObsidianRobot && state.obsidianRobots < maxObsidianRobots) { val newStateWithObsidian = state.copy( minute = minute, ore = newOre - this.obsidianRobotCost.ore, clay = newClay - this.obsidianRobotCost.clay, obsidian = newObsidian - this.obsidianRobotCost.obsidian, geode = newGeode, obsidianRobots = state.obsidianRobots + 1 ) queueIfEligible(newStateWithObsidian) } val newStateCollect = state.copy( minute = minute, ore = newOre, clay = newClay, obsidian = newObsidian, geode = newGeode ) queueIfEligible(newStateCollect) } return maxGeodes }
0
Kotlin
0
0
3c6bffd9ac60729f7e26c50f504fb4e08a395a97
7,159
aoc22-kotlin
Apache License 2.0
kotlin/src/main/kotlin/dev/mikeburgess/euler/problems/Problem027.kt
mddburgess
261,028,925
false
null
package dev.mikeburgess.euler.problems import dev.mikeburgess.euler.sequences.PrimeSequence import dev.mikeburgess.euler.sequences.isPrime /** * Problem 27 * * Euler discovered the remarkable quadratic formula: * * n^2 + n + 41 * * It turns out that the formula will produce 40 primes for the consecutive integer values * 0 <= n <= 39. However, when n = 40, 40^2 + 40 + 41 = 40(40 + 1) + 41 is divisible by 41, and * certainly when n = 41, 41^2 + 41 + 41 is clearly divisible by 41. * * The incredible formula n^2 − 79n + 1601 was discovered, which produces 80 primes for the * consecutive values 0 <= n <= 79. The product of the coefficients, −79 and 1601, is −126479. * * Considering quadratics of the form: * * n^2 + an + b, where |a| < 1000 and |b| <= 1000 * * where |n| is the modulus/absolute value of n (e.g. |11| = 11 and |−4| = 4) * * Find the product of the coefficients, a and b, for the quadratic expression that produces the * maximum number of primes for consecutive values of n, starting with n = 0. */ class Problem027 : Problem { private fun countConsecutivePrimes(a: Long, b: Long) = generateSequence(0L) { it + 1 } .map { it * (it + a) + b } .takeWhile { it.isPrime() } .count().toLong() override fun solve(): Long { val (a, b) = PrimeSequence() .takeWhile { it <= 1000 } .flatMap { b -> ((1 - b)..999L).map { it to b }.asSequence() } .associateWith { (a, b) -> countConsecutivePrimes(a, b) } .maxBy { it.value }!! .key return a * b } }
0
Kotlin
0
0
86518be1ac8bde25afcaf82ba5984b81589b7bc9
1,622
project-euler
MIT License
src/Day08.kt
mborromeo
571,999,097
false
{"Kotlin": 10600}
import kotlin.math.max fun main() { data class Mtx( val l: List<Int>, val r: List<Int>, val t: List<Int>, val b: List<Int>, ) { val dir = listOf(l, r, t, b) } fun List<List<Int>>.build(i: Int, j: Int) = Mtx( l = this[i].subList(0, j).reversed(), r = this[i].subList(j + 1, this[i].lastIndex + 1), t = this.subList(0, i).map { it[j] }.reversed(), b = this.subList(i + 1, this.lastIndex + 1).map { it[j] } ) fun part1(input: List<String>): Int { val forest = input.map { row -> row.map { it.digitToInt() } } var visibleTrees = 2 * (forest.size + forest.first().size - 2) for (i in 1 until forest.lastIndex) { for (j in 1 until forest[i].lastIndex) { if (forest.build(i, j).dir.map { it -> it.maxOf { it } }.any { it < forest[i][j] }) visibleTrees += 1 } } return visibleTrees } fun part2(input: List<String>): Int { var maxScore = 0 val forest = input.map { row -> row.map { it.digitToInt() } } for (i in 1 until forest.lastIndex) { for (j in 1 until forest[i].lastIndex) { val v = forest.build(i, j) val score = v.dir.map { direction -> val index = direction.indexOfFirst { it >= forest[i][j] } + 1 index.takeIf { it != 0 } ?: direction.size }.reduce { acc, idx -> acc * idx } maxScore = max(maxScore, score) } } return maxScore } val input = readInput("Day08_input") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
d01860ecaff005aaf8e1e4ba3777a325a84c557c
1,697
advent-of-code-kotlin-2022
Apache License 2.0
src/Day11.kt
razvn
573,166,955
false
{"Kotlin": 27208}
fun main() { val day = "Day11" fun part1(input: List<String>): Int { val monkeys = loadValues(input) // println("Start --->") // monkeys.forEach(::println) (1..20).forEach { monkeys.forEach { (_, m) -> m.items.forEach { item -> m.inspectedItems ++ val newWorry = m.operation.applyOperation(item) / 3 if (newWorry % m.test == 0L) { monkeys[m.testTrue]!!.items.add(newWorry) } else { monkeys[m.testFalse]!!.items.add(newWorry) } } m.items.clear() } // println("After $it --->") // monkeys.forEach(::println) } return monkeys.values.sortedByDescending { it.inspectedItems }.take(2).let { it.first().inspectedItems * it.last().inspectedItems } } fun part2(input: List<String>): Long { val monkeys = loadValues(input) // println("Start --->") // monkeys.forEach(::println) val div = monkeys.values.fold(1) { acc, value -> acc * value.test } (1..10000).forEach { monkeys.forEach { (_, m) -> m.items.forEach { item -> m.inspectedItems ++ val newWorry = m.operation.applyOperation(item) % div if (newWorry % m.test == 0L) { monkeys[m.testTrue]!!.items.add(newWorry) } else { monkeys[m.testFalse]!!.items.add(newWorry) } } m.items.clear() } // println("After $it --->") // monkeys.forEach(::println) } return monkeys.values.sortedByDescending { it.inspectedItems }.take(2).let { it.first().inspectedItems.toLong() * it.last().inspectedItems.toLong() } } // test if implementation meets criteria from the description, like: val testInput = readInput("${day}_test") // println(part1(testInput)) // println(part2(testInput)) check(part1(testInput) == 10605) check(part2(testInput) == 2713310158) val input = readInput(day) println(part1(input)) println(part2(input)) } private enum class Op { PLUS, TIMES } private data class Operation(val op: Op, val arg2: Long?) { constructor(params: List<String>) : this(if (params[0] == "+") Op.PLUS else Op.TIMES, params[1].toLongOrNull()) fun applyOperation(value: Long): Long = when(op) { Op.PLUS -> value + (arg2 ?: value) Op.TIMES -> value * (arg2 ?: value) } } private data class Monkey( val id: Int, val items: MutableList<Long>, val operation: Operation, val test: Int, val testTrue: Int, val testFalse: Int, var inspectedItems: Int = 0 ) private fun loadValues(input: List<String>): MutableMap<Int, Monkey> { return input.chunked(7).map { monkey -> val id = monkey[0].substringAfter("Monkey ").dropLast(1).toInt() val items = monkey[1].substringAfter("Starting items: ").split(", ").map { it.toLong() } val operation = monkey[2].substringAfter("Operation: new = old ").split(" ") val test = monkey[3].substringAfter("Test: divisible by ").toInt() val testTrue = monkey[4].substringAfter("If true: throw to monkey ").toInt() val testFalse = monkey[5].substringAfter("If false: throw to monkey ").toInt() id to Monkey(id, items.toMutableList(), Operation(operation), test, testTrue, testFalse) }.toMap().toMutableMap() }
0
Kotlin
0
0
73d1117b49111e5044273767a120142b5797a67b
3,670
aoc-2022-kotlin
Apache License 2.0
src/test/kotlin/Day07.kt
christof-vollrath
317,635,262
false
null
import io.kotest.core.spec.style.FunSpec import io.kotest.matchers.shouldBe /* --- Day 7: Handy Haversacks --- See https://adventofcode.com/2020/day/7 */ fun Collection<Bag>.findAllBagsContaining(color: String): Set<Bag> { val containingMap = this.flatMap {bag -> bag.content.map { bagQuantity -> bagQuantity.color to bag } }.groupBy { it.first } return sequence { var currentColors = listOf(color) while(true) { val nextColors = currentColors.flatMap { currentColor -> val containers = containingMap[currentColor] yield(containers?.map { it.second } ?: emptyList<Bag>()) containers?.map { it.second.color } ?: emptyList() } if(nextColors.isEmpty()) break else currentColors = nextColors } }.flatten().toSet() } fun Collection<BagQuantity>.sumByColor() = groupBy { it.color } .entries.map { (color, bagQuantities) -> BagQuantity(color, bagQuantities.map { it.quantity }.sum()) } fun Collection<Bag>.findAllBagsContainingWithQuantity(initialBagQuantity: BagQuantity): Set<BagQuantity> { val containingMap = this.flatMap {bag -> bag.content.map { bagQuantity -> bag.color to bagQuantity } }.groupBy { it.first } return sequence { var currentBagQuantities = listOf(initialBagQuantity) while(true) { val nextBagQuantities = currentBagQuantities.flatMap { currentBagQuantity -> val containers = containingMap[currentBagQuantity.color] val interimResult = containers?.map { (_, bagQuantity) -> BagQuantity(bagQuantity.color, currentBagQuantity.quantity * bagQuantity.quantity) } ?: emptyList() yield(interimResult) interimResult } if(nextBagQuantities.isEmpty()) break else currentBagQuantities = nextBagQuantities.sumByColor() } }.flatten().toList().sumByColor().toSet() } fun parseBagSpecifications(bagSpecifications: String): List<Bag> = bagSpecifications.split("\n") .map { parseBagSpecification(it) } fun parseBagSpecification(bagSpecString: String): Bag { val regex = """(\w+) (\w+) bags contain (.*)""".toRegex() val match = regex.find(bagSpecString) ?: throw IllegalArgumentException("Can not parse input") if (match.groupValues.size < 4) throw IllegalArgumentException("Not enough elements parsed") println(match.groupValues) val color = match.groupValues[1] + " " + match.groupValues[2] val content = if (match.groupValues[3] == "no other bags.") emptySet() else { val pattern = """(\d+) (\w+) (\w+) bags?,?""".toPattern() val matcher = pattern.matcher(match.groupValues[3]) sequence { while(matcher.find()) { val quantity = matcher.group(1).toInt() val containingColor = matcher.group(2) + " " + matcher.group(3) yield(BagQuantity(containingColor, quantity)) } }.toSet() } return Bag(color, content) } data class BagQuantity(val color: String, val quantity: Int) data class Bag(val color: String, val content: Set<BagQuantity>) class Day07_Part1 : FunSpec({ context("parse bag specification") { test("parse single bag specification with two containing bags") { val bagSpecification = "light red bags contain 1 bright white bag, 2 muted yellow bags." parseBagSpecification(bagSpecification) shouldBe Bag(color = "light red", content = setOf( BagQuantity(color = "bright white", quantity = 1), BagQuantity(color = "muted yellow", quantity = 2), ) ) } test("parse single bag specification with one containing bag") { val bagSpecification = "bright white bags contain 1 shiny gold bag." parseBagSpecification(bagSpecification) shouldBe Bag(color = "bright white", content = setOf( BagQuantity(color = "shiny gold", quantity = 1), ) ) } test("parse single bag specification with no containing bag") { val bagSpecification = "faded blue bags contain no other bags." parseBagSpecification(bagSpecification) shouldBe Bag(color = "faded blue", content = emptySet()) } test("parse single bag specification with four containing bags") { val bagSpecification = "light fuchsia bags contain 2 dotted silver bags, 3 dotted lavender bags, 3 shiny gold bags, 5 clear magenta bags." parseBagSpecification(bagSpecification) shouldBe Bag(color = "light fuchsia", content = setOf( BagQuantity(color = "dotted silver", quantity = 2), BagQuantity(color = "dotted lavender", quantity = 3), BagQuantity(color = "shiny gold", quantity = 3), BagQuantity(color = "clear magenta", quantity = 5), ) ) } } val bagSpecificationsString = """ light red bags contain 1 bright white bag, 2 muted yellow bags. dark orange bags contain 3 bright white bags, 4 muted yellow bags. bright white bags contain 1 shiny gold bag. muted yellow bags contain 2 shiny gold bags, 9 faded blue bags. shiny gold bags contain 1 dark olive bag, 2 vibrant plum bags. dark olive bags contain 3 faded blue bags, 4 dotted black bags. vibrant plum bags contain 5 faded blue bags, 6 dotted black bags. faded blue bags contain no other bags. dotted black bags contain no other bags. """.trimIndent() context("parse bags") { test("parse bag specifications") { parseBagSpecifications(bagSpecificationsString).size shouldBe 9 } } context("find all bags containing") { val bagSpecifications = parseBagSpecifications(bagSpecificationsString) val bagsContainingShinyGold = bagSpecifications.findAllBagsContaining("shiny gold") test("should contain the right number of bags") { bagsContainingShinyGold.size shouldBe 4 } test("should contain the right bags") { bagsContainingShinyGold.map { it.color }.toSet() shouldBe setOf("bright white", "muted yellow", "dark orange", "light red") } } }) class Day07_Part1_Exercise: FunSpec({ val input = readResource("day07Input.txt")!! val bagSpecifications = parseBagSpecifications(input) test("should have parsed all bag specifications") { bagSpecifications.size shouldBe 594 } val count = bagSpecifications.findAllBagsContaining("shiny gold").size test("solution") { count shouldBe 205 } }) class Day07_Part2 : FunSpec({ context("find all bags containing with quantity example 1") { val bagSpecificationsString = """ light red bags contain 1 bright white bag, 2 muted yellow bags. dark orange bags contain 3 bright white bags, 4 muted yellow bags. bright white bags contain 1 shiny gold bag. muted yellow bags contain 2 shiny gold bags, 9 faded blue bags. shiny gold bags contain 1 dark olive bag, 2 vibrant plum bags. dark olive bags contain 3 faded blue bags, 4 dotted black bags. vibrant plum bags contain 5 faded blue bags, 6 dotted black bags. faded blue bags contain no other bags. dotted black bags contain no other bags. """.trimIndent() val bagSpecifications = parseBagSpecifications(bagSpecificationsString) val bagsContainingShinyGold = bagSpecifications.findAllBagsContainingWithQuantity(BagQuantity("shiny gold", 1)) test("should contain the right number of bags") { bagsContainingShinyGold.size shouldBe 4 } test("should contain the right quantity") { bagsContainingShinyGold.map { it.quantity }.sum() shouldBe 32 } } context("find all bags containing with quantity example 2") { val bagSpecificationsString = """ shiny gold bags contain 2 dark red bags. dark red bags contain 2 dark orange bags. dark orange bags contain 2 dark yellow bags. dark yellow bags contain 2 dark green bags. dark green bags contain 2 dark blue bags. dark blue bags contain 2 dark violet bags. dark violet bags contain no other bags. """.trimIndent() val bagSpecifications = parseBagSpecifications(bagSpecificationsString) val bagsContainingShinyGold = bagSpecifications.findAllBagsContainingWithQuantity(BagQuantity("shiny gold", 1)) println(bagsContainingShinyGold) test("should contain the right quantity") { bagsContainingShinyGold.map { it.quantity }.sum() shouldBe 126 } } }) class Day07_Part2_Exercise: FunSpec({ val input = readResource("day07Input.txt")!! val bagSpecifications = parseBagSpecifications(input) test("should have parsed all bag specifications") { bagSpecifications.size shouldBe 594 } val quantity = bagSpecifications.findAllBagsContainingWithQuantity(BagQuantity("shiny gold", 1)).map { it.quantity }.sum() test("solution") { quantity shouldBe 80902 } })
1
Kotlin
0
0
8ad08350aa4bd1a29b7e18765fc7a2d6de8021e8
9,511
advent_of_code_2020
Apache License 2.0
advent-of-code-2021/src/code/day3/Main.kt
Conor-Moran
288,265,415
false
{"Kotlin": 53347, "Java": 14161, "JavaScript": 10111, "Python": 6625, "HTML": 733}
package code.day3 import code.common.BinDigit import code.common.flipBits import java.io.File fun main() { doIt("Day 3 Part 1: Test Input", "src/code/day3/test.input", part1) doIt("Day 3 Part 1: Real Input", "src/code/day3/part1.input", part1) doIt("Day 3 Part 2: Test Input", "src/code/day3/test.input", part2) doIt("Day 3 Part 2: Real Input", "src/code/day3/part1.input", part2) } fun doIt(msg: String, input: String, calc: (nums: List<String>) -> Int) { val lines = arrayListOf<String>() File(input).forEachLine { lines.add(it) } println(String.format("%s: Ans: %d", msg , calc(lines))) } val part1: (List<String>) -> Int = { lines -> val numLength = lines[0].length val zeroCounts = MutableList(numLength) {0} lines.forEach { val numStr = it for (i in numStr.indices) { if ('0' == numStr[i]) { val count = zeroCounts[i] zeroCounts[i] = count + 1 } } } val gammaMcStr = zeroCounts.map { if (it > lines.size / 2) 0.toString() else 1.toString() } .reduce { acc, v -> acc + v } val gammaMC = Integer.parseInt(gammaMcStr, 2) val epsilonLC = flipBits(gammaMC, numLength) gammaMC * epsilonLC } val part2: (List<String>) -> Int = { lines -> val oxyGenRating = filter(lines, 0, mostCommonBit) val co2ScrubRating = filter(lines, 0, leastCommonBit) Integer.parseInt(oxyGenRating, 2) * Integer.parseInt(co2ScrubRating, 2) } fun filter(numList: List<String>, pos: Int, pred: (numList: List<String>, pos: Int) -> BinDigit): String { val tmp = arrayListOf<String>() val filtered = arrayListOf<String>() tmp.addAll(numList) val predDigit = pred(tmp, pos) tmp.forEach { if (it[pos] == predDigit.char) { filtered.add(it) } } return if (filtered.size > 1) { filter(filtered, pos + 1, pred) } else { filtered[0] } } val mostCommonBit: (List<String>, Int) -> BinDigit = { numList, pos -> var zeroCount = 0 numList.forEach { val numStr = it if (BinDigit.ZERO.char == numStr[pos]) { zeroCount += 1 } } val oneCount = numList.size - zeroCount if(zeroCount > oneCount) BinDigit.ZERO else BinDigit.ONE } val leastCommonBit: (List<String>, Int) -> BinDigit = { numList, pos -> mostCommonBit(numList, pos).inv() }
0
Kotlin
0
0
ec8bcc6257a171afb2ff3a732704b3e7768483be
2,407
misc-dev
MIT License
src/Day15.kt
akijowski
574,262,746
false
{"Kotlin": 56887, "Shell": 101}
import kotlin.math.abs import kotlin.math.max import kotlin.math.min data class SensorBeacon(val x: Int, val y: Int, val isBeacon: Boolean = false) { fun dist(other: SensorBeacon): Int { // manhattan distance return abs(x - other.x) + abs(y - other.y) } fun contains(a: Int, b: Int, other: SensorBeacon): Boolean { val man = dist(other) val xLo = (x - man) + abs(y - b) val xHi = (x + man) - abs(y - b) return a in xLo..xHi } } data class Sensor(val coord: Coord = Coord(), val beacon: Coord = Coord()) { fun fromStrings(x: String, y: String, bx: String, by: String) = Sensor( Coord(x.trim().toLong(), y.trim().toLong()), Coord(bx.trim().toLong(), by.trim().toLong()), ) fun manhattan(): Long = abs(coord.x - beacon.x) + abs(coord.y - beacon.y) fun covers(other: Coord) = abs(other.x - coord.x) + abs(other.y - coord.y) <= manhattan() fun circumference() = buildList { val dist = manhattan() val lowerY = (coord.y - dist - 1) val upperY = (coord.y + dist + 1) for (y in lowerY..upperY) { val rem = dist - abs(coord.y - y) + 1 add(Coord(coord.x - rem, y)) if (rem > 0) { add(Coord(coord.x + rem, y)) } } }.distinct() } data class Boundary(val start: Int, val end: Int) { fun overlaps(other: Boundary) = end >= other.start } data class Coord(val x: Long = 0, val y: Long = 0) { operator fun plus(other: Coord): Coord = Coord(x + other.x, y + other.y) } fun main() { val sensorRegex = """^.*x=(-?\d+), y=(-?\d+)$""".toRegex() val re = """^Sensor at x=(-?\d+), y=(-?\d+): closest beacon is at x=(-?\d+), y=(-?\d+)""".toRegex() fun part1(input: List<String>, target: Int): Int { val m = buildMap { input.map { it.split(":") }.forEach { (s, b) -> val (sx, sy) = sensorRegex.matchEntire(s.trim())?.destructured ?: throw IllegalArgumentException("invalid input: $s") val (bx, by) = sensorRegex.matchEntire(b.trim())?.destructured ?: throw IllegalArgumentException("invalid input: $b") val sensor = SensorBeacon(sx.toInt(), sy.toInt()) val beacon = SensorBeacon(bx.toInt(), by.toInt(), isBeacon = true) put(sensor, beacon) } } val beacons = m.values.toSet() // store ranges for y. At each insert: combine the overlaps val otherIdea = mutableMapOf<Int, MutableList<Boundary>>() m.entries.forEach { (s, b) -> val dist = s.dist(b) for (y in (s.y - dist)..(s.y + dist)) { val xlo = (s.x - dist) + abs(s.y - y) val xhi = (s.x + dist) - abs(s.y - y) val newBound = Boundary(xlo, xhi) val existing = otherIdea[y] ?: mutableListOf() existing.add(newBound) otherIdea[y] = existing } } val x = otherIdea.entries.associate { (y, boundaries) -> y to boundaries.sortedBy { it.start }.fold(mutableListOf<Boundary>()) { acc, b -> if (acc.isEmpty()) { acc.add(b) } else { var boundary = b val existingLowest = acc.minBy { it.start } val existingHighest = acc.maxBy { it.end } if (boundary.overlaps(existingLowest) && existingLowest.overlaps(boundary)) { val lo = min(boundary.start, existingLowest.start) val hi = max(boundary.end, existingLowest.end) acc.remove(existingLowest) boundary = Boundary(lo, hi) } else if (boundary.overlaps(existingHighest) && existingHighest.overlaps(boundary)) { val lo = min(boundary.start, existingHighest.start) val hi = max(boundary.end, existingHighest.end) acc.remove(existingHighest) boundary = Boundary(lo, hi) } acc.add(boundary) } acc } } val y = x.entries.associate { (y, boundaries) -> y to boundaries.fold(0) { acc, (s, e) -> acc + ((e - s) + 1) - beacons.count { it.y == y } } } return y[target]!! } fun part2(input: List<String>): Long { val maxCoord = 4_000_000 val sensors = input.map { val (sx, sy, bx, by) = re.matchEntire(it)?.destructured ?: throw IllegalArgumentException("error: $it") Sensor().fromStrings(sx, sy, bx, by) } val res = sensors .asSequence() .flatMap { sensor -> sensor.circumference() } .filter { coord -> coord.x in 0..maxCoord && coord.y in 0..maxCoord } .find { coord ->sensors.none { sensor -> sensor.covers(coord) } } return if (res != null) { (res.x * maxCoord) + res.y } else { 0L } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day15_test") //part1(listOf("Sensor at x=8, y=7: closest beacon is at x=2, y=10"), 12) //check(part1(testInput, 10) == 26) // val cs = Sensor(Coord(1L, 1L), Coord(3L, 3L)).circumference() val input = readInput("Day15") // println(part1(input, 2_000_000)) println(part2(input)) }
0
Kotlin
1
0
84d86a4bbaee40de72243c25b57e8eaf1d88e6d1
5,520
advent-of-code-2022
Apache License 2.0
src/main/kotlin/day07/Day07.kt
qnox
575,581,183
false
{"Kotlin": 66677}
package day07 import readInput sealed interface FSNode { val name: String } class Dir(override val name: String, val parent: Dir? = null) : FSNode { private val _children: MutableMap<String, FSNode> = mutableMapOf() val children: Map<String, FSNode> get() = _children operator fun get(name: String) = children[name] ?: error("Unknown name $name") fun add(fsNode: FSNode) { if (_children.contains(fsNode.name)) { error("Name ${fsNode.name} already exists!") } _children[fsNode.name] = fsNode } } class File(override val name: String, val size: Long) : FSNode { override fun toString(): String { return "$name($size)" } } fun main() { fun buildTree(input: List<String>): Dir { val root = Dir("/") var current = root input.forEach { line -> if (line.startsWith("$ ls")) { //skip } else if (line.startsWith("$ cd ")) { val name = line.substring(5) current = if (name == "/") { root } else if (name == "..") { current.parent ?: error("No parent") } else { current[name] as Dir } } else if (line.startsWith("dir ")) { val name = line.substring(4) current.add(Dir(name, current)) } else { val (size, name) = line.split("\\s+".toRegex()) current.add(File(name, size.toLong())) } } return root } fun part1(input: List<String>): Long { val root = buildTree(input) fun postorder(dir: Dir): Pair<Long, Long> { var total = 0L var result = 0L dir.children.values.forEach { when (it) { is Dir -> { val (size, sub) = postorder(it) total += size result += sub } is File -> { total += it.size } } } if (total <= 100_000) { result += total } return total to result } return postorder(root).second } fun part2(input: List<String>): Long { val root = buildTree(input) fun total(dir: Dir): Long { return dir.children.values.sumOf { when (it) { is Dir -> { total(it) } is File -> { it.size } } } } val total = total(root) val need = 30000000 - (70000000 - total) fun postorder(dir: Dir, need: Long): Pair<Long, Long> { var total = 0L var result = Long.MAX_VALUE dir.children.values.forEach { when (it) { is Dir -> { val (size, sub) = postorder(it, need) total += size result = minOf(result, sub) } is File -> { total += it.size } } } if (total >= need) { result = minOf(result, total) } return total to result } return postorder(root, need).second } val testInput = readInput("day07", "test") val input = readInput("day07", "input") check(part1(testInput) == 95437L) println(part1(input)) check(part2(testInput) == 24933642L) println(part2(input)) }
0
Kotlin
0
0
727ca335d32000c3de2b750d23248a1364ba03e4
3,798
aoc2022
Apache License 2.0
src/y2022/Day09.kt
gaetjen
572,857,330
false
{"Kotlin": 325874, "Mermaid": 571}
package y2022 import util.readInput import kotlin.math.abs object Day09 { enum class Direction { UP, DOWN, LEFT, RIGHT; companion object { fun fromChar(c: Char): Direction { return when (c) { 'R' -> RIGHT 'U' -> UP 'D' -> DOWN 'L' -> LEFT else -> error("$c is not a direction") } } } fun move(pos: Pair<Int, Int>): Pair<Int, Int> { val (fromX, fromY) = pos return when (this) { UP -> fromX to fromY + 1 DOWN -> fromX to fromY - 1 LEFT -> fromX - 1 to fromY RIGHT -> fromX + 1 to fromY } } } data class Move(val direction: Direction, val steps: Int) private fun parse(input: String): Move { return Move( Direction.fromChar(input.first()), input.split(" ").last().toInt() ) } fun part1(input: List<String>): Int { val moves = input.map { parse(it) } var headPos = 0 to 0 var tailPos = headPos val visited = mutableSetOf(tailPos) moves.forEach { move -> repeat(move.steps) { // move head headPos = move.direction.move(headPos) // follow tail tailPos = follow(headPos, tailPos) // add new pos to visited visited.add(tailPos) } } return visited.size } private fun follow(headPos: Pair<Int, Int>, tailPos: Pair<Int, Int>): Pair<Int, Int> { val (headX, headY) = headPos val (tailX, tailY) = tailPos val (distX, distY) = headX - tailX to headY - tailY if (distX == 0 && abs(distY) == 2) { assert(abs(distY) == 2) return tailX to tailY + (distY / 2) } if (distY == 0 && abs(distX) == 2) { return tailX + (distX / 2) to tailY } if (abs(distX) <= 1 && abs(distY) <= 1) { return tailPos } // diagonal return tailX + (distX / abs(distX)) to tailY + (distY / abs(distY)) } fun part2(input: List<String>): Int { val moves = input.map { parse(it) } val rope = MutableList(10) { 0 to 0 } val visited = mutableSetOf(rope.last()) moves.forEach { move -> repeat(move.steps) { rope.forEachIndexed { index, pos -> if (index == 0) { rope[0] = move.direction.move(pos) } else { rope[index] = follow(rope[index - 1], pos) } } visited.add(rope.last()) } } return visited.size } } fun main() { println(listOf(1, 2, 3).slice(0..1)) val testInput = """ R 4 U 4 L 3 D 1 R 4 D 1 L 5 R 2 """.trimIndent().split("\n") val test2 = """ R 5 U 8 L 8 D 3 R 17 D 10 L 25 U 20 """.trimIndent().split("\n") println("------Tests------") println(Day09.part1(testInput)) println(Day09.part2(test2)) println("------Real------") val input = readInput("resources/2022/day09") // wrong: 11292 println(Day09.part1(input)) // wrong: 2627 println(Day09.part2(input)) }
0
Kotlin
0
0
d0b9b5e16cf50025bd9c1ea1df02a308ac1cb66a
3,537
advent-of-code
Apache License 2.0
src/day07/a/day07a.kt
pghj
577,868,985
false
{"Kotlin": 94937}
package day07.a import readInputLines import shouldBe fun main() { val root = readInput() var acc = 0 root.treeReduce(0, Integer::sum) { dir, subTreeSize -> val size = subTreeSize + dir.sumFileSize() if (size <= 100000) acc += size size } shouldBe(1513699, acc) } class Dir ( val parent: Dir?, val name: String, ) { private val dir = HashMap<String, Dir>() private var files = HashMap<String, Int>() fun subDir(s: String): Dir { return dir.computeIfAbsent(s) { Dir(this, it) } } fun addFile(name: String, size: Int) { files[name] = size } fun sumFileSize(): Int { return if (files.isEmpty()) 0 else files.values.reduce { a, b -> a+b } } fun <R> treeReduce(init: R, r: (R, R) -> R, f: (Dir, R) -> R) : R { var a = init for (d in dir.values) a = r(a, d.treeReduce(init, r, f)) return f(this, a) } } fun readInput(): Dir { val root = Dir(null, "") var cur = root readInputLines(7).forEach { line -> if (line.startsWith("$")) { when(line.substring(2..3)) { "cd" -> { val arg = line.substring(5) cur = if (arg == "..") cur.parent!! else if (arg == "/") root else cur.subDir(arg) } } } else if (line.startsWith("dir ")) { // do nothing: no point in adding an empty entry } else { val (size, name) = line.split(" ").let { Pair(it[0].toInt(), it[1]) } // we might reasonably encounter the same file twice, so do not simply increment a size counter cur.addFile(name, size) } } return root }
0
Kotlin
0
0
4b6911ee7dfc7c731610a0514d664143525b0954
1,722
advent-of-code-2022
Apache License 2.0
src/Day09.kt
xNakero
572,621,673
false
{"Kotlin": 23869}
import kotlin.math.pow import kotlin.math.sign import kotlin.math.sqrt object Day09 { fun part1() = process(1) fun part2() = process(9) private fun process(tailSize: Int) = readCommands() .fold(Rope(tailSize)) { rope, cmd -> processCommand(cmd, rope) } .visitedCoordinates.size private fun processCommand(command: RopeCommand, rope: Rope): Rope = (0 until command.times).toList().fold(rope) { r, _ -> val updatedHead = r.head.move(command.direction) val updatedTail = updateTail(updatedHead, r) r.updated(updatedHead, updatedTail) } private fun updateTail(newHead: Coordinate, rope: Rope): Tail = (listOf(newHead) + rope.tail).toMutableList() .also { knots -> knots.indices.windowed(2, 1).forEach { pair -> takeIf { knots[pair[0]].isRequiredToMove(knots[pair[1]]) } ?.also { knots[pair[1]] = knots[pair[1]].move(knots[pair[0]]) } } }.let { it.subList(1, it.size).toList() } private fun readCommands() = readInput("day09") .map { line -> line.split(" ").let { RopeCommand(it[0], it[1].toInt()) } } } data class Rope(val head: Coordinate, val tail: Tail, val visitedCoordinates: Set<Coordinate>) { constructor(tailSize: Int) : this( head = Coordinate(), tail = (0 until tailSize).toList().map { Coordinate() }, visitedCoordinates = emptySet() ) fun updated(updatedHead: Coordinate, updatedTail: Tail): Rope = copy( head = updatedHead, tail = updatedTail, visitedCoordinates = visitedCoordinates + updatedTail.last() ) } data class Coordinate(val x: Int = 0, val y: Int = 0) { fun move(direction: String): Coordinate = when (direction) { "L" -> copy(x = x - 1) "R" -> copy(x = x + 1) "U" -> copy(y = y + 1) "D" -> copy(y = y - 1) else -> throw InvalidDirectionException(direction) } fun move(other: Coordinate): Coordinate = Coordinate( x = (other.x - x).sign + x, y = (other.y - y).sign + y ) fun isRequiredToMove(other: Coordinate): Boolean = distanceToOther(other) !in setOf(0.0, 1.0, sqrt(2.0)) private fun distanceToOther(other: Coordinate): Double = sqrt((x - other.x.toDouble()).pow(2) + (y - other.y.toDouble()).pow(2)) } data class RopeCommand(val direction: String, val times: Int) private typealias Tail = List<Coordinate> class InvalidDirectionException(direction: String) : RuntimeException("There is no such direction: $direction") fun main() { println(Day09.part1()) println(Day09.part2()) }
0
Kotlin
0
0
c3eff4f4c52ded907f2af6352dd7b3532a2da8c5
2,767
advent-of-code-2022
Apache License 2.0
src/Day13.kt
arhor
572,349,244
false
{"Kotlin": 36845}
import java.util.* fun main() { val input = readInput {} println("Part 1: ${solvePuzzle1(input)}") println("Part 2: ${solvePuzzle2(input)}") } private fun solvePuzzle1(input: List<String>): Int { var sum = 0 for ((index, packets) in input.split("").map { it.map(::parse) }.withIndex()) { checkOrder(packets[0], packets[1])?.also { ordered -> if (ordered) { sum += (index + 1) } } } return sum } private fun solvePuzzle2(input: List<String>): Int { val one = listOf(listOf(2)) val two = listOf(listOf(6)) val orderedPackets = input.split("").flatMap { it.map(::parse) }.toMutableList().apply { add(one) add(two) sortWith { l, r -> if (checkOrder(l, r) == true) 1 else -1 } } return orderedPackets.run { indexOf(one) * indexOf(two) } } private fun checkOrder(left: Any?, right: Any?): Boolean? { when { left is Int && right is Int -> return when { left < right -> true left > right -> false else -> null } left is List<*> && right is List<*> -> { var i = 0 while (true) { when { i > left.lastIndex && i <= right.lastIndex -> return true i <= left.lastIndex && i > right.lastIndex -> return false i > left.lastIndex && i > right.lastIndex -> return null } checkOrder(left[i], right[i])?.let { return it } i++ } } left is Int -> return checkOrder(listOf(left), right) right is Int -> return checkOrder(left, listOf(right)) else -> return null } } private fun parse(input: String): List<Any> { val stack = ArrayDeque<ArrayList<Any>>() val value = StringBuilder() var last = emptyList<Any>() for (char in input) { when (char) { '[' -> { val nextList = ArrayList<Any>() stack.peek()?.add(nextList) stack.push(nextList) } ']' -> { last = stack.pop() value.extractTo { last.add(it.toInt()) } } ',' -> { value.extractTo { stack.peek().add(it.toInt()) } } else -> value.append(char) } } return last }
0
Kotlin
0
0
047d4bdac687fd6719796eb69eab2dd8ebb5ba2f
2,462
aoc-2022-in-kotlin
Apache License 2.0
src/main/kotlin/se/brainleech/adventofcode/aoc2016/Aoc2016Day01.kt
fwangel
435,571,075
false
{"Kotlin": 150622}
package se.brainleech.adventofcode.aoc2016 import se.brainleech.adventofcode.compute import se.brainleech.adventofcode.readLines import se.brainleech.adventofcode.verify import kotlin.math.abs class Aoc2016Day01 { enum class Facing { NORTH, EAST, SOUTH, WEST; fun turn(direction: Char) : Facing { if (direction == 'R') { return when (this) { NORTH -> EAST; EAST -> SOUTH; SOUTH -> WEST; WEST -> NORTH } } return when (this) { NORTH -> WEST; WEST -> SOUTH; SOUTH -> EAST; EAST -> NORTH } } } class Location(var x: Int, var y: Int, private var facing: Facing = Facing.NORTH) { fun moveBy(instruction: String) : Location { facing = facing.turn(instruction.first()) val steps = instruction.substring(1).toInt() when (facing) { Facing.NORTH -> y -= steps Facing.EAST -> x += steps Facing.SOUTH -> y += steps Facing.WEST -> x -= steps } return this } fun pathBy(instruction: String) : List<Location> { val path = mutableListOf<Location>() val facingNext = facing.turn(instruction.first()) val steps = instruction.substring(1).toInt() var xNext = x var yNext = y when (facingNext) { Facing.NORTH -> repeat(steps) { path.add(Location(x, --yNext, facingNext)) } Facing.EAST -> repeat(steps) { path.add(Location(++xNext, y, facingNext)) } Facing.SOUTH -> repeat(steps) { path.add(Location(x, ++yNext, facingNext)) } Facing.WEST -> repeat(steps) { path.add(Location(--xNext, y, facingNext)) } } return path } fun id() = x.times(100_000_000).plus(y) fun distance() = abs(x) + abs(y) } fun part1(input: String) : Int { val location = Location(0, 0) val instructions = input .replace(" ", "") .split(",") .toList() instructions.forEach { location.moveBy(it) } return location.distance() } fun part2(input: String) : Int { var location = Location(0, 0) val instructions = input .replace(" ", "") .split(",") .toList() val visited = mutableSetOf(location.id()) instructions.forEach { instruction -> val path = location.pathBy(instruction).also { location = it.last() } val revisited = path.firstOrNull { visited.contains(it.id()) } if (revisited != null) { return revisited.distance() } visited.addAll(path.map { it.id() }) } // no revisited location! return -1 } } fun main() { val solver = Aoc2016Day01() val prefix = "aoc2016/aoc2016day01" val testData = readLines("$prefix.test.txt").filter { it.isNotBlank() } val realData = readLines("$prefix.real.txt").filter { it.isNotBlank() } listOf(5, 2, 12).forEachIndexed { index, expected -> verify(expected, solver.part1(testData[index])) } compute({ solver.part1(realData.first()) }, "$prefix.part1 = ") verify(4, solver.part2(testData.last())) compute({ solver.part2(realData.first()) }, "$prefix.part2 = ") }
0
Kotlin
0
0
0bba96129354c124aa15e9041f7b5ad68adc662b
3,369
adventofcode
MIT License
src/main/kotlin/Day11.kt
ueneid
575,213,613
false
null
class Day11(inputs: List<String>) { private val monkeys = parse(inputs) class Monkey( var itemList: ArrayDeque<Long>, private var operationPair: Pair<String, String>, var divisible: Long, private var destMonkeys: List<Int>, ) { var inspectCount = 0L fun calcNewWorryLevel(worryLevel: Long): Long { val (op, opValue) = operationPair val v = if (opValue == "old") worryLevel else opValue.toLong() return when (op) { "+" -> worryLevel + v "-" -> worryLevel - v "*" -> worryLevel * v "/" -> worryLevel / v else -> worryLevel } } private fun isDivisible(worryLevel: Long): Boolean { return worryLevel % divisible == 0L } fun getNextMonkeyIndex(worryLevel: Long): Int { return if (this.isDivisible(worryLevel)) { this.destMonkeys[0] } else { this.destMonkeys[1] } } } private fun parse(inputs: List<String>): List<Monkey> { val pat = """ Monkey \d+: Starting items: ([0-9, ]+) Operation: new = old (.+) (\d+|old) Test: divisible by (\d+) If true: throw to monkey (\d+) If false: throw to monkey (\d+) """.trim().toRegex() return inputs.map { bunch -> pat.matchEntire(bunch)!!.destructured.let { Monkey( ArrayDeque(it.component1().split(", ").map(String::toLong)), Pair(it.component2(), it.component3()), it.component4().toLong(), listOf(it.component5().toInt(), it.component6().toInt()) ) } } } fun solve1(): Long { repeat(20) { monkeys.forEach { monkey -> while (monkey.itemList.isNotEmpty()) { monkey.inspectCount++ val item = monkey.itemList.removeFirst() val newWorryLevel = monkey.calcNewWorryLevel(item) / 3 monkeys[monkey.getNextMonkeyIndex(newWorryLevel)].itemList.add(newWorryLevel) } } } return monkeys.map { it.inspectCount }.sorted().takeLast(2).reduce(Long::times) } fun solve2(): Long { // I totally don't understand the purpose of this part, so referred https://yonatankarp.com/advent-of-code-2022-day-11-kotlin-edition val commonMultiple = monkeys.map { monkey -> monkey.divisible }.reduce(Long::times) repeat(10000) { monkeys.forEach { monkey -> while (monkey.itemList.isNotEmpty()) { monkey.inspectCount++ val item = monkey.itemList.removeFirst() val newWorryLevel = monkey.calcNewWorryLevel(item) % commonMultiple monkeys[monkey.getNextMonkeyIndex(newWorryLevel)].itemList.add(newWorryLevel) } } } return monkeys.map { it.inspectCount }.sorted().takeLast(2).reduce(Long::times) } } fun main() { val obj = Day11(Resource.resourceAsListOfBunchOfString("day11/input.txt")) println(obj.solve1()) println(obj.solve2()) }
0
Kotlin
0
0
743c0a7adadf2d4cae13a0e873a7df16ddd1577c
3,303
adventcode2022
MIT License
src/Day07.kt
brigittb
572,958,287
false
{"Kotlin": 46744}
fun main() { fun findDirs(input: List<String>): MutableMap<String, Long> { val stack = ArrayDeque<String>() val dirSizes = mutableMapOf<String, Long>() input.forEach { when { it.contains(Regex("cd /")) -> stack.addLast(it.substringAfter("cd ")) it.contains(Regex("cd [a-z]")) -> stack.addLast("${it.substringAfter("cd ")}/") it.contains("cd ..") -> stack.removeLast() it.contains(Regex("[0-9]")) -> { val path = stack.joinToString("") val sizeOfCurrentFile = it.substringBefore(" ").toLong() dirSizes[path] = dirSizes[path] ?.plus(sizeOfCurrentFile) ?: sizeOfCurrentFile } it.contains(Regex("dir [a-z]")) -> { val path = stack.joinToString("") dirSizes[path] = dirSizes[path] ?: 0 } } } return dirSizes } fun getSummedUpDirSizes(input: List<String>): MutableMap<String, Long> { val result = mutableMapOf<String, Long>() findDirs(input) .toSortedMap(compareByDescending { it }) .forEach { (path, size) -> result[path] = result[path] ?.plus(size) ?: size val parent = path .substringBeforeLast("/") .substringBeforeLast("/") .plus("/") if (result[parent] != result[path]) { result[parent] = result[parent] ?.plus(result.getValue(path)) ?: result.getValue(path) } } return result } fun part1(input: List<String>): Long { val result = getSummedUpDirSizes(input) return result .filter { it.value <= 100000 } .values .sum() } fun part2(input: List<String>): Long { val total = 70000000 val spaceRequired = 30000000 val result = getSummedUpDirSizes(input) val rootSize = result["/"] ?: error("root should exist") val spaceNeeded = spaceRequired - (total - rootSize) return result .filter { it.value >= spaceNeeded } .values .min() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day07_test") check(part1(testInput) == 95437L) check(part2(testInput) == 24933642L) val input = readInput("Day07") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
470f026f2632d1a5147919c25dbd4eb4c08091d6
2,703
aoc-2022
Apache License 2.0
2023/src/main/kotlin/day15.kt
madisp
434,510,913
false
{"Kotlin": 388138}
import utils.Parser import utils.Solution fun main() { Day15.run() } object Day15 : Solution<List<String>>() { override val name = "day15" override val parser = Parser { it.trim().split(",") } private fun hash(str: String): Int { var reg = 0 for (c in str) { reg += c.code reg += (reg shl 4) reg = reg and 255 } return reg } private class Hashmap { val buckets = Array(256) { mutableListOf<Pair<String, Int>>() } operator fun get(key: String): Int? { return buckets[hash(key)].firstNotNullOfOrNull { (k, v) -> v.takeIf { k == key } } } operator fun set(key: String, value: Int): Int { val h = hash(key) val index = buckets[h].indexOfFirst { it.first == key } if (index == -1) { buckets[h].add(key to value) } else { buckets[h][index] = key to value } return value } fun remove(key: String) { buckets[hash(key)].removeIf { it.first == key } } } override fun part1(): Int { return input.sumOf { hash(it) } } override fun part2(): Int { val hashmap = Hashmap() input.forEach { str -> val oper = str.indexOfAny(charArrayOf('=', '-')) when (str[oper]) { '=' -> { // store val key = str.substring(0 until oper) val value = str.substring(oper + 1).toInt() hashmap[key] = value } else -> { // delete val key = str.substring(0 until oper) hashmap.remove(key) } } } return hashmap.buckets.withIndex().flatMap { (box, list) -> list.withIndex().map { (slot, length) -> (box + 1) * (slot + 1) * length.second } }.sum() } }
0
Kotlin
0
1
3f106415eeded3abd0fb60bed64fb77b4ab87d76
1,733
aoc_kotlin
MIT License
src/Day09.kt
D000L
575,350,411
false
{"Kotlin": 23716}
import kotlin.math.pow data class Position(val x: Int = 0, val y: Int = 0) { private fun isNear(position: Position): Boolean = distance(position) <= 2.0 private fun distance(position: Position) = (x - position.x.toDouble()).pow(2.0) + (y - position.y.toDouble()).pow(2.0) fun moved(dx: Int, dy: Int): Position = Position(x + dx, y + dy) fun movedNearTo(target: Position): Position { if (isNear(target)) return this val dir = listOf(0 to 0, 0 to 1, 0 to -1, 1 to 0, -1 to 0, 1 to -1, 1 to 1, -1 to 1, -1 to -1) return dir.map { (dx, dy) -> moved(dx, dy) }.minByOrNull { it.distance(target) } ?: this } } class Snake(length: Int) { private val headAndTails = MutableList(length) { Position() } private val lastTailHistory = mutableSetOf(headAndTails.last()) fun move(dir: Char, amount: Int) { val (dx, dy) = when (dir) { 'R' -> 1 to 0 'U' -> 0 to 1 'L' -> -1 to 0 'D' -> 0 to -1 else -> 0 to 0 } repeat(amount) { headAndTails[0] = headAndTails[0].moved(dx, dy) for (index in 1 until headAndTails.size) { headAndTails[index] = headAndTails[index].movedNearTo(headAndTails[index - 1]) } lastTailHistory.add(headAndTails.last()) } } fun count(): Int { return lastTailHistory.count() } } fun main() { fun part1(input: List<String>): Int { val snake = Snake(2) input.forEach { val (dir, amount) = it.split(" ") snake.move(dir[0], amount.toInt()) } return snake.count() } fun part2(input: List<String>): Int { val snake = Snake(10) input.forEach { val (dir, amount) = it.split(" ") snake.move(dir[0], amount.toInt()) } return snake.count() } val input = readInput("Day09") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
b733a4f16ebc7b71af5b08b947ae46afb62df05e
2,001
adventOfCode
Apache License 2.0