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/Day15.kt
CrazyBene
573,111,401
false
{"Kotlin": 50149}
import kotlin.math.abs fun main() { data class Position(val xPos: Int, val yPos: Int) { fun distanceTo(otherPosition: Position): Int = abs(xPos - otherPosition.xPos) + abs(yPos - otherPosition.yPos) } data class Sensor(val position: Position, val beaconPosition: Position) fun part1(input: List<String>, yToCheck: Int): Int { val sensors = input.map { val regex = "Sensor at x=(-?\\d+), y=(-?\\d+): closest beacon is at x=(-?\\d+), y=(-?\\d+)".toRegex() val result = regex.find(it) result?.groupValues?.get(0) ?: error("Can not map line $$it to Sensor.") val sensorXPos = result.groupValues[1].toInt() val sensorYPos = result.groupValues[2].toInt() val beaconXPos = result.groupValues[3].toInt() val beaconYPos = result.groupValues[4].toInt() Sensor(Position(sensorXPos, sensorYPos), Position(beaconXPos, beaconYPos)) } val obstacles = sensors.flatMap { listOf(it.position, it.beaconPosition) } val xStart = sensors.minOf { it.position.xPos - it.position.distanceTo(it.beaconPosition) } - 2 val xEnd = sensors.maxOf { it.position.xPos + it.position.distanceTo(it.beaconPosition) } + 2 val positions = mutableListOf<Position>() for (x in xStart..xEnd) { val positionToCheck = Position(x, yToCheck) var closer = false for (sensor in sensors) { val beaconDistance = sensor.position.distanceTo(sensor.beaconPosition) val distanceToSensor = positionToCheck.distanceTo(sensor.position) if (distanceToSensor <= beaconDistance) { closer = true break } } if (closer) { positions.add(positionToCheck) } } return positions.filterNot { it in obstacles }.count() } fun part2(input: List<String>, maxCheckSize: Int): Long { val sensors = input.map { val regex = "Sensor at x=(-?\\d+), y=(-?\\d+): closest beacon is at x=(-?\\d+), y=(-?\\d+)".toRegex() val result = regex.find(it) result?.groupValues?.get(0) ?: error("Can not map line $$it to Sensor.") val sensorXPos = result.groupValues[1].toInt() val sensorYPos = result.groupValues[2].toInt() val beaconXPos = result.groupValues[3].toInt() val beaconYPos = result.groupValues[4].toInt() Sensor(Position(sensorXPos, sensorYPos), Position(beaconXPos, beaconYPos)) } (0..maxCheckSize).forEach { y -> val ranges = sensors.mapNotNull { sensor -> val beaconDistance = sensor.position.distanceTo(sensor.beaconPosition) val begin = sensor.position.xPos + (beaconDistance - abs(y - sensor.position.yPos)).unaryMinus() val end = sensor.position.xPos + beaconDistance - abs(y - sensor.position.yPos) (begin..end).takeUnless { it.isEmpty() } }.sortedBy { it.first() } ranges.reduce { acc, range -> (acc union range) ?: return (acc.last + 1) * 4_000_000L + y } } error("Error") } val testInput = readInput("Day15Test") check(part1(testInput, 10) == 26) check(part2(testInput, 20) == 56000011L) val input = readInput("Day15") println("Question 1 - Answer: ${part1(input, 2000000)}") println("Question 2 - Answer: ${part2(input, 4_000_000)}") } private infix fun IntRange.union(other: IntRange): IntRange? { return when (this.first <= other.last && this.last >= other.first) { true -> IntRange(minOf(first, other.first), maxOf(last, other.last)) false -> null } }
0
Kotlin
0
0
dfcc5ba09ca3e33b3ec75fe7d6bc3b9d5d0d7d26
3,873
AdventOfCode2022
Apache License 2.0
app/src/main/java/com/betulnecanli/kotlindatastructuresalgorithms/CodingPatterns/01Knapsack.kt
betulnecanli
568,477,911
false
{"Kotlin": 167849}
/* This technique is used to solve optimization problems. Use this technique to select elements that give maximum profit from a given set with a limitation on capacity and that each element can only be picked once. */ //1. Equal Subset Sum Partition fun canPartition(nums: IntArray): Boolean { val totalSum = nums.sum() // If the total sum is odd, equal partition is not possible if (totalSum % 2 != 0) { return false } val targetSum = totalSum / 2 val n = nums.size // Create a 2D array to store the intermediate results of the subproblems val dp = Array(n + 1) { BooleanArray(targetSum + 1) } // Initialization: An empty subset can always achieve a sum of 0 for (i in 0..n) { dp[i][0] = true } // Populate the 2D array using the 0/1 Knapsack approach for (i in 1..n) { for (j in 1..targetSum) { if (j >= nums[i - 1]) { dp[i][j] = dp[i - 1][j] || dp[i - 1][j - nums[i - 1]] } else { dp[i][j] = dp[i - 1][j] } } } return dp[n][targetSum] } fun main() { // Example usage val nums = intArrayOf(1, 5, 11, 5) val result = canPartition(nums) println("Can the array be partitioned into two equal subsets? $result") } //2. Minimum Subset Sum Difference in a Sorted Matrix fun minSubsetSumDifference(matrix: Array<IntArray>): Int { val totalSum = matrix.flatten().sum() val targetSum = totalSum / 2 val numRows = matrix.size val numCols = matrix[0].size // Create a 2D array to store the intermediate results of the subproblems val dp = Array(numRows + 1) { IntArray(targetSum + 1) } // Populate the 2D array using the 0/1 Knapsack approach for (i in 1..numRows) { for (j in 1..targetSum) { if (j >= matrix[i - 1][numCols - 1]) { dp[i][j] = maxOf(dp[i - 1][j], dp[i - 1][j - matrix[i - 1][numCols - 1]] + matrix[i - 1][numCols - 1]) } else { dp[i][j] = dp[i - 1][j] } } } // The minimum subset sum difference is equal to the total sum minus twice the maximum subset sum val maxSubsetSum = dp[numRows][targetSum] val minSubsetSumDifference = totalSum - 2 * maxSubsetSum return minSubsetSumDifference } fun main() { // Example usage val matrix = arrayOf( intArrayOf(1, 2, 3), intArrayOf(4, 5, 6), intArrayOf(7, 8, 9) ) val result = minSubsetSumDifference(matrix) println("Minimum Subset Sum Difference in the Sorted Matrix: $result") } /* Equal Subset Sum Partition: The canPartition function determines whether it's possible to partition an array into two subsets with equal sums using the 0/1 Knapsack approach. It uses a 2D array to store the intermediate results of subproblems. Minimum Subset Sum Difference in a Sorted Matrix: The minSubsetSumDifference function calculates the minimum subset sum difference in a sorted matrix using the 0/1 Knapsack approach. It aims to partition the matrix into two subsets with sums as close as possible. The minimum subset sum difference is then computed based on the total sum and the maximum subset sum. */
2
Kotlin
2
40
70a4a311f0c57928a32d7b4d795f98db3bdbeb02
3,219
Kotlin-Data-Structures-Algorithms
Apache License 2.0
src/main/day8/Day8.kt
Derek52
572,850,008
false
{"Kotlin": 22102}
package main.day8 import main.readInput fun main() { val input = readInput("day8/day8") val firstHalf = true testAlg(firstHalf) if (firstHalf) { //println(part1(input)) } else { println(part2(input)) } } enum class Direction { LEFT, RIGHT, UP, DOWN, ALL } data class Vertex(val x: Int, val y:Int) data class ElfTree(val height: Int, var visible: Boolean = true, var visited: Boolean = false) fun part1(input: List<String>) : Int { val matrix = Array(input.size) { Array(input[0].length) { ElfTree(0)} } for (i in input.indices) { for (j in input[i].indices) { if (i == 0 || i == input.size - 1 || j == 0 || j == input.size - 1) { matrix[i][j] = ElfTree(input[i][j].digitToInt(), true) } else matrix[i][j] = ElfTree(input[i][j].digitToInt()) } } val visited = HashMap<Direction, HashSet<Vertex>>() for (direction in Direction.values()) { visited[direction] = HashSet<Vertex>() } for (i in matrix.indices) { for (j in 0 until matrix[i].size) { dfs(Vertex(i, j), matrix, Direction.ALL, 10, visited) } } var visibleCount = 0 for (i in matrix.indices) { for (j in 0 until matrix[i].size) { if (matrix[i][j].visible) { print("${matrix[i][j].height} ") visibleCount++ } else { print("X ") } } println() } return visibleCount } fun dfs(vertex: Vertex, graph: Array<Array<ElfTree>>, direction: Direction, prevHeight: Int, visited: HashMap<Direction, HashSet<Vertex>>) { if(isOutOfBounds(vertex, graph.size -1) || visited[direction]!!.contains(vertex) ) { return } if (graph[vertex.x][vertex.y].height < prevHeight) { graph[vertex.x][vertex.y].visible = false } visited[direction]!!.add(vertex) //graph[vertex.x][vertex.y].visited = true //graph[vertex.x][vertex.y].visib // le = true val height = graph[vertex.x][vertex.y].height println("Checking $height") when(direction) { Direction.ALL -> { dfs(Vertex(vertex.x-1, vertex.y), graph, Direction.LEFT, height, visited) dfs(Vertex(vertex.x+1, vertex.y), graph, Direction.RIGHT, height, visited) dfs(Vertex(vertex.x, vertex.y+1), graph, Direction.UP, height, visited) dfs(Vertex(vertex.x, vertex.y-1), graph, Direction.DOWN, height, visited) } Direction.LEFT -> { dfs(Vertex(vertex.x-1, vertex.y), graph, Direction.LEFT, height, visited) } Direction.RIGHT -> { dfs(Vertex(vertex.x+1, vertex.y), graph, Direction.RIGHT, height, visited) } Direction.UP -> { dfs(Vertex(vertex.x, vertex.y+1), graph, Direction.UP, height, visited) } Direction.DOWN -> { dfs(Vertex(vertex.x, vertex.y-1), graph, Direction.DOWN, height, visited) } } } fun isOutOfBounds(vertex: Vertex, bounds: Int) : Boolean { //println("isOutOfBounds") return vertex.x == 0 || vertex.x == bounds || vertex.y == 0 || vertex.y == bounds } fun part2(input: List<String>) { } fun testAlg(firstHalf : Boolean) { val input = readInput("day8/day8_test") if (firstHalf) { println(part1(input)) } else { println(part2(input)) } }
0
Kotlin
0
0
c11d16f34589117f290e2b9e85f307665952ea76
3,422
2022AdventOfCodeKotlin
Apache License 2.0
aoc2022/day8.kt
davidfpc
726,214,677
false
{"Kotlin": 127212}
package aoc2022 import utils.InputRetrieval fun main() { Day8.execute() } object Day8 { fun execute() { val input = readInput() val (visibleCount, highestScenicScore) = solve(input) println("Part 1: $visibleCount") println("Part 2: $highestScenicScore") } private fun solve(input: List<String>): Pair<Int, Int> { val columnLength = input.size val lineLength = input[0].length var visibleCount = (columnLength * 2) + (lineLength * 2) - 4 var highestScenicScore = 0 for (y in 1 until columnLength - 1) { for (x in 1 until lineLength - 1) { val treeSize = input[y][x] // Verify visibility if ( input[y].subSequence(0, x).all { it < treeSize } // Check left || input[y].subSequence(x + 1, lineLength).all { it < treeSize }// Check Right || input.subList(0, y).map { it[x] }.all { it < treeSize }// Check top || input.subList(y + 1, columnLength).map { it[x] }.all { it < treeSize }// Check bottom ) { visibleCount++ } // Calculate Scenic Score val scenicScore = input[y].subSequence(0, x).toList().reversed().countVisibleTrees(treeSize) * // Check left input[y].subSequence(x + 1, lineLength).toList().countVisibleTrees(treeSize) * // Check Right input.subList(0, y).map { it[x] }.reversed().countVisibleTrees(treeSize) * // Check top input.subList(y + 1, columnLength).map { it[x] }.countVisibleTrees(treeSize)// Check bottom if (scenicScore > highestScenicScore) { highestScenicScore = scenicScore } } } return visibleCount to highestScenicScore } private fun List<Char>.countVisibleTrees(treeSize: Char): Int { val size = this.size val filteredSize = this.takeWhile { it < treeSize }.size return if (filteredSize < size) { filteredSize + 1 } else { filteredSize } } private fun readInput(): List<String> = InputRetrieval.getFile(2022, 8).readLines() }
0
Kotlin
0
0
8dacf809ab3f6d06ed73117fde96c81b6d81464b
2,289
Advent-Of-Code
MIT License
src/day2/Day02.kt
francoisadam
573,453,961
false
{"Kotlin": 20236}
package day2 import day2.Outcome.DRAW import day2.Outcome.LOOSE import day2.Outcome.WIN import day2.Shape.PAPER import day2.Shape.ROCK import day2.Shape.SCISSOR import readInput fun main() { fun part1(input: List<String>): Int { val rounds = input.map { val rawRound = it.split(" ") Round( yourShape = rawRound.last().toShape(), opponentShape = rawRound.first().toShape(), ) } return rounds.sumOf { it.result() } } fun part2(input: List<String>): Int { val rounds = input.map { val rawRound = it.split(" ") val opponentShape = rawRound.first().toShape() Round( yourShape = rawRound.last().toOutcome().neededShapeAgainst(opponentShape), opponentShape = opponentShape, ) } return rounds.sumOf { it.result() } } // test if implementation meets criteria from the description, like: val testInput = readInput("day2/Day02_test") val testPart1 = part1(testInput) println("testPart1: $testPart1") val testPart2 = part2(testInput) println("testPart2: $testPart2") check(testPart1 == 15) check(testPart2 == 12) val input = readInput("day2/Day02") println("part1 : ${part1(input)}") println("part2 : ${part2(input)}") } private data class Round( val yourShape: Shape, val opponentShape: Shape, ) { fun result(): Int = yourShape.outcomeAgainst(opponentShape).value + yourShape.value } private enum class Shape(val value: Int) { ROCK(1), PAPER(2), SCISSOR(3); fun outcomeAgainst(opponentShape: Shape): Outcome = when (this) { ROCK -> when (opponentShape) { ROCK -> DRAW PAPER -> LOOSE SCISSOR -> WIN } PAPER -> when (opponentShape) { ROCK -> WIN PAPER -> DRAW SCISSOR -> LOOSE } SCISSOR -> when (opponentShape) { ROCK -> LOOSE PAPER -> WIN SCISSOR -> DRAW } } } private enum class Outcome(val value: Int) { WIN(6), DRAW(3), LOOSE(0); fun neededShapeAgainst(opponentShape: Shape): Shape = Shape.values().first { it.outcomeAgainst(opponentShape) == this } } private fun String.toOutcome(): Outcome = when (this) { "X" -> LOOSE "Y" -> DRAW else -> WIN } private fun String.toShape(): Shape = when (this) { "A", "X" -> ROCK "B", "Y" -> PAPER else -> SCISSOR }
0
Kotlin
0
0
e400c2410db4a8343c056252e8c8a93ce19564e7
2,537
AdventOfCode2022
Apache License 2.0
src/main/kotlin/com/groundsfam/advent/y2015/d09/Day09.kt
agrounds
573,140,808
false
{"Kotlin": 281620, "Shell": 742}
package com.groundsfam.advent.y2015.d09 import com.groundsfam.advent.DATAPATH import kotlin.io.path.div import kotlin.io.path.useLines data class TourPlan(val start: Int, val destinations: Set<Int>) fun findExtremeTour(distances: Array<IntArray>, minimize: Boolean = true): Int { // store the minimum achievable tour of a subset of our locations val extremeTours = mutableMapOf<TourPlan, Int>() fun findExtremeSubtour(tourPlan: TourPlan): Int { val (start, destinations) = tourPlan if (tourPlan in extremeTours) return extremeTours[tourPlan]!! // only one possible tour if (destinations.size == 1) { return distances[start][destinations.first()] .also { extremeTours[tourPlan] = it } } // try each possible subtour recursively return if (minimize) { destinations.minOf { next -> distances[start][next] + findExtremeSubtour(TourPlan(next, destinations - next)) } } else { destinations.maxOf { next -> distances[start][next] + findExtremeSubtour(TourPlan(next, destinations - next)) } }.also { extremeTours[tourPlan] = it } } return if (minimize) { distances.indices.minOf { start -> findExtremeSubtour(TourPlan(start, distances.indices.toSet() - start)) } } else { distances.indices.maxOf { start -> findExtremeSubtour(TourPlan(start, distances.indices.toSet() - start)) } }.also { println() } } fun main() { // forget the actual location names. just store as indices 0-7. // the distance from i to j is in distances[i][j] val distances = (DATAPATH / "2015/day09.txt").useLines { lines -> val namesList = mutableListOf<String>() val distances = Array(8) { IntArray(8) } // there are exactly eight locations in input file lines.forEach { line -> val parts = line.split(" ") if (parts[0] !in namesList) namesList.add(parts[0]) val a = namesList.indexOf(parts[0]) if (parts[2] !in namesList) namesList.add(parts[2]) val b = namesList.indexOf(parts[2]) distances[a][b] = parts[4].toInt() distances[b][a] = parts[4].toInt() } distances } findExtremeTour(distances, minimize = true) .also { println("Part one: $it") } findExtremeTour(distances, minimize = false) .also { println("Part two: $it") } }
0
Kotlin
0
1
c20e339e887b20ae6c209ab8360f24fb8d38bd2c
2,562
advent-of-code
MIT License
src/Day10.kt
vjgarciag96
572,719,091
false
{"Kotlin": 44399}
private val cyclesToSelect = setOf(20, 60, 100, 140, 180, 220) private fun part1(input: List<String>): Int { return input.fold(initial = listOf(1)) { state, instruction -> when (instruction) { "noop" -> state + listOf(state.last()) else -> { val (_, valueToAdd) = instruction.split(" ") state + listOf(state.last(), state.last() + valueToAdd.toInt()) } } }.mapIndexed { cycle, value -> if (cycle + 1 in cyclesToSelect) { (cycle + 1) * value } else { 0 } }.sum() } private fun part2(input: List<String>): String { return input.fold(initial = listOf(1)) { state, instruction -> when (instruction) { "noop" -> state + listOf(state.last()) else -> { val (_, valueToAdd) = instruction.split(" ") state + listOf(state.last(), state.last() + valueToAdd.toInt()) } } }.mapIndexed { index, x -> val crtPixels = setOf(x - 1, x, x + 1) if (index % 40 in crtPixels) '#' else '.' }.joinToString(separator = "") } fun main() { val testInput = readInput("Day10_test") check(part1(testInput) == 13140) println(part2(testInput)) val input = readInput("Day10") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
ee53877877b21166b8f7dc63c15cc929c8c20430
1,373
advent-of-code-2022
Apache License 2.0
src/Day02.kt
gillyobeast
574,413,213
false
{"Kotlin": 27372}
import utils.appliedTo import utils.readInput enum class Shape(val score: Int) { ROCK(1), PAPER(2), SCISSORS(3), ; } // X == lose // Y == draw // Z == win! fun String.toTheirShape(): Shape { return when (this) { "A" -> Shape.ROCK "B" -> Shape.PAPER else -> Shape.SCISSORS } } fun String.toYourShape(theirs: Shape): Shape { return when(this) { "X" -> when(theirs){ Shape.ROCK -> Shape.SCISSORS Shape.PAPER -> Shape.ROCK Shape.SCISSORS -> Shape.PAPER } "Y" -> theirs else -> when(theirs){ Shape.ROCK -> Shape.PAPER Shape.PAPER -> Shape.SCISSORS Shape.SCISSORS -> Shape.ROCK } } } fun String.toShape(): Shape { return if ("X" == this || "A" == this) Shape.ROCK else if ("Y" == this || "B" == this) Shape.PAPER else Shape.SCISSORS } private fun youWin(you: Shape, opponent: Shape) = ((you == Shape.ROCK && opponent == Shape.SCISSORS) || (you == Shape.PAPER && opponent == Shape.ROCK) || (you == Shape.SCISSORS && opponent == Shape.PAPER)) fun main() { fun outcomeScore(you: Shape, opponent: Shape): Int { if (you == opponent) return 3 return if (youWin(you, opponent)) 6 else 0 } fun toMap(input: List<String>): List<Pair<Shape, Shape>> = input.map { val parts = it.split(' '); parts[0].toShape() to parts[1].toShape() } fun toMapPart2(input: List<String>): List<Pair<Shape, Shape>> = input.map { val parts = it.split(' ') val theirShape = parts[0].toTheirShape() theirShape to parts[1].toYourShape(theirShape) } fun calculateScore(pairs: List<Pair<Shape, Shape>>): Int { var score = 0 for ((opponent, you) in pairs) { // println("$opponent - $you") val shapeScore = you.score val outcomeScore = outcomeScore(you, opponent) val thisScore = shapeScore + outcomeScore // println("shapeScore = ${shapeScore}") // println("outcomeScore = ${outcomeScore}") // println("thisScore = ${thisScore}") // println() score += thisScore } return score } fun totalRpsScore(input: List<String>): Int { val pairs = toMap(input) return calculateScore(pairs) } fun part2(input: List<String>): Int { return calculateScore(toMapPart2(input)) } // test if implementation meets criteria from the description, like: val testInput = readInput("Day02_test") val input = readInput("Day02") // part 1 ::totalRpsScore.appliedTo(testInput, returns = 15) println("Part 1: ${totalRpsScore(input)}") // part 2 ::part2.appliedTo(testInput, returns = 12) println("Part 2: ${part2(input)}") }
0
Kotlin
0
0
8cdbb20c1a544039b0e91101ec3ebd529c2b9062
2,859
aoc-2022-kotlin
Apache License 2.0
src/Day02.kt
wellithy
571,903,945
false
null
package day02 import util.* import day02.Result.* import day02.Hand.* import day02.Symbol.* enum class Hand(val score: Int, val symbol: String) { Rock(1, "A"), Paper(2, "B"), Scissors(3, "C"), ; val defeats: Hand get() = when (this) { Rock -> Scissors Paper -> Rock Scissors -> Paper } fun result(other: Hand): Result = when (other) { defeats -> Won this -> Draw else -> Lost } companion object { val hands = values().associateBy(Hand::symbol) fun of(symbol: String): Hand = hands.getValue(symbol) val defeated = values().associateBy(Hand::defeats) } val defeatedBy: Hand get() = defeated.getValue(this) } enum class Symbol { X, Y, Z; companion object { val symbols = values().associateBy(Symbol::name) fun of(symbol: String): Symbol = symbols.getValue(symbol) } } enum class Result(val score: Int) { Lost(0), Draw(3), Won(6) } fun Sequence<String>.parse(): Sequence<Pair<Hand, Symbol>> = sequence { forEach { line -> yield(line.split(" ").let { Hand.of(it[0]) to Symbol.of(it[1]) }) } } fun Hand.score(other: Hand): Int = score + result(other).score val Symbol.strategy1: Hand get() = when (this) { X -> Rock Y -> Paper Z -> Scissors } fun part1(input: Sequence<String>): Int = input.parse().map { (other, self) -> self.strategy1.score(other) }.sum() val Symbol.strategy2: Result get() = when (this) { X -> Lost Y -> Draw Z -> Won } fun Result.of(other: Hand): Hand = when (this) { Lost -> other.defeats Draw -> other Won -> other.defeatedBy } fun Result.score(other: Hand): Int = score + of(other).score fun part2(input: Sequence<String>): Int = input.parse().map { (other, self) -> self.strategy2.score(other) }.sum() fun main() { test(::part1, 15) go(::part1, 11449) test(::part2, 12) go(::part2, 13187) }
0
Kotlin
0
0
6d5fd4f0d361e4d483f7ddd2c6ef10224f6a9dec
2,020
aoc2022
Apache License 2.0
marathons/atcoder/ahc3_shortestPathQueries/shortestPathQueries.kt
mikhail-dvorkin
93,438,157
false
{"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408}
package marathons.atcoder.ahc3_shortestPathQueries import kotlin.random.Random private fun solve(queries: Int = 1000, size: Int = 30, averageEdge: Int = 5000) { val noiseLevel = 0.2 val random = Random(566) fun vertexId(y: Int, x: Int) = y * size + x data class Edge(val from: Int, val to: Int, val label: Char, val id: Int) val vertices = size * size val nei = List(vertices) { mutableListOf<Edge>() } var edges = 0 for (y in 0 until size) for (x in 0 until size) { val id = vertexId(y, x) for (d in 0..1) { val (yy, xx) = y + DY[d] to x + DX[d] if (yy >= size || xx >= size) continue val id2 = vertexId(yy, xx) nei[id].add(Edge(id, id2, DIR[d], edges)) nei[id2].add(Edge(id2, id, DIR[d xor 2], edges)) edges++ } } val noise = DoubleArray(edges) val edgeSum = DoubleArray(edges) { 1.0 } val edgeNum = IntArray(edges) { 1 } val mark = BooleanArray(vertices) val dist = DoubleArray(vertices) val how = Array<Edge?>(vertices) { null } val inf = 1e20 fun edgeLength(id: Int): Double { return edgeSum[id] / edgeNum[id] + noise[id] } fun shortestPath(from: Int, to: Int): List<Edge> { mark.fill(false) dist.fill(inf) dist[from] = 0.0 val queue = sortedMapOf(0.0 to from) while (true) { val vDist = queue.firstKey()!! val v = queue.remove(vDist)!! if (v == to) break mark[v] = true for (e in nei[v]) { val u = e.to val newDist = vDist + edgeLength(e.id) if (newDist < dist[u]) { queue.remove(dist[u]) queue[newDist] = u dist[u] = newDist how[u] = e } } } val path = mutableListOf<Edge>() var v = to while (v != from) { path.add(how[v]!!) v = how[v]!!.from } return path.reversed() } repeat(queries) { val (yFrom, xFrom, yTo, xTo) = readInts() val (from, to) = vertexId(yFrom, xFrom) to vertexId(yTo, xTo) for (i in noise.indices) noise[i] = random.nextDouble() * noiseLevel val path = shortestPath(from, to) println(path.joinToString("") { "" + it.label }) val pathLength = readInt().toDouble() / averageEdge / path.size for (e in path) { edgeNum[e.id]++ edgeSum[e.id] += pathLength } } } fun main() = solve() val DX = intArrayOf(1, 0, -1, 0) val DY = intArrayOf(0, 1, 0, -1) const val DIR = "RDLU" private fun readLn() = readLine()!! private fun readInt() = readLn().toInt() private fun readStrings() = readLn().split(" ") private fun readInts() = readStrings().map { it.toInt() }
0
Java
1
9
30953122834fcaee817fe21fb108a374946f8c7c
2,438
competitions
The Unlicense
src/twentytwo/Day01.kt
Monkey-Matt
572,710,626
false
{"Kotlin": 73188}
package twentytwo fun main() { // test if implementation meets criteria from the description, like: val testInput = readInputLines("Day01_test") // println(part1(testInput)) check(part1(testInput) == 24_000) // println(part2(testInput)) check(part2(testInput) == 45_000) val input = readInputLines("Day01_input") println(part1(input)) println(part2(input)) testAlternativeSolutions() } private fun part1(input: List<String>): Int { val groupTotals = getElfTotals(input) return groupTotals.max() } private fun getElfTotals(input: List<String>): MutableList<Int> { val groups = input.split("") return groups.map { group -> group.sumOf { it.toInt() } }.toMutableList() } private fun part2(input: List<String>): Int { val elfTotals = getElfTotals(input) val one = elfTotals.max() elfTotals.remove(one) val two = elfTotals.max() elfTotals.remove(two) val three = elfTotals.max() return one + two + three } // ------------------------------------------------------------------------------------------------ private fun testAlternativeSolutions() { val testInput = readInput("Day01_test") check(part1AlternativeSolution(testInput) == 24_000) check(part2AlternativeSolution(testInput) == 45_000) println("Alternative Solutions:") val input = readInputLines("Day01_input") println(part1(input)) println(part2(input)) } private fun part1AlternativeSolution(input: String): Int { val elfTotals = getElfTotalsAlternative(input) return elfTotals.max() } private fun part2AlternativeSolution(input: String): Int { val elfTotals = getElfTotalsAlternative(input) return elfTotals.sortedDescending().take(3).sum() } private fun getElfTotalsAlternative(input: String): List<Int> { return input.split("\n\n").map { elfGroup -> elfGroup.lines().sumOf { it.toInt() } } }
1
Kotlin
0
0
600237b66b8cd3145f103b5fab1978e407b19e4c
1,906
advent-of-code-solutions
Apache License 2.0
src/jvmMain/kotlin/day02/initial/Day02.kt
liusbl
726,218,737
false
{"Kotlin": 109684}
package day02.initial import java.io.File fun main() { // solvePart1() // Solution: 2268, solved at 07:31 solvePart2() // Solution: 63542, solved at 07:46 } // max amount of: 12 red cubes, 13 green cubes, and 14 blue cubes fun solvePart1() { val input = File("src/jvmMain/kotlin/day02/input/input.txt") // val input = File("src/jvmMain/kotlin/day02/input/input_part1_test.txt") val lines = input.readLines() val gameList = lines.map(::Game) val result = gameList.filter { game -> val cubeDrawList = game.list cubeDrawList.all { val redCubeCount = it.list.firstOrNull { it.color == Color.Red }?.count ?: 0 val greenCubeCount = it.list.firstOrNull { it.color == Color.Green }?.count ?: 0 val blueCubeCount = it.list.firstOrNull { it.color == Color.Blue }?.count ?: 0 redCubeCount <= 12 && greenCubeCount <= 13 && blueCubeCount <= 14 } }.sumOf { it.id } println(result) } fun solvePart2() { // val input = File("src/jvmMain/kotlin/day02/input/input.txt") val input = File("src/jvmMain/kotlin/day02/input/input.txt") val lines = input.readLines() val gameList = lines.map(::Game) val initialHighestList = listOf( Cube(count = 0, color = Color.Red), Cube(count = 0, color = Color.Green), Cube(count = 0, color = Color.Blue) ) val result = gameList.map { game -> game.list.fold(GameWithCount(initialHighestList, game)) { acc, cubeDraw -> val redCubeCount = cubeDraw.list.firstOrNull { it.color == Color.Red }?.count ?: 0 val greenCubeCount = cubeDraw.list.firstOrNull { it.color == Color.Green }?.count ?: 0 val blueCubeCount = cubeDraw.list.firstOrNull { it.color == Color.Blue }?.count ?: 0 val redMaxCount = maxOf(acc.highestCubeCount[0].count, redCubeCount) val greenMaxCount = maxOf(acc.highestCubeCount[1].count, greenCubeCount) val blueMaxCount = maxOf(acc.highestCubeCount[2].count, blueCubeCount) acc.copy( highestCubeCount = listOf( Cube(count = redMaxCount, color = Color.Red), Cube(count = greenMaxCount, color = Color.Green), Cube(count = blueMaxCount, color = Color.Blue) ) ) } }.sumOf { it.highestCubeCount[0].count * it.highestCubeCount[1].count * it.highestCubeCount[2].count } println(result) } data class GameWithCount( val highestCubeCount: List<Cube>, // red 23, green 54, blue 123 val game: Game ) // Parsing fun Game(line: String): Game { val split = line.split(":") val cubeDraw = split[1].trim() .split(";") .map(::CubeDraw) val id = split[0].split(" ")[1].toInt() return Game(id = id, list = cubeDraw) } // 3 blue, 4 red fun CubeDraw(cubeText: String): CubeDraw { val list = cubeText.trim() .split(",") .map(::Cube) return CubeDraw(list) } // 4 red fun Cube(cubeText: String): Cube { val count = cubeText.trim().split(" ")[0].toInt() val color = Color.values().first { cubeText.contains(it.text) } return Cube( count = count, color = color ) } data class Game( val id: Int, val list: List<CubeDraw> ) data class CubeDraw( val list: List<Cube> ) data class Cube( val count: Int, val color: Color ) enum class Color(val text: String) { Blue("blue"), Red("red"), Green("green") }
0
Kotlin
0
0
1a89bcc77ddf9bc503cf2f25fbf9da59494a61e1
3,524
advent-of-code
MIT License
kotlin-examples/src/main/kotlin/de/rieckpil/learning/fpbook/datatypes/FunctionalTreeDataStructure.kt
rieckpil
127,932,091
false
null
package de.rieckpil.learning.fpbook.datatypes sealed class Tree<out A> { companion object { fun <A> size(tree: Tree<A>): Int = when (tree) { is Leaf -> 1 is Branch -> 1 + size(tree.left) + size(tree.right) } fun maximum(tree: Tree<Int>): Int = when (tree) { is Leaf -> tree.value is Branch -> maxOf(maximum(tree.left), maximum(tree.right)) } fun <A> depth(tree: Tree<A>): Int = when (tree) { is Leaf -> 0 is Branch -> 1 + maxOf(depth(tree.left), depth(tree.left)) } fun <A, B> map(tree: Tree<A>, f: (A) -> B): Tree<B> = when (tree) { is Leaf -> Leaf(f(tree.value)) is Branch -> Branch(map(tree.left, f), map(tree.right, f)) } fun <A, B> fold(tree: Tree<A>, l: (A) -> B, f: (B, B) -> B): B = when (tree) { is Leaf -> l(tree.value) is Branch -> f(fold(tree.left, l, f), fold(tree.right, l, f)) } fun <A> sizeFold(tree: Tree<A>): Int = fold(tree, { 1 }, { a, b -> a + b + 1 }) fun <A> maximumFold(tree: Tree<Int>): Int = fold(tree, { it }, { a, b -> maxOf(a, b) }) fun <A> depthFold(tree: Tree<A>): Int = fold(tree, { 0 }, { a, b -> 1 + maxOf(a, b) }) fun <A, B> mapFold(tree: Tree<A>, f: (A) -> B): Tree<B> = fold(tree, { a: A -> Leaf(f(a)) }, { a: Tree<B>, b: Tree<B> -> Branch(a, b) }) } } data class Leaf<A>(val value: A) : Tree<A>() data class Branch<A>(val left: Tree<A>, val right: Tree<A>) : Tree<A>() fun main() { // println(Tree.size(Branch(Branch(Leaf(1), Leaf(2)), Leaf(2)))) // println(Tree.maximum(Branch(Branch(Leaf(4), Leaf(2)), Leaf(7)))) // println(Tree.depth(Branch(Branch(Leaf(4), Leaf(2)), Leaf(7)))) // println(Tree.map(Branch(Branch(Leaf(4), Leaf(2)), Leaf(7))) { it * it }) println(Tree.sizeFold(Branch(Branch(Leaf(4), Leaf(2)), Leaf(7)))) }
23
Java
7
11
33d8f115c81433abca8f4984600a41350a1d831d
1,869
learning-samples
MIT License
src/main/kotlin/icfp2019/Parsers.kt
jzogg
193,197,477
true
{"JavaScript": 797354, "Kotlin": 19302, "HTML": 9922, "CSS": 9434}
package icfp2019 import com.google.common.base.CharMatcher import com.google.common.base.Splitter import com.google.common.collect.Range import com.google.common.collect.TreeRangeSet val matcher = CharMatcher.anyOf("()") fun parsePoint(mapEdges: String): Point { return parseEdges(mapEdges)[0] } fun parseEdges(mapEdges: String): List<Point> { return mapEdges.split(',') .map { matcher.trimFrom(it) } .windowed(2, step = 2) .map { Point(Integer.parseInt(it[0]), Integer.parseInt(it[1])) } } fun parseDesc(problem: ProblemDescription): Problem { val (mapEdges, startPosition, obstacles, boosters) = problem.line.split('#') val startPoint = parsePoint(startPosition) val verticies = parseEdges(mapEdges) val obstacleEdges = parseEdges(obstacles) val parsedBosters = parseBoosters(boosters) val maxY = verticies.maxBy { it.y }?.y ?: throw RuntimeException() val maxX = verticies.maxBy { it.x }?.x ?: throw RuntimeException() val xArrayIndices = 0.until(maxX) val yArrayIndices = 0.until(maxY) val grid = xArrayIndices.map { x -> yArrayIndices.map { y -> Node(Point(x, y), isObstacle = true) }.toTypedArray() }.toTypedArray() val xEdgeGroups = (verticies + obstacleEdges).groupBy { it.x }.mapValues { entry -> val set: TreeRangeSet<Int> = TreeRangeSet.create() val points: List<Point> = entry.value val sortedBy = points.map { it.y }.sortedBy { it } sortedBy.windowed(2, step = 2).forEach { val (y1, y2) = it set.add(Range.closed(y1, y2)) } set } println(xEdgeGroups) yArrayIndices.forEach { y -> var inObstacle = true xArrayIndices.forEach { x -> val yEdges = xEdgeGroups[x] val column = grid[x] if (yEdges?.encloses(Range.closed(y, y + 1)) == true) { inObstacle = !inObstacle } column[y] = column[y].copy(isObstacle = inObstacle) } } parsedBosters.forEach { grid[it.second.x][it.second.y] = grid[it.second.x][it.second.y].copy(booster = it.first) } // Read lines /* 1. Read lines 2. Parse map Grammar: x,y: Nat point ::= (x,y) map ::= repSep(point,”,”) BoosterCode ::= B|F|L|X boosterLocation ::= BoosterCode point obstacles ::= repSep(map,”; ”) boosters ::= repSep(boosterLocation,”; ”) task ::= map # point # obstacles # boosters */ return Problem(problem.problemId, Size(maxX, maxY), startPoint, grid) } fun parseBoosters(boosters: String): List<Pair<Boosters, Point>> { return Splitter.on(';') .omitEmptyStrings() .split(boosters) .map { Boosters.valueOf(it[0].toString()) to parsePoint(it.substring(1)) } }
0
JavaScript
0
0
8d637f7feee33d2c7a030f94732bb16c850e047c
2,951
icfp-2019
The Unlicense
solutions/aockt/y2022/Y2022D15.kt
Jadarma
624,153,848
false
{"Kotlin": 435090}
package aockt.y2022 import io.github.jadarma.aockt.core.Solution import kotlin.math.absoluteValue object Y2022D15 : Solution { /** Represents a discrete point in 2D space. */ private data class Point(val x: Int, val y: Int) /** Returns the Manhattan distance between the two points. */ private infix fun Point.manhattanDistanceTo(other: Point): Int = (x - other.x).absoluteValue + (y - other.y).absoluteValue /** Generates all points that are [radius] units away (using Manhattan distance) from the original point. */ private fun Point.manhattanCircle(radius: Int): Sequence<Point> = sequence { var cx = x - radius var cy = y repeat(radius) { yield(Point(cx, cy)); cx++; cy++ } repeat(radius) { yield(Point(cx, cy)); cx++; cy-- } repeat(radius) { yield(Point(cx, cy)); cx--; cy-- } repeat(radius) { yield(Point(cx, cy)); cx--; cy++ } } /** A distress beacon sensor and its current detection [range]. */ private data class Sensor(val location: Point, val range: Int) /** Tests if the [point] is inside the sensor's detection range. */ private fun Sensor.observes(point: Point): Boolean = location.manhattanDistanceTo(point) <= range /** Expression that validates a sensor reading. */ private val inputRegex = Regex("""^Sensor at x=(-?\d+), y=(-?\d+): closest beacon is at x=(-?\d+), y=(-?\d+)$""") /** Parse the [input] and return the sequence of sensor readings as pairs of sensor to beacon locations. */ private fun parseInput(input: String): Map<Sensor, Point> = input .lineSequence() .map { line -> inputRegex.matchEntire(line)!!.groupValues.drop(1).map(String::toInt) } .associate { (sx, sy, bx, by) -> val sensor = Point(sx, sy) val beacon = Point(bx, by) Sensor(sensor, sensor.manhattanDistanceTo(beacon)) to beacon } override fun partOne(input: String): Int { val scan = parseInput(input) val range = scan.keys.minOf { it.location.x - it.range }.rangeTo(scan.keys.maxOf { it.location.x + it.range }) val targetLine = 2_000_000 val beaconsOnLine = scan.values.filter { it.y == targetLine }.toSet() return range.count { x -> val p = Point(x, targetLine) p !in beaconsOnLine && scan.keys.any { it.observes(p) } } } override fun partTwo(input: String): Long { val scan = parseInput(input) val scanRange = 0..4_000_000 return scan.keys .asSequence() .flatMap { (location, range) -> location.manhattanCircle(range + 1) } .filter { it.x in scanRange && it.y in scanRange } .first { p -> scan.keys.none { it.observes(p) } } .let { it.x * 4_000_000L + it.y } } }
0
Kotlin
0
3
19773317d665dcb29c84e44fa1b35a6f6122a5fa
2,866
advent-of-code-kotlin-solutions
The Unlicense
jvm/src/main/kotlin/io/prfxn/aoc2021/day09.kt
prfxn
435,386,161
false
{"Kotlin": 72820, "Python": 362}
// Smoke Basin (https://adventofcode.com/2021/day/9) package io.prfxn.aoc2021 object Day09 { val lines = textResourceReader("input/09.txt").useLines { seq -> seq.map { it.map(Char::digitToInt) }.toList() } fun isValidCoords(row: Int, col: Int) = row in lines.indices && col in lines[0].indices fun adjCoordsSeq(row: Int, col: Int) = sequenceOf( row - 1 to col, row + 1 to col, row to col - 1, row to col + 1 ) .filter { (r, c) -> isValidCoords(r, c) } fun isLow(row: Int, col: Int) = lines[row][col].let { value -> adjCoordsSeq(row, col) .all { (r, c) -> lines[r][c] > value } } val lowPoints = lines.indices .flatMap { row -> lines[0].indices.map { col -> row to col } } .filter { (r, c) -> isLow(r, c) } fun crawlBasin(row: Int, col: Int, visitedCoords: MutableSet<Pair<Int, Int>> = mutableSetOf()): Set<Pair<Int, Int>> { visitedCoords.add(row to col) adjCoordsSeq(row, col) .filter { (r, c) -> val h = lines[r][c] lines[row][col] < h && h < 9 && r to c !in visitedCoords } .forEach { (r, c) -> crawlBasin(r, c, visitedCoords) } return visitedCoords } fun getBasinSize(row: Int, col: Int) = crawlBasin(row, col).count() } fun main() { Day09.apply { fun part1() = lowPoints.sumOf { (r, c) -> Day09.lines[r][c] + 1 } fun part2() = lowPoints .map { (r, c) -> getBasinSize(r, c) } .sorted() .takeLast(3) .reduce { p, bs -> p * bs } println(part1()) println(part2()) } } /** output * 532 * 1110780 */
0
Kotlin
0
0
148938cab8656d3fbfdfe6c68256fa5ba3b47b90
1,969
aoc2021
MIT License
src/Day03.kt
krisbrud
573,455,086
false
{"Kotlin": 8417}
fun main() { // TODO: Make prioritization function fun priority(s: Char): Int { return when(s.isLowerCase()) { true -> s.code - "a".toCharArray().first().code false -> s.code - "A".toCharArray().first().code + 26 } + 1 } fun compartmentalize(s: String): List<String> { // Always even number of items return s.chunked(s.length / 2) } fun findCommon(compartments: List<String>): String? { val compartmentSets = compartments.map { it.toSet() } return compartmentSets.reduce { acc, item -> acc.intersect(item) }.toList().first().toString() } fun part1(input: List<String>): Int { val sacksOfCompartments = input.map { compartmentalize(it) } val commonLettersPerSack = sacksOfCompartments.map { compartments -> findCommon(compartments) } val priorities = commonLettersPerSack.map { priority(it!!.first()) } return priorities.sum() } fun part2(input: List<String>): Int { val groups = input.chunked(3) val commonLettersPerGroup = groups.map { findCommon(it) } val priorities = commonLettersPerGroup.map { priority(it!!.first()) } return priorities.sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day03_test") check(part1(testInput) == 157) val input = readInput("Day03") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
02caf3a30a292d7b8c9e2b7788df74650e54573c
1,480
advent-of-code-2022
Apache License 2.0
src/Day13.kt
mikemac42
573,071,179
false
{"Kotlin": 45264}
import java.io.File fun main() { val testInput = """[1,1,3,1,1] [1,1,5,1,1] [[1],[2,3,4]] [[1],4] [9] [[8,7,6]] [[4,4],4,4] [[4,4],4,4,4] [7,7,7,7] [7,7,7] [] [3] [[[]]] [[]] [1,[2,[3,[4,[5,6,7]]]],8,9] [1,[2,[3,[4,[5,6,0]]]],8,9]""" val realInput = File("src/Day13.txt").readText() val part1TestOutput = sumOfCorrectPairIndices(testInput) println("Part 1 Test Output: $part1TestOutput") check(part1TestOutput == 13) val part1RealOutput = sumOfCorrectPairIndices(realInput) println("Part 1 Real Output: $part1RealOutput") val part2TestOutput = decoderKey(testInput) println("Part 2 Test Output: $part2TestOutput") check(part2TestOutput == 140) val part2RealOutput = decoderKey(realInput) println("Part 2 Real Output: $part2RealOutput") } /** * Part 1 * * Determine how many pairs of packets are in the right order. * Packet data consists of lists and integers. * If both values are integers, the lower integer should come first. * If both values are lists, compare the first value of each list, then the second value, and so on. */ fun sumOfCorrectPairIndices(input: String): Int { val correctIndices = mutableListOf<Int>() input.split("\n\n").forEachIndexed { index, section -> val lines = section.lines() val leftPacket = ListValue(lines[0]) val rightPacket = ListValue(lines[1]) if (leftPacket.compareTo(rightPacket) < 1) { correctIndices.add(index + 1) } } return correctIndices.sum() } /** * Part 2 */ fun decoderKey(input: String): Int { val decoderPacket1 = ListValue("[[2]]") val decoderPacket2 = ListValue("[[6]]") val inputPackets = input.lines().filter { it.isNotEmpty() }.map { ListValue(it) } val packets = (inputPackets + decoderPacket1 + decoderPacket2).sorted() return (packets.indexOf(decoderPacket1) + 1) * (packets.indexOf(decoderPacket2) + 1) } private sealed class Value : Comparable<Value> { override fun compareTo(other: Value): Int = if (this is IntValue && other is IntValue) { when { this.value < other.value -> -1 this.value > other.value -> 1 else -> 0 } } else if (this is ListValue && other is ListValue) { val maxLength = maxOf(this.values.size, other.values.size) (0 until maxLength).forEach { index -> val leftValue = this.values.getOrNull(index) val rightValue = other.values.getOrNull(index) if (leftValue != null && rightValue != null) { val comp = leftValue.compareTo(rightValue) if (comp != 0) return comp } else { return if (leftValue == null && rightValue != null) { -1 } else { 1 } } } 0 } else if (this is ListValue && other is IntValue) { this.compareTo(ListValue(listOf(other))) } else { ListValue(listOf(this)).compareTo(other) } } private class IntValue(val value: Int) : Value() { constructor(string: String) : this(string.toInt()) override fun toString(): String = value.toString() } private class ListValue(val values: List<Value>) : Value() { constructor(string: String) : this( if (string == "[]") { emptyList<Value>() } else { val values = mutableListOf<Value>() val currentString = StringBuilder() var openBrackets = 0 string.substring(1, string.lastIndex).forEach { char -> when (char) { '[' -> { currentString.append(char) openBrackets++ } ']' -> { currentString.append(char) openBrackets-- if (openBrackets == 0) { values.add(ListValue(currentString.toString())) currentString.clear() } } ',' -> { if (openBrackets > 0) { currentString.append(char) } else if (currentString.isNotEmpty()) { values.add(IntValue(currentString.toString())) currentString.clear() } } else -> { currentString.append(char) } } } if (currentString.isNotEmpty()) { values.add(IntValue(currentString.toString())) } values } ) override fun equals(other: Any?): Boolean = if (other is ListValue) { this.toString() == other.toString() } else { super.equals(other) } override fun toString(): String = "[${values.joinToString { it.toString() }}]" }
0
Kotlin
1
0
909b245e4a0a440e1e45b4ecdc719c15f77719ab
4,474
advent-of-code-2022
Apache License 2.0
src/day05/Day05.kt
andreas-eberle
573,039,929
false
{"Kotlin": 90908}
package day05 import readInput const val day = "05" fun main() { fun calculatePart1Score(input: List<String>): String { val (stacks, moves) = input.parseStacksAndMoves() val mutableStacks = stacks.map { it.toMutableList() } moves.forEach { (times, from, to) -> repeat(times) { val removed = mutableStacks[from - 1].removeFirst() mutableStacks[to - 1].add(0, removed) } } return mutableStacks.map { it.first() }.joinToString("") } fun calculatePart2Score(input: List<String>): String { val (stacks, moves) = input.parseStacksAndMoves() val mutableStacks = stacks.map { it.toMutableList() } moves.forEach { (times, from, to) -> val removed = (0 until times).map { mutableStacks[from - 1].removeFirst() } mutableStacks[to - 1].addAll(0, removed) } return mutableStacks.map { it.first() }.joinToString("") } // test if implementation meets criteria from the description, like: val testInput = readInput("/day$day/Day${day}_test") val input = readInput("/day$day/Day${day}") val part1TestPoints = calculatePart1Score(testInput) val part1Points = calculatePart1Score(input) println("Part1 test points: $part1TestPoints") println("Part1 points: $part1Points") check(part1TestPoints == "CMZ") val part2TestPoints = calculatePart2Score(testInput) val part2Points = calculatePart2Score(input) println("Part2 test points: $part2TestPoints") println("Part2 points: $part2Points") check(part2TestPoints == "MCD") } fun List<String>.parseStacksAndMoves(): Pair<List<List<Char>>, List<Triple<Int, Int, Int>>> { val (stackLines, moveLines) = this.partition { !it.startsWith("move") } val stackParts = stackLines.dropLast(2) .map { it.toCharArray().slice(1 until it.length step 4) } val stacks = stackParts .fold((0 until stackParts.last().size).map { emptyList<Char>() }) { acc, lineChars -> acc.mapIndexed { index, list -> list + (lineChars.getOrNull(index) ?: ' ') } } .map { stack -> stack.filter { it != ' ' } } val moves = moveLines.map { val moveParts = it.split("move ", " from ", " to ") .drop(1) .map { num -> num.toInt() } Triple(moveParts[0], moveParts[1], moveParts[2]) } return stacks to moves }
0
Kotlin
0
0
e42802d7721ad25d60c4f73d438b5b0d0176f120
2,452
advent-of-code-22-kotlin
Apache License 2.0
src/Day12.kt
Shykial
572,927,053
false
{"Kotlin": 29698}
fun main() { fun part1(input: List<String>): Int { lateinit var start: GeoPoint lateinit var end: GeoPoint val geoMap = input.mapIndexed { lineIndex, line -> line.mapIndexed { charIndex, char -> when (char) { 'S' -> GeoPoint(y = lineIndex, x = charIndex, height = 'a'.code).also { start = it } 'E' -> GeoPoint(y = lineIndex, x = charIndex, height = 'z'.code).also { end = it } else -> GeoPoint(y = lineIndex, x = charIndex, height = char.code) } } } return findShortestPath(geoMap = geoMap, start = start, endPredicate = end::equals) } fun part2(input: List<String>): Int { lateinit var start: GeoPoint val geoMap = input.mapIndexed { lineIndex, line -> line.mapIndexed { charIndex, char -> when (char) { 'S' -> GeoPoint(y = lineIndex, x = charIndex, height = 'a'.code) 'E' -> GeoPoint(y = lineIndex, x = charIndex, height = 'z'.code).also { start = it } else -> GeoPoint(y = lineIndex, x = charIndex, height = char.code) } } } return findShortestPath(geoMap = geoMap, start = start, inverseHeightFilter = true) { it.height == 'a'.code } } val input = readInput("Day12") println(part1(input)) println(part2(input)) } private data class GeoPoint( val x: Int, val y: Int, val height: Int, ) private fun GeoPoint.getAvailableNeighbors( geoMap: List<List<GeoPoint>>, visitedPoints: Set<GeoPoint>, inverseHeightFilter: Boolean ) = sequenceOf( geoMap[(y - 1).coerceAtLeast(0)][x], geoMap[y][(x - 1).coerceAtLeast(0)], geoMap[y][(x + 1).coerceAtMost(geoMap[y].lastIndex)], geoMap[(y + 1).coerceAtMost(geoMap.lastIndex)][x] ).filter { p -> p !in visitedPoints && if (!inverseHeightFilter) (p.height <= this.height + 1) else (this.height <= p.height + 1) }.toList() private inline fun findShortestPath( geoMap: List<List<GeoPoint>>, start: GeoPoint, inverseHeightFilter: Boolean = false, endPredicate: (GeoPoint) -> Boolean, ): Int { val visitedNodes = mutableSetOf<GeoPoint>() val unvisitedNodes = geoMap.flatten().toMutableList() val pointsMap = mutableMapOf(start to 0) while (unvisitedNodes.isNotEmpty()) { val currentNode = unvisitedNodes.minBy { pointsMap[it] ?: Int.MAX_VALUE } unvisitedNodes -= currentNode visitedNodes += currentNode val currentLength = pointsMap[currentNode] ?: return Int.MAX_VALUE currentNode .getAvailableNeighbors(geoMap, visitedNodes, inverseHeightFilter) .forEach { point -> if (endPredicate(point)) { return currentLength + 1 } pointsMap.merge(point, currentLength + 1) { oldValue, newValue -> oldValue.takeIf { it <= currentLength + 1 } ?: newValue } } } error("no proper path found") }
0
Kotlin
0
0
afa053c1753a58e2437f3fb019ad3532cb83b92e
3,116
advent-of-code-2022
Apache License 2.0
solutions/src/Day04.kt
khouari1
573,893,634
false
{"Kotlin": 132605, "HTML": 175}
fun main() { fun part1(input: List<String>): Int { return input.count { line -> val (one, two) = line.asNumberPairs() val (oneLowInt, oneHighInt) = one val (twoLowInt, twoHighInt) = two (oneLowInt >= twoLowInt && oneHighInt <= twoHighInt) || (twoLowInt >= oneLowInt && twoHighInt <= oneHighInt) } } fun part2(input: List<String>): Int { return input.count { line -> val (one, two) = line.asNumberPairs() val (oneLowInt, oneHighInt) = one val (twoLowInt, twoHighInt) = two val oneRange: IntRange = oneLowInt..oneHighInt val twoRange = twoLowInt..twoHighInt oneRange.any { it in twoRange } } } // 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)) } private fun String.asNumberPairs(): Pair<Pair<Int, Int>, Pair<Int, Int>> { val (one, two) = split(",") val (oneLow, oneHigh) = one.split("-") val (twoLow, twoHigh) = two.split("-") val oneLowInt = oneLow.toInt() val oneHighInt = oneHigh.toInt() val twoLowInt = twoLow.toInt() val twoHighInt = twoHigh.toInt() return (oneLowInt to oneHighInt) to (twoLowInt to twoHighInt) }
0
Kotlin
0
1
b00ece4a569561eb7c3ca55edee2496505c0e465
1,441
advent-of-code-22
Apache License 2.0
2021/src/Day15.kt
Bajena
433,856,664
false
{"Kotlin": 65121, "Ruby": 14942, "Rust": 1698, "Makefile": 454}
import java.util.* // https://adventofcode.com/2021/day/15 fun main() { fun <T> List<Pair<T, T>>.getUniqueValuesFromPairs(): Set<T> = this .map { (a, b) -> listOf(a, b) } .flatten() .toSet() fun <T> List<Pair<T, T>>.getUniqueValuesFromPairs(predicate: (T) -> Boolean): Set<T> = this .map { (a, b) -> listOf(a, b) } .flatten() .filter(predicate) .toSet() data class Graph<T>( val vertices: Set<T>, val edges: Map<T, Set<T>>, val weights: Map<Pair<T, T>, Int> ) { constructor(weights: Map<Pair<T, T>, Int>): this( vertices = weights.keys.toList().getUniqueValuesFromPairs(), edges = weights.keys .groupBy { it.first } .mapValues { it.value.getUniqueValuesFromPairs { x -> x !== it.key } } .withDefault { emptySet() }, weights = weights ) } fun <T> dijkstra(graph: Graph<T>, start: T): Map<T, Int> { class VertexDistancePairComparator<T> : Comparator<Pair<T, Int>> { override fun compare(o1: Pair<T, Int>, o2: Pair<T, Int>): Int { return o1.second.compareTo(o2.second) } } val priorityQueue = PriorityQueue<Pair<T, Int>>(VertexDistancePairComparator()) val visited = mutableSetOf<T>() val totalRiskLevel = mutableMapOf<T, Int>() totalRiskLevel[start] = 0 priorityQueue.add(Pair(start, 0)) while (priorityQueue.isNotEmpty()){ val point = priorityQueue.remove() val vertex = point.first val distance = point.second visited.add(vertex) if (totalRiskLevel.getOrDefault(vertex, Int.MAX_VALUE) < distance) continue graph.edges.getValue(vertex).minus(visited).forEach { neighbor -> val newRiskLevel = totalRiskLevel.getOrDefault(vertex, Int.MAX_VALUE) + graph.weights.getOrDefault(Pair(vertex, neighbor), null)!! if (newRiskLevel < totalRiskLevel.getOrDefault(neighbor, Int.MAX_VALUE)){ totalRiskLevel[neighbor] = newRiskLevel priorityQueue.add(Pair(neighbor, newRiskLevel)) } } } println(totalRiskLevel.count()) return totalRiskLevel } class Table(cols: Int, rows: Int, numbers: Array<Int>) { val cols = cols val rows = rows var numbers = numbers // Returns list of pairs of <Index, Value> fun getNeighbours(index : Int) : List<Pair<Int, Int>> { val point = indexToPoint(index) val x = point.first val y = point.second return listOf( Pair(x, y - 1), Pair(x - 1, y), Pair(x + 1, y), Pair(x, y + 1), ).filter { it.first >= 0 && it.first < cols && it.second >= 0 && it.second < rows }.map { Pair(pointToIndex(it.first, it.second), get(it.first, it.second)!!) } } fun pointToIndex(x : Int, y : Int) : Int { return y * cols + x } fun indexToPoint(index : Int) : Pair<Int, Int> { return Pair(index % cols, index / cols) } fun get(x : Int, y : Int) : Int? { return numbers.elementAtOrNull(y * cols + x) } fun printMe(shortestPath: List<String> = listOf()) { numbers.forEachIndexed { index, v -> if (index % cols == 0) { println("") print("${index / rows }: ") } if (shortestPath.contains("V$index")) { print(" *$v* ") } else { print(" $v ") } } println() } fun toGraph() : Graph<String> { val weights = mutableMapOf<Pair<String, String>, Int>() numbers.forEachIndexed { index, value -> var neighbours = getNeighbours(index) for (neighbour in neighbours) { weights[Pair("V$index", "V${neighbour.first}")] = neighbour.second } } return Graph(weights) } } fun readTable() : Table { val numbers = mutableListOf<Int>() var cols = -1 var rows = 0 for (i in 0..4) { for (sline in readInput("Day15")) { val ints = sline.split("").filter { it.isNotEmpty() }.map { it.toInt() } val lineNums = mutableListOf<Int>() for (j in 0..4) { lineNums.addAll(ints.map { val newNumber = it + i + j if (newNumber > 9) newNumber - 9 else newNumber }) } cols = lineNums.count() rows++ numbers.addAll(lineNums) } } return Table(cols, rows, numbers.toTypedArray()) } fun part1() { val t = readTable() val g = t.toGraph() val start = "V0" val end = "V${t.numbers.count() - 1}" println(dijkstra(g, start).getOrDefault(end, null)) } fun part2() { } part1() part2() }
0
Kotlin
0
0
a5ca56b7ac8d9d48f82dc079c8ea0cf06d17109a
4,597
advent-of-code
Apache License 2.0
src/main/kotlin/io/steinh/aoc/day02/CubeConundrum.kt
daincredibleholg
726,426,347
false
{"Kotlin": 25396}
package io.steinh.aoc.day02 class CubeConundrum { fun sumIds(lines: List<String>, bagLimits: List<CubeCount>): Int { val processed = analyze(lines) var sum = 0 for (game in processed) { var match = true for (entry in game.value) { for (limit in bagLimits) { match = match && entry.any { it.color == limit.color && it.count <= limit.count } } } if (match) { print("Game ${game.key} is possible\n") sum += game.key } } return sum } fun powerOfTheFewest(lines: List<String>): Int { val processed = analyze(lines) val fewest = getFewest(processed) var result = 0 for (game in fewest) { val value = game.value.map { it.count }.reduce { acc, i -> acc * i } result += value } return result } private fun getFewest(processed: Map<Int, List<List<CubeCount>>>): Map<Int, List<CubeCount>> { val result = mutableMapOf<Int, List<CubeCount>>() for (game in processed) { var red = 0 var green = 0 var blue = 0 for (set in game.value) { for (entry in set) { when (entry.color) { "red" -> red = if (red < entry.count) entry.count else red "green" -> green = if (green < entry.count) entry.count else green "blue" -> blue = if (blue < entry.count) entry.count else blue } } } result[game.key] = listOf( CubeCount(red, "red"), CubeCount(green, "green"), CubeCount(blue, "blue") ) } return result } private fun analyze(lines: List<String>): Map<Int, List<List<CubeCount>>> { val result: MutableMap<Int, List<List<CubeCount>>> = mutableMapOf() for (line in lines) { val gameId = "Game (\\d+)".toRegex().find(line)!!.groupValues[1].toInt() val drawnSets = line.split(": ").last().split(";") val sets = buildList { for (set in drawnSets) { add( buildList { var redCubes = 0 var greenCubes = 0 var blueCubes = 0 for (matches in "(\\d+) (red|green|blue)".toRegex().findAll(set)) { val cnt = matches.groups[1]!!.value.toInt() when (matches.groups[2]!!.value) { "red" -> redCubes += cnt "green" -> greenCubes += cnt "blue" -> blueCubes += cnt } } add(CubeCount(redCubes, "red")) add(CubeCount(blueCubes, "blue")) add(CubeCount(greenCubes, "green")) }) } } result.put(gameId, sets) } return result } } data class CubeCount( val count: Int, val color: String, ) fun main() { val input = {}.javaClass.classLoader?.getResource("day02/input.txt")?.readText()?.lines()!! val bagLimits = listOf( CubeCount(12, "red"), CubeCount(13, "green"), CubeCount(14, "blue") ) val cubeConundrum = CubeConundrum() val result = cubeConundrum.sumIds(input, bagLimits) val resultPart2 = cubeConundrum.powerOfTheFewest(input) print("Solution for Day 2, Part I: $result\n") print("Solution for Day 2, Part II: $resultPart2\n") }
0
Kotlin
0
0
4aa7c684d0e337c257ae55a95b80f1cf388972a9
3,894
AdventOfCode2023
MIT License
src/main/kotlin/day3.kt
danielfreer
297,196,924
false
null
import kotlin.math.absoluteValue import kotlin.time.ExperimentalTime @ExperimentalTime fun day3(paths: List<String>): List<Solution> { return listOf( solve(3, 1) { findIntersection(paths) }, solve(3, 2) { findSteps(paths) } ) } data class Point(val x: Int, val y: Int) fun manhattanDistance(points: Set<Point>): Int { return points .map { it.x.absoluteValue + it.y.absoluteValue } .minOrNull() ?: throw IllegalArgumentException("Cannot find min of empty set: $points") } private fun Point.moveRight() = copy(x = x + 1) private fun Point.moveUp() = copy(y = y + 1) private fun Point.moveLeft() = copy(x = x - 1) private fun Point.moveDown() = copy(y = y - 1) private fun movement(direction: Char): (Point) -> Point { return when (direction) { 'R' -> Point::moveRight 'U' -> Point::moveUp 'L' -> Point::moveLeft 'D' -> Point::moveDown else -> throw IllegalArgumentException("Unknown direction: $direction") } } private fun calculatePointsTraveled(path: String): List<Point> { val startingPoint = Point(x = 0, y = 0) return path.split(",") .flatMap { val distance = it.drop(1).toInt() val movement = it.first().let(::movement) List(distance) { movement } } .runningFold(startingPoint) { point, move -> move(point) } } private fun ignoreStartingPoint(points: List<Point>) = points.drop(1) fun findIntersection(paths: List<String>): Int { val intersections = paths .map(::calculatePointsTraveled) .map(::ignoreStartingPoint) .map { it.toSet() } .reduce { acc, points -> acc.intersect(points) } return manhattanDistance(intersections) } fun findStepsToIntersections(paths: List<String>): List<Map<Point, Int>> { val allPointsTraveled = paths .map(::calculatePointsTraveled) val intersections = allPointsTraveled .map(::ignoreStartingPoint) .map { it.toSet() } .reduce { acc, points -> acc.intersect(points) } return allPointsTraveled.map { pointsTraveled -> intersections.associateWith { intersection -> pointsTraveled.indexOf(intersection) } } } fun findSteps(paths: List<String>): Int { val stepsToIntersections = findStepsToIntersections(paths) val intersectionsToSteps = stepsToIntersections .reduce { acc, map -> val newMap = acc.toMutableMap() map.forEach { (point, steps) -> newMap.compute(point) { _, value -> value?.plus(steps) ?: steps } } newMap } return intersectionsToSteps .minByOrNull { it.value } ?.value ?: throw IllegalArgumentException("Empty collection") }
0
Kotlin
0
0
74371d15f95492dee1ac434f0bfab3f1160c5d3b
2,817
advent2019
The Unlicense
2023/src/main/kotlin/day19.kt
madisp
434,510,913
false
{"Kotlin": 388138}
import utils.Component4 import utils.Parse import utils.Parser import utils.Solution import utils.Vec4i import utils.cut import utils.mapItems fun main() { Day19.run() } object Day19 : Solution<Pair<List<Day19.Workflow>, List<Vec4i>>>() { override val name = "day19" override val parser = Parser.compound( Parser.lines.mapItems { Workflow.parseWorkflow(it) }, Parser.lines.mapItems { parseItem(it.removeSurrounding("{", "}")) } .mapItems { Vec4i(it.variables["x"]!!, it.variables["m"]!!, it.variables["a"]!!, it.variables["s"]!!) }, ) @Parse("{r ',' variables}") data class Item( @Parse("{key}={value}") val variables: Map<String, Int> ) private val varMap = mapOf( "x" to Component4.X, "m" to Component4.Y, "a" to Component4.Z, "s" to Component4.W, ) data class Workflow( val name: String, val rules: List<Rule>, ) { companion object { fun parseWorkflow(input: String): Workflow { val (name, rulestr) = input.trim().cut("{") val ruleStrs = rulestr.removeSuffix("}").split(",") return Workflow( name, ruleStrs.map { Rule.parse(it) }, ) } } } sealed interface Rule { val target: String data class DefaultRule(override val target: String): Rule data class LtRule(override val target: String, val varIndex: Component4, val constant: Int): Rule data class GtRule(override val target: String, val varIndex: Component4, val constant: Int): Rule companion object { fun parse(input: String): Rule { if (':' !in input) { return DefaultRule(input) } val (expr, target) = input.cut(":") val variable = expr[0] val const = expr.substring(2).toInt() return when (expr[1]) { '>' -> GtRule(target, varMap[variable.toString()]!!, const) '<' -> LtRule(target, varMap[variable.toString()]!!, const) else -> throw IllegalArgumentException("Unsupported operator ${expr[1]}") } } } } override fun part1(): Int { val rules = input.first.associateBy { it.name } var result = Vec4i(0, 0, 0, 0) input.second.forEach { item -> var target = "in" outer@while (target !in setOf("A", "R")) { val workflow = rules[target]!! for (rule in workflow.rules) { when (rule) { is Rule.DefaultRule -> { target = rule.target continue@outer } is Rule.GtRule -> if (item[rule.varIndex] > rule.constant) { target = rule.target continue@outer } is Rule.LtRule -> if (item[rule.varIndex] < rule.constant) { target = rule.target continue@outer } } } } if (target == "A") { result += item } } return Component4.entries.sumOf { result[it] } } sealed interface Node { data class Leaf(val accept: Boolean) : Node data class Tree(val expr: Rule, val left: Node, val right: Node) : Node } private fun buildNode(workflows: Map<String, Workflow>, rules: List<Rule>): Node { if (rules.size == 1) { val rule = rules.last() require(rule is Rule.DefaultRule) return if (rule.target == "R" || rule.target == "A") { Node.Leaf(rule.target == "A") } else { buildNode(workflows, workflows[rule.target]!!.rules) } } val rule = rules.first() return Node.Tree( expr = rule, left = workflows[rule.target]?.let { buildNode(workflows, it.rules) } ?: Node.Leaf(rule.target == "A"), right = buildNode(workflows, rules.drop(1)), ) } private fun Vec4i.coerceAtLeast(i: Component4, value: Int) = copy(i, maxOf(value, this[i])) private fun Vec4i.coerceAtMost(i: Component4, value: Int) = copy(i, minOf(value, this[i])) private fun countVariants(node: Node, minimum: Vec4i, maximum: Vec4i): Long { return when (node) { is Node.Leaf -> if (!node.accept) 0L else { val answ = (maximum - minimum + Vec4i(1, 1, 1, 1)) Component4.entries.map { answ[it].toLong() }.reduce { a, b -> a * b } } is Node.Tree -> { when (val expr = node.expr) { is Rule.DefaultRule -> TODO("should not happen") is Rule.GtRule -> { val left = countVariants(node.left, minimum.coerceAtLeast(expr.varIndex, expr.constant + 1), maximum) val right = countVariants(node.right, minimum, maximum.coerceAtMost(expr.varIndex, expr.constant)) left + right } is Rule.LtRule -> { val left = countVariants(node.left, minimum, maximum.coerceAtMost(expr.varIndex, expr.constant - 1)) val right = countVariants(node.right, minimum.coerceAtLeast(expr.varIndex, expr.constant), maximum) left + right } } } } } override fun part2(): Long { val workflows = input.first.associateBy { it.name } val root = buildNode(workflows, workflows["in"]!!.rules) return countVariants(root, Vec4i(1, 1, 1, 1), Vec4i(4000, 4000, 4000, 4000)) } }
0
Kotlin
0
1
3f106415eeded3abd0fb60bed64fb77b4ab87d76
5,174
aoc_kotlin
MIT License
src/Day03.kt
mhuerster
572,728,068
false
{"Kotlin": 24302}
fun main() { var lowercase = ('a'..'z') var uppercase = ('A'..'Z') class Rucksack(val contents: String ) { val midpoint: Int get() = (contents.length / 2) val firstCompartment: String get() = contents.substring(0..midpoint) val secondCompartment: String get() = contents.substring(midpoint..contents.lastIndex) fun commonItem(): Char { return firstCompartment.find { secondCompartment.contains(it) }!!.toChar() } fun toSet(): Set<Char> { return contents.toSet() } } class Item(val item: Char) { fun priority(): Int { val p = if (lowercase.contains(item)) { lowercase.indexOf(item) + 1 } else { uppercase.indexOf(item) + 27 } return p.toInt()!! } } class Group(val rucksacks: List<Rucksack>) { fun badge(): Item { val (firstElf, secondElf, thirdElf) = rucksacks.map { it.toSet() } return Item(firstElf.intersect(secondElf).intersect(thirdElf).single()) } } fun inputToRucksacks(input: List<String>): List<Rucksack> { return input.map { Rucksack(it) } } // Find the item type that appears in both compartments of each rucksack. // What is the sum of the priorities of those item types? fun part1(input: List<String>): Int { return inputToRucksacks(input).fold(0) { sum, rucksack -> sum + Item(rucksack.commonItem()).priority() } } // Find the item type that corresponds to the badges of each three-Elf group. // What is the sum of the priorities of those item types? fun part2(input: List<String>): Int { val groups = inputToRucksacks(input).chunked(3).map { Group(it) } return groups.fold(0) { sum, group -> sum + group.badge().priority() } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day03_sample") println(part1(testInput)) check(part1(testInput) == 157) check(part2(testInput) == 70) val input = readInput("Day03") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
5f333beaafb8fe17ff7b9d69bac87d368fe6c7b6
2,030
2022-advent-of-code
Apache License 2.0
src/Day12.kt
thpz2210
575,577,457
false
{"Kotlin": 50995}
private class Solution12(input: List<String>) { var grid = Grid2D(input.map { it.toCharArray().toList() }) fun part1() = distanceFrom('E' to 'S') fun part2() = distanceFrom('E' to 'a') private fun distanceFrom(fromTo: Pair<Char, Char>): Int { val fromChar = fromTo.first val toChar = fromTo.second val walked = mutableSetOf(grid.findFirstCoordinate { it == fromChar }) var nextLayer = walked.toSet() for (layerCounter in generateSequence(1) { it + 1 }) { nextLayer = nextLayer.flatMap { admissibleSteps(it, walked) }.toSet() if (nextLayer.map { grid.itemAt(it) }.contains(toChar)) return layerCounter walked.addAll(nextLayer) } return 0 } private fun admissibleSteps(coordinate: Coordinate, walked: MutableSet<Coordinate>) = grid.orthogonalNeighborsOf(coordinate).filter { it !in walked && height(coordinate) - 1 <= height(it) } private fun height(coordinate: Coordinate) = when (grid.itemAt(coordinate)) { 'S' -> 'a' 'E' -> 'z' else -> grid.itemAt(coordinate) } } fun main() { val testSolution = Solution12(readInput("Day12_test")) check(testSolution.part1() == 31) check(testSolution.part2() == 29) val solution = Solution12(readInput("Day12")) println(solution.part1()) println(solution.part2()) }
0
Kotlin
0
0
69ed62889ed90692de2f40b42634b74245398633
1,407
aoc-2022
Apache License 2.0
src/aoc2017/kot/Day24.kt
Tandrial
47,354,790
false
null
package aoc2017.kot import java.io.File object Day24 { fun solve(input: List<String>): Pair<Int, Int> { val (pairs, doubles) = input.map { val (l, r) = it.split("/").map { it.toInt() }; l to r }.partition { it.first != it.second } val (p1, p2) = dfs(listOf(0), pairs, doubles) return Pair(p1, p2.second) } private fun dfs(bridge: List<Int>, pieces: List<Pair<Int, Int>>, doubles: List<Pair<Int, Int>>): Pair<Int, Pair<Int, Int>> { val matchDbl = doubles.filter { bridge.contains(it.first) } var strength = bridge.sumBy { it } + 2 * matchDbl.sumBy { it.first } val length = bridge.size + 2 * matchDbl.size var longest = Pair(length, strength) for ((l, r) in pieces) { if (l == bridge.last() || r == bridge.last()) { val newLink = if (l == bridge.last()) listOf(l, r) else listOf(r, l) val result = dfs(bridge + newLink, pieces.filter { it != Pair(l, r) }, doubles) strength = maxOf(strength, result.first) if (length > longest.first || (length == longest.first && strength > longest.second)) { longest = Pair(length, strength) } } } return Pair(strength, longest) } } fun main(args: Array<String>) { val input = File("./input/2017/Day24_input.txt").readLines() val (partOne, partTwo) = Day24.solve(input) println("Part One = $partOne") println("Part Two = $partTwo") }
0
Kotlin
1
1
9294b2cbbb13944d586449f6a20d49f03391991e
1,391
Advent_of_Code
MIT License
src/Day07.kt
PascalHonegger
573,052,507
false
{"Kotlin": 66208}
private sealed interface SystemNode { val name: String val size: Int } private data class SystemDirectory(override val name: String, val children: List<SystemNode>) : SystemNode { override val size = children.sumOf { it.size } } private data class SystemFile(override val name: String, override val size: Int) : SystemNode private sealed interface SystemCommand { data class SystemCommandCD(val target: String) : SystemCommand object SystemCommandLS : SystemCommand } fun main() { fun String.isSystemCommand() = startsWith('$') fun String.toSystemCommand(): SystemCommand { val parts = split(' ') return when(parts[1]) { "ls" -> SystemCommand.SystemCommandLS "cd" -> SystemCommand.SystemCommandCD(parts[2]) else -> error("Couldn't parse '$this'") } } fun List<String>.toSystem(): SystemDirectory { // var currentDirectory = "/" val pathSegments = mutableListOf("") val childrenStack = ArrayDeque<MutableList<SystemNode>>() childrenStack.addLast(mutableListOf()) drop(1).forEach { if (it.isSystemCommand()) { when (val cmd = it.toSystemCommand()) { is SystemCommand.SystemCommandLS -> Unit is SystemCommand.SystemCommandCD -> { when (cmd.target) { ".." -> { val children = childrenStack.removeLast() childrenStack.last().add(SystemDirectory(name = pathSegments.joinToString(separator = "/"), children = children)) pathSegments.removeLast() } else -> { childrenStack.addLast(mutableListOf()) pathSegments += cmd.target } } } } } else { when { it.startsWith("dir") -> Unit // Parsed when we CD into and out of directory else -> { val (size, name) = it.split(' ') childrenStack.last().add(SystemFile(name = name, size = size.toInt())) } } } } while (pathSegments.size > 1) { val children = childrenStack.removeLast() childrenStack.last().add(SystemDirectory(name = pathSegments.joinToString(separator = "/"), children = children)) pathSegments.removeLast() } return SystemDirectory(name = "/", children = childrenStack.single()) } fun SystemDirectory.flatmap(): Sequence<SystemNode> = sequence { yield(this@flatmap) children.forEach { when(it) { is SystemFile -> yield(it) is SystemDirectory -> yieldAll(it.flatmap()) } } } fun part1(input: List<String>): Int { return input .toSystem() .flatmap() .filterIsInstance<SystemDirectory>() .filter { it.size <= 100_000 } .sumOf { it.size } } fun part2(input: List<String>): Int { val diskSpace = 70_000_000 val targetFreeSpace = 30_000_000 val system = input.toSystem() val currentFreeSpace = diskSpace - system.size val toDelete = targetFreeSpace - currentFreeSpace return system .flatmap() .filterIsInstance<SystemDirectory>() .map { it.size } .sorted() .first { it >= toDelete } } val testInput = readInput("Day07_test") check(part1(testInput) == 95437) check(part2(testInput) == 24933642) val input = readInput("Day07") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
2215ea22a87912012cf2b3e2da600a65b2ad55fc
3,925
advent-of-code-2022
Apache License 2.0
src/Day03.kt
Akaneiro
572,883,913
false
null
fun main() { fun Char.calculatePriority(): Int { var priority = this.lowercaseChar() - 'a' + 1 if (this.isUpperCase()) priority += 26 return priority } fun List<String>.asListOfCharLists() = this .asSequence() .map { it.toCharArray().toList() } fun part1(input: List<String>): Int { return input.asListOfCharLists() .map { it.chunked(it.size / 2) } .map { it.first() to it.last() } .map { (first, second) -> first.intersect(second.toSet()) } .map { it.sumOf { it.calculatePriority() } } .sum() } fun part2(input: List<String>): Int { return input.asListOfCharLists() .chunked(3) .map { group -> val first = group.first() val resultList = mutableListOf<Char>().apply { addAll(first) } group.forEach { s -> val intersectWithCurrent = first.intersect(s.toSet()) val intersectWithResult = resultList.intersect(intersectWithCurrent) resultList.clear() resultList.addAll(intersectWithResult) } resultList } .map { it.first() } .map { it.calculatePriority() } .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(part1(input)) println(part2(input)) }
0
Kotlin
0
0
f987830a70a2a1d9b88696271ef668ba2445331f
1,635
aoc-2022
Apache License 2.0
src/Day23.kt
jstapels
572,982,488
false
{"Kotlin": 74335}
fun main() { data class Dir(val dir: String, val offset: Pos, val checks: List<Pos>) { fun valid(pos: Pos, used: Set<Pos>) = checks.map { pos + it } .none { it in used } } val startDirs = listOf( Dir("N", 0 by -1, listOf(-1 by -1, 0 by -1, 1 by -1)), Dir("S", 0 by 1, listOf(-1 by 1, 0 by 1, 1 by 1)), Dir("W", -1 by 0, listOf(-1 by -1, -1 by 0, -1 by 1)), Dir("E", 1 by 0, listOf(1 by -1, 1 by 0, 1 by 1)) ) val doNothing = Dir("*", 0 by 0, listOf(-1 by -1, 0 by -1, 1 by -1, -1 by 0, 1 by 0, -1 by 1, 0 by 1, 1 by 1)) data class Grove(val elves: List<Pos>) { val minX = elves.minOf { it.x } val minY = elves.minOf { it.y } val maxX = elves.maxOf { it.x } val maxY = elves.maxOf { it.y } fun dump() { (minY..maxY).forEach { y -> (minX..maxX).forEach { x -> val c = if (x by y in elves) '#' else '.' print(c) } println() } } fun empties() = (minY..maxY).flatMap { y -> (minX..maxX).map { x -> if (x by y in elves) 0 else 1 } }.sum() } fun parseInput(input: List<String>) = input.flatMapIndexed { y, line -> line.mapIndexedNotNull { x, d -> if (d == '#') Pos(x, y) else null } }.let { Grove(it) } fun doRound(grove: Grove, dirs: List<Dir>): Grove { val usedPos = grove.elves.toSet() val dirCheck = listOf(doNothing) + dirs val newPos = grove.elves .map { pos -> val dir = dirCheck.firstOrNull { it.valid(pos, usedPos) } val offset = dir?.offset ?: (0 by 0) pos + offset }.toList() val dups = newPos.groupingBy { it } .eachCount() .filterValues { it > 1 } .keys val movedElves = grove.elves .mapIndexed { i, p -> if (newPos[i] in dups) p else newPos[i] } return Grove(movedElves) } fun part1(input: List<String>): Int { var grove = parseInput(input) var dirs = startDirs.toMutableList() repeat(10) { grove = doRound(grove, dirs) dirs.removeFirst().let { dirs.add(it) } } return grove.empties() } fun part2(input: List<String>): Int { var grove = parseInput(input) var dirs = startDirs.toMutableList() var count = 0 var lastGrove = grove while(true) { count++ grove = doRound(grove, dirs) dirs.removeFirst().let { dirs.add(it) } if (grove == lastGrove) return count else lastGrove = grove } } val day = 23 println("OUTPUT FOR DAY $day") println("-".repeat(64)) val testInput = readInput("Day${day.pad(2)}_test") checkTest(110) { part1(testInput) } checkTest(20) { part2(testInput) } println("-".repeat(64)) val input = readInput("Day${day.pad(2)}") solution { part1(input) } solution { part2(input) } println("-".repeat(64)) }
0
Kotlin
0
0
0d71521039231c996e2c4e2d410960d34270e876
3,299
aoc22
Apache License 2.0
src/Day07.kt
zuevmaxim
572,255,617
false
{"Kotlin": 17901}
private fun part1(input: List<String>): Int { val root = parse(input) val dirs = root.toDirList() return dirs.filter { it.size <= 100000 }.sumOf { it.size } } private fun part2(input: List<String>): Int { val root = parse(input) val dirs = root.toDirList() val currentData = root.size val currentSpace = 70000000 - currentData val requiredSpace = 30000000 val toDelete = requiredSpace - currentSpace return dirs.filter { it.size > toDelete }.minOf { it.size } } private interface MockElement { val size: Int val name: String val children: List<MockElement> } private data class MockFile(override val name: String, override val size: Int) : MockElement { override val children get() = emptyList<MockElement>() } private data class MockDir(override val name: String) : MockElement { override val children = mutableListOf<MockElement>() override val size: Int get() = children.sumOf { it.size } fun toDirList(): List<MockDir> = mutableListOf<MockDir>().also { this.addToList(it) } private fun addToList(list: MutableList<MockDir>) { list.add(this) for (dir in children) { if (dir is MockDir) dir.addToList(list) } } } private fun parse(input: List<String>): MockDir { val root = MockDir("/") check(input[0] == "$ cd /") var i = 1 val stack = mutableListOf(root) while (i < input.size) { if (input[i].startsWith("$ cd ..")) { stack.removeLast() } else if (input[i].startsWith("$ cd ")) { val dir = MockDir(input[i].substring("$ cd ".length)) stack.last().children.add(dir) stack.add(dir) } else if (input[i] == "$ ls") { } else if (input[i].startsWith("dir ")) { } else { val (size, name) = input[i].split(" ") stack.last().children.add(MockFile(name, size.toInt())) } i++ } return root } fun main() { val testInput = readInput("Day07_test") check(part1(testInput) == 95437) check(part2(testInput) == 24933642) val input = readInput("Day07") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
34356dd1f6e27cc45c8b4f0d9849f89604af0dfd
2,191
AOC2022
Apache License 2.0
src/main/kotlin/Day05.kt
todynskyi
573,152,718
false
{"Kotlin": 47697}
import java.util.* fun main() { fun parse(input: List<String>): Pair<MutableMap<Int, LinkedList<String>>, List<MoveCommand>> { val data = input.takeWhile { it.isNotBlank() } val numberOfStacks = data.last().mapIndexedNotNull { index, c -> if (c.isDigit()) c.toString().toInt() to index else null } val stacks = mutableMapOf<Int, LinkedList<String>>() data.dropLast(1).forEach { line -> numberOfStacks.forEach { (stack, charIndex) -> val value = line.getOrNull(charIndex)?.toString() if (!value.isNullOrBlank()) { stacks[stack] = stacks.getOrDefault(stack, LinkedList<String>()).also { it.add(value) } } } } val commands = input.subList(data.size + 1, input.size).map { val parts = it.split(" ") MoveCommand(amount = parts[1].toInt(), from = parts[3].toInt(), to = parts.last().toInt()) } return stacks to commands } fun Map<Int, List<String>>.toMessage(): String = this.map { it.key to it.value.first() } .sortedBy { it.first } .mapNotNull { it.second } .joinToString("") fun part1(input: List<String>): String { val (stacks, commands) = parse(input) commands.forEach { command -> val from = stacks[command.from]!! val to = stacks[command.to]!! repeat(command.amount) { val value = from.pollFirst() to.addFirst(value) } } return stacks.toMessage() } fun part2(input: List<String>): String { val (stacks, commands) = parse(input) commands.forEach { command -> val from = stacks[command.from]!! val to = stacks[command.to]!! val data = mutableListOf<String>() repeat(command.amount) { data.add(from.pollFirst()) } data.reversed().forEach { to.addFirst(it) } } return stacks.toMessage() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day05_test") check(part1(testInput) == "CMZ") println(part2(testInput)) val input = readInput("Day05") println(part1(input)) println(part2(input)) } data class MoveCommand(val amount: Int, val from: Int, val to: Int)
0
Kotlin
0
0
5f9d9037544e0ac4d5f900f57458cc4155488f2a
2,444
KotlinAdventOfCode2022
Apache License 2.0
src/Day04.kt
allwise
574,465,192
false
null
import java.io.File fun main() { fun part1(input: List<String>): Int { val areas= Areas(input) return areas.process() } fun part2(input: List<String>): Int { val areas= Areas(input) return areas.processContains() } // 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)) } class Areas(val input:List<String>) { //Lines 4-6,5-9 fun process():Int{ val rows= input.map { line -> line.split(",").map{ range -> range.split("-").toPair()}} //[(2, 4), (6, 8)] val number = rows.map { row-> ((row.first().toInt() within row.last().toInt()) || (row.last().toInt() within row.first().toInt())) }.count {it} println ("within $number") return number } fun processContains():Int{ var count = 0 val rows= input.map { line -> line.split(",").map{ range -> range.split("-").toPair()}} //[(2, 4), (6, 8)] val nrContains = rows.map { row-> ((row.first().toInt() contains row.last().toInt()) || (row.last().toInt() contains row.first().toInt())) }.count {it} println ("contains $nrContains") return nrContains } fun List<String>.toPair(): Pair<String, String> { return Pair(this.first(),this.last()) } fun Pair<String,String>.toInt():Pair<Int,Int>{ return this.first.toInt() to this.second.toInt() } infix fun Pair<Int,Int>.within(range1:Pair<Int,Int>):Boolean{ if(this.first.isBetween(range1.first,range1.second) && this.second.isBetween(range1.first,range1.second)) return true return false } infix fun Pair<Int,Int>.contains(range1:Pair<Int,Int>):Boolean{ if(this.first.isBetween(range1.first,range1.second) ||this.second.isBetween(range1.first,range1.second)) return true return false } fun Int.isBetween(start:Int, finish:Int):Boolean{ return this>=start && this<=finish } }
0
Kotlin
0
0
400fe1b693bc186d6f510236f121167f7cc1ab76
2,169
advent-of-code-2022
Apache License 2.0
aoc-2022/src/main/kotlin/nerok/aoc/aoc2022/day05/Day05.kt
nerok
572,862,875
false
{"Kotlin": 113337}
package nerok.aoc.aoc2022.day05 import nerok.aoc.utils.Input import kotlin.time.DurationUnit import kotlin.time.measureTime fun main() { fun part1(input: String): String { val (mapInput, instructionInput) = input.split("\n\n") val parsedMap = mapInput .lines() .map { lines -> lines.chunked(4).map { point -> point.trim() } } val containerArray = Array(parsedMap.last().size) { emptyList<String>().toMutableList() } for (line in parsedMap) { if (line == parsedMap.last()) continue line.onEachIndexed { index, s -> if (s.isNotEmpty()) containerArray[index] = listOf(s).plus(containerArray[index]).toMutableList() } } instructionInput .lines() .map { line -> line.split(" from ") } .filter { it.first().isNotEmpty() } .forEach { line -> val count = line.first().removePrefix("move ").toInt() val tmpSplit = line.last().split(" to ") val source = tmpSplit.first().toInt().minus(1) val destination = tmpSplit.last().toInt().minus(1) for (round in 1..count) { val tmp = containerArray[source].removeLast() containerArray[destination].add(tmp) } } return containerArray .map { it.last().removePrefix("[").removeSuffix("]") } .reduce { acc, s -> acc.plus(s) } } fun part2(input: String): String { val (mapInput, instructionInput) = input.split("\n\n") val parsedMap = mapInput .lines() .map { lines -> lines.chunked(4).map { point -> point.trim() } } val containerArray = Array(parsedMap.last().size) { emptyList<String>().toMutableList() } for (line in parsedMap) { if (line == parsedMap.last()) continue line.onEachIndexed { index, s -> if (s.isNotEmpty()) containerArray[index] = listOf(s).plus(containerArray[index]).toMutableList() } } instructionInput .lines() .map { line -> line.split(" from ") } .filter { it.first().isNotEmpty() } .forEach { line -> val count = line.first().removePrefix("move ").toInt() val tmpSplit = line.last().split(" to ") val source = tmpSplit.first().toInt().minus(1) val destination = tmpSplit.last().toInt().minus(1) val tmp = emptyList<String>().toMutableList() for (round in 1..count) { tmp.add(containerArray[source].removeLast()) } tmp.reverse() containerArray[destination].addAll(tmp) } return containerArray .map { it.last().removePrefix("[").removeSuffix("]") } .reduce { acc, s -> acc.plus(s) } } // test if implementation meets criteria from the description, like: val testInput = Input.getInput("Day05_test") check(part1(testInput) == "CMZ") check(part2(testInput) == "MCD") val input = Input.getInput("Day05") println(measureTime { println(part1(input)) }.toString(DurationUnit.SECONDS, 3)) println(measureTime { println(part2(input)) }.toString(DurationUnit.SECONDS, 3)) }
0
Kotlin
0
0
7553c28ac9053a70706c6af98b954fbdda6fb5d2
3,442
AOC
Apache License 2.0
src/commonMain/kotlin/search/SimpleTrie.kt
jillesvangurp
271,782,317
false
null
package search private class TrieNode { val children: MutableMap<Char, TrieNode> = mutableMapOf() var isLeaf = false fun strings(): List<String> { return children.entries.flatMap { entry -> val n = entry.value if (n.isLeaf) { listOf("" + entry.key) + n.strings().map { s: String -> "" + entry.key + s } } else { n.strings() .map { s: String -> "" + entry.key + s } } } } } /** * Simple implementation of a Trie that may be used to match input strings to the longest matching prefix. */ class SimpleStringTrie { private val root: TrieNode = TrieNode() /** * Add a string to the trie. * @param input any String */ fun add(input: String) { var currentNode = root for (c in input) { val children = currentNode.children val matchingNode = children[c] if (matchingNode != null) { currentNode = matchingNode } else { val newNode = TrieNode() children[c] = newNode currentNode = newNode } } currentNode.isLeaf = true // this is the end of an input that was added, there may be more children } /** * Return the longest matching prefix of the input string that was added to the trie. * @param input a string * @return Optional of longest matching prefix that was added to the trie */ operator fun get(input: String): String? { var currentNode = root var i = 0 for (c in input) { val nextNode = currentNode.children[c] if (nextNode != null) { i++ currentNode = nextNode } else { if (i > 0 && currentNode.isLeaf) { return input.substring(0, i) } } } return if (i > 0 && currentNode.isLeaf) { input.substring(0, i) } else null } fun match(input: String): List<String> { return addMoreStrings(input, "", root) } private fun addMoreStrings( input: String, prefix: String, startNode: TrieNode ): List<String> { var currentNode = startNode var i = 0 val results: MutableList<String> = mutableListOf() for (c in input) { val nextNode = currentNode.children[c] if (nextNode != null) { i++ currentNode = nextNode } } val matched = input.substring(0, i) if (i > 0 && currentNode.isLeaf) { results.add(prefix + matched) // fully matched against something } if (currentNode != root && i == input.length) { results.addAll( currentNode.strings() .map { s: String -> prefix + matched + s } .toList() ) } return results } companion object { /** * Useful if you want to build a trie for an existing map so you can figure out a matching prefix that has an entry * @param map a map * @return a search.SimpleStringTrie for the map. */ fun from(map: Map<String, *>): SimpleStringTrie { val st = SimpleStringTrie() map.keys.forEach { key: String -> st.add(key) } return st } } }
0
Kotlin
1
4
0f4236bf891faa841c6e32fe37c9ab9d2e6ce7c5
3,524
querylight
MIT License
aoc21/day_21/main.kt
viktormalik
436,281,279
false
{"Rust": 227300, "Go": 86273, "OCaml": 82410, "Kotlin": 78968, "Makefile": 13967, "Roff": 9981, "Shell": 2796}
import java.io.File import kotlin.math.max enum class Player { P1, P2; fun opposite(): Player = if (this == P1) P2 else P1 } data class Game( var p1Pos: Int, var p2Pos: Int, var p1Score: Int = 0, var p2Score: Int = 0, val winningScore: Int, var playing: Player = Player.P1, ) { var rolls = 0 fun clone(): Game = Game(p1Pos, p2Pos, p1Score, p2Score, winningScore, playing) fun round(dice: List<Int>) { rolls += dice.size if (playing == Player.P1) { p1Pos = (p1Pos + dice.sum()) % 10 p1Score += p1Pos + 1 } else { p2Pos = (p2Pos + dice.sum()) % 10 p2Score += p2Pos + 1 } playing = playing.opposite() } fun end(): Boolean = p1Score >= winningScore || p2Score >= winningScore fun winner(): Player = playing.opposite() fun looserScore(): Int = if (playing == Player.P1) p1Score else p2Score } class QuantumGame { var activeGames = mapOf<Game, Long>() val endedGames = mutableMapOf<Game, Long>() constructor (initGame: Game) { activeGames = mapOf(initGame to 1) } fun round(roll: Map<Int, Long>) { val newGames = mutableMapOf<Game, Long>() for ((game, gameCnt) in activeGames) { for ((rollVal, rollCnt) in roll) { val newGame = game.clone() newGame.round(listOf(rollVal)) if (newGame.end()) endedGames.merge(newGame, rollCnt * gameCnt, Long::plus) else newGames.merge(newGame, rollCnt * gameCnt, Long::plus) } } activeGames = newGames } fun end(): Boolean = activeGames.isEmpty() fun p1Wins(): Long = endedGames.filter { it.key.winner() == Player.P1 }.values.sum() fun p2Wins(): Long = endedGames.filter { it.key.winner() == Player.P2 }.values.sum() } fun normalDie(): Sequence<Int> = sequence { while (true) { yieldAll(1..100) } } fun quantumDie(): Map<Int, Long> = mapOf(3 to 1, 4 to 3, 5 to 6, 6 to 7, 7 to 6, 8 to 3, 9 to 1) fun main() { val input = File("input").readLines() val p1Pos = input[0][28].toString().toInt() - 1 val p2Pos = input[1][28].toString().toInt() - 1 val normalGame = Game(p1Pos, p2Pos, winningScore = 1000) for (nums in normalDie().chunked(3)) { normalGame.round(nums) if (normalGame.end()) { println("First: ${normalGame.looserScore() * normalGame.rolls}") break } } var quantumGame = QuantumGame(Game(p1Pos, p2Pos, winningScore = 21)) while (!quantumGame.end()) { quantumGame.round(quantumDie()) } val second = max(quantumGame.p1Wins(), quantumGame.p2Wins()) println("Second: $second") }
0
Rust
1
0
f47ef85393d395710ce113708117fd33082bab30
2,768
advent-of-code
MIT License
src/main/kotlin/biz/koziolek/adventofcode/year2022/day03/day3.kt
pkoziol
434,913,366
false
{"Kotlin": 715025, "Shell": 1892}
package biz.koziolek.adventofcode.year2022.day03 import biz.koziolek.adventofcode.findInput fun main() { val inputFile = findInput(object {}) val rucksacks = parseRucksacks(inputFile.bufferedReader().readLines()) println("Sum of shared item priorities: ${getSumOfSharedItemPriorities(rucksacks)}") val groups = groupRucksacks(rucksacks) println("Sum of group badge priorities: ${getSumOfGroupBadges(groups)}") } data class Rucksack(val contents: String) { val compartment1: String get() = contents.substring(0, contents.length / 2) val compartment2: String get() = contents.substring(contents.length / 2) fun findSharedItem(): Char = compartment1.toSet().intersect(compartment2.toSet()).single() } data class ElfGroup(val rucksacks: List<Rucksack>) { fun findBadge(): Char = rucksacks .fold(rucksacks.first().contents.toSet()) { acc, rucksack -> acc.intersect(rucksack.contents.toSet()) } .single() } fun parseRucksacks(lines: Iterable<String>): List<Rucksack> = lines.map { line -> Rucksack(line) } fun groupRucksacks(rucksacks: List<Rucksack>, size: Int = 3): List<ElfGroup> = rucksacks.chunked(size).map { ElfGroup(it) } fun getItemPriority(item: Char): Int = when (item) { in 'a'..'z' -> item - 'a' + 1 in 'A'..'Z' -> item - 'A' + 27 else -> throw IllegalArgumentException("Unsupported item: '$item'") } fun getSumOfSharedItemPriorities(rucksacks: Iterable<Rucksack>): Int = rucksacks .map { it.findSharedItem() } .sumOf { getItemPriority(it) } fun getSumOfGroupBadges(groups: List<ElfGroup>): Int = groups .map { it.findBadge() } .sumOf { getItemPriority(it) }
0
Kotlin
0
0
1b1c6971bf45b89fd76bbcc503444d0d86617e95
1,779
advent-of-code
MIT License
src/Day05.kt
emersonf
572,870,317
false
{"Kotlin": 17689}
import java.util.* data class Instruction(val count: Int, val from: Int, val to: Int) typealias Stack = LinkedList<Char> fun main() { fun readStacksAndInstructions(input: List<String>): Pair<Array<Stack>, List<Instruction>> { val (instructionLines, stackLines) = input.partition { line -> line.startsWith("m") } val instructions = instructionLines.asInstructions() val stacks = stackLines .dropLast(1) // blank line .asStacks() return Pair(stacks, instructions) } fun part1(input: List<String>): String { val (stacks, instructions) = readStacksAndInstructions(input) instructions .forEach { instruction -> repeat(instruction.count) { stacks[instruction.to].push(stacks[instruction.from].pop()) } } return stacks.map { it.first() } .joinToString(separator = "") } fun part2(input: List<String>): String { val (stacks, instructions) = readStacksAndInstructions(input) instructions .forEach { instruction -> val fromStack = stacks[instruction.from] val toStack = stacks[instruction.to] for (index in instruction.count downTo 1) { toStack.push(fromStack[index - 1]) } repeat(instruction.count) { fromStack.pop() } } return stacks.map { it.first() } .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)) } private fun List<String>.asStacks(): Array<Stack> { val stackCount = last().substringAfterLast(" ").toInt() val stacks = Array(stackCount) { Stack() } for (lineIndex in size - 2 downTo 0) { val line = get(lineIndex) for (stack in 0 until stackCount) { val stackCharIndex = stack * 4 + 1 if (stackCharIndex > line.length) { break } val stackChar = line[stackCharIndex] if (stackChar == ' ') { continue } stacks[stack].push(stackChar) } } return stacks } private fun List<String>.asInstructions(): List<Instruction> { val regex = """move (\d+) from (\d+) to (\d+)\n?""".toRegex() return mapNotNull { line -> regex.matchEntire(line) ?.groupValues ?.subList(1, 4) ?.map(String::toInt) } .map { numbers -> Instruction(numbers[0], numbers[1] - 1, numbers[2] - 1) } } private fun print(stacks: Array<Stack>) { for (index in stacks.indices) { println("${index + 1}: " + stacks.get(index).joinToString()) } }
0
Kotlin
0
0
0e97351ec1954364648ec74c557e18ccce058ae6
3,016
advent-of-code-2022-kotlin
Apache License 2.0
src/main/kotlin/com/hopkins/aoc/day5/main.kt
edenrox
726,934,488
false
{"Kotlin": 88215}
package com.hopkins.aoc.day5 import java.io.File const val debug = true const val part = 2 /** Advent of Code 2023: Day 5 */ fun main() { // Read the input val lines: List<String> = File("input/input5.txt").readLines() // Step 1: read the seeds val (_, seedsPart) = lines[0].split(": ") val seedNumbers = seedsPart.split(" ").map { it.toLong() } val seedRanges = if (part == 1) { seedNumbers.map { LongRange(it, it) } } else { seedNumbers.zipWithNext{ a, b -> LongRange(a, a + b - 1)}.filterIndexed { index, _ -> index % 2 == 0} } if (debug) { println("Seed Ranges:") println(seedRanges) } // Step 2: read the Range increments val ranges = lines.drop(1).filter { it.isNotBlank() }.fold(mutableListOf<MutableList<RangeIncrement>>()) { acc, line -> if (line.endsWith("map:")) { acc.add(mutableListOf<RangeIncrement>()) } else { acc.last().add(parseRangeIncrement(line)) } acc } // Step 3: map the seeds through the ranges var current: List<LongRange> = seedRanges for (rangeList in ranges) { val splits: List<Long> = rangeList.flatMap { listOf(it.range.first, it.range.last)}.sorted().distinct() val splitRanges = current.flatMap { inputRange -> splitRange(inputRange, splits) } if (debug) { println("Range List: $rangeList") println("Splits: $splits") println("Split Ranges: $splitRanges") } current = splitRanges.map { inputRange -> var output = inputRange for (rangeIncrement in rangeList) { if (rangeIncrement.contains(inputRange)) { output = rangeIncrement.convert(inputRange) break } } output } } val minLocation = current.minOf { it.first } println("Minimum location: $minLocation") // Part 1: 621354867 // Part 2: } fun parseRangeIncrement(line: String): RangeIncrement { val (dest, src,length) = line.split(" ").map { it.toLong() } return RangeIncrement(LongRange(src, src + length - 1), dest - src) } data class RangeIncrement(val range: LongRange, val increment: Long) { fun contains(inputRange: LongRange) = range.contains(inputRange.first) fun convert(inputRange: LongRange) = LongRange(inputRange.first + increment, inputRange.last + increment) } fun splitRange(range: LongRange, splits: List<Long>): List<LongRange> { return if (splits.isEmpty()) { listOf(range) } else if (range.contains(splits.first())) { val (left, right) = splitRange(range, splits.first()) listOf(left) + splitRange(right, splits.drop(1)) } else { splitRange(range, splits.drop(1)) } } fun splitRange(range: LongRange, split: Long): List<LongRange> { require(range.contains(split)) return listOf(LongRange(range.start, split - 1), LongRange(split, range.last)) }
0
Kotlin
0
0
45dce3d76bf3bf140d7336c4767e74971e827c35
3,061
aoc2023
MIT License
advent-of-code-2023/src/test/kotlin/Day2Test.kt
yuriykulikov
159,951,728
false
{"Kotlin": 1666784, "Rust": 33275}
import io.kotest.matchers.shouldBe import org.junit.jupiter.api.Test /** [Day 2: Day 2: Cube Conundrum](https://adventofcode.com/2023/day/2) */ class Day2Test { data class Game( val gameId: Int, val sets: List<CubeSet>, ) { fun max(color: String): Int { return sets.maxOf { it.cubes[color] ?: 0 } } val power: Int get() { return listOf("red", "green", "blue") .map { color -> sets.maxOf { it.cubes[color] ?: 0 } } .reduce { acc, next -> acc * next } } } data class CubeSet( val cubes: Map<String, Int>, ) @Test fun `Silver - ids of possible games (example)`() { val input = """Game 1: 3 blue, 4 red; 1 red, 2 green, 6 blue; 2 green Game 2: 1 blue, 2 green; 3 green, 4 blue, 1 red; 1 green, 1 blue Game 3: 8 green, 6 blue, 20 red; 5 blue, 4 red, 13 green; 5 green, 1 red Game 4: 1 green, 3 red, 6 blue; 3 green, 6 red; 3 green, 15 blue, 14 red Game 5: 6 red, 1 blue, 3 green; 2 blue, 1 red, 2 green """ val games = parseGames(input) // only 12 red cubes, 13 green cubes, and 14 blue cubes? val possibleCode = games .filter { game -> game.max("red") <= 12 && game.max("green") <= 13 && game.max("blue") <= 14 } .sumOf { it.gameId } possibleCode shouldBe 8 } @Test fun `Silver - ids of possible games`() { val games = parseGames(loadResource("Day2")) // only 12 red cubes, 13 green cubes, and 14 blue cubes? val possibleCode = games .filter { game -> game.max("red") <= 12 && game.max("green") <= 13 && game.max("blue") <= 14 } .sumOf { it.gameId } possibleCode shouldBe 2061 } @Test fun `Gold - sum of set powers (example)`() { val input = """ Game 1: 3 blue, 4 red; 1 red, 2 green, 6 blue; 2 green Game 2: 1 blue, 2 green; 3 green, 4 blue, 1 red; 1 green, 1 blue Game 3: 8 green, 6 blue, 20 red; 5 blue, 4 red, 13 green; 5 green, 1 red Game 4: 1 green, 3 red, 6 blue; 3 green, 6 red; 3 green, 15 blue, 14 red Game 5: 6 red, 1 blue, 3 green; 2 blue, 1 red, 2 green """ .trimIndent() val games = parseGames(input) games.sumOf { it.power } shouldBe 2286 } @Test fun `Gold - sum of set powers`() { val games = parseGames(loadResource("Day2")) games.sumOf { it.power } shouldBe 72596 } private fun parseGames(input: String): List<Game> { return input .trim() .lines() .map { it.substringAfter("Game ").split(": ", limit = 2) } .map { (gameId, gameStr) -> val sets = gameStr.split("; ").map { setStr -> val colorToCount = setStr .split(", ") .map { it.split(" ") } .associate { (count, color) -> color to count.toInt() } CubeSet(colorToCount) } Game(gameId.toInt(), sets) } } }
0
Kotlin
0
1
f5efe2f0b6b09b0e41045dc7fda3a7565cb21db3
3,100
advent-of-code
MIT License
codeforces/globalround16/d.kt
mikhail-dvorkin
93,438,157
false
{"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408}
package codeforces.globalround16 private fun solve() { val (hei, wid) = readInts() val a = readInts() val places = mutableMapOf<Int, MutableList<Pair<Int, Int>>>() val aSorted = a.sorted() for (i in aSorted.indices) { places.getOrPut(aSorted[i]) { mutableListOf() }.add(i / wid to i % wid) } places.forEach { (_, list) -> list.sortBy { - it.first * wid + it.second } } val f = List(hei) { FenwickTree(wid) } val ans = a.sumOf { v -> val (x, y) = places[v]!!.removeLast() f[x].sum(y).also { f[x].add(y, 1) } } println(ans) } class FenwickTree(n: Int) { var t: LongArray fun add(index: Int, value: Long) { var i = index while (i < t.size) { t[i] += value i += i + 1 and -(i + 1) } } fun sum(index: Int): Long { var i = index var res: Long = 0 i-- while (i >= 0) { res += t[i] i -= i + 1 and -(i + 1) } return res } fun sum(start: Int, end: Int): Long { return sum(end) - sum(start) } operator fun get(i: Int): Long { return sum(i, i + 1) } operator fun set(i: Int, value: Long) { add(i, value - get(i)) } init { t = LongArray(n) } } fun main() = repeat(readInt()) { solve() } private fun readLn() = readLine()!! private fun readInt() = readLn().toInt() private fun readStrings() = readLn().split(" ") private fun readInts() = readStrings().map { it.toInt() }
0
Java
1
9
30953122834fcaee817fe21fb108a374946f8c7c
1,334
competitions
The Unlicense
2023/src/main/kotlin/day18.kt
madisp
434,510,913
false
{"Kotlin": 388138}
import utils.Parse import utils.Parser import utils.SegmentL import utils.Solution import utils.Vec2l import utils.mapItems fun main() { Day18.run() } object Day18 : Solution<List<Day18.Line>>() { override val name = "day18" override val parser = Parser.lines.mapItems { parseLine(it) } @Parse("{direction} {len} (#{color})") data class Line( val direction: String, val len: Long, val color: String, ) data class Instruction( val direction: Vec2l, val len: Long ) private fun solve(insns: List<Instruction>): Long { var location = Vec2l(0, 0) val segments = mutableListOf<SegmentL>() val areas = mutableListOf<Long>() insns.forEach { insn -> segments.add(SegmentL(location, location + (insn.direction * insn.len))) location += (insn.direction * insn.len) if (insn.direction.x != 0L) { areas.add(location.y) } } val edges = segments.map { if (it.start.y > it.end.y) SegmentL(it.end, it.start) else it } val sortedAreas = areas.toSet().sorted() val verts = edges.filter { it.isVertical } val hors = edges.filter { it.isHorizontal }.map { if (it.start.x > it.end.x) SegmentL(it.end, it.start) else it } var sz = 0L sortedAreas.windowed(2).forEach { (top, bottom) -> sz += countFilled(verts, hors, top) if (bottom > top + 1) { sz += countFilled(verts, hors, top + 1) * (bottom - top - 1) } } // add last bottom to the size sz += countFilled(verts, hors, sortedAreas.last()) return sz } private fun countFilled(verts: List<SegmentL>, hors: List<SegmentL>, y: Long): Long { var sz = 0L val topSq = verts.filter { y in minOf(it.start.y, it.end.y) .. maxOf(it.start.y, it.end.y) }.sortedBy { it.start.x } val horiz = hors.filter { it.start.y == y }.toSet() var fill = true for (i in 0 until topSq.size - 1) { val s1 = topSq[i] val s2 = topSq[i + 1] if (SegmentL(Vec2l(s1.start.x, y), Vec2l(s2.start.x, y)) in horiz) { // always add segments on this line sz += (s2.start.x - s1.start.x) val s1up = minOf(s1.start.y, s1.end.y) < y val s2up = minOf(s2.start.y, s2.end.y) < y if (s1up != s2up) { // twist only, it doesn't change current fill state fill = !fill } } else { if (fill) { sz += (s2.start.x - s1.start.x) } else sz += 1 } fill = !fill } sz += 1 // add the final right edge return sz } override fun part1(input: List<Line>): Long { val insns = input.map { line -> val direction = when (line.direction) { "R" -> Vec2l.RIGHT "D" -> Vec2l.DOWN "U" -> Vec2l.UP "L" -> Vec2l.LEFT else -> throw IllegalStateException("Unknown direction char ${line.direction}") } Instruction(direction, line.len) } return solve(insns) } override fun part2(): Long { val directions = listOf(Vec2l.RIGHT, Vec2l.DOWN, Vec2l.LEFT, Vec2l.UP) val corrected = input.map { line -> val direction = directions[line.color.last() - '0'] val len = line.color.substring(0, line.color.length - 1).toLong(16) Instruction(direction, len) } return solve(corrected) } }
0
Kotlin
0
1
3f106415eeded3abd0fb60bed64fb77b4ab87d76
3,280
aoc_kotlin
MIT License
src/Day08.kt
ajmfulcher
573,611,837
false
{"Kotlin": 24722}
fun main() { fun makeGrid(input: List<String>): List<List<Int>> { return input.map { line -> line.toCharArray().map { it.digitToInt() } } } fun List<List<Int>>.row(idx: Int) = this[idx] fun List<List<Int>>.col(idx: Int) = map { it[idx] } fun findVisible(row: List<Int>, isVisible: (Int) -> Unit) { var leftMax = Int.MIN_VALUE var rightMax = Int.MIN_VALUE var left = 0 var right = row.lastIndex while (right >= 0) { if (row[left] > leftMax) { isVisible(left) leftMax = row[left] } if (row[right] > rightMax) { isVisible(right) rightMax = row[right] } left += 1 right -= 1 } } fun part1(input: List<String>): Int { val grid = makeGrid(input) val lastRow = grid[0].lastIndex val lastCol = grid.lastIndex val visibility = Array(lastCol + 1) { IntArray(lastRow + 1) { 0 } } (0..lastRow).forEach { idx -> findVisible(grid.row(idx)) { col -> visibility[idx][col] = 1 } } (1..lastCol - 1).forEach { idx -> findVisible(grid.col(idx)) { row -> visibility[row][idx] = 1 } } return visibility .map { it.fold(0) { acc, i -> acc + i } } .fold(0) { acc, i -> acc + i } } fun scoreLinear(line: List<Int>, height: Int): Int { var score = 0 (0..line.lastIndex).forEach { idx -> score += 1 if (line[idx] >= height) return score } return score } fun score(line: List<Int>, idx: Int): Int { if (idx == 0 || idx == line.lastIndex) return 0 return scoreLinear(line.subList(idx + 1, line.size), line[idx]) * scoreLinear(line.subList(0, idx).reversed(), line[idx]) } fun viewingScore(grid: List<List<Int>>, row: Int, col: Int): Int { return score(grid.row(col), row) * score(grid.col(row), col) } fun part2(input: List<String>): Int { val grid = makeGrid(input) val lastRow = grid[0].lastIndex val lastCol = grid.lastIndex var maxScore = 0 (0..lastRow).forEach { row -> (0..lastCol).forEach { col -> val score = viewingScore(grid, row, col) if (score > maxScore) maxScore = score } } return maxScore } // test if implementation meets criteria from the description, like: val testInput = readInput("Day08_test") println(part1(testInput)) check(part1(testInput) == 21) val input = readInput("Day08") println(part1(input)) println(part2(testInput)) check(part2(testInput) == 8) println(part2(input)) }
0
Kotlin
0
0
981f6014b09e347241e64ba85e0c2c96de78ef8a
2,810
advent-of-code-2022-kotlin
Apache License 2.0
kata/src/main/kotlin/kata/HowGreenIsMyValley.kt
gualtierotesta
129,613,223
false
null
package kata import java.util.* import java.util.stream.Collectors.toList /* Input : an array of integers. Output : this array, but sorted in such a way that there are two wings: the left wing with numbers decreasing, the right wing with numbers increasing. the two wings have the same length. If the length of the array is odd the wings are around the bottom, if the length is even the bottom is considered to be part of the right wing. each integer l of the left wing must be greater or equal to its counterpart r in the right wing, the difference l - r being as small as possible. In other words the right wing must be nearly as steeply as the left wing. The function is make_valley or makeValley or make-valley. */ fun makeValley(arr: IntArray): IntArray { val sarr = arr.sortedArrayDescending() val n = sarr.size val half = n / 2 + (n % 2) val last = n - if (n % 2 == 0) 1 else 0 return (0 until n) .map { i -> if (i < half) sarr[i * 2] else sarr[last - ((i - n / 2) * 2)] } .toList().toIntArray() } fun makeValley2(arr:IntArray) = when (arr.size) { 1 -> arr else -> arr.sortedArrayDescending().withIndex().groupBy { it.index % 2 }.map { it.value.map { it.value } }.windowed(2) { it[0] + it[1].sorted() }.flatten().toIntArray() } fun makeValley3(arr:IntArray):IntArray { val answer = IntArray(arr.size) arr.sort() for (i in 0 until arr.size) { if (i % 2 == 0) { answer[i / 2] = arr[arr.size - 1 - i] } else { answer[arr.size - 1 - i / 2] = arr[arr.size - 1 - i] } } return answer } fun main(args: Array<String>) { val arr = arrayOf(79, 35, 54, 19, 35, 25) //val arr = arrayOf(67, 93, 100, -16, 65, 97, 92) val x = arr .sortedArrayDescending() .withIndex() .groupBy { it.index % 2 } //.map { it.value } //.map { it.value.map { it.value } } //.windowed(2) { it[0] + it[1].sorted() } //.flatten() //.forEach { println(it) } //.forEach { t, u -> println("t=$t u=$u") } //.forEach { i -> System.out.println("index=${i.index} value=${i.value}")} // else -> arr.sortedArrayDescending().withIndex().groupBy { it.index % 2 } // .map { it.value.map { it.value } }.windowed(2) { it[0] + it[1].sorted() }.flatten().toIntArray() }
0
Kotlin
0
0
8366bb3aed765fff7fb5203abce9a20177529a8e
2,537
PlayWithKotlin
Apache License 2.0
2022/src/main/kotlin/day2_func.kt
madisp
434,510,913
false
{"Kotlin": 388138}
import utils.Parser import utils.Solution import utils.badInput import utils.cut import utils.mapItems fun main() { Day2Func.run() } enum class Play(val score: Int) { Rock(1), Paper(2), Scissors(3); val winsOver: Play get() = when (this) { Rock -> Scissors Paper -> Rock Scissors -> Paper } val losesTo: Play get() = values().first { it.winsOver == this } companion object { fun fromL(left: Char): Play { return when (left) { 'A' -> Rock 'B' -> Paper 'C' -> Scissors else -> badInput() } } fun fromR(right: Char): Play { return when (right) { 'X' -> Rock 'Y' -> Paper 'Z' -> Scissors else -> badInput() } } } } val Pair<Play, Play>.score: Int get() { val outcome = when { second.winsOver == first -> 6 second == first -> 3 else -> 0 } return second.score + outcome } object Day2Func : Solution<List<Pair<Play, Char>>>() { override val name = "day2" override val parser = Parser.lines.mapItems { line -> line.cut(" ", { l -> Play.fromL(l[0]) }) { it[0] } } override fun part1(input: List<Pair<Play, Char>>): Number { return input .map { (play, char) -> play to Play.fromR(char) } .sumOf { it.score } } override fun part2(input: List<Pair<Play, Char>>): Number { return input.map { (play, char) -> val other = when (char) { 'X' -> play.winsOver // lose 'Y' -> play // draw 'Z' -> play.losesTo // win else -> badInput() } play to other }.sumOf { it.score } } }
0
Kotlin
0
1
3f106415eeded3abd0fb60bed64fb77b4ab87d76
1,605
aoc_kotlin
MIT License
src/Day02.kt
HylkeB
573,815,567
false
{"Kotlin": 83982}
import java.lang.IllegalArgumentException private sealed class Hand(val pickScore: Int) { protected abstract val winsVersus: Hand private val losesVersus: Hand get() = winsVersus.winsVersus fun winsVersus(other: Hand): Boolean { return winsVersus == other } fun getLosingHand(): Hand { return winsVersus } fun getWinningHand(): Hand { return losesVersus } } private object Rock : Hand(pickScore = 1) { override val winsVersus = Scissors } private object Paper : Hand(pickScore = 2) { override val winsVersus = Rock } private object Scissors : Hand(pickScore = 3) { override val winsVersus = Paper } fun main() { fun decodeHand(char: Char): Hand { return when (char) { in listOf('A', 'X') -> Rock in listOf('B', 'Y') -> Paper in listOf('C', 'Z') -> Scissors else -> throw IllegalArgumentException("Unknown hand: $char") } } // Rock - Paper - Scissors // A - B - C // X - Y - Z // 1 - 2 - 3 fun calculateGameScore(opponent: Hand, myself: Hand): Int { return when { opponent.winsVersus(myself) -> 0 myself.winsVersus(opponent) -> 6 else -> 3 } } fun part1(input: List<String>): Int { return input.sumOf { game -> val opponent = decodeHand(game[0]) val myself = decodeHand(game[2]) calculateGameScore(opponent, myself) + myself.pickScore } } // x = lose, y = draw, z = win fun part2(input: List<String>): Int { return input.sumOf { game -> val opponent = decodeHand(game[0]) val myself = when (game[2]) { 'X' -> opponent.getLosingHand() 'Y' -> opponent 'Z' -> opponent.getWinningHand() else -> throw IllegalArgumentException("Unknown outcome: ${game[2]}") } calculateGameScore(opponent, myself) + myself.pickScore } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day02_test") check(part1(testInput) == 15) check(part2(testInput) == 12) val input = readInput("Day02") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
8649209f4b1264f51b07212ef08fa8ca5c7d465b
2,302
advent-of-code-2022-kotlin
Apache License 2.0
src/main/kotlin/day16/Day16.kt
Mee42
433,459,856
false
{"Kotlin": 42703, "Java": 824}
package dev.mee42.day16 import dev.mee42.* sealed class Packet(val vNumber: Int) { data class LiteralValue(val value: Long, val vNum: Int): Packet(vNum) { override fun toString() = "$value" } data class Op(val packets: List<Packet>, val vNum: Int, val typeID: Int): Packet(vNum) { override fun toString() = when(this.typeID) { 0, 1, 2, 3 -> "" + mapOf(0 to "+", 1 to "*", 2 to "min", 3 to "max")[typeID] + "(" + packets.joinToString(", ") + ")" 5, 6, 7 -> "(" + packets[0] + " " + mapOf(5 to ">", 6 to "<", 7 to "=")[typeID] + " " + packets[1] + ")" else -> e() } } } fun Packet.versionSum(): Int = this.vNumber + when(this) { is Packet.LiteralValue -> 0 is Packet.Op -> packets.sumOf { it.versionSum() } } fun Packet.evalT(): Long = when (this) { is Packet.LiteralValue -> value is Packet.Op -> when (typeID) { 0 -> packets.sumOf { it.eval() } 1 -> packets.fold(1) { a, p -> a * p.eval() } 2 -> packets.minOf { it.eval() } 3 -> packets.maxOf { it.eval() } 5 -> if (packets[0].eval() > packets[1].eval()) 1 else 0 6 -> if (packets[0].eval() < packets[1].eval()) 1 else 0 7 -> if (packets[0].eval() == packets[1].eval()) 1 else 0 else -> error("got type id that was wrong $typeID") } } private var depth = 0 fun Packet.eval(): Long { println(" ".repeat(depth) + "==> $this") depth++ val res = evalT() depth-- println(" ".repeat(depth) + "<== $res") return res } fun main() { val input = input(16, 2021).trim().flatMap { digit -> digit.digitToInt(16).toString(2).padStart(4, '0').map(::id) } val parsed = parsePacket(ArrayDeque(input)) val part2 = parsed.eval() println("Part 1: " + parsed.versionSum()) println("Part 2: $part2") } fun parsePacket(bits: ArrayDeque<Char>): Packet { val packetVersion = bits.removeN(3).fromBin().toInt() val packetTypeID = bits.removeN(3).fromBin().toInt() if(packetTypeID == 4) { val literalValue = mutableListOf<Char>() while(true) { val nextFive = bits.removeN(5) literalValue.addAll(nextFive.drop(1)) if(nextFive.first() == '0') break } return Packet.LiteralValue(literalValue.fromBin(), packetVersion) } else { // it is an operator packet val lengthTypeID = bits.removeFirst() == '0' val packets = mutableListOf<Packet>() if(lengthTypeID) { val bitsOfNextPackets = bits.removeN(15).fromBin() val startingSize = bits.size while(bits.size > startingSize - bitsOfNextPackets) { packets.add(parsePacket(bits)) } } else { val numberOfNextPackets = bits.removeN(11).fromBin() for(n in 0 until numberOfNextPackets) { packets.add(parsePacket(bits)) } } return Packet.Op(packets, packetVersion, packetTypeID) } }
0
Kotlin
0
0
db64748abc7ae6a92b4efa8ef864e9bb55a3b741
3,022
aoc-2021
MIT License
src/Day16.kt
kpilyugin
572,573,503
false
{"Kotlin": 60569}
import kotlin.math.max fun main() { data class Valve(val id: String, val rate: Int, var tunnels: List<Pair<String, Int>>, val index: Int) { var opened = false fun needOpen() = rate > 0 && !opened } fun parseValves(input: List<String>): Map<String, Valve> { var index = 0 return input.associate { line -> val (valvePart, tunnelsPart) = line.split(";") val (valveStr, rateStr) = valvePart.split(" has") val id = valveStr.substringAfter("Valve ") val rate = rateStr.substringAfter("=").toInt() val tunnels = if ("valves" in tunnelsPart) tunnelsPart.substringAfter("valves ").split(", ") else listOf(tunnelsPart.substringAfter("valve ")) val valve = Valve(id, rate, tunnels.map { it to 1 }, index) index++ id to valve } } fun prepareValves(input: List<String>): Map<String, Valve> { val valves = parseValves(input).toMutableMap() val initial = valves["AA"]!! fun Valve.useful() = this == initial || rate > 0 fun Valve.replaceUnused() { val resolved = mutableListOf<Pair<String, Int>>() for ((id, dist) in tunnels) { val next = valves[id]!! if (next.useful()) { resolved += id to dist } else { resolved += next.tunnels.map { it.first to (it.second + dist) } } } tunnels = resolved.filter { it.first != id } .groupBy { it.first } .map { entry -> entry.key to entry.value.minOf { it.second } } } repeat(valves.size) { for (valve in valves.values) { valve.replaceUnused() } } valves.values.removeIf { !it.useful() } return valves } fun solve(valves: Map<String, Valve>, minutes: Int): Int { data class Key(val id: String, val minute: Int, val mask: Long) val memo = hashMapOf<Key, Int>() fun solveRecursive(minute: Int, sumOpened: Int, openedMask: Long, current: Valve): Int { if (minute > minutes) return 0 val key = Key(current.id, minute, openedMask) val existing = memo[key] if (existing != null) { return existing } var res = sumOpened * (minutes - minute + 1) if (current.needOpen()) { current.opened = true val newSum = sumOpened + current.rate val mask = openedMask or (1L shl current.index) res = max(res, sumOpened + solveRecursive(minute + 1, newSum, mask, current)) current.opened = false } for ((idNext, dist) in valves[current.id]!!.tunnels) { val valve = valves[idNext] if (valve != null && minute + dist <= minutes) { res = max(res, sumOpened * dist + solveRecursive(minute + dist, sumOpened, openedMask, valve)) } } memo[key] = res return res } return solveRecursive(1, 0, 0L, valves["AA"]!!) } fun part1(input: List<String>) = solve(prepareValves(input), 30) fun part2(input: List<String>): Int { val valves = prepareValves(input) val initial = valves["AA"]!! val list = valves.values.filter { it != initial } val maskAll = (1 shl list.size) - 1 var res = 0 for (mask in 0..maskAll) { val set1 = mutableMapOf<String, Valve>().apply { put(initial.id, initial) } val set2 = mutableMapOf<String, Valve>().apply { put(initial.id, initial) } for (i in list.indices) { if ((mask and (1 shl i)) != 0) { set1[list[i].id] = list[i] } else { set2[list[i].id] = list[i] } } res = max(res, solve(set1, 26) + solve(set2, 26)) } return res } val testInput = readInputLines("Day16_test") check(part1(testInput), 1651) check(part2(testInput), 1707) val input = readInputLines("Day16") println(part1(input)) println(part2(input)) }
0
Kotlin
0
1
7f0cfc410c76b834a15275a7f6a164d887b2c316
4,329
Advent-of-Code-2022
Apache License 2.0
src/Day05.kt
niltsiar
572,887,970
false
{"Kotlin": 16548}
fun main() { fun part1(input: List<String>): String { val stacks = processStacks(input[0]) val instructions = processInstructions(input[1]) instructions.forEach { instruction -> val number = instruction.first val from = instruction.second - 1 val to = instruction.third - 1 for (i in 1..number) { val crate = stacks[from].removeFirst() stacks[to].add(0, crate) } } return stacks.joinToString("") { it.first().toString() } } fun part2(input: List<String>): String { val stacks = processStacks(input[0]) val instructions = processInstructions(input[1]) instructions.forEach { instruction -> val number = instruction.first val from = instruction.second - 1 val to = instruction.third - 1 val crates = stacks[from].take(number) for (i in 1..number) { stacks[from].removeFirst() } stacks[to].addAll(0, crates) } return stacks.joinToString("") { it.first().toString() } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day05_test", "\n\n") check(part1(testInput) == "CMZ") check(part2(testInput) == "MCD") val input = readInput("Day05", "\n\n") println(part1(input)) println(part2(input)) } private fun processStacks(input: String): List<MutableList<Char>> { val cratesPerLine = input .split('\n') .dropLast(1) .map { it.chunked(4) } val numStacks = cratesPerLine.first().size val stacks = List(numStacks) { mutableListOf<Char>() } cratesPerLine.forEach { line -> line.forEachIndexed { index, s -> if (s[1].isLetter()) { stacks[index].add(s[1]) } } } return stacks } private fun processInstructions(input: String): List<Triple<Int, Int, Int>> { val instructionRegex = Regex("move (\\d+) from (\\d+) to (\\d+)") return input.split('\n') .filter { line -> line.isNotBlank() } .map { line -> val match = instructionRegex.matchEntire(line) ?: error("BAD INPUT") Triple(match.groupValues[1].toInt(), match.groupValues[2].toInt(), match.groupValues[3].toInt()) } }
0
Kotlin
0
0
766b3e168fc481e4039fc41a90de4283133d3dd5
2,392
advent-of-code-kotlin-2022
Apache License 2.0
src/day12/Day12.kt
spyroid
433,555,350
false
null
package day12 import readInput import kotlin.system.measureTimeMillis fun main() { fun find1(map: Map<String, List<String>>, el: String, target: String, visited: MutableSet<String>, cPath: MutableList<String>, distinctPaths: MutableSet<List<String>>) { if (el == target) { val copy = cPath.toMutableList() copy += target distinctPaths += copy return } if (el in visited) { return } if (el[0].isLowerCase()) { visited += el } cPath += el for (v in map[el]!!) { find1(map, v, target, visited, cPath, distinctPaths) } if (el[0].isLowerCase()) { visited -= el } cPath.removeAt(cPath.lastIndex) } fun toMap(input: List<String>): Map<String, List<String>> { val adj = mutableMapOf<String, MutableList<String>>() for (line in input) { val (u, v) = line.split("-") adj.getOrPut(u) { mutableListOf() } += v adj.getOrPut(v) { mutableListOf() } += u } return adj } fun part1(input: List<String>): Int { val paths = mutableSetOf<List<String>>() find1(toMap(input), "start", "end", mutableSetOf(), mutableListOf(), paths) return paths.size } fun find2(map: Map<String, List<String>>, el: String, target: String, visited: MutableMap<String, Int>, cPath: MutableList<String>, distinctPaths: MutableSet<List<String>>) { if (el == target) { val copy = cPath.toMutableList() copy += target distinctPaths += copy return } if (el in visited && (el == "start" || visited[el] == 2 || cPath.any { x -> visited[x] == 2 })) { return } if (el[0].isLowerCase()) { visited[el] = (visited[el] ?: 0) + 1 } cPath += el for (v in map[el]!!) { find2(map, v, target, visited, cPath, distinctPaths) } if (el[0].isLowerCase()) { if (visited[el] == 1) { visited -= el } else { visited[el] = visited[el]!! - 1 } } cPath.removeAt(cPath.lastIndex) } fun part2(input: List<String>): Int { val paths = mutableSetOf<List<String>>() find2(toMap(input), "start", "end", mutableMapOf(), mutableListOf(), paths) return paths.size } val testData = readInput("day12/test") val inputData = readInput("day12/input") var res1 = part1(testData) check(res1 == 10) { "Expected 10 but got $res1" } var time = measureTimeMillis { res1 = part1(inputData) } println("Part1: $res1 in $time ms") time = measureTimeMillis { res1 = part2(inputData) } println("Part2: $res1 in $time ms") }
0
Kotlin
0
0
939c77c47e6337138a277b5e6e883a7a3a92f5c7
2,875
Advent-of-Code-2021
Apache License 2.0
src/day02/Day02.kt
palpfiction
572,688,778
false
{"Kotlin": 38770}
package day02 import readInput sealed interface Choice object Rock : Choice object Paper : Choice object Scissors : Choice sealed interface Outcome object Win : Outcome object Lose : Outcome object Draw : Outcome fun main() { fun Choice.score() = when (this) { Rock -> 1 Paper -> 2 Scissors -> 3 } fun Choice.againstValue(other: Choice) = when { this == Rock && other == Paper -> 0 this == Rock && other == Scissors -> 6 this == Paper && other == Scissors -> 0 this == Paper && other == Rock -> 6 this == Scissors && other == Rock -> 0 this == Scissors && other == Paper -> 6 else -> 3 } fun computeTurnScore(opponent: Choice, mine: Choice): Int = mine.againstValue(opponent) + mine.score() fun String.toOpponentChoice() = when (this) { "A" -> Rock "B" -> Paper "C" -> Scissors else -> throw Error("Error parsing opponent") } fun String.toMyChoice() = when (this) { "X" -> Rock "Y" -> Paper "Z" -> Scissors else -> throw Error("Error parsing my choice") } fun parseLine(line: String): Pair<Choice, Choice> { val (opponent, mine) = line.split(" ") return Pair(opponent.toOpponentChoice(), mine.toMyChoice()) } fun part1(input: List<String>): Int = input .map { line -> parseLine(line) } .sumOf { (opponent, mine) -> computeTurnScore(opponent, mine) } fun String.toOutcome() = when (this) { "X" -> Lose "Y" -> Draw "Z" -> Win else -> throw Error("Error parsing outcome") } fun Outcome.opposite() = when (this) { Draw -> Draw Win -> Lose Lose -> Win } fun Choice.against(other: Choice): Outcome = when { this == other -> Draw this == Rock && other == Paper -> Lose this == Rock && other == Scissors -> Win this == Paper && other == Scissors -> Lose else -> other.against(this).opposite() } fun getChoice(opponent: Choice, outcome: Outcome) = listOf(Rock, Paper, Scissors) .find { it.against(opponent) == outcome }!! fun parseLine2(line: String): Pair<Choice, Outcome> { val (choice, outcome) = line.split(" ") return Pair(choice.toOpponentChoice(), outcome.toOutcome()) } fun part2(input: List<String>): Int = input .map { parseLine2(it) } .sumOf { (choice, outcome) -> computeTurnScore(choice, getChoice(choice, outcome)) } val testInput = readInput("/day02/Day02_test") check(part1(testInput) == 15) check(part2(testInput) == 12) val input = readInput("/day02/Day02") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
5b79ec5fa4116e496cd07f0c7cea7dabc8a371e7
2,808
advent-of-code
Apache License 2.0
src/main/kotlin/days/y2023/day15/Day15.kt
jewell-lgtm
569,792,185
false
{"Kotlin": 161272, "Jupyter Notebook": 103410, "TypeScript": 78635, "JavaScript": 123}
package days.y2023.day15 import util.InputReader typealias PuzzleInput = String class Day15(val input: PuzzleInput) { fun partOne(): Int { // Determine the ASCII code for the current character of the string. // Increase the current value by the ASCII code you just determined. // Set the current value to itself multiplied by 17. // Set the current value to the remainder of dividing itself by 256. return input.split(",").sumOf { str -> str.fold(0 as Int) { hash, c -> ((hash + c.toInt()) * 17) % 256 } } } fun partTwo(): Int { val operations = input.split(",").map { when { it.last() == '-' -> Operation.Minus( it.dropLast(1), it.dropLast(1).fold(0) { hash, c -> ((hash + c.toInt()) * 17) % 256 } ) it.contains('=') -> it.split('=').let { (label, int) -> Operation.Eq( label, label.fold(0) { hash, c -> ((hash + c.toInt()) * 17) % 256 }, int.toInt() ) } else -> error("Unknown operation: $it") } } val boxes = mutableMapOf<Int, MutableList<Lens>>() for (op in operations) { when (op) { is Operation.Minus -> { val box = boxes[op.hash] ?: mutableListOf() box.removeAll { it.label == op.label } boxes[op.hash] = box } is Operation.Eq -> { val box = boxes[op.hash] ?: mutableListOf() val i = box .indexOfFirst { it.label == op.label } .takeIf { it != -1 } ?: box.size box[i] = Lens(op.label, op.focalLength) boxes[op.hash] = box } } } return (0..255).map { boxes[it] ?: mutableListOf() }.mapIndexed { i, lenses -> val box = i + 1 (lenses.mapIndexed { j, lens -> val slot = j + 1 val result = box * slot * lens.focalLength result }.sum()) }.sum() } data class Lens( val label: String, val focalLength: Int ) sealed class Operation { abstract val label: String abstract val hash: Int data class Minus( override val label: String, override val hash: Int, ) : Operation() data class Eq( override val label: String, override val hash: Int, val focalLength: Int ) : Operation() } } fun main() { val year = 2023 val day = 15 val exampleInput: PuzzleInput = InputReader.getExample(year, day) val puzzleInput: PuzzleInput = InputReader.getPuzzle(year, day) fun partOne(input: PuzzleInput) = Day15(input).partOne() fun partTwo(input: PuzzleInput) = Day15(input).partTwo() println("HASH: ${partOne("HASH")}") println("Example 1: ${partOne(exampleInput)}") println("Puzzle 1: ${partOne(puzzleInput)}") println("Example 2: ${partTwo(exampleInput)}") println("Puzzle 2: ${partTwo(puzzleInput)}") }
0
Kotlin
0
0
b274e43441b4ddb163c509ed14944902c2b011ab
3,459
AdventOfCode
Creative Commons Zero v1.0 Universal
src/main/kotlin/Day18.kt
todynskyi
573,152,718
false
{"Kotlin": 47697}
fun main() { fun part1(input: List<Coordinate>): Int = input.sumOf { it.neighbors().count { p -> p !in input } } fun part2(input: List<Coordinate>): Int { val minX = input.minBy { it.x }.x val minY = input.minBy { it.y }.y val minZ = input.minBy { it.z }.z val maxX = input.maxBy { it.x }.x val maxY = input.maxBy { it.y }.y val maxZ = input.maxBy { it.z }.z val area = mutableSetOf<Coordinate>() val start = Coordinate(minX - 1, minY - 1, minZ - 1) area.add(start) val queue = mutableListOf(start) while (queue.isNotEmpty()) { for (neighbor in queue.removeLast().neighbors()) { if (neighbor.x in minX - 1..maxX + 1 && neighbor.y in minY - 1..maxY + 1 && neighbor.z in minZ - 1..maxZ + 1 && neighbor !in input && area.add(neighbor) ) { queue.add(neighbor) } } } return input.sumOf { it.neighbors().count { p -> p in area } } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day18_test").toCoordinates() check(part1(testInput) == 64) println(part2(testInput)) val input = readInput("Day18").toCoordinates() println(part1(input)) println(part2(input)) } fun List<String>.toCoordinates(): List<Coordinate> = this.map { val (x, y, z) = it.split(",") Coordinate(x.toInt(), y.toInt(), z.toInt()) } data class Coordinate(val x: Int, val y: Int, val z: Int) { fun neighbors() = listOf( copy(x = x - 1), copy(x = x + 1), copy(y = y - 1), copy(y = y + 1), copy(z = z - 1), copy(z = z + 1), ) }
0
Kotlin
0
0
5f9d9037544e0ac4d5f900f57458cc4155488f2a
1,803
KotlinAdventOfCode2022
Apache License 2.0
src/Day03.kt
sebokopter
570,715,585
false
{"Kotlin": 38263}
fun main() { /** * a..z => 1..26 * A..Z => 27..52 */ fun priority(char: Char): Int { val priority = if (char.isLowerCase()) char - 'a' else char - 'A' + 26 //priority index starts with 1 return priority + 1 } fun findCommonItem(rucksacks: List<Set<Char>>): Char = rucksacks.reduce { rucksack1, rucksack2 -> rucksack1 intersect rucksack2 }.single() fun commonItemByCompartments(it: String): Char { val (length, items) = it.length to it return findCommonItem(items.chunked(length / 2) { it.toSet() }) } fun part1(input: List<String>): Int = input.sumOf { priority(commonItemByCompartments(it)) } fun commonItemByRucksacks(rucksacks: List<String>): Char = findCommonItem(rucksacks.map { it.toSet() }) fun part2(input: List<String>): Int = input.chunked(3).sumOf { rucksacks -> priority(commonItemByRucksacks(rucksacks)) } val testInput = readInput("Day03_test") println("part1(testInput): " + part1(testInput)) println("part2(testInput): " + part2(testInput)) check(part1(testInput) == 157) check(part2(testInput) == 70) val input = readInput("Day03") println("part1(input): " + part1(input)) println("part2(input): " + part2(input)) }
0
Kotlin
0
0
bb2b689f48063d7a1b6892fc1807587f7050b9db
1,308
advent-of-code-2022
Apache License 2.0
src/day03/Day03.kt
barbulescu
572,834,428
false
{"Kotlin": 17042}
package day03 import readInput import kotlin.streams.toList fun main() { val total = readInput("day03/Day03") .asSequence() .map(::toPriorities) .map { it.chunked(it.size / 2) } .onEach { require(it[0].size == it[1].size) } .map { it[0].intersect(it[1].toSet()) } .onEach { require(it.size == 1) } .sumOf { it.first() } println("Total: $total") val badgeTotal = readInput("day03/Day03") .asSequence() .map(::toPriorities) .chunked(3) .onEach { require(it.size == 3) { "each group must have 3 elves" } } .map { findBadge(it) } .onEach { require(it.size == 1) { "only 1 badge must be common" } } .map { it.first() } .sum() println("Badge total: $badgeTotal") } fun findBadge(group: List<List<Int>>): Set<Int> = group[0].intersect(group[1].toSet()).intersect(group[2].toSet()) fun split(line: String): Pair<String, String> { val middle = line.length / 2 return line.substring(0, middle) to line.substring(middle) } fun toPriorities(line: String): List<Int> { return line.chars() .map { toPriority(it) } .toList() } fun toPriority(value: Int): Int { return when (value) { in 97..122 -> value - 96 in 65..90 -> value - 38 else -> error("Value $value not supported") } }
0
Kotlin
0
0
89bccafb91b4494bfe4d6563f190d1b789cde7a4
1,374
aoc-2022-in-kotlin
Apache License 2.0
aoc-2023/src/main/kotlin/aoc/aoc12d.kts
triathematician
576,590,518
false
{"Kotlin": 615974}
import aoc.AocParser.Companion.parselines import aoc.* import aoc.util.getDayInput val testInput = """ ???.### 1,1,3 .??..??...?##. 1,1,3 ?#?#?#?#?#?#?#? 1,3,1,6 ????.#...#... 4,1,1 ????.######..#####. 1,6,5 ?###???????? 3,2,1 """.parselines class Springs(_line: String, val nums: List<Int>) { val max = nums.maxOrNull()!! val line = "." + _line .replace("?" + "#".repeat(max), "." + "#".repeat(max)) .replace("#".repeat(max) + "?", "#".repeat(max) + ".") .replace("[.]+".toRegex(), ".") // create five copies of line joined by "?" fun unfold() = Springs( "." + (1..5).joinToString("?") { line.drop(1) }, (1..5).flatMap { nums } ) fun arrangements2(print: Boolean): Long { val res2 = arrangementsCached(line, nums) if (print) { println("$line $nums res2 $res2") } return res2 } } val cache = mutableMapOf<String, Long>() fun arrangementsCached(str: String, nums: List<Int>): Long { if (str.length > 30) return arrangements2(str, nums) val case = "$str ${nums.joinToString(",")}" if (case in cache) return cache[case]!! val res = arrangements2(str, nums) cache[case] = res return res } fun arrangements2(str: String, nums: List<Int>): Long { if (nums.isEmpty()) return if ('#' in str) 0 else 1 val needToFind = nums.sum() val minLength = needToFind + nums.size - 1 val hashCount = str.count { it == '#' } if (str.length < minLength || needToFind < hashCount) return 0 val i = nums.indices.maxBy { nums[it] } val n = nums[i] val match = "[?.](?=[#?]{$n}([?.]|$))".toRegex() var sum = 0L match.findAll(str).forEach { val strLeft = str.substring(0, it.range.first) val strRight = str.substring(it.range.last + n + 1) val numLeft = arrangementsCached(strLeft, nums.take(i)) val numRight = arrangementsCached(strRight, nums.drop(i + 1)) sum += numLeft * numRight } // if (str.length >= 3) // println("$str $nums $sum") return sum } fun String.parse() = Springs(chunk(0), chunk(1).split(",").map { it.toInt() }) // part 1 fun List<String>.part1(): Long = sumOf { print(".") it.parse().arrangements2(print = false) }.also { println() } // part 2 fun List<String>.part2(): Long = withIndex().sumOf { val mod = (size / 100).coerceAtLeast(1) if (it.index % mod == 0) print("x") else print(".") it.value.parse().unfold().arrangements2(print = false) }.also { println() } // calculate answers val day = 12 val input = getDayInput(day, 2023) val testResult = testInput.part1().also { it.print } val answer1 = input.part1().also { it.print } val testResult2 = testInput.part2().also { it.print } val answer2 = input.part2().also { it.print } // print results AocRunner(day, test = { "$testResult, $testResult2" }, part1 = { answer1 }, part2 = { answer2 } ).run()
0
Kotlin
0
0
7b1b1542c4bdcd4329289c06763ce50db7a75a2d
2,993
advent-of-code
Apache License 2.0
advent-of-code-2020/src/main/kotlin/eu/janvdb/aoc2020/day17/Day17.kt
janvdbergh
318,992,922
false
{"Java": 1000798, "Kotlin": 284065, "Shell": 452, "C": 335}
package eu.janvdb.aoc2020.day17 import eu.janvdb.aocutil.kotlin.Combinations import eu.janvdb.aocutil.kotlin.MinMax import eu.janvdb.aocutil.kotlin.readLines fun main() { run(numberOfDimensions = 3) run(numberOfDimensions = 4) } private fun run(numberOfDimensions: Int) { println("$numberOfDimensions dimensions") val initialState = readInitialState("input17.txt", numberOfDimensions) initialState.print() var currentState = initialState for (i in 0 until 6) { println("Step $i") currentState = currentState.step() } currentState.print() println("${currentState.numberActive} cubes are active.") } fun readInitialState(fileName: String, numberOfDimensions: Int): Universe { val lines = readLines(2020, fileName) val points = mutableSetOf<Point>() for (y in lines.indices) { for (x in lines[y].indices) { if (lines[y][x] == '#') { val coordinates = MutableList(numberOfDimensions) { 0 } coordinates[0] = x coordinates[1] = y points += Point(coordinates) } } } return Universe(points) } data class Point(val coordinates: List<Int>) data class Universe(val activeCubes: Set<Point>) { private val numberOfDimensions = activeCubes.first().coordinates.size private val minimums = IntRange(0, numberOfDimensions - 1) .map { index -> activeCubes.minOfOrNull { point -> point.coordinates[index] } ?: 0 } private val maximums = IntRange(0, numberOfDimensions - 1) .map { index -> activeCubes.maxOfOrNull { point -> point.coordinates[index] } ?: 0 } val numberActive get() = activeCubes.size fun step(): Universe { fun shouldBeActiveInNextRound(point: Point): Boolean { fun countNeighbours(point: Point): Int { val minMaxes = IntRange(0, numberOfDimensions - 1) .map { MinMax(point.coordinates[it] - 1, point.coordinates[it] + 1) } return Combinations.iterate(minMaxes).map(::Point).count { it != point && this.hasActiveCube(it) } } val count = countNeighbours(point) val currentActive = hasActiveCube(point) return count == 3 || (currentActive && count == 2) } val minMaxes = IntRange(0, numberOfDimensions - 1).reversed().map { MinMax(minimums[it] - 1, maximums[it] + 1) } val newActiveCubes = Combinations.iterate(minMaxes).map(List<Int>::reversed).map(::Point) .filter(::shouldBeActiveInNextRound) .toSet() return Universe(newActiveCubes) } fun print() { val minMaxes = IntRange(0, numberOfDimensions - 1).reversed().map { MinMax(minimums[it], maximums[it]) } Combinations.iterate(minMaxes).map(List<Int>::reversed).forEach { coordinates -> val newLine = coordinates[0] == minimums[0] if (newLine) println() val newBlock = newLine && coordinates[1] == minimums[1] if (newBlock) { println("At ${coordinates.subList(2, numberOfDimensions)}") } if (hasActiveCube(Point(coordinates))) print('#') else print('.') } println() } private fun hasActiveCube(point: Point): Boolean { return activeCubes.contains(point) } }
0
Java
0
0
78ce266dbc41d1821342edca484768167f261752
2,960
advent-of-code
Apache License 2.0
src/main/kotlin/Day08.kt
akowal
434,506,777
false
{"Kotlin": 30540}
import Day08.Segment.* import java.util.* fun main() { println(Day08.solvePart1()) println(Day08.solvePart2()) } object Day08 { private val entries = readInput("day08") .map { val patterns = it.substringBefore("|").trim().split(' ') val output = it.substringAfter("|").trim().split(' ') Entry(patterns, output) } fun solvePart1() = entries.flatMap { it.output }.count { it.length in setOf(2, 3, 4, 7) } fun solvePart2() = entries.map { decipher(it) }.sum() private fun decipher(entry: Entry): Int { val wiring = decipherWiring(entry) return entry.output.map { it.map { c -> wiring[c]!! } } .map { it.toSet() } .map { digitBySegments[it]!! } .fold(0) { acc, digit -> acc * 10 + digit } } private fun decipherWiring(entry: Entry): Map<Char, Segment> { val patternByLen = entry.patterns.groupBy(String::length, String::toSet) val p1 = patternByLen[2]!!.single() val p7 = patternByLen[3]!!.single() val p4 = patternByLen[4]!!.single() val p8 = patternByLen[7]!!.single() val len5common = patternByLen[5]!!.reduce(Set<Char>::intersect) val len6common = patternByLen[6]!!.reduce(Set<Char>::intersect) val wiring = mutableMapOf<Char, Segment>() fun wiring(vararg segments: Segment) = wiring.filterValues { segments.contains(it) }.keys fun wire(segment: Segment, set: Set<Char>) { wiring[set.single()] = segment } wire(T, (p7 - p1)) wire(BR, (len6common % p1)) wire(TR, (p1 - wiring(BR))) wire(TL, (len6common % p4 - wiring(BR))) wire(M, (p4 - wiring(TL, TR, BR))) wire(B, (len5common - wiring(T, M))) wire(BL, (p8 - wiring(T, B, M, TL, TR, BR))) return wiring } /* T +--+ TL | | TR +--+<--M BL | | BR +--+ B */ enum class Segment { T, B, TL, TR, BL, BR, M } operator fun <T> Set<T>.rem(other: Set<T>) = this.intersect(other) val digitBySegments = mapOf( // @formatter:off setOf( TR, BR) to 1, setOf(T, TR, BR) to 7, setOf( M, TL, TR, BR) to 4, setOf(T, B, M, TL, TR, BL, BR) to 8, setOf(T, B, M, TR, BL ) to 2, setOf(T, B, M, TR, BR) to 3, setOf(T, B, M, TL, BR) to 5, setOf(T, B, M, TL, BL, BR) to 6, setOf(T, B, M, TL, TR, BR) to 9, setOf(T, B, TL, TR, BL, BR) to 0, // @formatter:on ) private data class Entry( val patterns: List<String>, val output: List<String>, ) }
0
Kotlin
0
0
08d4a07db82d2b6bac90affb52c639d0857dacd7
2,766
advent-of-kode-2021
Creative Commons Zero v1.0 Universal
src/day02/Day02.kt
zypus
573,178,215
false
{"Kotlin": 33417, "Shell": 3190}
package day02 import AoCTask // https://adventofcode.com/2022/day/2 enum class RPSMove(val score: Int) { ROCK(1), PAPER(2), SCISSORS(3); infix fun vs(other: RPSMove) = when (other) { this -> RPSOutcome.DRAW this.beats() -> RPSOutcome.WIN else -> RPSOutcome.LOSS } fun beats() = when(this) { ROCK -> SCISSORS PAPER -> ROCK SCISSORS -> PAPER } fun beatenBy() = beats().beats() } enum class RPSOutcome(val score: Int) { LOSS(0), DRAW(3), WIN(6) } class RPSRound(val opponent: RPSMove, val me: RPSMove) { companion object { fun fromOpponentString(string: String): RPSRound { val (op, me) = string.split(" ") return RPSRound( opponent = when(op) { "A" -> RPSMove.ROCK "B" -> RPSMove.PAPER else -> RPSMove.SCISSORS }, me = when(me) { "X" -> RPSMove.ROCK "Y" -> RPSMove.PAPER else -> RPSMove.SCISSORS } ) } fun fromInstructionString(string: String): RPSRound { val (op, instruction) = string.split(" ") val opponent = when (op) { "A" -> RPSMove.ROCK "B" -> RPSMove.PAPER else -> RPSMove.SCISSORS } return RPSRound( opponent = opponent, me = when(instruction) { "X" -> opponent.beats() "Y" -> opponent else -> opponent.beatenBy() } ) } } fun outcome() = me vs opponent fun score() = outcome().score + me.score } fun part1(input: List<String>): Int { val totalScore = input.map { RPSRound.fromOpponentString(it) }.sumOf { it.score() } return totalScore } fun part2(input: List<String>): Int { val totalScore = input.map { RPSRound.fromInstructionString(it) }.sumOf { it.score() } return totalScore } fun main() = AoCTask("day02").run { // test if implementation meets criteria from the description, like: check(part1(testInput) == 15) check(part2(testInput) == 12) println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
f37ed8e9ff028e736e4c205aef5ddace4dc73bfc
2,377
aoc-2022
Apache License 2.0
src/main/kotlin/days/Day9Solution.kt
yigitozgumus
434,108,608
false
{"Kotlin": 17835}
package days import BaseSolution class Day9Solution(inputList: List<String>) : BaseSolution(inputList) { private val grids = inputList.mapTo(mutableListOf()) { it.split("").filter { it != "" }.mapTo(mutableListOf()) { it.toInt() } }.also { it.forEach { grid -> grid.add(grid.size, 9) grid.add(0, 9) } it.add(it.size, MutableList(it.first().size) { 9 }) it.add(0, MutableList(it.first().size) { 9 }) } private fun getNeighbors(row: Int, col: Int): List<Int> = listOf(-1 to 0, 1 to 0, 0 to -1, 0 to 1).map { grids[row + it.first][col + it.second] } private fun getCheckList(row: Int, col: Int): Boolean = getNeighbors(row, col).minOf { it } > grids[row][col] override fun part1() { (1..grids.size - 2).map { row -> (1..grids.first().size - 2).map { col -> if (getCheckList(row, col)) grids[row][col] + 1 else 0 } }.sumOf { it.sum() }.also { println(it) } } override fun part2() { (1..grids.size - 2).map { row -> (1..grids.first().size - 2).map { col -> if (getCheckList(row, col)) computeBasinSize(row, col) else 0 } }.flatten().sortedBy { it }.reversed().also { println(it.take(3).reduce { acc, i -> acc * i }) } } private fun computeBasinSize(row: Int, col: Int): Int { val visited = mutableListOf<Pair<Int, Int>>() fun search(row: Int, col: Int) { visited.add(row to col) listOf(-1 to 0, 1 to 0, 0 to -1, 0 to 1).map { row + it.first to col + it.second }.forEach { if (grids[it.first][it.second] == 9) return@forEach if (visited.contains(it).not()) { search(it.first, it.second) } else return@forEach } } search(row, col) return visited.count() } }
0
Kotlin
0
0
c0f6fc83fd4dac8f24dbd0d581563daf88fe166a
1,939
AdventOfCode2021
MIT License
src/main/kotlin/com/oocode/Almanac.kt
ivanmoore
725,978,325
false
{"Kotlin": 42155}
package com.oocode fun almanacFrom(input: String): Almanac { val lines = input.split("\n") val seedNumbers = lines[0].split(" ").drop(1).map { it.toLong() } val seeds = seedNumbers.chunked(2).map { val startNumber = it[0] val rangeSize = it[1] InputRange(startNumber, (startNumber + rangeSize) - 1) } val converters = mutableListOf<Converter>() var currentMappings = mutableListOf<Mapping>() lines.drop(1).forEach { line -> if (line.isEmpty()) { if (currentMappings.isNotEmpty()) converters.add(Converter(currentMappings)) currentMappings = mutableListOf() } else { val numbers = numbersFrom(line) if (numbers.isNotEmpty()) { currentMappings.add(Mapping(numbers[0], numbers[1], numbers[2])) } } } if (currentMappings.isNotEmpty()) converters.add(Converter(currentMappings)) return Almanac(seeds, ConverterChain(converters)) } data class InputRange(val startNumber: Long, val endNumber: Long) private fun numbersFrom(line: String) = Regex("(\\d+)") .findAll(line) .map { it.value.toLong() } .toList() class Almanac(private val seeds: List<InputRange>, private val converterChain: ConverterChain) { fun lowestLocationNumber() = seeds.flatMap { converterChain.convert(it) }.map { it.startNumber }.min() } data class Mapping( private val destinationRangeStart: Long, private val sourceRangeStart: Long, private val rangeLength: Long, ) { val sourceRange = LongRange(sourceRangeStart, sourceRangeStart + rangeLength - 1) fun find(sourceNumber: Long) = if (sourceRange.contains(sourceNumber)) destinationRangeStart + (sourceNumber - sourceRangeStart) else null } class Converter(private val mappings: List<Mapping>) { fun convert(sourceNumber: Long) = mappings.firstNotNullOfOrNull { it.find(sourceNumber) } ?: sourceNumber fun convert(inputRanges: Set<InputRange>): Set<InputRange> = inputRanges.flatMap { convert(it) }.toSet() fun convert(inputRange: InputRange): Set<InputRange> { val mappingsInOrder = overlappingMappings(inputRange) if (mappingsInOrder.isEmpty()) { return setOf(inputRange) } val firstMappingSourceRange = mappingsInOrder[0].sourceRange val firstMappingStart = firstMappingSourceRange.start if (inputRange.startNumber < firstMappingStart) { return setOf(inputRange.copy(endNumber = firstMappingStart - 1)) + convert(inputRange.copy(startNumber = firstMappingStart)) } if (inputRange.endNumber <= firstMappingSourceRange.endInclusive) { return mapped(inputRange) } return mapped(inputRange.copy(endNumber = firstMappingSourceRange.endInclusive)) + convert(inputRange.copy(startNumber = firstMappingSourceRange.endInclusive + 1)) } private fun mapped(inputRange: InputRange): Set<InputRange> = setOf(InputRange(convert(inputRange.startNumber), convert(inputRange.endNumber))) private fun overlappingMappings(inputRange: InputRange) = mappings .sortedBy { it.sourceRange.first } .filter { it.sourceRange.overlapsWith(inputRange) } } private fun LongRange.overlapsWith(inputRange: InputRange) = !(inputRange.endNumber < start || inputRange.startNumber > endInclusive) class ConverterChain(private val converters: List<Converter>) { fun convert(sourceNumber: InputRange) = converters.fold(setOf(sourceNumber), { accumulator, converter -> converter.convert(accumulator) }) }
0
Kotlin
0
0
36ab66daf1241a607682e7f7a736411d7faa6277
3,672
advent-of-code-2023
MIT License
src/main/kotlin/Day10.kt
todynskyi
573,152,718
false
{"Kotlin": 47697}
fun main() { fun List<Command>.toCycles(): Map<Int, Int> { var index = 0 var x = 1 val values = mutableMapOf<Int, Int>() this.forEach { command -> if (command.instruction == "noop") { values[++index] = x } else { values[++index] = x values[++index] = x x += command.value!! } } return values } fun part1(input: List<Command>): Int { val cycles = input.toCycles() return listOf(20, 60, 100, 140, 180, 220).sumOf { (cycles[it] ?: 0) * it } } fun part2(input: List<Command>): List<String> { val cycles = input.toCycles() return cycles.map { if ((it.key - 1) % 40 in it.value - 1..it.value + 1) "#" else "." } .chunked(40) .map { it.joinToString("") } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day10_test").toCommands() check(part1(testInput) == 13140) part2(testInput).forEach { println(it) } val input = readInput("Day10").toCommands() println(part1(input)) part2(input).forEach { println(it) } } fun List<String>.toCommands(): List<Command> = this.map { val parts = it.split(" ") Command(parts.first(), parts.getOrNull(1)?.toInt()) } data class Command(val instruction: String, val value: Int? = null) {}
0
Kotlin
0
0
5f9d9037544e0ac4d5f900f57458cc4155488f2a
1,432
KotlinAdventOfCode2022
Apache License 2.0
src/Day09.kt
mjossdev
574,439,750
false
{"Kotlin": 81859}
import kotlin.math.abs import kotlin.math.sign private enum class Direction { LEFT, RIGHT, UP, DOWN } fun main() { data class Point(val x: Int, val y: Int) data class Knot(var position: Point) fun Point.move(direction: Direction) = when (direction) { Direction.LEFT -> copy(x = x - 1) Direction.RIGHT -> copy(x = x + 1) Direction.UP -> copy(y = y + 1) Direction.DOWN -> copy(y = y - 1) } fun String.toDirection(): Direction = when (this) { "L" -> Direction.LEFT "R" -> Direction.RIGHT "U" -> Direction.UP "D" -> Direction.DOWN else -> throw IllegalArgumentException() } class Rope(numberOfKnots: Int) { private var knots = Point(0, 0).let { p -> List(numberOfKnots) { Knot(p) } } private val tailPositions = mutableSetOf(knots.last().position) val visitedTailPositions get() = tailPositions.size fun moveHead(direction: Direction) { knots.first().apply { position = position.move(direction) } for ((head, tail) in knots.asSequence().windowed(2)) { val xDelta = head.position.x - tail.position.x val yDelta = head.position.y - tail.position.y val xUpdate = if (abs(xDelta).let { it > 1 || it == 1 && abs(yDelta) > 1 }) xDelta.sign else 0 val yUpdate = if (abs(yDelta).let { it > 1 || it == 1 && abs(xDelta) > 1 }) yDelta.sign else 0 if (xUpdate == 0 && yUpdate == 0) return tail.apply { position = Point(position.x + xUpdate, position.y + yUpdate) } } tailPositions.add(knots.last().position) } } fun readDirections(input: List<String>): List<Direction> = input.flatMap { val (d, s) = it.split(' ') val direction = d.toDirection() val steps = s.toInt() List(steps) { direction } } fun part1(input: List<String>): Int { val rope = Rope(2) readDirections(input).forEach { rope.moveHead(it) } return rope.visitedTailPositions } fun part2(input: List<String>): Int { val rope = Rope(10) readDirections(input).forEach { rope.moveHead(it) } return rope.visitedTailPositions } // test if implementation meets criteria from the description, like: check(part1(readInput("Day09_test")) == 13) check(part2(readInput("Day09_test2")) == 36) val input = readInput("Day09") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
afbcec6a05b8df34ebd8543ac04394baa10216f0
2,587
advent-of-code-22
Apache License 2.0
src/Day12.kt
timhillgit
572,354,733
false
{"Kotlin": 69577}
import java.util.PriorityQueue fun <T> dijkstra( graph: Map<T, List<Pair<Long, T>>>, start: Set<T>, goal: Set<T>, ): Pair<Long, List<T>>? { val visited = mutableSetOf<T>() val frontier = PriorityQueue<Pair<Long, List<T>>>(start.size) { a, b -> compareValuesBy(a, b) { it.first } } frontier.addAll(start.map { 0L to listOf(it) }) while(frontier.isNotEmpty()) { val (cost, path) = frontier.remove() val next = path.last() if (next in goal) { return cost to path } if (!visited.add(next)) { continue } graph[next]?.forEach { (edgeCost, neighbor) -> val newCost = cost + edgeCost val newPath = path + neighbor frontier.add(newCost to newPath) } } return null } private val Char.elevation: Int get() { return when (this) { 'S' -> 'a' 'E' -> 'z' else -> this }.minus('a') } fun main() { val squares = readInput("Day12").map(String::toList) val start = mutableSetOf<Position>() val end = mutableSetOf<Position>() val valleys = mutableSetOf<Position>() val graph: Map<Position, List<Pair<Long, Position>>> = buildMap { squares.forEachIndexed { i, row -> row.forEachIndexed { j, square -> val position = i to j val elevation = square.elevation when (square) { 'S' -> start.add(position) 'E' -> end.add(position) } if (elevation == 0) { valleys.add(position) } val neighbors: List<Position> = buildList { if (i != 0 && squares[i - 1][j].elevation <= elevation + 1) { add(i - 1 to j) } if (i < squares.size - 1 && squares[i + 1][j].elevation <= elevation + 1) { add(i + 1 to j) } if (j != 0 && squares[i][j - 1].elevation <= elevation + 1) { add(i to j - 1) } if (j < row.size - 1 && squares[i][j + 1].elevation <= elevation + 1) { add(i to j + 1) } } put(position, neighbors.map { 1L to it} ) } } } println(dijkstra(graph, start, end)) println(dijkstra(graph, valleys, end)) }
0
Kotlin
0
1
76c6e8dc7b206fb8bc07d8b85ff18606f5232039
2,540
advent-of-code-2022
Apache License 2.0
kotlin/src/main/kotlin/year2023/Day18.kt
adrisalas
725,641,735
false
{"Kotlin": 130217, "Python": 1548}
package year2023 fun main() { val input = readInput("Day18") Day18.part1(input).println() Day18.part2(input).println() } object Day18 { fun part1(input: List<String>): Long { val holes = input.map { getHole(it) } return holes.cubicMetersOfLava() } fun part2(input: List<String>): Long { val holes = input.map { getHole(it, true) } return holes.cubicMetersOfLava() } private data class Direction(val row: Long, val column: Long) private data class Hole(val direction: Direction, val meters: Long) private val colorMap = mapOf( 'U' to Direction(-1, 0), '3' to Direction(-1, 0), 'D' to Direction(1, 0), '1' to Direction(1, 0), 'L' to Direction(0, -1), '2' to Direction(0, -1), 'R' to Direction(0, 1), '0' to Direction(0, 1) ) private fun getHole(line: String, useColor: Boolean = false): Hole { val (direction, meters, color) = line.split(" ") return if (useColor) { Hole(colorMap.getValue(color[7]), color.substring(2..6).toLong(16)) } else { Hole(colorMap.getValue(direction[0]), meters.toLong()) } } private fun List<Hole>.cubicMetersOfLava(): Long { val firstHole = 1 val borderArea = this.borderArea() val interiorArea = this.shoelaceFormula() return firstHole + borderArea + interiorArea } private fun List<Hole>.borderArea(): Long { return this.sumOf { it.meters } } private fun List<Hole>.shoelaceFormula(): Long { val vertices = mutableListOf(Direction(0, 0)) for (hole in this) { vertices.add( Direction( row = hole.direction.row * hole.meters + vertices.last().row, column = hole.direction.column * hole.meters + vertices.last().column ) ) } var shoelaceSum = 0L for (i in vertices.indices) { val point1 = vertices[i] val point2 = vertices[(i + 1) % vertices.size] shoelaceSum += point1.column * point2.row - point1.row * point2.column } return (shoelaceSum / 2) - (this.borderArea() / 2) } }
0
Kotlin
0
2
6733e3a270781ad0d0c383f7996be9f027c56c0e
2,283
advent-of-code
MIT License
src/Day02.kt
SebastianHelzer
573,026,636
false
{"Kotlin": 27111}
enum class HandShape { Rock, Paper, Scissors; fun next(): HandShape = when(this) { Rock -> Paper Paper -> Scissors Scissors -> Rock } } fun main() { fun Char.toHandShape(): HandShape { return when(this) { 'A', 'X' -> HandShape.Rock 'B', 'Y' -> HandShape.Paper 'C', 'Z' -> HandShape.Scissors else -> throw Exception("unable to parse hand shape") } } fun getHandShapePair(input: String): Pair<HandShape, HandShape> = input.filterNot { it.isWhitespace() }.let { it.first().toHandShape() to it.last().toHandShape() } fun List<Pair<HandShape, HandShape>>.score(): List<Int> { return map { (opponent, player) -> val outcome = if (opponent == player) 3 else if (opponent.next() == player) 6 else 0 val shapeScore = player.ordinal + 1 outcome + shapeScore } } fun List<Pair<HandShape, HandShape>>.cheat(): List<Pair<HandShape, HandShape>> { return map { (opponent, outcome) -> val player = when(outcome) { HandShape.Rock -> opponent.next().next() HandShape.Paper -> opponent HandShape.Scissors -> opponent.next() } opponent to player } } fun part1(input: List<String>): Int { val handShapes = input.map { getHandShapePair(it) } val scores = handShapes.score() return scores.sum() } fun part2(input: List<String>): Int { val handShapes = input.map { getHandShapePair(it) } val scores = handShapes.cheat().score() return scores.sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day02_test") check(part1(testInput) == 15) check(part2(testInput) == 12) val input = readInput("Day02") println(part1(input)) check(part1(input) == 11475) println(part2(input)) }
0
Kotlin
0
0
e48757626eb2fb5286fa1c59960acd4582432700
1,998
advent-of-code-2022
Apache License 2.0
src/Day08.kt
jwalter
573,111,342
false
{"Kotlin": 19975}
fun main() { data class Tree(val height: Int, var visible: Boolean = false, val viewingDistances: MutableList<Int> = mutableListOf<Int>()) fun parse(input: List<String>): List<List<Tree>> { return input.map { it.map { height -> Tree(height.digitToInt()) } } } fun setViewingDistance(tree: Tree, currentLos: MutableList<Tree>) { val los = currentLos.indexOfFirst { it.height >= tree.height } if (los == -1) { tree.viewingDistances.add(currentLos.size) } else { tree.viewingDistances.add(los + 1) } } fun markVisibleTrees(forest: List<List<Tree>>, start: Pair<Int, Int>, direction: Pair<Int, Int>, step: Pair<Int, Int>) { var (x, y) = start repeat(forest.size) { x = start.first + step.first * it y = start.second + step.second * it var currMax = -1 var currentLos = mutableListOf<Tree>() repeat(forest.size) { val tree = forest[x][y] if (tree.height > currMax) { tree.visible = true currMax = tree.height } setViewingDistance(tree, currentLos) currentLos.add(0, tree) x += direction.first y += direction.second } } } fun part1(input: List<String>): Int { val forest = parse(input) val width = forest.size - 1 markVisibleTrees(forest, 0 to 0, 1 to 0, 0 to 1) markVisibleTrees(forest, 0 to 0, 0 to 1, 1 to 0) markVisibleTrees(forest, width to width, 0 to -1, -1 to 0) markVisibleTrees(forest, width to width, -1 to 0, 0 to -1) return forest.sumOf { row -> row.filter { it.visible }.size } } fun part2(input: List<String>): Int { val forest = parse(input) val width = forest.size - 1 markVisibleTrees(forest, 0 to 0, 1 to 0, 0 to 1) markVisibleTrees(forest, 0 to 0, 0 to 1, 1 to 0) markVisibleTrees(forest, width to width, 0 to -1, -1 to 0) markVisibleTrees(forest, width to width, -1 to 0, 0 to -1) val result = forest.map { row -> row.map { it.viewingDistances.reduce(Int::times) }.max() }.max() return result } val testInput = readInput("Day08_test") check(part1(testInput) == 21) check(part2(testInput) == 8) val input = readInput("Day08") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
576aeabd297a7d7ee77eca9bb405ec5d2641b441
2,492
adventofcode2022
Apache License 2.0
2022/src/test/kotlin/Day18.kt
jp7677
318,523,414
false
{"Kotlin": 171284, "C++": 87930, "Rust": 59366, "C#": 1731, "Shell": 354, "CMake": 338}
import io.kotest.core.spec.style.StringSpec import io.kotest.matchers.shouldBe import kotlin.math.absoluteValue private data class Cube(val x: Int, val y: Int, val z: Int) private val adjacent = listOf( Cube(1, 0, 0), Cube(-1, 0, 0), Cube(0, 1, 0), Cube(0, -1, 0), Cube(0, 0, 1), Cube(0, 0, -1) ) private data class Cocoon(val lava: Set<Cube>) { val minX = lava.minOf { it.x } - 1 val maxX = lava.maxOf { it.x } + 1 val minY = lava.minOf { it.y } - 1 val maxY = lava.maxOf { it.y } + 1 val minZ = lava.minOf { it.z } - 1 val maxZ = lava.maxOf { it.z } + 1 val sizeX = (maxX - minX + 1).absoluteValue val sizeY = (maxY - minY + 1).absoluteValue val sizeZ = (maxZ - minZ + 1).absoluteValue val cubes: Set<Cube> init { cubes = Cube(minX, minY, minZ).findAllAdjacent() } private fun Cube.findAllAdjacent(visited: MutableSet<Cube> = mutableSetOf()): Set<Cube> = setOf(this) + adjacent .map { n -> Cube(x + n.x, y + n.y, z + n.z) } .filterNot { it.x < minX || it.x > maxX || it.y < minY || it.y > maxY || it.z < minZ || it.z > maxZ || lava.contains(it) || visited.contains(it) } .onEach { visited.add(it) } .flatMap { it.findAllAdjacent(visited) } fun innerSurfaceSize() = cubes.exposedSides() - outerSurfaceSize() private fun outerSurfaceSize() = 2 * (sizeX * sizeY + sizeX * sizeZ + sizeY * sizeZ) } class Day18 : StringSpec({ "puzzle part 01" { getCubes().exposedSides() shouldBe 3542 } "puzzle part 02" { Cocoon(getCubes()).innerSurfaceSize() shouldBe 2080 } }) private fun Set<Cube>.exposedSides() = sumOf { 6 - adjacent.count { n -> contains(Cube(it.x + n.x, it.y + n.y, it.z + n.z)) } } private fun getCubes() = getPuzzleInput("day18-input.txt") .map { it.split(',').let { s -> Cube(s[0].toInt(), s[1].toInt(), s[2].toInt()) } } .toSet()
0
Kotlin
1
2
8bc5e92ce961440e011688319e07ca9a4a86d9c9
1,963
adventofcode
MIT License
src/main/kotlin/aoc2020/ex14.kt
noamfree
433,962,392
false
{"Kotlin": 93533}
fun main() { tests() val input = readInputFile("aoc2020/input14") require(part1(input) == 13727901897109L) val memory = executeCommands2(parseInput(input)) println(memory.values.sumOf { it }) } private fun part1(input: String): Long { val commands = parseInput(input) val memory = executeCommands1(commands) return memory.values.sumOf { it } } private class MaskCommand2(val mask: String, val address: Int, val value: Long) private fun executeCommands2(commands: List<MaskCommand>): MutableMap<Long, Long> { require(commands.first() is MaskCommand.Mask) val memory = mutableMapOf<Long, Long>() var mask = "0" val commands2 = mutableListOf<MaskCommand2>() commands.forEach { when (it) { is MaskCommand.Mask -> mask = it.mask is MaskCommand.Store -> commands2.add(MaskCommand2(mask, it.address, it.value)) } } commands2.forEachIndexed { index, command -> println("executing command $index") val places = command.address.places(command.mask) places.forEach { place -> memory[place] = command.value } } return memory } private fun executeCommands1(commands: List<MaskCommand>): Map<Int, Long> { require(commands.first() is MaskCommand.Mask) val memory = mutableMapOf<Int, Long>() var mask = "0" commands.forEach { when (it) { is MaskCommand.Mask -> mask = it.mask is MaskCommand.Store -> memory[it.address] = it.value.masked(mask) } } return memory } private fun parseInput(input: String): List<MaskCommand> { val commands = input.lines().map { val s = it.split(" = ") require(s.size == 2) if (s[0] == "mask") { require(s[1].length == 36) MaskCommand.Mask(s[1]) } else if (s[0].startsWith("mem")) { MaskCommand.Store(s[0].drop(4).dropLast(1).toInt(), s[1].toLong()) } else { error("cant") } } require(commands.first() is MaskCommand.Mask) return commands } private sealed class MaskCommand { class Mask(val mask: String) : MaskCommand() class Store(val address: Int, val value: Long) : MaskCommand() } private fun tests() { val mask = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXX1XXXX0X" require(11L.masked(mask) == 73L) require(101L.masked(mask) == 101L) require(0L.masked(mask) == 64L) val input = """ mask = XXXXXXXXXXXXXXXXXXXXXXXXXXXXX1XXXX0X mem[8] = 11 mem[7] = 101 mem[8] = 0 """.trimIndent() require(part1(input) == 165L) require( 42.masked2("000000000000000000000000000000X1001X") == "000000000000000000000000000000X1101X" ) require( 26.masked2("00000000000000000000000000000000X0XX") == "00000000000000000000000000000001X0XX" ) require( 42.places("000000000000000000000000000000X1001X") == listOf(26L, 27L, 58L, 59L) ) require( 26.places("00000000000000000000000000000000X0XX") == listOf(16L, 17L, 18L, 19L, 24L, 25L, 26L, 27L) ) } private fun Long.masked(mask: String): Long { val binaryValue = this.toString(2).padStart(36, '0') return mask.mapIndexed { index, char -> when (char) { 'X' -> binaryValue[index] '0' -> 0L '1' -> 1L else -> error("cant") } }.joinToString("").toLong(2) } private fun Int.masked2(mask: String): String { val binaryValue = this.toString(2).padStart(36, '0') return mask.mapIndexed { index, char -> when (char) { 'X' -> 'X' '0' -> binaryValue[index] '1' -> '1' else -> error("cant") } }.joinToString("") } private fun Int.places(mask: String): List<Long> { // todo consider sequence, or search val masked = masked2(mask) return places(masked.toList()) } val globalAddressMaskCache = mutableMapOf<List<Char>, List<Long>>() private fun places(string: List<Char>): List<Long> { val indexOfFirst = string.indexOfFirst { it == 'X' } if (indexOfFirst == -1) return listOf(string.joinToString("").toLong(2)) if (globalAddressMaskCache.contains(string)) return globalAddressMaskCache.getValue(string) val res = places(string.toMutableList().apply { set(indexOfFirst, '0') }) + places(string.toMutableList().apply { set(indexOfFirst, '1') }) globalAddressMaskCache.put(string, res) return res }
0
Kotlin
0
0
566cbb2ef2caaf77c349822f42153badc36565b7
4,541
AOC-2021
MIT License
src/Day24.kt
sabercon
648,989,596
false
null
fun main() { fun index(moves: List<String>): Pair<Int, Int> { return moves.fold(0 to 0) { (i, j), c -> when (c) { "e" -> i + 2 to j "w" -> i - 2 to j "se" -> i + 1 to j - 1 "sw" -> i - 1 to j - 1 "ne" -> i + 1 to j + 1 "nw" -> i - 1 to j + 1 else -> error("Unknown direction $c") } } } fun neighbours(i: Int, j: Int): List<Pair<Int, Int>> { return listOf( i + 2 to j, i - 2 to j, i + 1 to j - 1, i - 1 to j - 1, i + 1 to j + 1, i - 1 to j + 1, ) } fun flip(blackTiles: Set<Pair<Int, Int>>): Set<Pair<Int, Int>> { return blackTiles.flatMap { (i, j) -> neighbours(i, j) + (i to j) } .filter { (i, j) -> val blackNeighbours = neighbours(i, j).count { blackTiles.contains(it) } if (i to j in blackTiles) blackNeighbours in 1..2 else blackNeighbours == 2 } .toSet() } val input = readLines("Day24") .map { line -> line.fold(emptyList<String>()) { acc, c -> when (acc.lastOrNull()) { "s", "n" -> acc.dropLast(1) + (acc.last() + c) else -> acc + c.toString() } }.let { index(it) } } .groupBy { it } .filterValues { it.size % 2 == 1 } .keys input.size.println() generateSequence(input) { flip(it) } .elementAt(100) .size.println() }
0
Kotlin
0
0
81b51f3779940dde46f3811b4d8a32a5bb4534c8
1,634
advent-of-code-2020
MIT License
src/main/aoc2023/Day5.kt
nibarius
154,152,607
false
{"Kotlin": 963896}
package aoc2023 import kotlin.math.min class Day5(input: List<String>) { data class ElfMap(val source: LongRange, val diff: Long) { companion object { // Parse input and add all missing ranges between 0 and max UInt with zero // transformation to have ranges with complete coverage. fun parse(input: String): List<ElfMap> = buildList { val elfMaps = input.split("\n").drop(1).map { line -> val numbers = line.split(" ").map { it.toLong() } ElfMap( numbers[1]..<numbers[1] + numbers[2], numbers[0] - numbers[1] ) }.sortedBy { it.source.first } addAll(elfMaps) // Add missing numbers between 0 and the first range if needed if (elfMaps.first().source.first != 0L) { add(ElfMap(0..<elfMaps.first().source.first, 0)) } // Add missing numbers between two ranges if needed elfMaps.windowed(2).forEach { (first, second) -> if (first.source.last + 1 != second.source.first) { add(ElfMap(first.source.last + 1..<second.source.first, 0)) } } // Add missing numbers after the last range if needed if (elfMaps.last().source.last < 0xffffffffL) { add(ElfMap(elfMaps.last().source.last + 1..0xffffffffL, 0)) } } } } private val seeds = input[0].substringAfter(": ").split(" ").map { it.toLong() } private val seeds2 = input[0].substringAfter(": ").split(" ").map { it.toLong() } .windowed(2, 2).map { it.first()..<it.first() + it.last() } private val pipeline = (1..7).map { ElfMap.parse(input[it]) } fun solvePart1(): Long { return seeds.minOf { seed -> pipeline.fold(seed) { currentNumber, pipelineStep -> pipelineStep.firstNotNullOf { if (currentNumber in it.source) currentNumber + it.diff else null } } } } // For each of the source ranges, run them through this pipeline step and split them up in as many ranges // as needed to cover all the different destination ranges overlapping the source range. private fun processPipelineStep(sourceRanges: List<LongRange>, pipelineStep: List<ElfMap>): List<LongRange> { return buildList { sourceRanges.forEach { source -> var current = source.first while (current <= source.last) { val mapping = pipelineStep.first { current in it.source } add(current + mapping.diff..min(source.last, mapping.source.last) + mapping.diff) current = mapping.source.last + 1 } } } } fun solvePart2(): Long { return pipeline.fold(seeds2) { currentRanges, pipelineStep -> processPipelineStep(currentRanges, pipelineStep) }.minOf { it.first } } }
0
Kotlin
0
6
f2ca41fba7f7ccf4e37a7a9f2283b74e67db9f22
3,129
aoc
MIT License
src/main/kotlin/dev/bogwalk/batch8/Problem81.kt
bog-walk
381,459,475
false
null
package dev.bogwalk.batch8 import java.util.PriorityQueue /** * Problem 81: Path Sum 2 Ways * * https://projecteuler.net/problem=81 * * Goal: Find the minimum path sum for an NxN grid, starting at (0,0) and ending at (n,n), while * only being able to move to the right or down with each step. * * Constraints: 1 <= N <= 1000, numbers in [1, 1e9] * * e.g.: N = 3 * grid = 1 0 5 * 1 0 0 * 1 1 1 * minimum = 2: {1 -> R -> D -> R -> D -> 1} */ class PathSum2Ways { /** * Solution starts at top-left corner & works downwards replacing each grid value with the * smallest cumulative sum so far. * * The first row is treated specially in that sums can only be achieved by adding the value * from the previous column. The first column is also special in that sums can only be * achieved by adding the value from the previous row. * * N.B. The nested arrays have to be cloned, otherwise they will reference and alter the * original array, causing errors when testing a single grid with multiple solutions. An * alternative would be to provide the grid as a List<MutableList<Long>> & process as such or * cast to a 2D array. * * SPEED (BETTER) 1.46ms for N = 80 */ fun minPathSum(rows: Int, grid: Array<LongArray>): Long { val elements = Array(rows) { grid[it].clone() } for (row in 0 until rows) { for (col in 0 until rows) { if (row == 0) { if (col == 0) continue // no need to alter starter elements[row][col] += elements[row][col-1] } else { elements[row][col] += if (col == 0) { elements[row-1][col] } else { minOf(elements[row-1][col], elements[row][col-1]) } } } } return elements[rows-1][rows-1] } /** * Solution uses Dijkstra's algorithm for finding the shortest paths between nodes in a * graph, via a PriorityQueue that intrinsically stores the smallest weighted grid element * encountered at its head. A step is taken to the right and down, if either are possible, on * each smallest polled element until the bottom-right corner is found. * * This PriorityQueue stores its elements based on the grid element's weight, as described by * a Comparator. This means that equivalent grid elements will then be sorted naturally by * their first & second element, which will not cause errors in the end, but may cause * unnecessary processing. * * e.g. When using the 3X3 grid in the test suite, after grid[1][2] is encountered & * grid[2][2] is added to the queue, the next smallest & valid element should be grid[2][2], * but its value is identical with the sum at grid[2][1], which is prioritised as being lesser * because it's column value is smaller. This could be avoided by adding .thenByDescending * comparators to account for the other 2 components, but this increases the execution time ~4x. * * SPEED (WORSE) 34.34ms for N = 80 */ fun minPathSumDijkstra(rows: Int, grid: Array<IntArray>): Long { val visited = Array(rows) { BooleanArray(rows) } val compareByWeight = compareBy<Triple<Int, Int, Long>> { it.third } val queue = PriorityQueue(compareByWeight).apply { add(Triple(0, 0, grid[0][0].toLong())) } var minSum = 0L while (queue.isNotEmpty()) { val (row, col, weight) = queue.poll() if (visited[row][col]) continue if (row == rows - 1 && col == rows - 1) { minSum = weight break } visited[row][col] = true if (col + 1 < rows) { queue.add(Triple(row, col + 1, weight + grid[row][col+1])) } if (row + 1 < rows) { queue.add(Triple(row + 1, col, weight + grid[row + 1][col])) } } return minSum } }
0
Kotlin
0
0
62b33367e3d1e15f7ea872d151c3512f8c606ce7
4,145
project-euler-kotlin
MIT License
src/main/kotlin/day19/Day19.kt
qnox
575,581,183
false
{"Kotlin": 66677}
package day19 import readInput @JvmInline value class Resources(val resources: IntArray) { operator fun plus(other: Resources): Resources { return Resources(IntArray(resources.size) { resources[it] + other.resources[it] }) } operator fun minus(other: Resources): Resources { return Resources(IntArray(resources.size) { resources[it] - other.resources[it] }) } operator fun times(times: Int): Resources { return Resources(IntArray(resources.size) { resources[it] * times }) } operator fun get(index: Int): Int = resources[index] } @JvmInline value class Robots(val robots: IntArray) { fun produce(): Resources = Resources(robots) operator fun get(robot: Int): Int = robots[robot] } fun main() { data class Blueprint( val id: Int, val costs: List<Resources> ) { val maxConsumption = costs.reduce { acc, resources -> Resources(acc.resources.mapIndexed { index, v -> maxOf(v, resources[index]) }.toIntArray()) } } data class State(val round: Int, val resources: Resources, val robots: Robots) { fun build(cost: Resources, robot: Int): State = State( round + 1, resources - cost + robots.produce(), Robots(robots.robots.copyOf().also { it[robot] += 1 }) ) fun after(rounds: Int): State = if (rounds == 0) { this } else { copy(round = round + rounds, resources = resources + (robots.produce() * rounds)) } } val pattern = "Blueprint (\\d+): Each ore robot costs (\\d+) ore. Each clay robot costs (\\d+) ore. Each obsidian robot costs (\\d+) ore and (\\d+) clay. Each geode robot costs (\\d+) ore and (\\d+) obsidian.".toRegex() fun parseBlueprints(input: List<String>) = input.map { line -> pattern.matchEntire(line)?.let { match -> Blueprint( match.groups[1]!!.value.toInt(), listOf( Resources(intArrayOf(match.groups[2]!!.value.toInt(), 0, 0, 0)), Resources(intArrayOf(match.groups[3]!!.value.toInt(), 0, 0, 0)), Resources(intArrayOf(match.groups[4]!!.value.toInt(), match.groups[5]!!.value.toInt(), 0, 0)), Resources(intArrayOf(match.groups[6]!!.value.toInt(), 0, match.groups[7]!!.value.toInt(), 0)) ) ) } ?: error("No match: $line") } fun roundsForResources(blueprint: Blueprint, robot: Int, state: State): Int { var max = 0 for (index in 0..3) { val cost = blueprint.costs[robot][index] val v = if (cost == 0) { 0 } else if (state.robots[index] == 0) { 9999 } else { (cost - state.resources[index] + state.robots[index] - 1) / state.robots[index] } max = maxOf(max, v) } return max } fun round(state: State, blueprint: Blueprint, minutes: Int): State { return if (state.round == minutes) { state } else { val rest = minutes - state.round var max = state.after(rest) for (robot in 0 until 4) { if (robot == 3 || state.robots[robot] < blueprint.maxConsumption[robot]) { val roundsForResources = roundsForResources(blueprint, robot, state) if (roundsForResources < rest - 1) { val nextState = state.after(roundsForResources).build(blueprint.costs[robot], robot) val result = round(nextState, blueprint, minutes) if (result.resources[3] > max.resources[3]) { max = result } } } } max } } fun solve(blueprint: Blueprint, minutes: Int): Int { val resources = Resources(intArrayOf(0, 0, 0, 0)) val robots = Robots(intArrayOf(1, 0, 0, 0)) val initState = State(0, resources, robots) val result = round(initState, blueprint, minutes) println("$blueprint $result") return result.resources[3] } fun part1(input: List<String>): Int { return parseBlueprints(input).sumOf { it.id * solve(it, 24) } } fun part2(input: List<String>): Long { return parseBlueprints(input).take(3).map { solve(it, 32) }.fold(1L) { acc, v -> acc * v } } val testInput = readInput("day19", "test") val input = readInput("day19", "input") val part1 = part1(testInput) println(part1) check(part1 == 33) println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
727ca335d32000c3de2b750d23248a1364ba03e4
4,809
aoc2022
Apache License 2.0
src/main/kotlin/mkuhn/aoc/Day02.kt
mtkuhn
572,236,871
false
{"Kotlin": 53161}
package mkuhn.aoc import mkuhn.aoc.util.readInput fun main() { val input = readInput("Day02") println(day2part1(input)) println(day2part2(input)) } fun day2part1(input: List<String>): Int = input.map { l -> l.first().toRpsShape() to l.last().toRpsShape() } .sumOf { it.first.scoreAgainst(it.second) } fun day2part2(input: List<String>): Int = input.map { l -> l.first().toRpsShape() to l.last() } .map { it.first to it.findPickToAchieveOutcome() } .sumOf { it.first.scoreAgainst(it.second) } fun Char.toRpsShape(): RpsShape = RpsShape.values().find { it.pick == this || it.aliases.contains(this) } ?:error("invalid shape: $this") fun Pair<RpsShape, Char>.findPickToAchieveOutcome(): RpsShape = when(this.second) { 'X' /* lose */ -> this.first.defeats 'Y' /* draw */ -> this.first.pick 'Z' /* win */ -> this.first.defeatedBy else -> error("Invalid outcome ${this.second}") }.toRpsShape() enum class RpsShape(val pick: Char, val aliases: List<Char>, val defeats: Char, val defeatedBy: Char, val value: Int) { ROCK('R', listOf('A', 'X'), 'S', 'P', 1), PAPER('P', listOf('B', 'Y'), 'R', 'S', 2), SCISSORS('S', listOf('C', 'Z'), 'P', 'R', 3); fun scoreAgainst(yourPick: RpsShape) = yourPick.value + when { yourPick.defeats == this.pick -> 6 this.defeats == yourPick.pick -> 0 else -> 3 } }
0
Kotlin
0
1
89138e33bb269f8e0ef99a4be2c029065b69bc5c
1,450
advent-of-code-2022
Apache License 2.0
src/Day02.kt
stevennoto
573,247,572
false
{"Kotlin": 18058}
fun main() { fun part1(input: List<String>): Int { // Clean up input (map A/B/C and X/Y/Z to 0/1/2) // Then, calculate rock/paper/scissors winner using modulus, and sum chosen moves and victory values return input.map { val chars = it.toCharArray() Pair(chars[0] - 'A', chars[2] - 'X') }.sumOf { val moveValue = it.second + 1 val winValue = if ((it.first + 1) % 3 == it.second) 6 else if (it.first == it.second) 3 else 0 moveValue + winValue } } fun part2(input: List<String>): Int { // Clean up input (map A/B/C and X/Y/Z to 0/1/2) // Then, calculate rock/paper/scissors move needed, and sum chosen moves and victory values return input.map { val chars = it.toCharArray() Pair(chars[0] - 'A', chars[2] - 'X') }.sumOf { val moveValue = when (it.second) { 0 -> Math.floorMod(it.first - 1, 3) // To lose, move = 1 worse than opponent, mod 3. Use floorMod since negative. 1 -> it.first // To tie, copy move 2 -> (it.first + 1) % 3 // To win, move = 1 better than opponent, mod 3 else -> 0 } + 1 val winValue = it.second * 3 // Value of loss/tie/win = 0/1/2 * 3 moveValue + winValue } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day02_test") check(part1(testInput) == 15) check(part2(testInput) == 12) val input = readInput("Day02") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
42941fc84d50b75f9e3952bb40d17d4145a3036b
1,652
adventofcode2022
Apache License 2.0
archive/2022/Day21.kt
mathijs81
572,837,783
false
{"Kotlin": 167658, "Python": 725, "Shell": 57}
import kotlin.math.sign private const val EXPECTED_1 = 152L private const val EXPECTED_2 = 301L private class Day21(isTest: Boolean) : Solver(isTest) { fun Map<String, String>.solve(key: String): Long { key.toLongOrNull()?.let { return it } val parts = (this[key]!! + " XX").split(" ") return when (parts[1]) { "+" -> Math.addExact(solve(parts[0]), solve(parts[2])) "-" -> Math.subtractExact(solve(parts[0]), solve(parts[2])) "/" -> solve(parts[0]) / solve(parts[2]) "*" -> Math.multiplyExact(solve(parts[0]), solve(parts[2])) "XX" -> parts[0].toLong() else -> error("$key ${this[key]}") } } val operations = readAsLines().associate { line -> line.split(": ").let { it[0] to it[1] } }.toMutableMap() fun part1() = operations.solve("root") fun part2(): Any { val items = operations["root"]!!.split(" ").let { listOf(it[0], it[2]) } fun diff(probe: Long): Long { operations["humn"] = probe.toString() return Math.subtractExact(operations.solve(items[0]), operations.solve(items[1])) } fun isOverflow(probe: Long) = try { diff(probe) false } catch (e: ArithmeticException) { true } var min = Long.MIN_VALUE / 2 while (isOverflow(min)) min /= 2 var max = Long.MAX_VALUE / 2 while (isOverflow(max)) max /= 2 val minSign = diff(min).sign val maxSign = diff(max).sign check(minSign != maxSign) while (max > min) { val probe = (min + max) / 2 val value = diff(probe) if (value.sign == minSign) { min = probe + 1 } else { max = probe } } return min } } fun main() { val testInstance = Day21(true) val instance = Day21(false) testInstance.part1().let { check(it == EXPECTED_1) { "part1: $it != $EXPECTED_1" } } println("part1 ANSWER: ${instance.part1()}") testInstance.part2().let { check(it == EXPECTED_2) { "part2: $it != $EXPECTED_2" } println("part2 ANSWER: ${instance.part2()}") } }
0
Kotlin
0
2
92f2e803b83c3d9303d853b6c68291ac1568a2ba
2,238
advent-of-code-2022
Apache License 2.0
src/main/kotlin/Day03.kt
rgawrys
572,698,359
false
{"Kotlin": 20855}
import utils.intersectAll import utils.readInput import utils.splitIntoParts fun main() { fun part1(input: List<String>): Int = sumOfPrioritiesOfDuplicateItemTypesInBothCompartments(input) fun part2(input: List<String>): Int = sumOfPrioritiesOfItemTypesCommonByEveryThreeElvesInEachGroup(input) // test if implementation meets criteria from the description, like: val testInput = readInput("Day03_test") part1(testInput).let { check(it == 157) { "Part 1: Incorrect result. Is `$it`, but should be `157`" } } part2(testInput).let { check(it == 70) { "Part 2: Incorrect result. Is `$it`, but should be `70`" } } val input = readInput("Day03") println(part1(input)) println(part2(input)) } private fun sumOfPrioritiesOfDuplicateItemTypesInBothCompartments(rucksacks: List<String>): Int = rucksacks .map(String::toRucksackPriorityList) .map(List<Int>::toRucksackCompartments) .map(List<List<Int>>::intersectAll) .sumOf(Set<Int>::sum) private fun sumOfPrioritiesOfItemTypesCommonByEveryThreeElvesInEachGroup(rucksacks: List<String>): Int = rucksacks .map(String::toRucksackPriorityList) .chunked(3) .map(List<List<Int>>::intersectAll) .sumOf(Set<Int>::sum) private fun String.toRucksackPriorityList(): List<Int> = this.toList().map(Char::toPriority) private fun Char.toPriority(): Int = when { this.isUpperCase() -> this.code - 38 else -> this.code - 96 } private fun List<Int>.toRucksackCompartments() = this.splitIntoParts(2)
0
Kotlin
0
0
5102fab140d7194bc73701a6090702f2d46da5b4
1,592
advent-of-code-2022
Apache License 2.0
src/main/kotlin/aoc2021/Day15.kt
j4velin
572,870,735
false
{"Kotlin": 285016, "Python": 1446}
package aoc2021 import Point import modulo import readInput /** * @param inputMap the input risk map, see [getInputMap] * @return the lowest possible risk of all paths from the upper left corner to the bottom right corner */ private fun getLowestRisk(inputMap: Array<IntArray>): Int { val maxX = (inputMap.firstOrNull()?.size ?: 1) - 1 val maxY = inputMap.size - 1 val validGrid = Pair(Point(0, 0), Point(maxX, maxY)) val lowestRisks = Array(maxY + 1) { IntArray(maxX + 1) } val risksChanged = mutableSetOf<Point>() risksChanged.add(Point(0, 0)) fun updateRisk(riskToHere: Int, point: Point) { val currentRisk = lowestRisks[point.x][point.y] val newRisk = riskToHere + inputMap[point.x][point.y] val wasVisitedBefore = currentRisk > 0 || (point.x == 0 && point.y == 0) if (!wasVisitedBefore || currentRisk > newRisk) { risksChanged.add(point) lowestRisks[point.x][point.y] = newRisk } } while (risksChanged.isNotEmpty()) { val current = risksChanged.first() risksChanged.remove(current) val riskToHere = lowestRisks[current.x][current.y] current.getNeighbours(validGrid = validGrid).forEach { updateRisk(riskToHere, it) } } return lowestRisks[maxX][maxY] } /** * Parses the given input into a 2D array * @param original the original input * @param repeat optional value to repeat the input map this often in every dimension */ private fun getInputMap(original: List<String>, repeat: Int = 1): Array<IntArray> { val originalWidth = (original.firstOrNull()?.length ?: 0) val originalHeight = original.size val originalMap = original.map { line -> line.map { it.toString().toByte() }.toByteArray() }.toTypedArray() val repeatedMap = Array(originalHeight * repeat) { IntArray(originalWidth * repeat) } for (x in 0 until originalWidth) { for (y in 0 until originalHeight) { repeatedMap[x][y] = originalMap[x][y].toInt() for (xFactor in 1 until repeat) { for (yFactor in 1 until repeat) { repeatedMap[x + xFactor * originalWidth][y] = (originalMap[x][y].toInt() + xFactor).modulo(9) repeatedMap[x][y + yFactor * originalHeight] = (originalMap[x][y].toInt() + yFactor).modulo(9) repeatedMap[x + xFactor * originalWidth][y + yFactor * originalHeight] = (originalMap[x][y].toInt() + xFactor + yFactor).modulo(9) } } } } return repeatedMap } private fun part1(input: List<String>) = getLowestRisk(getInputMap(input)) private fun part2(input: List<String>) = getLowestRisk(getInputMap(input, 5)) fun main() { // test if implementation meets criteria from the description, like: val testInput = readInput("Day15_test") check(part1(testInput) == 40) check(part2(testInput) == 315) val input = readInput("Day15") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
f67b4d11ef6a02cba5b206aba340df1e9631b42b
3,024
adventOfCode
Apache License 2.0
2023/src/day02/day02.kt
Bridouille
433,940,923
false
{"Kotlin": 171124, "Go": 37047}
package day02 import GREEN import RESET import printTimeMillis import readInput import kotlin.math.max val maxes = mapOf( "red" to 12, "green" to 13, "blue" to 14 ) fun part1(input: List<String>): Int { return input.sumOf { val gameIdx = it.split(":")[0].split(" ")[1].toInt() val reveals = it.split(":")[1].split(";") for (reveal in reveals.flatMap { it.split(",").map { it.trim() } }) { val color = reveal.split(" ")[1] val amount = reveal.split(" ")[0].toInt() if (amount > maxes[color]!!) return@sumOf 0 } gameIdx } } fun part2(input: List<String>): Int { return input.sumOf { val reveals = it.split(":")[1].split(";") val maxCubes = mutableMapOf<String, Int>() for (reveal in reveals.flatMap { it.split(",").map { it.trim() } }) { val color = reveal.split(" ")[1] val amount = reveal.split(" ")[0].toInt() maxCubes[color] = max(maxCubes.getOrElse(color) { amount }, amount) } maxCubes.values.fold(1) { a, b -> a * b }.toInt() } } fun main() { val testInput = readInput("day02_example.txt") printTimeMillis { print("part1 example = $GREEN" + part1(testInput) + RESET) } printTimeMillis { print("part2 example = $GREEN" + part2(testInput) + RESET) } val input = readInput("day02.txt") printTimeMillis { print("part1 input = $GREEN" + part1(input) + RESET) } printTimeMillis { print("part2 input = $GREEN" + part2(input) + RESET) } }
0
Kotlin
0
2
8ccdcce24cecca6e1d90c500423607d411c9fee2
1,551
advent-of-code
Apache License 2.0
src/Day13.kt
anilkishore
573,688,256
false
{"Kotlin": 27023}
fun main() { fun endIndex(str: String, s: Int): Int { var cnt = 0 var i = s while (true) { if (str[i] == '[') ++cnt else { if (str[i] == ']') --cnt } if (cnt == 0) return i; ++i } } fun numIndex(str: String, s: Int, e: Int): Int { var i = s while (i < e && str[i].isDigit()) ++i return i } fun compare(str1: String, s1: Int, e1: Int, str2: String, s2: Int, e2: Int): Int { if (s1 >= e1) return if (s2 >= e2) 0 else -1 if (s2 >= e2) return 1 if (str1[s1] == ',') return compare(str1, s1 + 1, e1, str2, s2, e2) if (str2[s2] == ',') return compare(str1, s1, e1, str2, s2 + 1, e2) val mid1: Int val mid2: Int val res: Int if (str1[s1] == '[') { mid1 = endIndex(str1, s1) res = if (str2[s2] == '[') { mid2 = endIndex(str2, s2) compare(str1, s1 + 1, mid1, str2, s2 + 1, mid2) } else { mid2 = numIndex(str2, s2, e2) compare(str1, s1 + 1, mid1, str2, s2, mid2) } } else if (str2[s2] == '[') { mid1 = numIndex(str1, s1, e1) mid2 = endIndex(str2, s2) res = compare(str1, s1, mid1, str2, s2 + 1, mid2) } else { mid1 = numIndex(str1, s1, e1) mid2 = numIndex(str2, s2, e2) res = str1.substring(s1, mid1).toInt().compareTo(str2.substring(s2, mid2).toInt()) } return if (res != 0) res else compare(str1, mid1 + 1, e1, str2, mid2 + 1, e2) } fun compare(str1: String, str2: String): Int { return compare(str1, 0, str1.length, str2, 0, str2.length) } fun part1(input: List<String>): Int { return input.chunked(3).mapIndexed { index, packs -> if (compare(packs[0], packs[1]) < 0) index + 1 else 0 }.sum() } fun part2(input: List<String>) { val more = listOf("[[6]]", "[[2]]") val mlist = more.toMutableList() input.filter { it.isNotEmpty() }.forEach { mlist.add(it) } mlist.sortWith { s1, s2 -> compare(s1, s2) } var res = 1 for (i in mlist.indices) if (mlist[i] in more) res *= (i + 1) println(res) } val input = readInput("Day13") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
f8f989fa400c2fac42a5eb3b0aa99d0c01bc08a9
2,458
AOC-2022
Apache License 2.0
src/Day03.kt
SnyderConsulting
573,040,913
false
{"Kotlin": 46459}
fun main() { fun part1(input: List<String>): Int { val rucksacks = input.map { line -> Pair( line.take(line.length / 2), line.drop(line.length / 2) ) } return rucksacks.sumOf { rucksack -> rucksack.getDuplicate().getPointValue() } } fun part2(input: List<String>): Int { val elfList1 = mutableListOf<String>() val elfList2 = mutableListOf<String>() val elfList3 = mutableListOf<String>() var counter = 0 input.forEach { rucksack -> when (counter) { 0 -> { elfList1.add(rucksack) counter++ } 1 -> { elfList2.add(rucksack) counter++ } 2 -> { elfList3.add(rucksack) counter = 0 } } } val groups = mutableListOf<Triple<String, String, String>>() repeat(input.size / 3) { idx -> groups.add( Triple( elfList1[idx], elfList2[idx], elfList3[idx] ) ) } return groups.sumOf { group -> group.getDuplicate().getPointValue() } } val input = readInput("Day03") println(part1(input)) println(part2(input)) } fun Pair<String, String>.getDuplicate(): Char { val compartment1 = first.toList().distinct() val compartment2 = second.toList().distinct() return compartment1.first { char -> compartment2.contains(char) } } fun Triple<String, String, String>.getDuplicate(): Char { val rucksack1 = first.toList().distinct() val rucksack2 = second.toList().distinct() val rucksack3 = third.toList().distinct() return rucksack1.first { char -> rucksack2.contains(char) && rucksack3.contains(char) } } fun Char.getPointValue(): Int { val charList = listOf('a'..'z', 'A'..'Z').flatten() return charList.indexOf(this) + 1 }
0
Kotlin
0
0
ee8806b1b4916fe0b3d576b37269c7e76712a921
2,153
Advent-Of-Code-2022
Apache License 2.0
src/main/kotlin/aoc2017/ElectromagneticMoat.kt
komu
113,825,414
false
{"Kotlin": 395919}
package komu.adventofcode.aoc2017 import komu.adventofcode.utils.nonEmptyLines import java.util.Comparator.comparing fun electromagneticMoat(input: String, longest: Boolean = false): Int { val components = input.nonEmptyLines().map { Component.parse(it) }.toSet() val comparator = if (longest) comparing(Result::length).thenComparing(Result::strength) else comparing(Result::strength) return moat(0, components, comparator).strength } private fun moat(pin: Int, available: Set<Component>, comparator: Comparator<Result>): Result = available.filter { it.fits(pin) }.map { c -> moat(c.other(pin), available - c, comparator).add(c.strength) }.maxWithOrNull(comparator) ?: Result(0, 0) data class Result(val length: Int, val strength: Int) { fun add(strength: Int) = Result(length + 1, this.strength + strength) } private class Component(val pins1: Int, val pins2: Int) { val strength: Int get() = pins1 + pins2 fun fits(pin: Int) = pin == pins1 || pin == pins2 fun other(pin: Int) = strength - pin override fun toString() = "$pins1/$pins2" companion object { private val regex = Regex("""(\d+)/(\d+)""") fun parse(s: String): Component { val match = regex.matchEntire(s) ?: error("invalid input '$s'") return Component(match.groupValues[1].toInt(), match.groupValues[2].toInt()) } } }
0
Kotlin
0
0
8e135f80d65d15dbbee5d2749cccbe098a1bc5d8
1,409
advent-of-code
MIT License
src/main/kotlin/com/groundsfam/advent/y2022/d15/Day15.kt
agrounds
573,140,808
false
{"Kotlin": 281620, "Shell": 742}
package com.groundsfam.advent.y2022.d15 import com.groundsfam.advent.DATAPATH import com.groundsfam.advent.timed import kotlin.io.path.div import kotlin.io.path.useLines import kotlin.math.abs // (x, y) - position of this sensor // (bx, by) - position of closest beacon to this sensor data class Sensor(val x: Int, val y: Int, val bx: Int, val by: Int) { fun noBeacons(row: Int): Pair<Int, Int>? { val dist = abs(x - bx) + abs(y - by) val dy = abs(y - row) return (dist - dy).let { when { it <= 0 -> null by == row -> { when { bx > x -> x - it to x + it - 1 bx < x -> x - it + 1 to x + it else -> null } } else -> x - it to x + it } } } } fun parseSensor(line: String): Sensor { val parts = line.split(" ") return Sensor( parts[2].let { it.substring(2, it.length - 1).toInt() }, parts[3].let { it.substring(2, it.length - 1).toInt() }, parts[8].let { it.substring(2, it.length - 1).toInt() }, parts[9].let { it.substring(2, it.length).toInt() } ) } fun findNoBeaconsRanges(sensors: List<Sensor>, row: Int): List<Pair<Int, Int>> { val noBeaconsRanges = mutableListOf<Pair<Int, Int>>() sensors.mapNotNull { it.noBeacons(row) } .sortedBy { it.first } .forEach { range -> noBeaconsRanges.lastOrNull().let { when { it == null || it.second < range.first - 1 -> noBeaconsRanges.add(range) else -> { noBeaconsRanges.removeLast() noBeaconsRanges.add(it.first to maxOf(it.second, range.second)) } } } } return noBeaconsRanges } fun main() = timed { val sensors = (DATAPATH / "2022/day15.txt").useLines { lines -> lines.mapTo(mutableListOf(), ::parseSensor) } val knownBeacons = sensors.map { it.bx to it.by }.toSet() findNoBeaconsRanges(sensors, 2_000_000).sumOf { it.second - it.first + 1 } .also { println("Part one: $it") } for (row in 0..4_000_000) { findNoBeaconsRanges(sensors, row).forEach { range -> if (range.second in 1 until 4_000_000) { val beacon = range.second + 1 to row if (beacon !in knownBeacons) { println("Part two: ${beacon.first.toLong() * 4_000_000 + beacon.second.toLong()}") } } } } }
0
Kotlin
0
1
c20e339e887b20ae6c209ab8360f24fb8d38bd2c
2,741
advent-of-code
MIT License
src/day12/Day12.kt
seastco
574,758,881
false
{"Kotlin": 72220}
package day12 import readLines fun List<CharArray>.findEndpoints(): Pair<Pair<Int, Int>?, Pair<Int, Int>?> { var start: Pair<Int, Int>? = null var end: Pair<Int, Int>? = null for (i in this.indices) { for (j in this[i].indices) { if (this[i][j] == 'E') { start = Pair(i, j) } if (this[i][j] == 'S') { end = Pair(i, j) } } } return Pair(start, end) } fun validMove(oldChar: Char, newChar: Char): Boolean { return oldChar.code - newChar.code <= 1 } enum class Part { PART1, PART2 } fun bfs(input: List<CharArray>, part: Part): Int { val nodes = mutableListOf<Pair<Int,Int>>() val seen = mutableSetOf<Pair<Int,Int>>() val (S, E) = input.findEndpoints() input[S!!.first][S.second] = 'z' input[E!!.first][E.second] = 'a' nodes.add(S) seen.add(S) val dirs = listOf(Pair(1,0), Pair(0,1), Pair(-1,0), Pair(0,-1)) var pathLength = 0 while (nodes.isNotEmpty()) { var count = nodes.size while (count > 0) { val (i, j) = nodes.removeFirst() if (part == Part.PART1 && i == E.first && j == E.second || part == Part.PART2 && input[i][j] == 'a') { return pathLength } for ((x, y) in dirs) { val newI = i+y val newJ = j+x val validPosition = newI < input.size && newI >= 0 && newJ < input[i].size && newJ >= 0 if (validPosition && !seen.contains(Pair(newI, newJ)) && validMove(input[i][j], input[newI][newJ])) { nodes.add(Pair(newI, newJ)) seen.add(Pair(newI, newJ)) } } count-- } pathLength++ } throw error ("End position not found!") } fun part1(input: List<CharArray>): Int { return bfs(input, Part.PART1) } fun part2(input: List<CharArray>): Int { return bfs(input, Part.PART2) } fun main() { println(part1(readLines("day12/test").map { it.toCharArray()})) println(part2(readLines("day12/test").map { it.toCharArray()})) println(part1(readLines("day12/input").map { it.toCharArray()})) println(part2(readLines("day12/input").map { it.toCharArray()})) }
0
Kotlin
0
0
2d8f796089cd53afc6b575d4b4279e70d99875f5
2,315
aoc2022
Apache License 2.0
src/day11/Day11.kt
ritesh-singh
572,210,598
false
{"Kotlin": 99540}
package day11 import readInput fun main() { data class Monkey( val items: ArrayDeque<Long>, val op: String, val divBy: Long, val throwWhenTrue: Int, val throwWhenFalse: Int, var inspectCount: Long = 0L ) fun buildMonkey(input: List<String>): List<Monkey> { return buildList { input.filter { it.isNotBlank() } .chunked(6).map { it.map { it.trim() } } .forEach { list -> add( Monkey( items = ArrayDeque<Long>().also { dequeue -> list[1].substringAfter(":") .trim().split(",").map { it.trim().toLong() } .forEach { dequeue.add(it) } }, op = list[2].substringAfter("old").trim(), divBy = list[3].substringAfter("by").trim().toLong(), throwWhenTrue = list[4].substringAfter("monkey").trim().toInt(), throwWhenFalse = list[5].substringAfter("monkey").trim().toInt() ) ) } } } fun solve(input: List<String>, part1:Boolean): Long { val monkeys = buildMonkey(input) val modBy = monkeys.map { it.divBy }.reduce { a, b -> a * b } repeat(if (part1) 20 else 10000) { monkeys.forEach { monkey -> val ops = monkey.op.split(" ").map { it.trim() } monkey.items.forEach { item -> var worryLevel = item if (ops[0] == "*") { worryLevel *= if (ops[1].toLongOrNull() == null) worryLevel else ops[1].toLong() } else { worryLevel += if (ops[1].toLongOrNull() == null) worryLevel else ops[1].toLong() } if (part1) { worryLevel = Math.floorDiv(worryLevel, 3) } else { worryLevel %= modBy } val throwTo = if (worryLevel % monkey.divBy == 0L) { monkey.throwWhenTrue } else { monkey.throwWhenFalse } monkeys[throwTo].items.addLast(worryLevel) } monkey.inspectCount += monkey.items.size monkey.items.clear() } } return monkeys.sortedByDescending { it.inspectCount }.let { it[0].inspectCount * it[1].inspectCount } } val input = readInput("/day11/Day11") println(solve(input, true)) println(solve(input, false)) }
0
Kotlin
0
0
17fd65a8fac7fa0c6f4718d218a91a7b7d535eab
2,840
aoc-2022-kotlin
Apache License 2.0
src/main/kotlin/days/Day12Data.kt
yigitozgumus
572,855,908
false
{"Kotlin": 26037}
package days import utils.SolutionData import utils.Utils.getNeighbors fun main() = with(Day12Data()) { println(" --- Part 1 --- ") solvePart1() println(" --- Part 2 --- ") solvePart2() } data class Point(val x: Int, val y: Int, val value: Char) { fun getFilteredValue(): Char = when(value) { 'S' -> 'a' 'E' -> 'z' else -> value } } class Day12Data: SolutionData(inputFile = "inputs/day12.txt") { val grid = rawData.map { it.trim().toList() } .mapIndexed { row, ints -> ints.mapIndexed { columns, i -> Point(row, columns, i) } } fun getElement(x: Int, y: Int): Point = grid[x][y] fun findShortestBetween(start:Point, end: Point): Int { val visited: MutableMap<Point, Int> = mutableMapOf<Point, Int>().also { it[start] = 0 } val queue = mutableListOf<Point>().also { it.add(start) } while (queue.isNotEmpty()) { val current = queue.removeFirst() val step = visited[current]!! getNeighbors(current).forEach { if (it == end) return step.plus(1) if (!visited.keys.contains(it)) { queue.add(it) visited[it] = step.plus(1) } } } return Int.MAX_VALUE } } fun Day12Data.solvePart1() { val start = grid.flatten().sortedByDescending { it.value.code }.takeLast(2).first() val end = grid.flatten().sortedByDescending { it.value.code }.takeLast(2).last() println(findShortestBetween(start, end)) } fun Day12Data.solvePart2() { val startList = grid.flatten().filter { it.value == 'a' } val end = grid.flatten().sortedByDescending { it.value.code }.takeLast(2).last() println(startList.minOfOrNull { findShortestBetween(it, end) }) }
0
Kotlin
0
0
9a3654b6d1d455aed49d018d9aa02d37c57c8946
1,668
AdventOfCode2022
MIT License
src/day09/Day09.kt
xxfast
572,724,963
false
{"Kotlin": 32696}
package day09 import day09.Direction.* import readLines import kotlin.math.abs enum class Direction(val dx: Int, val dy: Int) { R(+1, 0), U(0, -1), L(-1, 0), D(0, +1) } typealias Move = Pair<Direction, Int> val List<String>.moves: List<Move> get() = this.map { it.split(" ").let { (direction, amount) -> valueOf(direction) to amount.toInt() } } class Knot(val index: Int, var x: Int, var y: Int, var next: Knot? = null) { val visited: MutableSet<Pair<Int, Int>> = mutableSetOf(x to y) } typealias Rope = List<Knot> val Rope.head: Knot get() = first() val Rope.tail: Knot get() = last() fun Rope(length: Int, x: Int = 0, y: Int = 0): Rope { val rope: MutableList<Knot> = mutableListOf() for (i in length - 1 downTo 0) { rope += Knot(i, x, y, next = rope.lastOrNull()) } return rope.reversed() } fun Knot.move(dx: Int, dy: Int, amount: Int) { x += dx y += dy visited += x to y val next: Knot = next ?: return val nextDx = next.x - x val nextDy = next.y - y if (abs(nextDx) <= 1 && abs(nextDy) <= 1) return val cx = -nextDx.coerceIn(-1..1) val cy = -nextDy.coerceIn(-1..1) next.move(cx, cy, amount - 1) } fun Rope.move(direction: Direction, amount: Int) { repeat(amount) { head.move(direction.dx, direction.dy, amount) } } fun Rope.move(moves: List<Move>): Rope = apply { moves.forEach { (direction, amount) -> move(direction, amount) } } fun main() { fun part1(inputs: List<String>): Int = Rope(2).move(inputs.moves).tail.visited.count() fun part2(inputs: List<String>): Int = Rope(10).move(inputs.moves).tail.visited.count() val testInput: List<String> = readLines("day09/test1.txt") check(part1(testInput) == 13) check(part2(testInput) == 1) val input: List<String> = readLines("day09/input.txt") check(part1(input) == 6266) val testInput2: List<String> = readLines("day09/test2.txt") check(part2(testInput2) == 36) check(part2(input) == 2369) } // For debugging fun println(rope: Rope, width: Int, height: Int) { val startX = rope.head.x val startY = rope.head.y for (y in -height..height) { for (x in -width..width) { val knot = rope.find { knot -> knot.x == x && knot.y == y } val tail = rope.tail when { knot == null && y == startY && x == startX -> print("s") knot == null && tail.visited.contains(x to y) -> print("#") knot == null -> print(".") knot.index == 0 -> print("H") knot.index == rope.lastIndex -> print("T") else -> print(knot.index) } } println() } }
0
Kotlin
0
1
a8c40224ec25b7f3739da144cbbb25c505eab2e4
2,542
advent-of-code-22
Apache License 2.0
y2018/src/main/kotlin/adventofcode/y2018/Day10.kt
Ruud-Wiegers
434,225,587
false
{"Kotlin": 503769}
package adventofcode.y2018 import adventofcode.io.AdventSolution import kotlin.math.abs object Day10 : AdventSolution(2018, 10, "The Stars Align") { override fun solvePartOne(input: String) = parse(input).findMessage().value.asMessage() override fun solvePartTwo(input: String) = parse(input).findMessage().index private fun parse(input: String) = input.lineSequence() .map { it .split("position=<", ",", "> velocity=<", ">") .map(String::trim) .filter(String::isNotEmpty) .map(String::toInt) } .map { (px, py, vx, vy) -> Light(px, py, vx, vy) } .toList() .let(::Sky) private fun Sky.findMessage(): IndexedValue<Sky> = generateSequence(this, Sky::nextSecond) .withIndex() .dropWhile { it.value.isVisible() } .first { it.value.isAMessage() } private data class Sky(val lights: List<Light>) { val width: IntRange by lazy { lights.minOf { it.p.x }..lights.maxOf { it.p.x } } val height: IntRange by lazy { lights.minOf { it.p.y }..lights.maxOf { it.p.y } } fun nextSecond() = Sky(lights.map(Light::nextSecond)) fun isVisible() = width.first >= 0 && height.first >= 0 fun isAMessage() = lights.all { light -> lights.any { other -> light.adjacent(other) } } fun asMessage(): String { val grid = List(height.count()) { CharArray(width.count()).apply { fill(' ') } } lights.forEach { (p, _) -> grid[p.y - height.first][p.x - width.first] = '█' } return grid.joinToString("") { "\n" + String(it) } } } private data class Light(val p: Point, val v: Point) { constructor(px: Int, py: Int, vx: Int, vy: Int) : this(Point(px, py), Point(vx, vy)) fun nextSecond() = Light(p + v, v) fun adjacent(o: Light) = abs(p.x - o.p.x) + abs(p.y - o.p.y) in 1..2 } private data class Point(val x: Int, val y: Int) { operator fun plus(o: Point) = Point(x + o.x, y + o.y) } }
0
Kotlin
0
3
fc35e6d5feeabdc18c86aba428abcf23d880c450
2,268
advent-of-code
MIT License
y2023/src/main/kotlin/adventofcode/y2023/Day14.kt
Ruud-Wiegers
434,225,587
false
{"Kotlin": 503769}
package adventofcode.y2023 import adventofcode.io.AdventSolution import adventofcode.util.algorithm.transpose import adventofcode.util.collections.splitAfter import adventofcode.util.collections.splitBefore import adventofcode.util.collections.takeWhileDistinct fun main() { Day14.solve() } object Day14 : AdventSolution(2023, 14, "Parabolic Reflector Dish") { override fun solvePartOne(input: String) = input.lines().map { it.toList() }.tiltNorth().let(::calculateLoad) override fun solvePartTwo(input: String): Int { val grid = input.lines().map { it.toList() } val beforeRepetition = generateSequence(grid, ::cycle).takeWhileDistinct().withIndex().last() val firstDuplicate = cycle(beforeRepetition.value) val leadup = generateSequence(grid, ::cycle).indexOf(firstDuplicate) val length = beforeRepetition.index - leadup + 1 val remainder = (1_000_000_000 - leadup) % length val result = generateSequence(firstDuplicate, ::cycle).elementAt(remainder) return calculateLoad(result) } } private fun calculateLoad(result: List<List<Char>>): Int = result.asReversed().mapIndexed { y, row -> ( y+1) * row.count { it == 'O' } }.sum() private fun cycle(grid: List<List<Char>>): List<List<Char>> = grid.tiltNorth().tiltWest().tiltSouth().tiltEast() private fun List<List<Char>>.tiltNorth() = transpose().map(::moveRowWest).transpose() private fun List<List<Char>>.tiltWest() = map(::moveRowWest) private fun List<List<Char>>.tiltSouth() = transpose().map(::moveRowEast).transpose() private fun List<List<Char>>.tiltEast() = map(::moveRowEast) private fun moveRowWest(row: List<Char>) = row.splitAfter { it == '#' }.flatMap { it.sortedDescending() } private fun moveRowEast(row: List<Char>) = row.splitBefore { it == '#' }.flatMap { it.sorted() }
0
Kotlin
0
3
fc35e6d5feeabdc18c86aba428abcf23d880c450
1,838
advent-of-code
MIT License
src/main/kotlin/dev/wilerson/aoc/day2/Day02.kt
wilerson
572,902,668
false
{"Kotlin": 8272}
package dev.wilerson.aoc.day2 import dev.wilerson.aoc.utils.readInput fun main() { val input = readInput("day2input") // part 1 val part1Score = input.sumOf { line -> val (opponentHand, ourHand) = line.split(" ").map { parseHand(it) } ourHand.score + ourHand.match(opponentHand).score } println(part1Score) // part2 val part2Score = input.sumOf { line -> val (columnA, columnB) = line.split(" ") val opponentHand = parseHand(columnA) val desiredResult = parseResult(columnB) val ourHand = handForDesiredResult(opponentHand, desiredResult) ourHand.score + desiredResult.score } println(part2Score) } fun handForDesiredResult(opponentHand: Hand, desiredResult: Result) = when(desiredResult) { Result.DRAW -> opponentHand Result.WIN -> opponentHand.beaten() Result.LOSS -> opponentHand.beats() } fun parseHand(value: String) = when(value) { "A" -> Hand.ROCK "B" -> Hand.PAPER "C" -> Hand.SCISSORS "X" -> Hand.ROCK "Y" -> Hand.PAPER "Z" -> Hand.SCISSORS else -> throw IllegalArgumentException() } fun parseResult(value: String) = when(value) { "X" -> Result.LOSS "Y" -> Result.DRAW "Z" -> Result.WIN else -> throw IllegalArgumentException() } enum class Hand(val score: Int) { ROCK(1), PAPER(2), SCISSORS(3); fun match(other: Hand) = if (this == other) Result.DRAW else if (this.beats() == other) Result.WIN else Result.LOSS fun beats() = when(this) { ROCK -> SCISSORS PAPER -> ROCK SCISSORS -> PAPER } fun beaten() = when(this) { ROCK -> PAPER PAPER -> SCISSORS SCISSORS -> ROCK } } enum class Result(val score: Int) { WIN(6), LOSS(0), DRAW(3) }
0
Kotlin
0
0
d6121ef600783c18696211d43b62284f4700adeb
1,781
kotlin-aoc-2022
Apache License 2.0
src/main/kotlin/Day03.kt
bent-lorentzen
727,619,283
false
{"Kotlin": 68153}
import java.lang.Integer.max import java.time.LocalDateTime import java.time.ZoneOffset import kotlin.math.min fun main() { fun findNumbers(line: String): List<Pair<String, Int>> { var startIndex = 0 return line.split(Regex("\\D+")) .filterNot { it.isEmpty() } .map { val index = line.indexOf(it, startIndex) startIndex = index + it.length it to index } } fun part1(input: List<String>): Int { val symbolPositions: Map<Int, List<Int>> = input.mapIndexed { lineNumber, line -> var startIndex = 0 val symbolIndexes = line.split(Regex("[\\d.]+")) .filterNot { it.isEmpty() } .map { val index = line.indexOf(it, startIndex) startIndex = index + 1 index } lineNumber to symbolIndexes }.toMap() return input.mapIndexed { lineNumber, line -> findNumbers(line).filter { (max(lineNumber - 1, 0)..min(lineNumber + 1, input.size - 1)).any { index -> (max(it.second - 1, 0)..it.second + it.first.length).containsAny(symbolPositions[index]!!) } }.sumOf { it.first.toInt() } }.sum() } fun part2(input: List<String>): Int { val potentialGears: Map<Int, List<Int>> = input.mapIndexed { lineNumber, line -> var startIndex = 0 val gearIndexes = line.map { val index = line.indexOf("*", startIndex) startIndex = index + 1 index } lineNumber to gearIndexes }.toMap() return input.mapIndexed { lineNumber, line -> findNumbers(line).map { (max(lineNumber - 1, 0)..min(lineNumber + 1, input.size - 1)).map { mapkey -> (max(it.second - 1, 0)..it.second + it.first.length).mapNotNull { index -> if (potentialGears[mapkey]!!.contains(index)) { mapkey to index to it.first } else { null } } }.flatten() }.flatten() }.flatten() .groupBy({ it.first }, { it.second }) .values .filter { it.size == 2 } .sumOf { it.first().toInt() * it[1].toInt() } } val timer = LocalDateTime.now().toInstant(ZoneOffset.UTC).toEpochMilli() val input = readLines("day03-input.txt") val result1 = part1(input) "Result1: $result1".println() val result2 = part2(input) "Result2: $result2".println() println("${LocalDateTime.now().toInstant(ZoneOffset.UTC).toEpochMilli() - timer} ms") }
0
Kotlin
0
0
41f376bd71a8449e05bbd5b9dd03b3019bde040b
2,847
aoc-2023-in-kotlin
Apache License 2.0
src/Day07.kt
olezhabobrov
572,687,414
false
{"Kotlin": 27363}
fun main() { fun List<String>.toPath(): String = this.joinToString(separator = "/") fun part1(input: List<String>): Int { val currentPosition = mutableListOf("") val sizeMap = mutableMapOf<String, Int>() input.forEach { line -> val lineSplited = line.split(" ") if (lineSplited[0] == "$") { if (lineSplited[1] == "cd") { if (lineSplited[2] == "..") { val prevPath = currentPosition.toPath() currentPosition.removeLast() sizeMap[currentPosition.toPath()] = sizeMap.getOrDefault(currentPosition.toPath(), 0) + sizeMap[prevPath]!! } else { currentPosition.add(lineSplited[2]) } } } else { if (lineSplited[0] != "dir") { sizeMap[currentPosition.toPath()] = sizeMap.getOrDefault(currentPosition.toPath(), 0) + lineSplited[0].toInt() } } } return sizeMap.map { (_, size) -> size }.filter { it <= 100000 }.sum() } fun part2(input: List<String>): Int { val currentPosition = mutableListOf<String>() val sizeMap = mutableMapOf<String, Int>() input.forEach { line -> val lineSplited = line.split(" ") if (lineSplited[0] == "$") { if (lineSplited[1] == "cd") { if (lineSplited[2] == "..") { val prevPath = currentPosition.toPath() currentPosition.removeLast() sizeMap[currentPosition.toPath()] = sizeMap.getOrDefault(currentPosition.toPath(), 0) + sizeMap[prevPath]!! } else { if (lineSplited[2] != "/") currentPosition.add(lineSplited[2]) } } } else { if (lineSplited[0] != "dir") { sizeMap[currentPosition.toPath()] = sizeMap.getOrDefault(currentPosition.toPath(), 0) + lineSplited[0].toInt() } } } while (currentPosition.isNotEmpty()) { val prevPath = currentPosition.toPath() currentPosition.removeLast() sizeMap[currentPosition.toPath()] = sizeMap.getOrDefault(currentPosition.toPath(), 0) + sizeMap[prevPath]!! } val usedSpace = sizeMap[""]!! val spaceToFree = 30000000 - (70000000 - usedSpace) return sizeMap.map { (_, size) -> size }.sorted().filter { it >= spaceToFree}.first() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day07_test") check(part1(testInput) == 95437) check(part2(testInput) == 24933642) val input = readInput("Day07") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
31f2419230c42f72137c6cd2c9a627492313d8fb
3,059
AdventOfCode
Apache License 2.0
src/Day07.kt
emmanueljohn1
572,809,704
false
{"Kotlin": 12720}
fun main() { data class File( val parentPath: String, val name: String, val size: Long? = null ) fun joinPath(parent: String, path: String): String { if (parent.endsWith("/")) return parent + path return "$parent/$path" } fun getParentFromPath(path: String): String { if (path == "/" || path.count { it == '/' } == 1) return "/" return path.split("/").dropLast(1).joinToString("/") } fun listDir( restInput: List<String>, fullPath: String, files: Map<String, List<File>> ): Pair<Map<String, List<File>>, List<String>> { val content = restInput .takeWhile { !it.startsWith("$") } .map { f -> val parts = f.split(" ") if (f.startsWith("dir")) { return@map File(joinPath(fullPath, parts[1]), parts[1]) } return@map File(joinPath(fullPath, parts[1]), parts[1], parts[0].toLong()) } return Pair( files.plus(mapOf(Pair(fullPath, content))), restInput.drop(content.size) ) } tailrec fun walkDirectory( input: List<String>, files: Map<String, List<File>>, cwd: String ): Map<String, List<File>> { if (input.isEmpty()) { return files } val line = input.first() var fullPath = cwd var filesCurrent = files var restInput = input.drop(1) if (line.startsWith("$")) { if (line.contains("cd")) { val cmdArg = line.split(" ").last() fullPath = when (cmdArg) { ".." -> getParentFromPath(cwd) "/" -> "/" else -> joinPath(fullPath, cmdArg) } if (!files.containsKey(fullPath)) { filesCurrent = files.plus(mapOf(Pair(fullPath, listOf()))) } } else if (line.contains("ls")) { val (first, second) = listDir(restInput, fullPath, files) filesCurrent = first restInput = second } } return walkDirectory(restInput, filesCurrent, fullPath) } fun part1(input: List<String>): Long { val directories = walkDirectory(input, mapOf(), "") val sizes = directories.map { directories.filter { entry -> entry.key.startsWith(it.key) } .flatMap { entry -> entry.value.map { f -> f.size ?: 0 } }.sum() } return sizes.map { it }.filter { it < 100000 }.sum() } fun part2(input: List<String>): Long { val directories = walkDirectory(input, mapOf(), "") val sizes = directories.map { Pair(it.key, directories.filter { entry -> entry.key.startsWith(it.key) } .flatMap { entry -> entry.value.map { f -> f.size ?: 0 } }.sum()) } val unused = 70000000L - sizes.maxBy { it.second }.second return sizes.filter { it.second >= 30000000 - unused }.minBy { it.second }.second } println("----- Test input -------") val testInput = readInput("inputs/Day07_test") println(part1(testInput)) println(part2(testInput)) println("----- Real input -------") val input = readInput("inputs/Day07") println(part1(input)) println(part2(input)) } // //----- Test input ------- //95437 //24933642 //----- Real input ------- //1297159 //3866390
0
Kotlin
0
0
154db2b1648c9d12f82aa00722209741b1de1e1b
3,584
advent22
Apache License 2.0
AdventOfCodeDay03/src/nativeMain/kotlin/Day03.kt
bdlepla
451,523,596
false
{"Kotlin": 153773}
class Day03(private val lines:List<String>) { val width = lines[0].length val height = lines.count() fun solvePart1() = countTrees(3, 1, lines) fun solvePart1a() = treesOnSlope(3 to 1) private fun treesOnSlope(slope:Pair<Int,Int>) = path(slope).count{ it in lines } private operator fun List<String>.contains(location: Pair<Int, Int>): Boolean = this[location.second][location.first % width] == '#' private fun path(slope: Pair<Int,Int>): Sequence<Pair<Int, Int>> = generateSequence(Pair(0,0)) { prev -> (prev + slope).takeIf { next -> next.second < height } } private operator fun Pair<Int,Int>.plus(that: Pair<Int,Int>): Pair<Int,Int> = Pair(this.first+that.first, this.second+that.second) fun solvePart2() = listOf(1 to 1, 3 to 1, 5 to 1, 7 to 1, 1 to 2) .map { countTrees(it.first, it.second, lines) } .multiply() fun solvePart2a(): Long = listOf(1 to 1, 3 to 1, 5 to 1, 7 to 1, 1 to 2) .map { treesOnSlope(it).toLong() } .multiply() private fun countTrees(moveRight: Int, moveDown: Int, lines: List<String>) : Long { var xPos = 0 var treesFound = 0L var yPos = 0 while(yPos < height) { val line = lines[yPos] val c = line[xPos] if (c == '#') treesFound++ xPos += moveRight xPos %= width yPos += moveDown } return treesFound } } fun List<Long>.multiply():Long = this.reduce { x, y -> x * y }
0
Kotlin
0
0
043d0cfe3971c83921a489ded3bd45048f02ce83
1,545
AdventOfCode2020
The Unlicense
aoc2023/day11.kt
davidfpc
726,214,677
false
{"Kotlin": 127212}
package aoc2023 import utils.InputRetrieval import kotlin.math.max import kotlin.math.min fun main() { Day11.execute() } private object Day11 { fun execute() { val input = readInput() println("Part 1: ${part1(input)}") println("Part 2: ${part2(input)}") } private fun part1(input: List<String>): Long = input.sumDifferencesBetweenTheGalaxies(2) private fun part2(input: List<String>): Long = input.sumDifferencesBetweenTheGalaxies(1_000_000) private fun readInput(): List<String> = InputRetrieval.getFile(2023, 11).readLines() private fun List<String>.sumDifferencesBetweenTheGalaxies(universeExpansionRate: Int = 2): Long { // Get Galaxy positions val galaxies = mutableListOf<GalaxyPosition>() this.forEachIndexed { y: Int, row: String -> row.forEachIndexed { x, c -> if (c == '#') { galaxies.add(GalaxyPosition(x + 1L, y + 1L)) } } } // Expand universe val universe = galaxies.expandUniverse(universeExpansionRate).toList() // Calculate distance between galaxies val pairs = universe.flatMapIndexed { index, s -> universe.slice(index + 1 until universe.size).map { s to it } } return pairs.sumOf { val (a, b) = it max(a.x, b.x) - min(a.x, b.x) + max(a.y, b.y) - min(a.y, b.y) } } private fun List<GalaxyPosition>.expandUniverse(universeExpansionRate: Int): List<GalaxyPosition> { val expandedUniverseTransformation = this.associateWith { it }.toMutableMap() val xPositions = this.map { it.x }.toSet() val yPositions = this.map { it.y }.toSet() val xSpacesToExpand = (xPositions.min()..<xPositions.max()).filter { !xPositions.contains(it) } val ySpacesToExpand = (yPositions.min()..<yPositions.max()).filter { !yPositions.contains(it) } xSpacesToExpand.forEach { expandedUniverseTransformation.keys.forEach { galaxy -> if (galaxy.x > it) { val tmp = expandedUniverseTransformation[galaxy]!! expandedUniverseTransformation[galaxy] = GalaxyPosition(tmp.x + (universeExpansionRate - 1), tmp.y) } } } ySpacesToExpand.forEach { expandedUniverseTransformation.keys.forEach { galaxy -> if (galaxy.y > it) { val tmp = expandedUniverseTransformation[galaxy]!! expandedUniverseTransformation[galaxy] = GalaxyPosition(tmp.x, tmp.y + (universeExpansionRate - 1)) } } } return expandedUniverseTransformation.values.toList() } private data class GalaxyPosition(val x: Long, val y: Long) }
0
Kotlin
0
0
8dacf809ab3f6d06ed73117fde96c81b6d81464b
2,811
Advent-Of-Code
MIT License
src/Day13.kt
weberchu
573,107,187
false
{"Kotlin": 91366}
private data class Packet( val list: List<Packet>?, val integer: Int? ) : Comparable<Packet> { override fun toString(): String { return list?.toString() ?: integer.toString() } // negative if self is right order, positive if not, 0 if equal override fun compareTo(other: Packet): Int { if (integer != null && other.integer != null) { return integer.compareTo(other.integer) } val selfList = list ?: listOf(Packet(null, integer)) val otherList = other.list ?: listOf(Packet(null, other.integer)) for (i in selfList.indices) { if (i >= otherList.size) { return 1 } val itemCompare = selfList[i].compareTo(otherList[i]) if (itemCompare != 0) { return itemCompare } } return if (selfList.size < otherList.size) { -1 } else { 0 } } } private fun parsePacket(string: String): Packet { if (string.startsWith('[')) { val list = mutableListOf<Packet>() var start = 1 var bracketCount = 0 for (i in 1 until string.length) { when (string[i]) { '[' -> bracketCount++ ']' -> bracketCount-- ',' -> if (bracketCount == 0) { list.add(parsePacket(string.substring(start, i))) start = i + 1 } } } if (start < string.length - 1) { list.add(parsePacket(string.substring(start, string.length - 1))) } return Packet(list, null) } else { return Packet(null, string.toInt()) } } private fun part1(input: List<String>): Int { var sumOfRightIndices = 0 for (i in 0..input.size / 3) { val left = parsePacket(input[i * 3]) val right = parsePacket(input[i * 3 + 1]) if (left < right) { sumOfRightIndices += i + 1 } } return sumOfRightIndices } private fun part2(input: List<String>): Int { val packetTwo = parsePacket("[[2]]") val packetSix = parsePacket("[[6]]") val allPackets = mutableListOf(packetTwo, packetSix) for (i in 0..input.size / 3) { allPackets.add(parsePacket(input[i * 3])) allPackets.add(parsePacket(input[i * 3 + 1])) } val sortedPackets = allPackets.sorted() return (sortedPackets.indexOf(packetTwo) + 1) * (sortedPackets.indexOf(packetSix) + 1) } fun main() { val input = readInput("Day13") // val input = readInput("Test") println("Part 1: " + part1(input)) println("Part 2: " + part2(input)) }
0
Kotlin
0
0
903ff33037e8dd6dd5504638a281cb4813763873
2,683
advent-of-code-2022
Apache License 2.0
archive/2022/Day11.kt
mathijs81
572,837,783
false
{"Kotlin": 167658, "Python": 725, "Shell": 57}
private const val EXPECTED_1 = 10605L private const val EXPECTED_2 = 2713310158L private class Monkey { val items = mutableListOf<Long>() var testDiv = 0L var trueMonk = 0 var falseMonk = 0 lateinit var operation: (Long) -> Long var inspectCount = 0L } private class Day11(isTest: Boolean) : Solver(isTest) { fun parseMonkeys(): List<Monkey> { val monkeys = mutableListOf<Monkey>() var currentMonkey = Monkey() readAsLines().map { it.trim() }.forEach { line -> if (line.startsWith("Monkey")) { currentMonkey = Monkey() monkeys.add(currentMonkey) } else if (line.startsWith("Starting")) { currentMonkey.items.addAll(line.substringAfter(":").split(",").map { it.trim().toLong() }) } else if (line.startsWith("Operation")) { val expression = line.substringAfter("= ").split(" ") currentMonkey.operation = { old -> val arg1 = if (expression[0] == "old") old else expression[0].toLong() val arg2 = if (expression[2] == "old") old else expression[2].toLong() if (expression[1] == "*") arg1 * arg2 else arg1 + arg2 } } else if (line.startsWith("Test")) { currentMonkey.testDiv = line.substringAfter("by ").toLong() } else if (line.startsWith("If true")) { currentMonkey.trueMonk = line.substringAfter("monkey ").toInt() } else if (line.startsWith("If false")) { currentMonkey.falseMonk = line.substringAfter("monkey ").toInt() } else if(line.isNotEmpty()) error("unexpected input: $line") } return monkeys } fun simulate(monkeys: List<Monkey>, postOperation: (Long) -> Long) { for (monkey in monkeys) { val items = monkey.items.toList().also { monkey.inspectCount += it.size } monkey.items.clear() for (item in items) { val newItem = postOperation(monkey.operation(item)) if (newItem % monkey.testDiv == 0L) { monkeys[monkey.trueMonk].items.add(newItem) } else { monkeys[monkey.falseMonk].items.add(newItem) } } } } fun part1(): Any { val monkeys = parseMonkeys() repeat(20) { simulate(monkeys) { it / 3 } } return monkeys.map { it.inspectCount }.sortedDescending().let { it[0] * it[1] } } fun part2(): Any { val monkeys = parseMonkeys() val commonProduct = monkeys.fold(1L) { value, monkey -> value * monkey.testDiv } repeat(10000) { simulate(monkeys) { it % commonProduct } } return monkeys.map { it.inspectCount }.sortedDescending().let { it[0] * it[1] } } } fun main() { val testInstance = Day11(true) val instance = Day11(false) testInstance.part1().let { check(it == EXPECTED_1) { "part1: $it != $EXPECTED_1" } } println("part1 ANSWER: ${instance.part1()}") testInstance.part2().let { check(it == EXPECTED_2) { "part2: $it != $EXPECTED_2" } println("part2 ANSWER: ${instance.part2()}") } }
0
Kotlin
0
2
92f2e803b83c3d9303d853b6c68291ac1568a2ba
3,285
advent-of-code-2022
Apache License 2.0
src/main/kotlin/se/brainleech/adventofcode/aoc2021/Aoc2021Day09.kt
fwangel
435,571,075
false
{"Kotlin": 150622}
package se.brainleech.adventofcode.aoc2021 import se.brainleech.adventofcode.compute import se.brainleech.adventofcode.readLines import se.brainleech.adventofcode.verify import java.util.stream.Stream import kotlin.streams.toList class Aoc2021Day09 { companion object { private const val MAX_HEIGHT = '9' private const val OUTSIDE = '_' private const val BASIN = '~' } data class Position(val row: Int, val col: Int, val height: Long) class Heightmap( private val rows: Int, private val columns: Int, private var heights: List<CharArray> ) { private fun heightAt(row: Int, col: Int): Char { if (row < 0 || row >= rows || col < 0 || col >= columns) return OUTSIDE return heights[row][col] } private fun fillAt(row: Int, col: Int): Int { if (row < 0 || row >= rows || col < 0 || col >= columns) return 0 if (heights[row][col] >= MAX_HEIGHT) return 0 heights[row][col] = BASIN return 1 } fun lowPoints(): List<Position> { val lowPoints = mutableListOf<Position>() for (row in 0 until rows) { for (col in 0 until columns) { val current = heightAt(row, col) if ((current != MAX_HEIGHT) // never a low-point && (heightAt(row - 1, col) >= current) // up && (heightAt(row, col + 1) >= current) // right && (heightAt(row + 1, col) >= current) // down && (heightAt(row, col - 1) >= current) // left ) { lowPoints.add(Position(row, col, current.digitToInt().toLong())) } } } return lowPoints.toList() } private fun fillBasin(row: Int, col: Int): Int { if (heightAt(row, col) >= MAX_HEIGHT) return 0 return fillAt(row, col) + // fill and count current position fillBasin(row - 1, col) + // up fillBasin(row, col + 1) + // right fillBasin(row + 1, col) + // down fillBasin(row, col - 1) // left } fun basinSizes(max: Int): List<Long> { val basinSizes = mutableListOf<Long>() lowPoints().forEach { position -> basinSizes.add(fillBasin(position.row, position.col).toLong()) // keep only the largest N basins basinSizes.sortDescending() if (basinSizes.size > max) basinSizes.removeAt(max) } return basinSizes.toList() } } private fun Stream<String>.asHeightmap(): Heightmap { val heights = this.map { it.toCharArray() }.toList() val rows = heights.count() val columns = heights.first().size return Heightmap(rows, columns, heights) } fun part1(input: List<String>): Long { return input.stream() .asHeightmap() .lowPoints() .sumOf { it.height + 1 } } fun part2(input: List<String>): Long { return input.stream() .asHeightmap() .basinSizes(3) .reduce { totalBasinSize, basinSize -> totalBasinSize.times(basinSize) } } } fun main() { val solver = Aoc2021Day09() val prefix = "aoc2021/aoc2021day09" val testData = readLines("$prefix.test.txt") val realData = readLines("$prefix.real.txt") verify(15L, solver.part1(testData)) compute({ solver.part1(realData) }, "$prefix.part1 = ") verify(1_134L, solver.part2(testData)) compute({ solver.part2(realData) }, "$prefix.part2 = ") }
0
Kotlin
0
0
0bba96129354c124aa15e9041f7b5ad68adc662b
3,770
adventofcode
MIT License
src/main/kotlin/com/groundsfam/advent/y2015/d06/Day06.kt
agrounds
573,140,808
false
{"Kotlin": 281620, "Shell": 742}
package com.groundsfam.advent.y2015.d06 import com.groundsfam.advent.DATAPATH import kotlin.io.path.div import kotlin.io.path.useLines enum class Action { TurnOn, TurnOff, Toggle, } data class Instruction(val action: Action, val fromX: Int, val fromY: Int, val toX: Int, val toY: Int) fun parseInstruction(line: String): Instruction { val parts = line.split(" ") var ret = Instruction(Action.TurnOn, 0, 0, 0, 0) when (parts[0]) { "turn" -> { ret = when (parts[1]) { "on" -> ret.copy(action = Action.TurnOn) "off" -> ret.copy(action = Action.TurnOff) else -> throw RuntimeException("Invalid instruction: $line") } parts[2].split(",").also { ret = ret.copy(fromX = it[0].toInt(), fromY = it[1].toInt()) } parts[4].split(",").also { ret = ret.copy(toX = it[0].toInt(), toY = it[1].toInt()) } } "toggle" -> { ret = ret.copy(action = Action.Toggle) parts[1].split(",").also { ret = ret.copy(fromX = it[0].toInt(), fromY = it[1].toInt()) } parts[3].split(",").also { ret = ret.copy(toX = it[0].toInt(), toY = it[1].toInt()) } } else -> throw RuntimeException("Invalid instruction: $line") } return ret } fun partOne(instructions: List<Instruction>): Int { val grid = Array(1000) { BooleanArray(1000) } instructions.forEach { ins -> (ins.fromX..ins.toX).forEach { x -> (ins.fromY..ins.toY).forEach { y -> when (ins.action) { Action.TurnOn -> grid[x][y] = true Action.TurnOff -> grid[x][y] = false Action.Toggle -> grid[x][y] = !grid[x][y] } } } } return grid.sumOf { row -> row.count { it } } } fun partTwo(instructions: List<Instruction>): Int { val grid = Array(1000) { IntArray(1000) } instructions.forEach { ins -> (ins.fromX..ins.toX).forEach { x -> (ins.fromY..ins.toY).forEach { y -> when (ins.action) { Action.TurnOn -> grid[x][y]++ Action.TurnOff -> grid[x][y] = maxOf(grid[x][y]-1, 0) Action.Toggle -> grid[x][y] += 2 } } } } return grid.sumOf { row -> row.sum() } } fun main() { val instructions = (DATAPATH / "2015/day06.txt").useLines { lines -> lines.toList().map(::parseInstruction) } partOne(instructions) .also { println("Part one: $it") } partTwo(instructions) .also { println("Part two: $it") } }
0
Kotlin
0
1
c20e339e887b20ae6c209ab8360f24fb8d38bd2c
2,770
advent-of-code
MIT License