path
stringlengths
5
169
owner
stringlengths
2
34
repo_id
int64
1.49M
755M
is_fork
bool
2 classes
languages_distribution
stringlengths
16
1.68k
content
stringlengths
446
72k
issues
float64
0
1.84k
main_language
stringclasses
37 values
forks
int64
0
5.77k
stars
int64
0
46.8k
commit_sha
stringlengths
40
40
size
int64
446
72.6k
name
stringlengths
2
64
license
stringclasses
15 values
src/main/kotlin/leetcode/Problem1895.kt
fredyw
28,460,187
false
{"Java": 1280840, "Rust": 363472, "Kotlin": 148898, "Shell": 604}
package leetcode import kotlin.math.max /** * https://leetcode.com/problems/largest-magic-square/ */ class Problem1895 { fun largestMagicSquare(grid: Array<IntArray>): Int { val maxRow = grid.size val maxCol = if (maxRow > 0) grid[0].size else 0 val rowSums = Array(maxRow) { IntArray(maxCol) } val colSums = Array(maxRow) { IntArray(maxCol) } val rightDiagonalSums = Array(maxRow) { IntArray(maxCol) } val leftDiagonalSums = Array(maxRow) { IntArray(maxCol) } for (row in 0 until maxRow) { for (col in 0 until maxCol) { // Direction: -- rowSums[row][col] = if (col == 0) { grid[row][col] } else { rowSums[row][col - 1] + grid[row][col] } // Direction: | colSums[row][col] = if (row == 0) { grid[row][col] } else { colSums[row - 1][col] + grid[row][col] } // Direction: \ rightDiagonalSums[row][col] = if (row == 0 || col == 0) { grid[row][col] } else { rightDiagonalSums[row - 1][col - 1] + grid[row][col] } // Direction: / leftDiagonalSums[row][col] = if (row == 0 || col == maxCol - 1) { grid[row][col] } else { leftDiagonalSums[row - 1][col + 1] + grid[row][col] } } } var answer = 1 for (row in 0 until maxRow) { for (col in 0 until maxCol) { var k = 1 while (row + k <= maxRow && col + k <= maxCol) { if (isMagicSquare(rowSums, colSums, leftDiagonalSums, rightDiagonalSums, row, col, k)) { answer = max(answer, k) } k++ } } } return answer } private fun isMagicSquare(rowSums: Array<IntArray>, colSums: Array<IntArray>, leftDiagonalSums: Array<IntArray>, rightDiagonalSums: Array<IntArray>, row: Int, col: Int, size: Int): Boolean { val maxRow = rowSums.size val maxCol = if (maxRow > 0) rowSums[0].size else 0 var sum = 0 for (r in row until row + size) { val rowSum = rowSums[r][col + size - 1] - (if (col - 1 >= 0) rowSums[r][col - 1] else 0) if (sum == 0) { sum = rowSum } else { if (sum != rowSum) { return false } } } for (c in col until col + size) { val colSum = colSums[row + size - 1][c] - (if (row - 1 >= 0) colSums[row - 1][c] else 0) if (sum != colSum) { return false } } val rightDiagonalSum = rightDiagonalSums[row + size - 1][col + size - 1] - (if (row - 1 >= 0 && col - 1 >= 0) rightDiagonalSums[row - 1][col - 1] else 0) if (sum != rightDiagonalSum) { return false } val leftDiagonalSum = leftDiagonalSums[row + size - 1][col] - (if (row - 1 >= 0 && col + size < maxCol) leftDiagonalSums[row - 1][col + size] else 0) if (sum != leftDiagonalSum) { return false } return true } }
0
Java
1
4
a59d77c4fd00674426a5f4f7b9b009d9b8321d6d
3,601
leetcode
MIT License
src/Day02.kt
BjornstadThomas
572,616,128
false
{"Kotlin": 9666}
fun main() { fun calcualteValueOfMove(input: String): Int { var AlvMove = 0 var HumanMove = 0 // println(input[0]) when (input[0]) { 'A' -> AlvMove = 1 'B' -> AlvMove = 2 'C' -> AlvMove = 3 } when (input[2]) { 'X' -> HumanMove = 1 'Y' -> HumanMove = 2 'Z' -> HumanMove = 3 } println("Human: " + HumanMove) println("Alv: " + AlvMove) if (HumanMove > AlvMove) { return HumanMove + 6 } else if (HumanMove == AlvMove) return HumanMove + 3 else if (HumanMove < AlvMove) return HumanMove + 0 return 999999 } fun assignValueToMove(input: String): Int { // println(input) //Print input for å se opprinnelig liste var score = 0 val inputSplit = input.split("\r\n") val iterator = inputSplit.iterator() iterator.forEach { // println("Element $it") score += calcualteValueOfMove(it) println("Score: " + score) } /* val inputSplit2 = input.split("\r\n") .map{ it.lines() val score = it[0] + it[2].code println(score) } println(inputSplit2) //Print av sortert liste, descending*/ return score } fun getThreeLargestValuesAndSumThemTogheter(calories: List<Int>): Int { val first = calories.get(0) val second = calories.get(1) val third = calories.get(2) println("Første: " + first).toString() println("Andre: " + second).toString() println("Tredje: " + third).toString() val sum = first + second + third return sum } fun part1(input: String): String { val inputSplit = input.split("\r\n") return inputSplit .map { when (it[0] to it[2]) { 'A' to 'X' -> 1 + 3 'A' to 'Y' -> 2 + 6 'A' to 'Z' -> 3 + 0 'B' to 'X' -> 1 + 0 'B' to 'Y' -> 2 + 3 'B' to 'Z' -> 3 + 6 'C' to 'X' -> 1 + 6 'C' to 'Y' -> 2 + 0 'C' to 'Z' -> 3 + 3 else -> 0 } }.sum().toString() } fun part1_forLoop(input: String): String { return assignValueToMove(input).toString() } fun part2(input: String): String { val inputSplit = input.split("\r\n") return inputSplit .map { when (it[0] to it[2]) { 'A' to 'X' -> 3 + 0 'A' to 'Y' -> 1 + 3 'A' to 'Z' -> 2 + 6 'B' to 'X' -> 1 + 0 'B' to 'Y' -> 2 + 3 'B' to 'Z' -> 3 + 6 'C' to 'X' -> 2 + 0 'C' to 'Y' -> 3 + 3 'C' to 'Z' -> 1 + 6 else -> 0 } }.sum().toString() } val input = readInput("input_Day02") println("Mennesket scorer i Runde 1: " + part1(input)) println("Mennesket scorer i Runde 2: " + part2(input)) }
0
Kotlin
0
0
553e3381ca26e1e316ecc6c3831354928cf7463b
3,280
AdventOfCode-2022-Kotlin
Apache License 2.0
src/aoc2023/Day16.kt
dayanruben
433,250,590
false
{"Kotlin": 79134}
package aoc2023 import checkValue import readInput fun main() { val (year, day) = "2023" to "Day16" fun energizedTiles(layout: List<String>, startBeam: Beam): Int { val rows = layout.size val cols = layout.first().length val energized = Array(rows) { BooleanArray(cols) } val beams = mutableListOf(startBeam) val visited = mutableSetOf<Beam>() while (beams.isNotEmpty()) { val newBeams = mutableListOf<Beam>() for (beam in beams) { energized[beam.row][beam.col] = true visited.add(beam) val tile = layout[beam.row][beam.col] when (tile) { '.' -> { newBeams.add(beam.move()) } '\\' -> { val newDir = when (beam.dir) { Direction.Down -> Direction.Right Direction.Left -> Direction.Up Direction.Right -> Direction.Down Direction.Up -> Direction.Left } newBeams.add(beam.move(newDir)) } '/' -> { val newDir = when (beam.dir) { Direction.Down -> Direction.Left Direction.Left -> Direction.Down Direction.Right -> Direction.Up Direction.Up -> Direction.Right } newBeams.add(beam.move(newDir)) } '|' -> { if (beam.dir == Direction.Left || beam.dir == Direction.Right) { newBeams.add(beam.move(Direction.Up)) newBeams.add(beam.move(Direction.Down)) } else { newBeams.add(beam.move()) } } '-' -> { if (beam.dir == Direction.Up || beam.dir == Direction.Down) { newBeams.add(beam.move(Direction.Left)) newBeams.add(beam.move(Direction.Right)) } else { newBeams.add(beam.move()) } } } } beams.clear() beams.addAll(newBeams.filter { it.isValid(rows, cols) && it !in visited }) } return energized.sumOf { row -> row.count { it } } } fun part1(input: List<String>) = energizedTiles(layout = input, startBeam = Beam(0, 0, Direction.Right)) fun part2(input: List<String>): Int { val vertical = input.indices.flatMap { rowIndex -> listOf( energizedTiles(layout = input, startBeam = Beam(rowIndex, 0, Direction.Right)), energizedTiles(layout = input, startBeam = Beam(rowIndex, input.first().length - 1, Direction.Left)) ) } val horizontal = input.first().indices.flatMap { colIndex -> listOf( energizedTiles(layout = input, startBeam = Beam(0, colIndex, Direction.Down)), energizedTiles(layout = input, startBeam = Beam(input.size - 1, colIndex, Direction.Up)) ) } return maxOf(vertical.max(), horizontal.max()) } val testInput = readInput(name = "${day}_test", year = year) val input = readInput(name = day, year = year) checkValue(part1(testInput), 46) println(part1(input)) checkValue(part2(testInput), 51) println(part2(input)) } data class Beam(val row: Int, val col: Int, val dir: Direction) { fun isValid(rows: Int, cols: Int) = row in 0..<rows && col in 0..<cols fun move(newDir: Direction = dir) = Beam(row + newDir.dr, col + newDir.dc, newDir) } sealed class Direction(val dr: Int, val dc: Int) { data object Right : Direction(0, 1) data object Left : Direction(0, -1) data object Up : Direction(-1, 0) data object Down : Direction(1, 0) }
1
Kotlin
2
30
df1f04b90e81fbb9078a30f528d52295689f7de7
4,183
aoc-kotlin
Apache License 2.0
src/Day18.kt
azat-ismagilov
573,217,326
false
{"Kotlin": 75114}
data class Cube3D(val x: Int, val y: Int, val z: Int) { private fun toList() = listOf(x, y, z) constructor(list: List<Int>) : this(list[0], list[1], list[2]) private operator fun get(index: Int) = toList()[index] fun adjacentBlock(side: Int): Cube3D { val coordinates = this.toList().toMutableList() when (side) { in 0 until 3 -> coordinates[side % 3]++ else -> coordinates[side % 3]-- } return Cube3D(coordinates) } fun isAdjacent(other: Cube3D, side: Int): Boolean = other == adjacentBlock(side) companion object { fun of(string: String): Cube3D { val (x, y, z) = string.split(',').map { it.toInt() } return Cube3D(x, y, z) } } } fun main() { val day = 18 fun prepareInput(input: List<String>) = input.map { Cube3D.of(it) } fun part1(input: List<String>): Int { val cubes = prepareInput(input) return (0 until 6).sumOf { side -> cubes.count { cube -> cubes.none { otherCube -> cube.isAdjacent(otherCube, side) } } } } fun part2(input: List<String>): Int { val cubes = prepareInput(input) var possibleSides = cubes.flatMap { cube -> (0 until 6).map { side -> cube.adjacentBlock(side) } } possibleSides = possibleSides.filter { it !in cubes } val canEscape = mutableSetOf<Cube3D>() val cannotEscape = mutableSetOf<Cube3D>() for (block in possibleSides) { val queue = mutableListOf(block) val used = mutableSetOf(block) var isPossibleToLeave: Boolean? = null while (queue.isNotEmpty()) { val cube = queue.removeFirst() if (cube in canEscape) { isPossibleToLeave = true break } if (cube in cannotEscape) { isPossibleToLeave = false break } if (used.size >= cubes.size * cubes.size) { isPossibleToLeave = true break } for (side in (0 until 6)) { val newBlock = cube.adjacentBlock(side) if (newBlock !in used && newBlock !in cubes) { queue.add(newBlock) used.add(newBlock) } } } if (isPossibleToLeave == true) for (cube in used) canEscape.add(cube) else for (cube in used) cannotEscape.add(cube) } return possibleSides.count { it in canEscape } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day${day}_test") check(part1(testInput) == 64) check(part2(testInput) == 58) val input = readInput("Day${day}") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
abdd1b8d93b8afb3372cfed23547ec5a8b8298aa
3,102
advent-of-code-kotlin-2022
Apache License 2.0
archive/src/main/kotlin/com/grappenmaker/aoc/year21/Day21.kt
770grappenmaker
434,645,245
false
{"Kotlin": 409647, "Python": 647}
package com.grappenmaker.aoc.year21 import com.grappenmaker.aoc.PuzzleSet import com.grappenmaker.aoc.repeatInfinitely import com.grappenmaker.aoc.splitInts import kotlin.math.max fun PuzzleSet.day21() = puzzle(day = 21) { val (startOne, startTwo) = inputLines.map { it.splitInts().last() } data class PlayerState( val pos: Int, val score: Int = 0, ) { fun advance(rolls: Int): PlayerState { val new = (pos + rolls - 1) % 10 + 1 return PlayerState(new, score + new) } } data class GameState(val p1: PlayerState, val p2: PlayerState, val turn: Boolean = true) { fun advance(rolls: Int) = GameState( p1 = if (turn) p1.advance(rolls) else p1, p2 = if (!turn) p2.advance(rolls) else p2, turn = !turn ) fun winner(score: Int): PlayerState? = p1.takeIf { it.score >= score } ?: p2.takeIf { it.score >= score } fun other(player: PlayerState) = if (p1 == player) p2 else p1 } var rolls = 0 val die = (1..100).asSequence().repeatInfinitely().onEach { rolls++ }.iterator() val initial = GameState(PlayerState(startOne), PlayerState(startTwo)) var state = initial while (true) { state = state.advance(die.next() + die.next() + die.next()) val winner = state.winner(1000) if (winner != null) { partOne = (state.other(winner).score * rolls).s() break } } data class Stats(val p1: Long, val p2: Long) operator fun Stats.plus(other: Stats) = Stats(p1 + other.p1, p2 + other.p2) operator fun Stats.times(other: Long) = Stats(p1 * other, p2 * other) fun Iterable<Stats>.sum() = reduce { acc, curr -> acc + curr } val outcomes = (1..3).toList() val poss = outcomes.flatMap { a -> outcomes.flatMap { b -> outcomes.map { c -> listOf(a, b, c).sum() } } } val freq = poss.groupingBy { it }.eachCount().mapValues { (_, v) -> v.toLong() } val memo = hashMapOf<GameState, Stats>() fun GameState.find(): Stats = memo.getOrPut(this) { when (val winner = winner(21)) { null -> freq.map { (roll, f) -> advance(roll).find() * f }.sum() else -> Stats( p1 = if (winner == p1) 1 else 0, p2 = if (winner == p2) 1 else 0 ) } } val total = initial.find() partTwo = max(total.p1, total.p2).s() }
0
Kotlin
0
7
92ef1b5ecc3cbe76d2ccd0303a73fddda82ba585
2,429
advent-of-code
The Unlicense
src/day18/Day18.kt
ritesh-singh
572,210,598
false
{"Kotlin": 99540}
package day18 import readInput import java.util.Stack fun main() { data class Coord( val x: Int, val y: Int, val z: Int ) fun List<String>.toCoordsSet(): Set<Coord> { return buildSet { this@toCoordsSet.forEach { add( it.split(",").map { it.trim().toInt() }.let { Coord(it[0], it[1], it[2]) } ) } } } fun part1(input: List<String>): Int { val cubes = input.toCoordsSet() var sf = 0 cubes.forEach { // check for all 6 faces, if they are not adjacents to other cubes if (!cubes.contains(Coord(it.x + 1, it.y, it.z))) sf++ if (!cubes.contains(Coord(it.x - 1, it.y, it.z))) sf++ if (!cubes.contains(Coord(it.x, it.y + 1, it.z))) sf++ if (!cubes.contains(Coord(it.x, it.y - 1, it.z))) sf++ if (!cubes.contains(Coord(it.x, it.y, it.z + 1))) sf++ if (!cubes.contains(Coord(it.x, it.y, it.z - 1))) sf++ } return sf } fun part2(input: List<String>): Int { val cubes = input.toCoordsSet() val minCoord = Coord(x = cubes.minOf { it.x }, y = cubes.minOf { it.y }, z = cubes.minOf { it.z }) val maxCoord = Coord(x = cubes.maxOf { it.x }, y = cubes.maxOf { it.y }, z = cubes.maxOf { it.z }) fun Coord.external() = x < minCoord.x || y < minCoord.y || z < minCoord.z || x > maxCoord.x || y > maxCoord.y || z > maxCoord.z fun Coord.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), ) fun canMoveOut(src: Coord): Boolean { val stack = Stack<Coord>() stack.push(src) val visited = hashSetOf<Coord>() visited.add(src) while (stack.isNotEmpty()) { val current = stack.pop() if (cubes.contains(current)) continue if (current.external()) return true for (neighbor in current.neighbors()) { if (!visited.contains(neighbor)) { visited.add(neighbor) stack.push(neighbor) } } } return false } var sf = 0 cubes.forEach { if (canMoveOut(Coord(it.x + 1, it.y, it.z))) sf++ if (canMoveOut(Coord(it.x - 1, it.y, it.z))) sf++ if (canMoveOut(Coord(it.x, it.y + 1, it.z))) sf++ if (canMoveOut(Coord(it.x, it.y - 1, it.z))) sf++ if (canMoveOut(Coord(it.x, it.y, it.z + 1))) sf++ if (canMoveOut(Coord(it.x, it.y, it.z - 1))) sf++ } return sf } val input = readInput("/day18/Day18") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
17fd65a8fac7fa0c6f4718d218a91a7b7d535eab
3,065
aoc-2022-kotlin
Apache License 2.0
src/Day02.kt
llama-0
574,081,845
false
{"Kotlin": 6422}
enum class Goal(val value: Char) { Win('Z'), Loose('X'), Draw('Y'), } enum class Variant(val value: Char) { Rock('A'), Paper('B'), Scissors('C') } fun main() { val outcomesForSecond = mapOf( Pair('A', 'A') to 4, // Pair('A', 'B') to 8, Pair('A', 'C') to 3, Pair('B', 'B') to 5, // Pair('B', 'A') to 1, Pair('B', 'C') to 9, Pair('C', 'C') to 6, // Pair('C', 'B') to 2, Pair('C', 'A') to 7, ) val unknownToValues = mapOf( 'X' to 'A', 'Y' to 'B', 'Z' to 'C', ) fun part1(input: List<String>): Int { var res = 0 for (i in input) { val friend = i[0] val me = unknownToValues[i[2]] res += outcomesForSecond[Pair(friend, me)] ?: 0 } return res } fun mapGoalToWinningStrategy(goal: Goal, friendVariant: Variant): Char = when(goal) { Goal.Loose -> when(friendVariant) { Variant.Rock -> 'C' Variant.Paper -> 'A' Variant.Scissors -> 'B' } Goal.Draw -> when(friendVariant) { Variant.Rock -> 'A' Variant.Paper -> 'B' Variant.Scissors -> 'C' } Goal.Win -> when(friendVariant) { Variant.Rock -> 'B' Variant.Paper -> 'C' Variant.Scissors -> 'A' } } fun Char.toGoal(): Goal = when(this) { 'Z' -> Goal.Win 'Y' -> Goal.Draw else -> Goal.Loose } fun Char.toVariant(): Variant = when(this) { 'A' -> Variant.Rock 'B' -> Variant.Paper else -> Variant.Scissors } fun part2(input: List<String>): Int { var res = 0 for (i in input) { val friend = i[0] val me = mapGoalToWinningStrategy(i[2].toGoal(), friend.toVariant()) res += outcomesForSecond[Pair(friend, me)] ?: 0 } return res } // test if implementation meets criteria from the description, like: // val testInput = readInput("Day02_test") // println(testInput) // check(part1(testInput) == 15) // check(part2(testInput) == 12) val input = readInput("Day02") // val input = readInput("Day02_test") // println(part1(input)) println(part2(input)) } private operator fun <E> Set<E>.get(e: E): Any { return e as Char }
0
Kotlin
0
0
a3a9a07be54a764a707ab25332a9f324cb84ac2a
2,481
AoC-2022
Apache License 2.0
src/Day16.kt
catcutecat
572,816,768
false
{"Kotlin": 53001}
import kotlin.system.measureTimeMillis fun main() { measureTimeMillis { Day16.run { solve1(1651) // 1638 solve2(1707) // 2400 } }.let { println("Total: $it ms") } } object Day16 : Day.LineInput<Day16.Data, Int>("16") { data class Data(private val valves: List<Valve>, private val start: Int, private val minDistance: List<List<Int>>) { fun start(totalTime: Int, totalRounds: Int): Int { var res = 0 val turnedOn = BooleanArray(valves.size) fun traverse(curr: Int, remainMinutes: Int, totalPressure: Int, remainRounds: Int) { if (remainMinutes == 0 || remainRounds == 0) return for ((next, isTurnedOn) in turnedOn.withIndex()) { val flowRate = valves[next].flowRate val distance = minDistance[curr][next] if (!isTurnedOn && flowRate > 0 && remainMinutes > distance) { turnedOn[next] = true val nextRemainMinutes = remainMinutes - distance - 1 val nextTotalPressure = totalPressure + flowRate * nextRemainMinutes res = maxOf(res, nextTotalPressure) traverse(next, nextRemainMinutes, nextTotalPressure, remainRounds) traverse(start, 26, nextTotalPressure, remainRounds - 1) turnedOn[next] = false } } } traverse(start, totalTime, 0, totalRounds) return res } } data class Valve(val flowRate: Int, val tunnels: List<Int>) override fun parse(input: List<String>): Data { val matchResults = input.map { Regex("""Valve ([A-Z]{2}) has flow rate=(\d+); tunnels? leads? to valves? ([A-Z, ]+)""") .matchEntire(it)!!.groupValues } val valveIndex = matchResults.withIndex().associate { it.value[1] to it.index } val valves = matchResults.map { Valve(it[2].toInt(), it[3].split(", ").map { valve -> valveIndex[valve]!! }) } val minDistance = MutableList(valves.size) { MutableList(valves.size) { valves.size } } for ((from, valve) in valves.withIndex()) { for (neighbor in valve.tunnels) { minDistance[from][neighbor] = 1 } } for (mid in valves.indices) { for (from in valves.indices) { for (to in valves.indices) { minDistance[from][to] = minOf(minDistance[from][to], minDistance[from][mid] + minDistance[mid][to]) } } } return Data(valves, valveIndex["AA"]!!, minDistance) } override fun part1(data: Data) = data.start(30, 1) override fun part2(data: Data) = data.start(26, 2) }
0
Kotlin
0
2
fd771ff0fddeb9dcd1f04611559c7f87ac048721
2,878
AdventOfCode2022
Apache License 2.0
src/main/kotlin/com/dvdmunckhof/aoc/event2020/Day12.kt
dvdmunckhof
318,829,531
false
{"Kotlin": 195848, "PowerShell": 1266}
package com.dvdmunckhof.aoc.event2020 import kotlin.math.absoluteValue class Day12(private val input: List<String>) { fun solvePart1(initialState: AbsoluteState): Int { val finalState = input.fold(initialState) { state, instruction -> state + Instruction(instruction) } return manhattanDistance(initialState, finalState) } fun solvePart2(initialState: WaypointState): Int { val finalState = input.fold(initialState) { state, instruction -> state + Instruction(instruction) } return manhattanDistance(initialState, finalState) } class Instruction(line: String) { val action = line[0] val value = line.substring(1).toInt() } enum class Direction(val north: Int, val east: Int) { NORTH(1, 0), EAST(0, 1), SOUTH(-1, 0), WEST(0, -1); operator fun plus(degrees: Int) = values()[Math.floorMod(ordinal + degrees / 90, values().size)] operator fun minus(degrees: Int) = plus(-degrees) } data class AbsoluteState(val direction: Direction, override val north: Int, override val east: Int) : Coordinate { operator fun plus(instruction: Instruction): AbsoluteState { val value = instruction.value return when (instruction.action) { 'N' -> this.copy(north = north + value) 'E' -> this.copy(east = east + value) 'S' -> this.copy(north = north - value) 'W' -> this.copy(east = east - value) 'L' -> this.copy(direction = direction - value) 'R' -> this.copy(direction = direction + value) 'F' -> this.copy(north = north + (value * direction.north), east = east + (value * direction.east)) else -> this } } } data class WaypointState(override val north: Int, override val east: Int, val wpNorth: Int, val wpEast: Int) : Coordinate { operator fun plus(instruction: Instruction): WaypointState { val value = instruction.value return when (instruction.action) { 'N' -> this.copy(wpNorth = wpNorth + value) 'E' -> this.copy(wpEast = wpEast + value) 'S' -> this.copy(wpNorth = wpNorth - value) 'W' -> this.copy(wpEast = wpEast - value) 'L' -> rotate(-value) 'R' -> rotate(value) 'F' -> this.copy(north = north + (value * wpNorth), east = east + (value * wpEast)) else -> this } } private fun rotate(degrees: Int): WaypointState = when (Math.floorMod(degrees, 360)) { 90 -> copy(wpNorth = -wpEast, wpEast = wpNorth) 180 -> copy(wpNorth = -wpNorth, wpEast = -wpEast) 270 -> copy(wpNorth = wpEast, wpEast = -wpNorth) else -> this } } private interface Coordinate { val north: Int val east: Int } private fun manhattanDistance(c1: Coordinate, c2: Coordinate): Int { return (c1.north - c2.north).absoluteValue + (c1.east - c2.east).absoluteValue } }
0
Kotlin
0
0
025090211886c8520faa44b33460015b96578159
3,119
advent-of-code
Apache License 2.0
src/Day09.kt
frango9000
573,098,370
false
{"Kotlin": 73317}
fun main() { val input = readInput("Day09") println(Day09.part1(input)) println(Day09.part2(input)) } data class HeadMovement(val direction: Direction, val steps: Int) enum class Direction { U, R, D, L, } class Day09 { companion object { fun part1(input: List<String>): Int { return getTailPositions(input, 2) } fun part2(input: List<String>): Int { return getTailPositions(input, 10) } fun getTailPositions(input: List<String>, numOfKnots: Int): Int { val moves = input.map { it.split(" ") }.map { HeadMovement(Direction.valueOf(it[0]), it[1].toInt()) } val knots = (1..numOfKnots.coerceAtLeast(2)).toList().map { Coordinate(0, 0) } val tailPositions = mutableSetOf<String>("0,0") val head = knots.first() val tail = knots.last() for (move in moves) { for (step in (1..move.steps)) { when (move.direction) { Direction.R -> head.x++ Direction.U -> head.y-- Direction.D -> head.y++ Direction.L -> head.x-- } for (index in (1 until knots.size)) { val lead = knots[index - 1] val current = knots[index] if (current.x in (lead.x - 1..lead.x + 1) && current.y in (lead.y - 1..lead.y + 1)) break if (lead.x > current.x) current.x++ else if (lead.x < current.x) current.x-- if (lead.y > current.y) current.y++ else if (lead.y < current.y) current.y-- } tailPositions.add("${tail.x},${tail.y}") } } return tailPositions.size } } }
0
Kotlin
0
0
62e91dd429554853564484d93575b607a2d137a3
1,865
advent-of-code-22
Apache License 2.0
src/main/kotlin/com/github/ferinagy/adventOfCode/aoc2023/2023-22.kt
ferinagy
432,170,488
false
{"Kotlin": 787586}
package com.github.ferinagy.adventOfCode.aoc2023 import com.github.ferinagy.adventOfCode.println import com.github.ferinagy.adventOfCode.readInputLines import java.util.LinkedList import kotlin.math.max import kotlin.math.min fun main() { val input = readInputLines(2023, "22-input") val test1 = readInputLines(2023, "22-test1") println("Part1:") part1(test1).println() part1(input).println() println() println("Part2:") part2(test1).println() part2(input).println() } private fun part1(input: List<String>): Int { val mapped = parseAndSettle(input) return mapped.count { (_, brick) -> brick.supports.all { 1 < mapped[it]!!.supportedBy.size } } } private fun part2(input: List<String>): Int { val mapped = parseAndSettle(input) return mapped.keys.sumOf { disintegrate(it, mapped) } } private fun parseAndSettle(input: List<String>): Map<Int, Brick> { var id = 0 val bricks = input.map { Brick.parse(it, id++) }.sortedBy { it.bottom } val settled = mutableListOf<Brick>() bricks.forEach { brick -> var offset = 0 while (brick.canDrop(offset + 1, settled)) { offset++ } val moved = brick.copyWithOffset(offset) val supportedBy = settled.filter { moved.intersects(it, 1) } supportedBy.forEach { it.supports += moved.id moved.supportedBy += it.id } settled += moved } return settled.associateBy { it.id } } private fun disintegrate(id: Int, bricks: Map<Int, Brick>): Int { val queue = LinkedList<Int>() queue += id val destroyed = mutableSetOf<Int>() while (queue.isNotEmpty()) { val current = queue.removeFirst() val brick = bricks[current]!! destroyed += current val next = brick.supports.filter { val b = bricks[it]!! (b.supportedBy - destroyed).isEmpty() } queue += next } return destroyed.size - 1 } private data class Brick( val id: Int, val xRange: IntRange, val yRange: IntRange, val zRange: IntRange, val supports: MutableSet<Int> = mutableSetOf(), val supportedBy: MutableSet<Int> = mutableSetOf() ) { val bottom = zRange.first fun canDrop(offset: Int, settled: List<Brick>): Boolean { return 0 < bottom - offset && settled.none { intersects(it, offset) } } fun intersects(other: Brick, zOffset: Int): Boolean { val zRange = zRange.first - zOffset .. zRange.last - zOffset return !(xRange intersect other.xRange).isEmpty() && !(yRange intersect other.yRange).isEmpty() && !(zRange intersect other.zRange).isEmpty() } fun copyWithOffset(zOffset: Int) = copy(zRange = zRange.first - zOffset .. zRange.last - zOffset) companion object { fun parse(text: String, id: Int) = text.split('~').let { (c1, c2) -> val (x1, y1, z1) = c1.split(',').map { it.toInt() } val (x2, y2, z2) = c2.split(',').map { it.toInt() } Brick(id, x1 .. x2, y1 .. y2, z1 ..z2) } } } private infix fun IntRange.intersect(other: IntRange): IntRange = max(first, other.first) .. min(last, other.last)
0
Kotlin
0
1
f4890c25841c78784b308db0c814d88cf2de384b
3,258
advent-of-code
MIT License
src/Day05.kt
Arclights
574,085,358
false
{"Kotlin": 11490}
fun main() { fun part1(input: Input): String = input .instructions .fold(input.stacks) { stacks, (move, from, to) -> stacks[to - 1] = stacks[to - 1].plus(stacks[from - 1].takeLast(move).reversed()) stacks[from - 1] = stacks[from - 1].dropLast(move) stacks } .joinToString("") { it.last().toString() } fun part2(input: Input) = input .instructions .fold(input.stacks) { stacks, (move, from, to) -> stacks[to - 1] = stacks[to - 1].plus(stacks[from - 1].takeLast(move)) stacks[from - 1] = stacks[from - 1].dropLast(move) stacks } .joinToString("") { it.lastOrNull()?.toString()?:"" } fun parseInput(rawInput: List<String>): Input { fun parseStacks(rawStacks: List<String>): MutableList<String> { return rawStacks .map { line -> line.drop(1).windowed(1, 4) } .reversed() .reduce { acc, list -> val paddedList = list.plus(List(acc.size - list.size) { " " }) acc.zip(paddedList) { a, b -> a.plus(b) } } .map { it.drop(1) } .map { it.filter { item -> item != ' ' } } .toMutableList() } fun parseInstructions(rawInstructions: List<String>): List<Triple<Int, Int, Int>> { return rawInstructions .map { it.split(" ") } .map { Triple(it[1].toInt(), it[3].toInt(), it[5].toInt()) } } return Input( parseStacks(rawInput.takeWhile { it != "" }), parseInstructions(rawInput.dropWhile { it != "" }.drop(1)) ) } val testInput = readInput("Day05_test") println(part1(parseInput(testInput))) println(part2(parseInput(testInput))) val input = readInput("Day05") println(part1(parseInput(input))) println(part2(parseInput(input))) } data class Input(val stacks: MutableList<String>, val instructions: List<Triple<Int, Int, Int>>)
0
Kotlin
0
0
121a81ba82ba0d921bd1b689241ffa8727bc806e
2,071
advent_of_code_2022
Apache License 2.0
src/aoc2022/Day07.kt
RobertMaged
573,140,924
false
{"Kotlin": 225650}
package aoc2022 fun main() { fun ArrayDeque<String>.toPWDs(): List<String> = runningReduce { pwdAcc, curDir -> pwdAcc + curDir } fun Map<String, Int>.getDeviceFreeSpace(): Int = (70_000_000 - this.getValue("/")) fun List<String>.readDirsSizes(): Map<String, Int> { val filesStack = ArrayDeque(listOf("/")) val sizes = mutableMapOf<String, Int>() for (line in this) when { // accumulate dirs hierarchy sizes line.first().isDigit() -> for (pwd in filesStack.toPWDs()) sizes[pwd] = sizes.getOrDefault(pwd, 0) + line.split(" ").first().toInt() line.startsWith("\$ cd ").not() -> continue // from here we sure cmd in cd, index after "$ cd " is 5 line[5] == '/' -> run { filesStack.clear(); filesStack.addLast("/") } line[5] == '.' -> filesStack.removeLast() else -> filesStack.addLast("${line.substringAfter("cd ")}/") } return sizes.toMap() } fun part1(input: List<String>): Int = input.readDirsSizes().values.filter { it <= 100_000 }.sum() fun part2(input: List<String>): Int { val sizes = input.readDirsSizes() val neededFreeSpace = 30_000_000L - sizes.getDeviceFreeSpace() return sizes.values.filter { it >= neededFreeSpace }.min() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day07_test") check(part1(testInput).also(::println) == 95437) check(part2(testInput).also(::println) == 24933642) val input = readInput("Day07") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
e2e012d6760a37cb90d2435e8059789941e038a5
1,676
Kotlin-AOC-2023
Apache License 2.0
src/nativeMain/kotlin/Day13.kt
rubengees
576,436,006
false
{"Kotlin": 67428}
import Day13.Tree.Node import Day13.Tree.Num import kotlin.math.max class Day13 : Day { private sealed class Tree { class Num(val value: Int) : Tree() class Node(vararg val items: Tree) : Tree(), Comparable<Node> { override fun compareTo(other: Node): Int { val otherNumbers = other.items for (i in 0 until max(items.size, otherNumbers.size)) { val thisItem = items.getOrNull(i) val otherItem = otherNumbers.getOrNull(i) if (thisItem == null) return -1 if (otherItem == null) return 1 if (thisItem is Num && otherItem is Num) { if (thisItem.value < otherItem.value) return -1 if (thisItem.value > otherItem.value) return 1 } else { val thisItemList = if (thisItem is Num) Node(Num(thisItem.value)) else thisItem as Node val otherItemList = if (otherItem is Num) Node(Num(otherItem.value)) else otherItem as Node val result = thisItemList.compareTo(otherItemList) if (result != 0) return result } } return 0 } } } private fun parseLineRecursive(line: String): Pair<Node, String> { var current = line.substring(1) val items = mutableListOf<Tree>() while (current.first() != ']') { val char = current.first() if (char.isDigit()) { val number = current.substringBefore(",").substringBefore("]") items.add(Num(number.toInt())) current = current.substring(number.length) } else if (char == '[') { val (newItem, remainder) = parseLineRecursive(current) items.add(newItem) current = remainder } else if (char == ',') { current = current.substring(1) } else { error("Illegal char $char") } } return Node(*items.toTypedArray()) to current.substring(1) } private fun parseLine(line: String): Node { return parseLineRecursive(line).first } private fun parse(input: String): List<Pair<Node, Node>> { val groups = input.split("\n\n") return groups.map { group -> val left = group.lines()[0] val right = group.lines()[1] parseLine(left) to parseLine(right) } } override suspend fun part1(input: String): String { val trees = parse(input) return trees .mapIndexedNotNull { index, (left, right) -> if (left < right) index + 1 else null } .sum() .toString() } override suspend fun part2(input: String): String { val trees = parse(input).flatMap { (a, b) -> listOf(a, b) } val dividerTwo = Node(Node(Num(2))) val dividerSix = Node(Node(Num(6))) val sortedTrees = (trees + dividerTwo + dividerSix).sorted() return ((sortedTrees.indexOf(dividerTwo) + 1) * (sortedTrees.indexOf(dividerSix) + 1)).toString() } }
0
Kotlin
0
0
21f03a1c70d4273739d001dd5434f68e2cc2e6e6
3,256
advent-of-code-2022
MIT License
src/Day17.kt
er453r
572,440,270
false
{"Kotlin": 69456}
import kotlin.math.min fun main() { val blockShapes = """#### .#. ### .#. ..# ..# ### # # # # ## ##""" class Block(val points: List<Vector2d>) { fun move(vector2d: Vector2d) = points.forEach { it.increment(vector2d) } fun collides(other: Set<Vector2d>) = points.any { it in other } fun copy(): Block = Block(points.map { it.copy() }) } val blocks = blockShapes.lines().separateByBlank().asSequence() .map { it.map { line -> line.toCharArray().toList() } } .map { Grid(it) } .map { grid -> grid.data.flatten().filter { cell -> cell.value == '#' }.map { it.position } } .map { val dy = it.maxOf { point -> point.y } + 1 it.map { point -> point.increment(Vector2d(0, -dy)) } } .map { Block(it) } .toList() fun tetris(input: List<String>, blocksToFall: Int): Pair<Long, List<Int>> { val moves = input.first().toCharArray().map { if (it == '<') Vector2d.LEFT else Vector2d.RIGHT } val rightWall = 8 val settled = mutableSetOf<Vector2d>() val increments = mutableListOf<Int>() var currentTop = 0L var currentBlockIndex = 0 var currentMoveIndex = 0 var rocksFallen = blocksToFall while (rocksFallen-- != 0) { val block = blocks[currentBlockIndex++ % blocks.size].copy() block.move(Vector2d(3, currentTop.toInt() - 3)) // move to start position while (true) { val wind = moves[currentMoveIndex++ % moves.size] // first wind movement block.move(wind) if (block.collides(settled) || block.points.minOf { it.x } == 0 || block.points.maxOf { it.x } == rightWall ) block.move(wind.negative()) // move back block.move(Vector2d.DOWN) if (block.collides(settled) || block.points.minOf { it.y } == 0) { // block settles block.move(Vector2d.UP) // move back settled.addAll(block.points) val newCurrentTop = min(currentTop, block.points.minOf { it.y }.toLong()) increments.add((currentTop - newCurrentTop).toInt()) currentTop = newCurrentTop break } } } return Pair(-currentTop, increments) } fun part1(input: List<String>) = tetris(input, 2022).first fun part2(input: List<String>): Long { val (_, increments) = tetris(input, 8000) val bestSequence = increments.findLongestSequence() val iters = 1000000000000L val sequenceHeight = increments.subList(bestSequence.first, bestSequence.first + bestSequence.second).sum() var height = increments.subList(0, bestSequence.first).sum().toLong() var itersLeft = iters - bestSequence.first val sequencesLeft = itersLeft / bestSequence.second height += sequencesLeft * sequenceHeight itersLeft -= sequencesLeft * bestSequence.second height += increments.subList(bestSequence.first, bestSequence.first + itersLeft.toInt()).sum() return height } test( day = 17, testTarget1 = 3068L, testTarget2 = 1514285714288L, part1 = ::part1, part2 = ::part2, ) }
0
Kotlin
0
0
9f98e24485cd7afda383c273ff2479ec4fa9c6dd
3,403
aoc2022
Apache License 2.0
2021/src/main/kotlin/day12_fast.kt
madisp
434,510,913
false
{"Kotlin": 388138}
import utils.Parser import utils.Solution fun main() { Day12Fast.run() } object Day12All { @JvmStatic fun main(args: Array<String>) { mapOf("func" to Day12Func, "imp" to Day12Imp, "fast" to Day12Fast).forEach { (header, solution) -> solution.run(header = header, skipPart1 = false, skipTest = false, printParseTime = false) } } } object Day12Fast : Solution<Day12Fast.Vertex>() { override val name = "day12" override val parser = Parser { input -> val vertices = mutableMapOf<String, Vertex>() input.lines().filter { it.isNotBlank() }.forEach { line -> val (n1, n2) = line.split('-', limit = 2) val v1 = vertices.getOrPut(n1) { Vertex(n1.toKind(), false, mutableListOf()) } val v2 = vertices.getOrPut(n2) { Vertex(n2.toKind(), false, mutableListOf()) } v1.edges.add(v2) v2.edges.add(v1) } return@Parser vertices["start"]!! } enum class Kind { BIG, SMALL, START, END } fun String.toKind(): Kind { return when (this) { "start" -> Kind.START "end" -> Kind.END else -> { if (toCharArray().all { it.isUpperCase() }) Kind.BIG else Kind.SMALL } } } class Vertex(val kind: Kind, var visited: Boolean, val edges: MutableList<Vertex>) /** * Perform a depth-first search to count all the paths */ fun countPaths(vertex: Vertex, doubleVisitAllowed: Boolean): Int { if (vertex.kind == Kind.END) { return 1 } var count = 0 for (v in vertex.edges) { if (!v.visited || v.kind == Kind.BIG) { v.visited = true count += countPaths(v, doubleVisitAllowed) v.visited = false } else if (v.visited && v.kind == Kind.SMALL && doubleVisitAllowed) { count += countPaths(v, false) } } return count } override fun part1(input: Vertex): Int { return countPaths(input, false) } override fun part2(input: Vertex): Int { return countPaths(input, true) } }
0
Kotlin
0
1
3f106415eeded3abd0fb60bed64fb77b4ab87d76
1,963
aoc_kotlin
MIT License
src/day23/Day23.kt
andreas-eberle
573,039,929
false
{"Kotlin": 90908}
package day23 import Coordinate import maxEach import minEach import readInput const val day = "23" val directions = listOf( Triple(Coordinate(-1, -1), Coordinate(0, -1), Coordinate(1, -1)), // N Triple(Coordinate(-1, 1), Coordinate(0, 1), Coordinate(1, 1)), // S Triple(Coordinate(-1, -1), Coordinate(-1, 0), Coordinate(-1, 1)), // W Triple(Coordinate(1, -1), Coordinate(1, 0), Coordinate(1, 1)) // E ) val allNeighbors = listOf( Coordinate(-1, -1), Coordinate(0, -1), Coordinate(1, -1), Coordinate(1, 0), Coordinate(1, 1), Coordinate(0, 1), Coordinate(-1, 1), Coordinate(-1, 0), ) fun main() { fun calculatePart1Score(input: List<String>, rounds: Int = 10): Int { val elvStartCoordinates = input.flatMapIndexed { y, line -> line.withIndex().filter { it.value == '#' }.map { (x, _) -> Coordinate(x, y) } }.toSet() val allStates = (0 until rounds).runningFold(elvStartCoordinates) { elvLocations, directionIdx -> playRound(elvLocations, directionIdx) } // allStates.printElvBoards() val min = allStates.flatten().minEach() val max = allStates.flatten().maxEach() val (width, height) = max - min return width * height - elvStartCoordinates.size } fun calculatePart2Score(input: List<String>): Int { val elvStartCoordinates = input.flatMapIndexed { y, line -> line.withIndex().filter { it.value == '#' }.map { (x, _) -> Coordinate(x, y) } }.toSet() var elvLocations = elvStartCoordinates var directionIdx = 0 while (true) { val nextLocations = playRound(elvLocations, directionIdx) if (elvLocations == nextLocations) { return directionIdx + 1 } elvLocations = nextLocations directionIdx++ } } // test if implementation meets criteria from the description, like: val testInput = readInput("/day$day/Day${day}_test") val input = readInput("/day$day/Day${day}") val part1TestPoints = calculatePart1Score(testInput) println("Part1 test points: $part1TestPoints") check(part1TestPoints == 88) val part1points = calculatePart1Score(input) println("Part1 points: $part1points") val part2TestPoints = calculatePart2Score(testInput) println("Part2 test points: $part2TestPoints") check(part2TestPoints == 20) val part2points = calculatePart2Score(input) println("Part2 points: $part2points") } fun Set<Coordinate>.printElvesBoard(mins: Coordinate = minEach(), maxs: Coordinate = maxEach()) { (mins.y..maxs.y).forEach { y -> (mins.x..maxs.x).forEach { x -> if (contains(Coordinate(x, y))) { print("#") } else { print(".") } } println() } println() } fun List<Set<Coordinate>>.printElvBoards() { val absoluteMin = flatten().minEach() val absoluteMax = flatten().maxEach() + 1 + Coordinate(1, 0) forEachIndexed { idx, board -> println("round $idx: offset: $absoluteMin") board.printElvesBoard(absoluteMin, absoluteMax) } } fun playRound(elvLocations: Set<Coordinate>, directionIdx: Int): Set<Coordinate> { val (noNeighborsElves, needToMoveElves) = elvLocations.partition { location -> allNeighbors.asSequence().map { it + location }.none { elvLocations.contains(it) } } val nextElvLocations = needToMoveElves.map { location -> directions.indices .asSequence() .map { directionOffset -> val (neighborDirection1, direction, neighborDirection2) = directions[(directionIdx + directionOffset) % directions.size] val nextLocation = location + direction val neighbor1 = location + neighborDirection1 val neighbor2 = location + neighborDirection2 val validLocation = !elvLocations.contains(neighbor1) && !elvLocations.contains(nextLocation) && !elvLocations.contains(neighbor2) Triple(location, nextLocation, validLocation) } .filter { it.third } .firstOrNull() ?: Triple(location, location, true) }.map { it.first to it.second } val validNextLocations = nextElvLocations .groupBy { it.second } .filter { (_, value) -> value.size == 1 } .keys val nextLocations = nextElvLocations.map { (location, nextLocation) -> if (validNextLocations.contains(nextLocation)) { nextLocation } else { location } }.toSet() return nextLocations + noNeighborsElves }
0
Kotlin
0
0
e42802d7721ad25d60c4f73d438b5b0d0176f120
4,698
advent-of-code-22-kotlin
Apache License 2.0
src/Day09.kt
thorny-thorny
573,065,588
false
{"Kotlin": 57129}
import kotlin.math.absoluteValue import kotlin.math.max data class Point(var x: Int, var y: Int) { companion object { fun zero() = Point(0, 0) } operator fun plusAssign(vector: Vector) { x += vector.dx y += vector.dy } operator fun minus(other: Point): Vector { return Vector(x - other.x, y - other.y) } } data class Vector(val dx: Int, val dy: Int) { fun abs(): Vector { return Vector(dx.absoluteValue, dy.absoluteValue) } operator fun div(other: Vector): Vector { return Vector(dx / max(other.dx, 1), dy / max(other.dy, 1)) } } class Rope(knotsAmount: Int = 2) { private val knots = List(knotsAmount) { Point.zero() } private val head = knots[0] val tailTrack = mutableSetOf(Point.zero()) fun moveHead(vector: Vector) { val abs = vector.abs() val steps = max(abs.dx, abs.dy) val step = vector / abs repeat(steps) { head += step (1..knots.lastIndex).forEach { val segmentHead = knots[it - 1] val segmentTail = knots[it] val segment = segmentHead - segmentTail val segmentAbs = segment.abs() val segmentStep = segment / segmentAbs val moveHorizontally = segmentAbs.dx > 1 val moveVertically = segmentAbs.dy > 1 segmentTail.x = when { moveVertically && !moveHorizontally -> segmentHead.x moveHorizontally -> segmentHead.x - segmentStep.dx else -> segmentTail.x } segmentTail.y = when { moveHorizontally && !moveVertically -> segmentHead.y moveVertically -> segmentHead.y - segmentStep.dy else -> segmentTail.y } } tailTrack.add(knots.last().copy()) } } } fun main() { fun parseInstruction(line: String): Vector { val (code, stepsString) = line.split(' ') val steps = stepsString.toInt() return when (code.first()) { 'U' -> Vector(0, -steps) 'D' -> Vector(0, steps) 'L' -> Vector(-steps, 0) 'R' -> Vector(steps, 0) else -> throw Exception("Unknown instruction") } } fun part1(input: List<String>): Int { val rope = Rope() input.forEach { rope.moveHead(parseInstruction(it)) } return rope.tailTrack.size } fun part2(input: List<String>): Int { val rope = Rope(10) input.forEach { rope.moveHead(parseInstruction(it)) } return rope.tailTrack.size } val testInput = readInput("Day09_test") check(part1(testInput) == 13) check(part2(testInput) == 1) val input = readInput("Day09") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
843869d19d5457dc972c98a9a4d48b690fa094a6
2,919
aoc-2022
Apache License 2.0
advent-of-code-2022/src/Day05.kt
osipxd
572,825,805
false
{"Kotlin": 141640, "Shell": 4083, "Scala": 693}
import java.util.* // Use run { ... } to reuse the same local variables names :P fun main() { run { val (testStacks, testCommands) = readInput("Day05_test") check(part1(testStacks.clone(), testCommands) == "CMZ") val (inputStacks, inputCommands) = readInput("Day05") println("Part 1: " + part1(inputStacks.clone(), inputCommands)) } run { val (testStacks, testCommands) = readInput("Day05_test") check(part2(testStacks.clone(), testCommands) == "MCD") val (inputStacks, inputCommands) = readInput("Day05") println("Part 2: " + part2(inputStacks.clone(), inputCommands)) } } private fun part1(crates: Array<LinkedList<Char>>, commands: List<List<Int>>): String { for ((count, from, to) in commands) { repeat(count) { crates[to].push(crates[from].pop()) } } return crates.joinToString("") { it.firstOrNull()?.toString().orEmpty() } } private fun part2(crates: Array<LinkedList<Char>>, commands: List<List<Int>>): String { val buffer = LinkedList<Char>() for ((count, from, to) in commands) { repeat(count) { buffer.push(crates[from].pop()) } while (buffer.isNotEmpty()) crates[to].push(buffer.pop()) } return crates.joinToString("") { it.firstOrNull()?.toString().orEmpty() } } // See also Day05_input_reformat.gif if you want to simplify input private fun readInput(name: String): Pair<Array<LinkedList<Char>>, List<List<Int>>> { // Split input to two parts and convert to lines val (cratesLines, commandsLines) = readText(name).split("\n\n").map { it.lines() } val n = (cratesLines.last().length + 3) / 4 // size = n + 1 because indices of crates in commands start from 1, not 0 val crates = Array(n + 1) { LinkedList<Char>() } for (lineIndex in cratesLines.size - 2 downTo 0) { for (i in 0 until n) { val char = cratesLines[lineIndex][i * 4 + 1] if (char != ' ') crates[i + 1].push(char) } } // Just take all numbers from commands val commands = commandsLines.map { it.split(" ").mapNotNull(String::toIntOrNull) } return crates to commands }
0
Kotlin
0
5
6a67946122abb759fddf33dae408db662213a072
2,168
advent-of-code
Apache License 2.0
src/Day19.kt
schoi80
726,076,340
false
{"Kotlin": 83778}
import java.util.LinkedList import kotlin.math.max import kotlin.math.min typealias Workflow = Map<String, List<String>> typealias PartRange = Array<IntRange> fun initPartRange(i: Int) = arrayOf(1..i, 1..i, 1..i, 1..i) fun initWorkflow(input: Input): Workflow { return input.takeWhile { it.isNotEmpty() }.associate { val key = it.takeWhile { it != '{' } val value = it.takeLast(it.length - key.length).drop(1).dropLast(1).split(",") key to value } } fun List<Int>.getValue(c: Char) = this[c.getIndex()] fun Char.getIndex() = when (this) { 'x' -> 0 'm' -> 1 'a' -> 2 's' -> 3 else -> error("asdasd") } fun Workflow.result(state: String, input: List<Int>): String { if (state == "A" || state == "R") return state val conditions = this[state]!! return result(nextState(conditions, input), input) } fun nextState(s: List<String>, input: List<Int>): String { (0..<s.size - 1).forEach { i -> val (condition, next) = s[i].split(":", limit = 2) val n1 = input.getValue(condition[0]) val n2 = condition.drop(2).toInt() val c = condition[1] val conditionMet = when (c) { '<' -> n1 < n2 '>' -> n1 > n2 else -> error("asdad") } if (conditionMet) return next } return s.last() } fun PartRange.apply(partKey: Char, v: Int, eq: Char): PartRange { val input = this.clone() val partIndex = partKey.getIndex() when (eq) { '<' -> input[partIndex] = input[partIndex].first..<v '>' -> input[partIndex] = v + 1..input[partIndex].last else -> error("cannot happen") } return input } fun PartRange.negate(partKey: Char, v: Int, eq: Char): PartRange { val input = this.clone() val partIndex = partKey.getIndex() when (eq) { '>' -> input[partIndex] = input[partIndex].first..min(v, input[partIndex].last) '<' -> input[partIndex] = max(v, input[partIndex].first)..input[partIndex].last else -> error("cannot happen") } return input } fun main() { fun part1(input: List<String>): Long { val wf = initWorkflow(input) val parts = input.takeLastWhile { it.isNotEmpty() } .map { it.drop(1).dropLast(1).split(",", limit = 4).map { it.drop(2).toInt() } } return parts.sumOf { s -> val r = wf.result("in", s) if (r == "A") s.sum().toLong() else 0L } } fun part2(input: List<String>): Long { val wf = initWorkflow(input) val result = mutableSetOf<PartRange>() val queue = LinkedList<Pair<String, PartRange>>() queue.add("in" to initPartRange(4000)) while (queue.isNotEmpty()) { val (currState, currRange) = queue.pop() when (currState) { "A" -> result.add(currRange) "R" -> continue else -> { var tempRange = currRange wf[currState]!!.forEach { rule -> val (nextState, condition) = rule.split(":").let {t -> if (t.size == 1) t[0] to null else t[1] to t[0] } if (condition != null) { val partKey = condition[0] val v = condition.drop(2).toInt() val eq = condition[1] queue.add(nextState to tempRange.apply(partKey,v,eq)) tempRange = tempRange.negate(partKey,v,eq) } else { queue.add(nextState to tempRange) } } } } } return result.sumOf { (it[0].last - it[0].first + 1L) * (it[1].last - it[1].first + 1L) * (it[2].last - it[2].first + 1L) * (it[3].last - it[3].first + 1L) } } val input = readInput("Day19") part1(input).println() part2(input).println() }
0
Kotlin
0
0
ee9fb20d0ed2471496185b6f5f2ee665803b7393
4,133
aoc-2023
Apache License 2.0
src/aoc2023/Day15.kt
RobertMaged
573,140,924
false
{"Kotlin": 225650}
package aoc2023 import utils.checkEquals import utils.readInput fun main(): Unit = with(Day15) { part1(testInput.first()).checkEquals(52) part1(testInput[1]).checkEquals(1320) part1(input.single()) .checkEquals(516657) // .sendAnswer(part = 1, day = "15", year = 2023) part2(testInput[1]).checkEquals(145) part2(input.single()) .checkEquals(210906) // .sendAnswer(part = 2, day = "15", year = 2023) } object Day15 { fun part1(input: String): Int = input .split(',') .sumOf { it.getHash() } fun part2(input: String): Int { val regex = "(\\w+)([=-])(\\d*)".toRegex() val boxes = Array(256) { mutableListOf<Pair<String, Int>>() } for (it in input.split(',')) { val (label, operation, focalLengthOrBlank) = regex.matchEntire(it)!!.destructured val box = label.getHash() val slots = boxes[box] val slotIndexOrNull = slots.indexOfFirst { it.first == label }.takeUnless { it == -1 } when { operation == "-" && slotIndexOrNull != null -> slots.removeAt(slotIndexOrNull) operation == "=" -> with(label to focalLengthOrBlank.toInt()) { if (slotIndexOrNull == null) slots.add(this) else slots[slotIndexOrNull] = this } } } return boxes.flatMapIndexed { boxIndex, slots: List<Pair<String, Int>> -> slots.mapIndexed { slotIndex, slot -> (boxIndex + 1) * (slotIndex + 1) * slot.second } }.sum() } private fun String.getHash() = fold(0) { acc, c -> (acc + c.code) * 17 % 256 } val input get() = readInput("Day15", "aoc2023") val testInput get() = readInput("Day15_test", "aoc2023") }
0
Kotlin
0
0
e2e012d6760a37cb90d2435e8059789941e038a5
1,904
Kotlin-AOC-2023
Apache License 2.0
src/main/kotlin/org/sj/aoc2022/day05/CrateReArranger.kt
sadhasivam
573,168,428
false
{"Kotlin": 10910}
package org.sj.aoc2022.day05 import org.sj.aoc2022.util.readInput fun rearrange(crates: List<MutableList<String>>, count: Int, from: Int, to: Int, inOrder: Boolean) { val fromCrate = crates[from] val toCrate = crates[to] val toCrateSize = toCrate.size repeat(count) { if (inOrder) { toCrate.add(toCrateSize, fromCrate.removeLast()) } else { toCrate.add(fromCrate.removeLast()) } } /* println("--------------------------------") crates.forEachIndexed { index, stack -> println("stack$index $stack") } println("--------------------------------")*/ } fun makeCrates(input: List<String>): List<MutableList<String>> { val crates = List(input.reversed().first().split(" ").count()) { mutableListOf<String>() } input.reversed().subList(1, input.size).map { it.chunked(4).forEachIndexed { index, item -> if (item.trim().isNotBlank()) { crates[index].add(item.trim()) } } } return crates } private fun List<List<String>>.topItem(): String = this.joinToString("") { it.last().removePrefix("[").removeSuffix("]") } fun rearrangeCrate(input: List<String>, instructions: List<String>, inOrder: Boolean): String { val crates = makeCrates(input) instructions.map { val a = it.split(" ") val count = a[1].toInt() val from = a[3].toInt() val to = a[5].toInt() // println("$count -> $from -> $to") rearrange(crates, count, from - 1, to - 1, inOrder) } return crates.topItem() } fun main() { val basePath = "/org/sj/aoc2022/day05/" var input = readInput("${basePath}Day05Stack_test") var instructions = readInput("${basePath}Day05Instruction_test") check(rearrangeCrate(input, instructions, false) == "CMZ") check(rearrangeCrate(input, instructions, true) == "MCD") input = readInput("${basePath}Day05Stack") instructions = readInput("${basePath}Day05Instruction") check(rearrangeCrate(input, instructions, false) == "LJSVLTWQM") println(rearrangeCrate(input, instructions, true)) }
0
Kotlin
0
0
7a1ceaddbe7e72bad0e9dfce268387d333b62143
2,152
advent-of-code-kotlin-2022
Apache License 2.0
src/Day07.kt
ech0matrix
572,692,409
false
{"Kotlin": 116274}
fun main() { // Returns root directory fun setupFileSystem(input: List<String>): Directory { // Setup root val root = Directory("/", null) var currentDir = root // Run through commands for(line in input) { val split = line.split(' ') if (split[0] == "$" && split[1] == "cd") { // Change directory currentDir = when(split[2]) { "/" -> root ".." -> currentDir.parentDirectory!! else -> currentDir.subDirectories.find { it.name == split[2] }!! } } else if (split[0] == "$" && split[1] == "ls") { // List current directory // (Ignore -- we assume any non-commands are part of 'ls' results) } else if (split[0] == "dir") { // Dir in current directory currentDir.subDirectories.add(Directory(split[1], currentDir)) } else { // File in current directory currentDir.files.add(File(split[1], split[0].toInt())) } } return root } fun part1(input: List<String>): Int { val root = setupFileSystem(input) // Calculate sizes val allSizes = mutableListOf<Int>() root.getSize(allSizes) // Total all less than or equal to 100000 return allSizes.filter { it <= 100000 }.sum() } fun part2(input: List<String>): Int { val root = setupFileSystem(input) // Calculate sizes val allSizes = mutableListOf<Int>() root.getSize(allSizes) // Get amount needed to free up allSizes.sortDescending() val minFree = 30000000 - (70000000 - allSizes[0]) // Get smallest above minFree return allSizes.last { it >= minFree } } val testInput = readInput("Day07_test") check(part1(testInput) == 95437) check(part2(testInput) == 24933642) val input = readInput("Day07") println(part1(input)) println(part2(input)) } data class Directory( val name: String, val parentDirectory: Directory? ) { val files = mutableListOf<File>() val subDirectories = mutableListOf<Directory>() fun getSize(allSizes: MutableList<Int>): Int { val fileSizes = files.sumOf { it.size } val dirSizes = subDirectories.sumOf { it.getSize(allSizes) } val totalSize = fileSizes + dirSizes allSizes.add(totalSize) return totalSize } } data class File( val name: String, val size: Int )
0
Kotlin
0
0
50885e12813002be09fb6186ecdaa3cc83b6a5ea
2,603
aoc2022
Apache License 2.0
src/Day03.kt
rinas-ink
572,920,513
false
{"Kotlin": 14483}
import java.lang.IllegalArgumentException fun main() { fun evalLetter(c: Char) = 1 + if (c - 'a' + 1 > 0) c - 'a' else c - 'A' + 26 fun evalStep1(s: String): Int { val comp1: CharArray = s.substring(0, s.length / 2).toCharArray() comp1.sort() val comp2: CharArray = s.substring(s.length / 2).toCharArray() comp2.sort() var l = 0 var r = 0 while (r < comp1.size || l < comp2.size) { if (comp1[l] == comp2[r]) return evalLetter(comp1[l]) when { (r >= comp2.size - 1) -> l++ (l >= comp1.size - 1) -> r++ (comp1[l] < comp2[r]) -> l++ else -> r++ } } return 0 } fun part1(input: List<String>): Int = input.fold(0) { sum, step -> sum + evalStep1(step) } fun evalStep2(s: List<String>) = evalLetter(s[0].toList().intersect(s[1].toList()).intersect(s[2].toList()).single()) fun part2(input: List<String>): Int = input.chunked(3).map(::evalStep2).sum() // test if implementation meets criteria from the description, like: val testInput = readInput("Day03_test") check(part1(testInput) == 157) check(part2(testInput) == 12) val input = readInput("Day03") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
462bcba7779f7bfc9a109d886af8f722ec14c485
1,334
anvent-kotlin
Apache License 2.0
src/Day10.kt
FuKe
433,722,611
false
{"Kotlin": 19825}
import java.util.* private val pointMap: Map<String, Int> = mapOf( ")" to 3, "]" to 57, "}" to 1197, ">" to 25137 ) private val closes: Map<String, String> = mapOf( "(" to ")", "[" to "]", "{" to "}", "<" to ">" ) fun main() { test() val puzzleInput: List<String> = readInput("Day10.txt") val aResult: Int = aSolver(puzzleInput) println("Part one result: $aResult") } private fun aSolver(puzzleInput: List<String>): Int { var pointResult = 0 puzzleInput.forEach { chunk -> val open: Stack<String> = Stack() for (char in chunk) { val charStr: String = char.toString() if (charStr in closes.keys) { open.push(charStr) } else if (closes[open.peek()] == charStr) { open.pop() } else { pointResult += pointMap[charStr]!! break } } } return pointResult } private fun bSolver(puzzleInput: List<String>): Int { TODO() } private fun test() { val testInput: List<String> = listOf( "[({(<(())[]>[[{[]{<()<>>", "[(()[<>])]({[<{<<[]>>(", "{([(<{}[<>[]}>{[]{[(<()>", "(((({<>}<{<{<>}{[]{[]{}", "[[<[([]))<([[{}[[()]]]", "[{[{({}]{}}([{[{{{}}([]", "{<[[]]>}<{[{[{[]{()[[[]", "[<(<(<(<{}))><([]([]()", "<{([([[(<>()){}]>(<<{{", "<{([{{}}[<[[[<>{}]]]>[]]" ) val aTestResult: Int = aSolver(testInput) check(aTestResult == 26397) }
0
Kotlin
0
0
1cfe66aedd83ea7df8a2bc26c453df257f349b0e
1,537
advent-of-code-2021
Apache License 2.0
src/day08/Day08.kt
ivanovmeya
573,150,306
false
{"Kotlin": 43768}
package day08 import readInput import java.lang.Integer.max /** * indicates the highest tree to the left/up/right/down from this position */ data class HeightLookup(var left: Int, var up: Int, var right: Int, var down: Int) fun main() { fun copyOuterTreeRing( lookupHeights: Array<Array<HeightLookup>>, heightMap: Array<IntArray>, n: Int, m: Int ) { lookupHeights[0] = heightMap[0].map { HeightLookup(0, it, 0, 0) }.toTypedArray() lookupHeights[n - 1] = heightMap[n - 1].map { HeightLookup(0, 0, 0, it) }.toTypedArray() heightMap.forEachIndexed { row, heights -> lookupHeights[row][0] = HeightLookup(heights[0], 0, 0, 0) lookupHeights[row][m - 1] = HeightLookup(0, 0, heights[m - 1], 0) } } fun parseHeightMap(input: List<String>): Array<IntArray> { if (input.isEmpty()) throw IllegalArgumentException("Ooops, there are no trees! Get out of here!") return input .map { line -> line.map { it.digitToInt() }.toIntArray() } .toTypedArray() } fun printHeights(input: Array<IntArray>) { input.forEach { println(it.joinToString()) } } fun printLookup(input: Array<Array<HeightLookup>>) { input.forEach { row -> println(row.joinToString { it.left.toString() }) } } fun buildMaxHeightLookup(heightMap: Array<IntArray>): Array<Array<HeightLookup>> { val n = heightMap.size val m = heightMap[0].size val lookupHeights = Array(n) { Array(m) { HeightLookup(0, 0, 0, 0) } } //copy outer ring of trees as they are totally visible copyOuterTreeRing(lookupHeights, heightMap, n, m) //4 traversal //max Left for (row in 1 until n - 1) { for (column in 1 until m - 1) { lookupHeights[row][column].left = max(lookupHeights[row][column - 1].left, heightMap[row][column - 1]) } } //max Right for (row in 1 until n - 1) { for (column in m - 2 downTo 1) { lookupHeights[row][column].right = max(lookupHeights[row][column + 1].right, heightMap[row][column + 1]) } } //max Up for (column in 1 until n - 1) { for (row in 1 until m - 1) { lookupHeights[row][column].up = max(lookupHeights[row - 1][column].up, heightMap[row - 1][column]) } } //max Down for (column in 1 until n - 1) { for (row in m - 2 downTo 1) { lookupHeights[row][column].down = max(lookupHeights[row + 1][column].down, heightMap[row + 1][column]) } } return lookupHeights } fun buildScenicScoreMap(heightMap: Array<IntArray>): Array<IntArray> { val rows = heightMap.size val columns = heightMap[0].size val scenicScoreMap = Array(rows) { IntArray(columns) } for (row in 1 until rows - 1) { for (column in 1 until columns - 1) { val height = heightMap[row][column] var scenicScore: Int //go left var i = column - 1 var leftScore = 1 while (i > 0 && heightMap[row][i] < height) { leftScore++ i-- } //go right i = column + 1 var rightScore = 1 while (i < columns - 1 && heightMap[row][i] < height) { rightScore++ i++ } //go up var j = row - 1 var upScore = 1 while (j > 0 && heightMap[j][column] < height) { j-- upScore++ } //go down j = row + 1 var downScore = 1 while (j < rows - 1 && heightMap[j][column] < height) { downScore++ j++ } scenicScore = leftScore * upScore * rightScore * downScore scenicScoreMap[row][column] = scenicScore } } return scenicScoreMap } fun part1(input: List<String>): Int { val heightMap = parseHeightMap(input) val lookupMap = buildMaxHeightLookup(heightMap) //now look at each tree and check if it is visible //the tree is visible if value more than at least one value in all dimensions in lookupMap[row][column] val corners = 4 val outerRingSize = (heightMap.size + heightMap[0].size) * 2 - corners var visibleTreeCount = 0 for (row in 1 until heightMap.size - 1) { for (column in 1 until heightMap[0].size - 1) { val height = heightMap[row][column] val lookup = lookupMap[row][column] val isVisible = height > lookup.left || height > lookup.up || height > lookup.right || height > lookup.down if (isVisible) { visibleTreeCount++ } } } return outerRingSize + visibleTreeCount } fun part2(input: List<String>): Int { val heightMap = parseHeightMap(input) return buildScenicScoreMap(heightMap).maxOf { rows -> rows.maxOf { it } } } val testInput = readInput("day08/input_test") val test1Result = part1(testInput) val test2Result = part2(testInput) println(test1Result) println(test2Result) check(test1Result == 21) check(test2Result == 8) val input = readInput("day08/input") val part1 = part1(input) val part2 = part2(input) check(part1 == 1794) check(part2 == 199272) println(part1) println(part2) }
0
Kotlin
0
0
7530367fb453f012249f1dc37869f950bda018e0
5,942
advent-of-code-2022
Apache License 2.0
src/main/kotlin/adventofcode/year2023/Day07CamelCards.kt
pfolta
573,956,675
false
{"Kotlin": 199554, "Dockerfile": 227}
package adventofcode.year2023 import adventofcode.Puzzle import adventofcode.PuzzleInput import adventofcode.year2023.Day07CamelCards.Companion.HandType.FIVE_OF_A_KIND import adventofcode.year2023.Day07CamelCards.Companion.HandType.FOUR_OF_A_KIND import adventofcode.year2023.Day07CamelCards.Companion.HandType.FULL_HOUSE import adventofcode.year2023.Day07CamelCards.Companion.HandType.HIGH_CARD import adventofcode.year2023.Day07CamelCards.Companion.HandType.ONE_PAIR import adventofcode.year2023.Day07CamelCards.Companion.HandType.THREE_OF_A_KIND import adventofcode.year2023.Day07CamelCards.Companion.HandType.TWO_PAIR class Day07CamelCards(customInput: PuzzleInput? = null) : Puzzle(customInput) { override fun partOne() = input .lines() .asSequence() .map { it.split(" ") } .map { (hand, bid) -> Hand(hand) to bid.toInt() } .sortedBy { (hand) -> hand } .mapIndexed { rank, (_, bid) -> (rank + 1) * bid } .sum() companion object { private data class Card( val label: Char ) : Comparable<Card> { override fun compareTo(other: Card) = cardRank.indexOf(label) - cardRank.indexOf(other.label) companion object { private val cardRank = listOf('2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A') } } private data class Hand( val cards: List<Card> ) : Comparable<Hand> { private val cardCounts = cards.groupingBy { it }.eachCount() fun handType() = when { cardCounts.any { (_, count) -> count == 5 } -> FIVE_OF_A_KIND cardCounts.any { (_, count) -> count == 4 } -> FOUR_OF_A_KIND cardCounts.size == 2 -> FULL_HOUSE cardCounts.any { (_, count) -> count == 3 } -> THREE_OF_A_KIND cardCounts.filter { (_, count) -> count == 2 }.size == 2 -> TWO_PAIR cardCounts.any { (_, count) -> count == 2 } -> ONE_PAIR else -> HIGH_CARD } override fun compareTo(other: Hand) = when (val rank = handType().rank - other.handType().rank) { 0 -> cards .zip(other.cards) .map { (thisHandCard, otherHandCard) -> thisHandCard.compareTo(otherHandCard) } .first { it != 0 } else -> rank } companion object { operator fun invoke(input: String) = Hand(input.toList().map(::Card)) } } private enum class HandType(val rank: Int) { FIVE_OF_A_KIND(6), FOUR_OF_A_KIND(5), FULL_HOUSE(4), THREE_OF_A_KIND(3), TWO_PAIR(2), ONE_PAIR(1), HIGH_CARD(0) } } }
0
Kotlin
0
0
72492c6a7d0c939b2388e13ffdcbf12b5a1cb838
2,868
AdventOfCode
MIT License
kotlin/src/test/kotlin/nl/dirkgroot/adventofcode/year2022/Day24Test.kt
dirkgroot
724,049,902
false
{"Kotlin": 203339, "Rust": 123129, "Clojure": 78288}
package nl.dirkgroot.adventofcode.year2022 import io.kotest.core.spec.style.StringSpec import io.kotest.matchers.shouldBe import nl.dirkgroot.adventofcode.util.input import nl.dirkgroot.adventofcode.util.invokedWith private fun solution1(input: String) = Valley.parse(input).let { valley -> generateSequence(valley) { it.next() } .takeWhile { it.map[it.destinationY][it.destinationX] != '*' } .count() } private fun solution2(input: String) = Valley.parse(input).let { valley -> val (m1, goal1) = generateSequence(valley) { it.next() }.withIndex() .first { (_, v) -> v.map[v.destinationY][v.destinationX] == '*' } goal1.reset(goal1.destinationY, goal1.destinationX) val (m2, start) = generateSequence(goal1) { it.next() }.withIndex() .first { (_, v) -> v.map[Valley.START_Y][Valley.START_X] == '*' } start.reset(Valley.START_Y, Valley.START_X) val (m3, _) = generateSequence(start) { it.next() }.withIndex() .first { (_, v) -> v.map[v.destinationY][v.destinationX] == '*' } m1 + m2 + m3 } private class Valley(val map: Array<Array<Char>>, val blizzards: List<Blizzard>) { val height = map.size val width = map[0].size val destinationY = map.lastIndex val destinationX = map.last().lastIndex - 1 companion object { const val START_Y = 0 const val START_X = 1 fun parse(input: String): Valley { val lines = input.lines() val map = lines.mapIndexed { _, line -> line.map { c -> if (c == '#' || c == '.') c else '.' }.toTypedArray() }.toTypedArray() val blizzards = lines.flatMapIndexed { y, line -> line.withIndex() .filter { (_, v) -> v != '#' && v != '.' } .map { (x, c) -> Blizzard(y, x, Direction.parse(c)) } } map[START_Y][START_X] = '*' return Valley(map, blizzards) } } fun next(): Valley { val nextBlizzards = blizzards.map { blizzard -> val (dy, dx) = when (blizzard.dir) { Direction.U -> -1 to 0 Direction.D -> 1 to 0 Direction.L -> 0 to -1 Direction.R -> 0 to 1 } val path = generateSequence(blizzard.y + dy to blizzard.x + dx) { (y, x) -> (y + dy + height) % height to (x + dx + width) % width } val (newY, newX) = path.first { (y, x) -> map[y][x] != '#' } Blizzard(newY, newX, blizzard.dir) } val nextMap = Array(map.size) { i -> map[i].copyOf() } (1 until nextMap.lastIndex).forEach { y -> (1 until nextMap[y].lastIndex).forEach { x -> val setStar = sequenceOf(y to x - 1, y to x + 1, y - 1 to x, y + 1 to x) .filter { (y, x) -> y >= 0 && x < width } .any { (y, x) -> map[y][x] == '*' } if (setStar) nextMap[y][x] = '*' } } if (map[START_Y + 1][START_X] == '*') nextMap[START_Y][START_X] = '*' if (map[destinationY - 1][destinationX] == '*') nextMap[destinationY][destinationX] = '*' nextBlizzards.forEach { (y, x, _) -> nextMap[y][x] = '.' } return Valley(nextMap, nextBlizzards) } fun reset(startY: Int, startX: Int) { map.indices.forEach { y -> map[y].indices.forEach { x -> if (map[y][x] != '#') map[y][x] = '.' } } map[startY][startX] = '*' } data class Blizzard(val y: Int, val x: Int, val dir: Direction) enum class Direction { U, D, L, R; companion object { fun parse(c: Char) = when (c) { '^' -> U 'v' -> D '<' -> L '>' -> R else -> throw IllegalArgumentException() } } } } //===============================================================================================\\ private const val YEAR = 2022 private const val DAY = 24 class Day24Test : StringSpec({ "example part 1" { ::solution1 invokedWith exampleInput shouldBe 18 } "part 1 solution" { ::solution1 invokedWith input(YEAR, DAY) shouldBe 242 } "example part 2" { ::solution2 invokedWith exampleInput shouldBe 54 } "part 2 solution" { ::solution2 invokedWith input(YEAR, DAY) shouldBe 720 } }) private val exampleInput = """ #.###### #>>.<^<# #.<..<<# #>v.><># #<^v^^># ######.# """.trimIndent()
1
Kotlin
0
0
ced913cd74378a856813973a45dd10fdd3570011
4,547
adventofcode
MIT License
src/main/kotlin/days/Day7.kt
minibugdev
322,172,909
true
{"Kotlin": 17258}
package days class Day7 : Day(7) { private val bags = transformInputToBags(inputList) override fun partOne(): Any { fun searchBag(name: String): Set<Bag> { val containerBags = bags.filter { bag -> bag.contains?.keys?.contains(Bag(name, null)) == true }.toSet() return if (containerBags.isNotEmpty()) { containerBags + containerBags.flatMap { searchBag(it.name) } } else { emptySet() } } val shinyGoldContainerBags = searchBag("shiny gold") return shinyGoldContainerBags.size } override fun partTwo(): Any { fun insideBagCount(name: String): Int { val bagInsides = bags.first { it.name == name }.contains return bagInsides?.keys?.sumBy { bag -> val qty = bagInsides[bag]!! qty + (qty * insideBagCount(bag.name)) } ?: 0 } return insideBagCount("shiny gold") } private fun transformInputToBags(inputList: List<String>): List<Bag> = inputList.map { input -> val (bag, insideBags) = input.split(" bags contain ") if (insideBags == "no other bags.") { Bag(bag, null) } else { val contains = mutableMapOf<Bag, Int>() insideBags.split(", ").forEach { val insideBag = it.split(" ") val name = "${insideBag[1]} ${insideBag[2]}" val qty = insideBag[0].toInt() contains[Bag(name, null)] = qty } Bag(bag, contains) } } private data class Bag(val name: String, val contains: Map<Bag, Int>?) }
0
Kotlin
0
1
572f6b5620c87a41d90f1474b5e89eddb903fd6f
1,398
aoc-kotlin-starter
Creative Commons Zero v1.0 Universal
src/aoc2022/Day03.kt
anitakar
576,901,981
false
{"Kotlin": 124382}
package aoc2022 import println import readInput fun main() { fun priority(c: Char): Int { if (c in 'A'..'Z') { return c - 'A' + 27 } else if (c in 'a'..'z') { return c - 'a' + 1 } return 0 } fun part1(input: List<String>): Int { var sum = 0 for (line in input) { val first = line.substring(0, line.length / 2 + 1).toCharArray().toSet() val second = line.substring(line.length / 2).toCharArray().toSet() val elem = first.first { second.contains(it) } val priority = priority(elem) sum += priority } return sum } fun part2(input: List<String>): Int { var sum = 0 for (group in 0..input.size / 3 - 1) { val elf1 = input[3 * group].toCharArray().toSet() val elf2 = input[3 * group + 1].toCharArray().toSet() val elf3 = input[3 * group + 2].toCharArray().toSet() val elf1and2 = elf1.filter { it in elf2 } val elf1and3 = elf1.filter { it in elf3 } val allElves = elf1and2.first { it in elf1and3 } sum += priority(allElves) } return 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") part1(input).println() part2(input).println() }
0
Kotlin
0
1
50998a75d9582d4f5a77b829a9e5d4b88f4f2fcf
1,504
advent-of-code-kotlin
Apache License 2.0
src/main/kotlin/aoc2022/Day24.kt
j4velin
572,870,735
false
{"Kotlin": 285016, "Python": 1446}
package aoc2022 import Point import readInput import kotlin.math.min object Day24 { private enum class Direction(val delta: Point) { NORTH(Point(0, -1)), SOUTH(Point(0, 1)), EAST(Point(1, 0)), WEST(Point(-1, 0)); override fun toString() = when (this) { NORTH -> "^" SOUTH -> "v" EAST -> ">" WEST -> "<" } companion object { fun fromChar(char: Char) = when (char) { '>' -> EAST '<' -> WEST '^' -> NORTH 'v' -> SOUTH else -> throw IllegalArgumentException("Not a valid direction: $char") } } } private fun Point.move(direction: Direction) = this + direction.delta private data class Blizzard(val position: Point, val direction: Direction) private data class BlizzardConfig(val blizzards: Collection<Blizzard>) { fun next(maxX: Int, maxY: Int) = BlizzardConfig(blizzards.map { var newPosition = it.position.move(it.direction) if (newPosition.x == 0) { newPosition = Point(maxX - 1, newPosition.y) } else if (newPosition.x == maxX) { newPosition = Point(1, newPosition.y) } else if (newPosition.y == 0) { newPosition = Point(newPosition.x, maxY - 1) } else if (newPosition.y == maxY) { newPosition = Point(newPosition.x, 1) } Blizzard(newPosition, it.direction) }) } private data class State(val minute: Int, val position: Point, val blizzardConfig: BlizzardConfig) private data class Result(val minDuration: Int, val finalBlizzardConfig: BlizzardConfig) private fun move( start: Point, end: Point, blizzardConfig: BlizzardConfig, map: Array<CharArray> ): Result { val validGrid = Point(0, 0) to Point(map.first().size - 1, map.size - 1) val toVisit = mutableListOf(State(0, start, blizzardConfig)) val minDistances = mutableMapOf<Pair<Point, Int>, Int>() minDistances[start to blizzardConfig.hashCode()] = 0 var minDistanceToEnd = Int.MAX_VALUE var blizzardConfigAtEnd = blizzardConfig while (toVisit.isNotEmpty()) { val current = toVisit.minBy { it.minute + it.position.distanceTo(end) } toVisit.remove(current) val (currentMinute, currentPosition, currentBlizzardConfig) = current if (currentMinute + currentPosition.distanceTo(end) >= minDistanceToEnd) { continue } else if (currentPosition == end) { minDistanceToEnd = min(minDistanceToEnd, currentMinute) blizzardConfigAtEnd = currentBlizzardConfig } val neighbours = currentPosition.getNeighbours(validGrid = validGrid).filter { map[it.y][it.x] != '#' } val nextConfig = currentBlizzardConfig.next(validGrid.second.x, validGrid.second.y) val nextPositions = sequence { yield(currentPosition) // also consider waiting at the current position yieldAll(neighbours) } val next = nextPositions.filter { n -> nextConfig.blizzards.find { it.position == n } == null } .map { it to nextConfig.hashCode() } .filter { !minDistances.contains(it) || minDistances[it]!! > currentMinute + 1 }.onEach { minDistances[it] = currentMinute + 1 }.map { State(currentMinute + 1, it.first, nextConfig) } toVisit.addAll(next) } return Result(minDistanceToEnd, blizzardConfigAtEnd) } fun part1(input: List<String>): Int { val map = input.map { row -> row.toCharArray() }.toTypedArray() val blizzardConfig = BlizzardConfig(map.withIndex().flatMap { (y, row) -> row.withIndex().filter { it.value != '#' && it.value != '.' }.map { (x, direction) -> Blizzard(Point(x, y), Direction.fromChar(direction)) } }) val start = Point(map.first().indexOfFirst { it == '.' }, 0) val end = Point(map.last().indexOfFirst { it == '.' }, map.size - 1) return move(start, end, blizzardConfig, map).minDuration } fun part2(input: List<String>): Int { val map = input.map { row -> row.toCharArray() }.toTypedArray() val initialBlizzardConfig = BlizzardConfig(map.withIndex().flatMap { (y, row) -> row.withIndex().filter { it.value != '#' && it.value != '.' }.map { (x, direction) -> Blizzard(Point(x, y), Direction.fromChar(direction)) } }) val start = Point(map.first().indexOfFirst { it == '.' }, 0) val end = Point(map.last().indexOfFirst { it == '.' }, map.size - 1) val startToEnd = move(start, end, initialBlizzardConfig, map) val endToStart = move(end, start, startToEnd.finalBlizzardConfig, map) val startToEndAgain = move(start, end, endToStart.finalBlizzardConfig, map) return startToEnd.minDuration + endToStart.minDuration + startToEndAgain.minDuration } } fun main() { val testInput = readInput("Day24_test", 2022) check(Day24.part1(testInput) == 18) check(Day24.part2(testInput) == 54) val input = readInput("Day24", 2022) println(Day24.part1(input)) println(Day24.part2(input)) }
0
Kotlin
0
0
f67b4d11ef6a02cba5b206aba340df1e9631b42b
5,457
adventOfCode
Apache License 2.0
src/Day01.kt
thomasreader
573,047,664
false
{"Kotlin": 59975}
import java.io.Reader import java.util.SortedSet fun main() { val testInput = """ 1000 2000 3000 4000 5000 6000 7000 8000 9000 10000 """.trimIndent() check( partOne(countCalories(testInput.reader())) == 24000 ) val input = reader("Day01.txt") println(partOne(countCalories(input))) check( partTwo(countCalories(testInput.reader())) == 45000 ) println(partTwo(countCalories(reader("Day01.txt")))) } fun partOne(elves: SortedSet<Elf>): Int { return elves.first().calories } fun partTwo(elves: SortedSet<Elf>): Int { return elves .take(3) .fold(0) { value, elf -> value + elf.calories } } data class Elf( val number: Int, val calories: Int ): Comparable<Elf> { override fun compareTo(other: Elf): Int { return this.calories.compareTo(other.calories) } class Builder(val number: Int) { var calories: Int = 0 operator fun plusAssign(moreCalories: Int) { this.calories += moreCalories } fun build() = Elf(this.number, this.calories) } } fun countCalories(source: Reader): SortedSet<Elf> { val result: SortedSet<Elf> = sortedSetOf<Elf>().descendingSet() var currentElf = Elf.Builder(1) source.forEachLine { line -> if (line.isBlank()) { val elf = currentElf.build() currentElf = Elf.Builder(elf.number + 1) result.add(elf) } else { val calories = line.toInt() currentElf += calories } } result.add(currentElf.build()) return result }
0
Kotlin
0
0
eff121af4aa65f33e05eb5e65c97d2ee464d18a6
1,687
advent-of-code-2022-kotlin
Apache License 2.0
src/Day03.kt
bogdanbeczkowski
572,679,090
false
{"Kotlin": 8398}
fun main() { fun part1(input: List<String>): Int { var priority = 0 for (line in input) { val compartmentLength = line.length / 2 val compartments = line.chunked(compartmentLength) val first = compartments.first().toCharArray() val second = compartments.last().toCharArray() val commonElement = first.intersect(second.asIterable()).first() var elementPriority: Int if (commonElement in 'a'.rangeTo('z')) { elementPriority = commonElement.code - 'a'.code + 1 } else { elementPriority = commonElement.code - 'A'.code + 27 } priority += elementPriority } return priority } fun part2(input: List<String>): Int { var priority = 0 for (group in input.chunked(3)) { val sets = group.map { it.toCharArray().asIterable() } val commonElement = sets[0].intersect(sets[1]).intersect(sets[2]).first() var elementPriority: Int if (commonElement in 'a'.rangeTo('z')) { elementPriority = commonElement.code - 'a'.code + 1 } else { elementPriority = commonElement.code - 'A'.code + 27 } priority += elementPriority } return priority } // 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
03c29c7571e0d98ab00ee5c4c625954c0a46ab00
1,644
AoC-2022-Kotlin
Apache License 2.0
src/main/kotlin/Day3.kt
Ostkontentitan
434,500,914
false
{"Kotlin": 73563}
fun puzzleDayThreePartOne() { val inputs = readInput(3) val totalInputs = inputs.size val chunkSize = inputs[0].length val mostSignificant = (0 until chunkSize).joinToString(separator = "") { index -> val oneCount = inputs.map { it[index] }.count { char -> char == '1' } if (oneCount > (totalInputs / 2)) "1" else "0" } val leastSignificant = mostSignificant.swapBinary() val gamma = Integer.parseUnsignedInt(mostSignificant, 2) val epsilon = Integer.parseUnsignedInt(leastSignificant, 2) println(gamma * epsilon) } fun puzzleDayThreePartTwo() { val inputs = readInput(3) val oxygenBinary = inputs.foldDownBySignificance(false) val co2Binary = inputs.foldDownBySignificance(true) val oxygen = Integer.parseUnsignedInt(oxygenBinary, 2) val co2 = Integer.parseUnsignedInt(co2Binary, 2) println(oxygen * co2) } fun List<String>.foldDownBySignificance(byLeast: Boolean = false) = (0 until this[0].length).fold(this) { acc: List<String>, index: Int -> if (acc.size == 1) return@fold acc val oneCount = acc.map { it[index] }.count { char -> char == '1' } val zeroCount = acc.map { it[index] }.count { char -> char == '0' } val significanceBit = if (byLeast) { if (oneCount < zeroCount) '1' else '0' } else { if (oneCount >= zeroCount) '1' else '0' } acc.filter { it[index] == significanceBit } }.first() fun String.swapBinary() = map { if (it == '1') '0' else '1' }.joinToString(separator = "")
0
Kotlin
0
0
e0e5022238747e4b934cac0f6235b92831ca8ac7
1,520
advent-of-kotlin-2021
Apache License 2.0
src/main/kotlin/day18/main.kt
janneri
572,969,955
false
{"Kotlin": 99028}
package day18 import util.readTestInput private data class Coord3d(val x: Int, val y: Int, val z: Int) { fun neighbors(): List<Coord3d> = 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) ) companion object { fun parse(str: String): Coord3d = str.split(",") .let{ Coord3d(it[0].toInt(), it[1].toInt(), it[2].toInt()) } } } private const val MAX_SIDES_EXPOSED: Int = 6 private fun part1(coords: List<Coord3d>): Int = coords.sumOf { coord -> val neighborCount: Int = coord.neighbors().count { coords.contains(it) } MAX_SIDES_EXPOSED - neighborCount } private fun part2(coords: Set<Coord3d>): Int { fun getRange(func: (Coord3d) -> Int): IntRange { val values = coords.map {func(it) } return values.min() - 1 .. values.max() + 1 } // Search space is a cube around the lava: val xRange = getRange { it.x } val yRange = getRange { it.y } val zRange = getRange { it.z } // Create a queue and start from a corner val queue = ArrayDeque<Coord3d>() queue.add(Coord3d(xRange.first, yRange.first, zRange.first)) // Search for all the points of air that touch lava var sideCount = 0 val seen = mutableSetOf<Coord3d>() while (queue.isNotEmpty()) { val nextCoord = queue.removeFirst() if (nextCoord !in seen) { seen += nextCoord nextCoord.neighbors() // Stay inside the search space .filter { it.x in xRange && it.y in yRange && it.z in zRange } .forEach { neighbor -> when (neighbor) { in coords -> sideCount += 1 else -> queue.add(neighbor) } } } } return sideCount } fun main() { val lavaCoords = readTestInput("day18").map { Coord3d.parse(it) } println(part1(lavaCoords)) println(part2(lavaCoords.toSet())) }
0
Kotlin
0
0
1de6781b4d48852f4a6c44943cc25f9c864a4906
2,062
advent-of-code-2022
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/CountSubgraphsForEachDiameter.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2022 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import kotlin.math.max /** * 1617. Count Subtrees With Max Distance Between Cities * @see <a href="https://leetcode.com/problems/count-subtrees-with-max-distance-between-cities/">Source</a> */ fun interface CountSubgraphsForEachDiameter { operator fun invoke(n: Int, edges: Array<IntArray>): IntArray } class CountSubgraphsForEachDiameterDFS : CountSubgraphsForEachDiameter { private var max = 0 override operator fun invoke(n: Int, edges: Array<IntArray>): IntArray { val graph: MutableMap<Int, MutableSet<Int>> = HashMap() for (edge in edges) { graph.computeIfAbsent( edge[0], ) { HashSet() }.add(edge[1]) graph.computeIfAbsent( edge[1], ) { HashSet() }.add(edge[0]) } val ans = IntArray(n - 1) for (bit in 0 until (1 shl n)) { val subtree: MutableSet<Int?> = HashSet() for (i in 0 until n) if (bit and (1 shl i) != 0) subtree.add(i + 1) var edgeCount = 0 max = 0 for (edge in edges) { if (subtree.contains(edge[0]) && subtree.contains(edge[1])) edgeCount++ } if (edgeCount == 0 || edgeCount != subtree.size - 1) continue dfs(subtree, graph, HashSet(), subtree.iterator().next()) ans[max - 1]++ } return ans } private fun dfs(subtree: Set<Int?>, graph: Map<Int, Set<Int>>, visited: MutableSet<Int>, beg: Int?): Int { var dist1 = 0 var dist2 = 0 beg?.let { visited.add(it) } for (neighbor in graph[beg] ?: emptySet()) { if (!visited.contains(neighbor) && subtree.contains(neighbor)) { val d = dfs(subtree, graph, visited, neighbor) if (d > dist1) { dist2 = dist1 dist1 = d } else if (d > dist2) dist2 = d } } max = max(max, dist1 + dist2) return 1 + dist1 } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
2,663
kotlab
Apache License 2.0
src/Day03.kt
BrianEstrada
572,700,177
false
{"Kotlin": 22757}
fun main() { // Test Case val testInput = readInput("Day03_test") val part1TestResult = Day03.part1(testInput) println(part1TestResult) check(part1TestResult == 157) val part2TestResult = Day03.part2(testInput) println(part2TestResult) check(part2TestResult == 70) // Actual Case val input = readInput("Day03") println("Part 1: " + Day03.part1(input)) println("Part 1: " + Day03.part2(input)) } private object Day03 { val charPoints = buildMap { for (i in 'a'..'z') { this[i] = i.toInt() - 96 } for (i in 'A'..'Z') { this[i] = i.toInt() - 38 } } fun part1(input: List<String>): Int { var total = 0 for (line in input) { val (first, second) = line.chunked(line.length / 2) val secondChars = second.toCharArray() total += first.toCharArray() .filter { char -> secondChars.contains(char) } .distinct() .mapNotNull { char -> charPoints[char] } .sum() } return total } fun part2(input: List<String>): Int { var total = 0 val lineGroups = input.chunked(3) for (lines in lineGroups) { val firstLine = lines[0].toCharArray().distinct() val secondLine = lines[1].toCharArray().distinct() total += lines[2].toCharArray() .distinct() .filter { firstLine.contains(it) && secondLine.contains(it) } .mapNotNull { char -> charPoints[char] } .sum() } return total } }
1
Kotlin
0
1
032a4693aff514c9b30e979e63560dc48917411d
1,767
aoc-kotlin-2022
Apache License 2.0
src/main/kotlin/com/groundsfam/advent/y2022/d07/Day07.kt
agrounds
573,140,808
false
{"Kotlin": 281620, "Shell": 742}
package com.groundsfam.advent.y2022.d07 import com.groundsfam.advent.DATAPATH import com.groundsfam.advent.timed import kotlin.io.path.div import kotlin.io.path.useLines sealed class File { abstract val name: String } data class RegularFile(override val name: String, val size: Int) : File() { override fun toString(): String = "RegularFile($name, $size)" } data class Directory(override val name: String, var entries: List<File>, val parent: Directory?, var totalSize: Int? = null) : File() { override fun toString(): String = "Directory($name)" } fun buildFileTree(commands: List<Command>): Directory { val root = Directory("/", emptyList(), null) var workingDir: Directory = root commands.forEach { command -> when (command) { is Cd -> { workingDir = when (command.arg) { ".." -> workingDir.parent!! "/" -> root else -> workingDir.entries.filterIsInstance<Directory>().first { it.name == command.arg } } } is Ls -> { workingDir.entries = command.outputFiles.mapTo(mutableListOf()) { (name, size) -> RegularFile(name, size) } + command.outputDirs.map { Directory(it, emptyList(), workingDir) } } } } return root } // side effect: fills in the totalSize attribute of all directories in the file tree fun sumDirectorySizes(fileTree: Directory, maxSize: Int): Int = fileTree.entries.filterIsInstance<Directory>() .sumOf { sumDirectorySizes(it, maxSize) } .let { fileTree.totalSize = fileTree.entries.sumOf { entry -> when (entry) { is RegularFile -> entry.size is Directory -> entry.totalSize ?: 0 } } if (fileTree.totalSize!! <= maxSize) it + fileTree.totalSize!! else it } // assumes totalSizes are already populated fun findDirectoryToDelete(fileTree: Directory, spaceToFree: Int): Int? = fileTree.entries.asSequence() .filterIsInstance<Directory>() .map { findDirectoryToDelete(it, spaceToFree) } .plus(fileTree.totalSize) .filter { it != null && it >= spaceToFree } .filterNotNull() .minOrNull() fun main() = timed { val fileTree = (DATAPATH / "2022/day07.txt").useLines { lines -> parseCommands(lines) } .let(::buildFileTree) sumDirectorySizes(fileTree, 100_000) .also { println("Part one: $it" )} val spaceRequred = 30_000_000 val totalDisk = 70_000_000 val spaceToFree = spaceRequred - (totalDisk - fileTree.totalSize!!) findDirectoryToDelete(fileTree, spaceToFree) .also { println("Part two: $it") } }
0
Kotlin
0
1
c20e339e887b20ae6c209ab8360f24fb8d38bd2c
2,899
advent-of-code
MIT License
src/main/kotlin/aoc2018/ImmuneSystemSimulator.kt
komu
113,825,414
false
{"Kotlin": 395919}
package komu.adventofcode.aoc2018 import komu.adventofcode.utils.nonEmptyLines import java.util.* fun immuneSystemSimulator1(input: String): Int { val (x, y) = runSimulation(input, boost = 0) return maxOf(x, y) } fun immuneSystemSimulator2(input: String): Int { var min = 0 var max = 1_000_000 while (min < max) { val mid = (min + max) / 2 if (immuneSystemWinsWithBoost(input, mid)) { max = mid } else { min = mid + 1 } } return runSimulation(input, min).first } private fun immuneSystemWinsWithBoost(input: String, boost: Int): Boolean { val (immune, infection) = runSimulation(input, boost = boost) return immune > 0 && infection == 0 } private fun runSimulation(input: String, boost: Int): Pair<Int, Int> { val lines = input.nonEmptyLines() val immuneSystem = Army.parse(lines.takeWhile { it != "Infection:" }.drop(1), boost = boost) val infection = Army.parse(lines.dropWhile { it != "Infection:" }.drop(1)) while (immuneSystem.groups.isNotEmpty() && infection.groups.isNotEmpty()) { val remaining = immuneSystem.remainingUnits + infection.remainingUnits fight(immuneSystem, infection) if (remaining == immuneSystem.remainingUnits + infection.remainingUnits) break } return Pair(immuneSystem.remainingUnits, infection.remainingUnits) } private fun fight(immuneSystem: Army, infection: Army) { val targets = immuneSystem.selectTargetsFrom(infection) + infection.selectTargetsFrom(immuneSystem) val groups = (immuneSystem.groups + infection.groups).sortedWith(Group.attackOrder) for (group in groups) { val target = targets[group] ?: continue target.takeDamage(group.damageTo(target)) } immuneSystem.removeEmptyGroups() infection.removeEmptyGroups() } private class Army( var groups: List<Group> ) { val remainingUnits: Int get() = groups.sumOf { it.units } fun selectTargetsFrom(defendingArmy: Army): Map<Group, Group> { val remainingDefenders = defendingArmy.groups.toMutableList() val targetMapping = IdentityHashMap<Group, Group>() for (attacker in groups.sortedWith(Group.selectionOrder)) { val defender = remainingDefenders.maxWithOrNull(Group.targetOrdering(attacker)) if (defender != null && attacker.damageTo(defender) > 0) { remainingDefenders.remove(defender) targetMapping[attacker] = defender } } return targetMapping } fun removeEmptyGroups() { groups = groups.filter { it.units > 0 } } companion object { fun parse(lines: List<String>, boost: Int = 0) = Army(lines.map { Group.parse(it, boost) }) } } private class Group( var units: Int, private val hp: Int, val weaknesses: List<String>, val immunities: List<String>, private val attackDamage: Int, val attackType: String, val initiative: Int, ) { fun damageTo(target: Group): Int = when (attackType) { in target.immunities -> 0 in target.weaknesses -> 2 * effectivePower else -> effectivePower } fun takeDamage(damage: Int) { // var remainingDamage = damage // while (remainingDamage >= hp) { // units-- // remainingDamage -= hp // } // units = units.coerceAtLeast(0) units -= (damage / hp).coerceAtMost(units) } val effectivePower: Int get() = units * attackDamage companion object { private val regex = Regex("""(\d+) units each with (\d+) hit points( \((.+)\))? with an attack that does (\d+) (.+) damage at initiative (\d+)""") fun parse(s: String, boost: Int): Group { val (count, hp, _, modifiers, attackDamage, attackDamageType, initiative) = regex.matchEntire(s)?.destructured ?: error("invalid '$s'") val (weaknesses, immunities) = parseModifiers(modifiers) return Group( count.toInt(), hp.toInt(), weaknesses, immunities, attackDamage.toInt() + boost, attackDamageType, initiative.toInt() ) } private fun parseModifiers(s: String): Pair<List<String>, List<String>> { var weaknesses = emptyList<String>() var immunities = emptyList<String>() for (part in s.split("; ")) { if (part.startsWith("immune to ")) immunities = part.removePrefix("immune to ").split(", ") if (part.startsWith("weak to ")) weaknesses = part.removePrefix("weak to ").split(", ") } return Pair(weaknesses, immunities) } val selectionOrder: Comparator<Group> = compareByDescending<Group> { it.effectivePower }.thenByDescending { it.initiative } val attackOrder: Comparator<Group> = compareByDescending { it.initiative } fun targetOrdering(attacker: Group): Comparator<Group> = compareBy<Group> { attacker.damageTo(it) } .thenBy { it.effectivePower } .thenBy { it.initiative } } }
0
Kotlin
0
0
8e135f80d65d15dbbee5d2749cccbe098a1bc5d8
5,332
advent-of-code
MIT License
src/main/kotlin/Day15.kt
SimonMarquis
570,868,366
false
{"Kotlin": 50263}
import kotlin.math.absoluteValue import kotlin.math.max class Day15(input: List<String>) { private val regex = """x=(-?\d+), y=(-?\d+).*x=(-?\d+), y=(-?\d+)""".toRegex() private val sensorsToBeacons = input.map { regex.find(it)!!.destructured.toList().map(String::toInt) }.map { (sensorX, sensorY, beaconX, beaconY) -> Sensor(sensorX, sensorY) to Beacon(beaconX, beaconY) } fun part1(y: Int): Int = sensorsToBeacons.mapNotNull { (sensor, beacon) -> (sensor to beacon).horizontalSpanAt(y = y) }.flatMapTo(mutableSetOf()) { it.toList() }.apply { sensorsToBeacons.forEach { (sensor, beacon) -> sensor.takeIf { it.y == y }?.x.let(::remove) beacon.takeIf { it.y == y }?.x.let(::remove) } }.size fun part2(max: Int) = (0..max).asSequence() .map { y -> sensorsToBeacons.mapNotNull { it.horizontalSpanAt(y = y) }.merge() } .withIndex() .first { (_, value) -> value.size > 1 } .let { (index, value) -> (value.first().last + 1) * 4_000_000L + index } private open class Point(val x: Int, val y: Int) private class Beacon(x: Int, y: Int) : Point(x, y) private class Sensor(x: Int, y: Int) : Point(x, y) private fun Pair<Sensor, Beacon>.horizontalSpanAt(y: Int = first.y): IntRange? { val range = first distanceTo second val d = first distanceTo Point(first.x, y) return if (d > range) null else (range - d).let { -it..it }.offset(first.x) } private infix fun Point.distanceTo(other: Point) = ((x - other.x).absoluteValue) + ((y - other.y).absoluteValue) private fun IntRange.offset(value: Int) = IntRange(start + value, last + value) private fun List<IntRange>.merge() = sortedBy(IntRange::first).foldInPlace(mutableListOf<IntRange>()) { if (isEmpty()) add(it).also { return@foldInPlace } val last = last() if (it.first > last.last) add(it) else this[size - 1] = last.first..max(last.last, it.last) } }
0
Kotlin
0
0
a2129cc558c610dfe338594d9f05df6501dff5e6
2,035
advent-of-code-2022
Apache License 2.0
src/day4/Day04.kt
ousa17
573,435,223
false
{"Kotlin": 8095}
package day4 import readInput fun main() { val input = readInput("day4/Day04") part1(input) part2(input) } private fun part1(input: List<String>) { val sum = input.map { it.split(",").let { (firstElfRange, secondElfRange) -> firstElfRange.toRange() to secondElfRange.toRange() } }.count { pair -> val secondInFirst = pair.first.map { pair.second.contains(it) }.reduce { acc, b -> acc && b } val firstInSecond = pair.second.map { pair.first.contains(it) }.reduce { acc, b -> acc && b } secondInFirst || firstInSecond } println(sum) } private fun part2(input: List<String>) { val sum = input.map { it.split(",").let { (firstElfRange, secondElfRange) -> firstElfRange.toRange() to secondElfRange.toRange() } }.count { pair -> (pair.first intersect pair.second).isNotEmpty() } println(sum) } fun String.toRange() = this.split("-").let { (a, b) -> a.toInt()..b.toInt() }
0
Kotlin
0
0
aa7f2cb7774925b7e88676a9ca64ca9548bce5b2
1,031
advent-day-1
Apache License 2.0
src/year2023/08/Day08.kt
Vladuken
573,128,337
false
{"Kotlin": 327524, "Python": 16475}
package year2023.`08` import readInput import utils.lcm import utils.printlnDebug private const val CURRENT_DAY = "08" private data class Node( val data: String, val left: String, val right: String, ) private fun parseLineIntoNode(line: String): Node { val a = line.substring(0, 3) val b = line.substring(7, 10) val c = line.substring(12, 15) return Node(a, b, c).also { printlnDebug { it } } } private fun countStepsUntilFound( destinations: Map<String, Node>, directions: String, initNode: Node, isFound: (String) -> Boolean, ): Int { var directionsIterator = directions.iterator() printlnDebug { "INIT NODE : $initNode" } var count = 0 var currentNode = initNode while (directionsIterator.hasNext() && isFound(currentNode.data).not()) { count++ currentNode = step( direction = directionsIterator.next(), destinations = destinations, currentNode = currentNode, ) printlnDebug { "NEW NODE : $currentNode" } if (isFound(currentNode.data)) { printlnDebug { "FOUND NODE: $currentNode" } return count } if (directionsIterator.hasNext().not()) { directionsIterator = directions.iterator() } } error("it should never arrive there") } private fun step( direction: Char, destinations: Map<String, Node>, currentNode: Node, ): Node { val nextKey = when (direction) { 'R' -> currentNode.right 'L' -> currentNode.left else -> error("Illegal step $direction") } return destinations[nextKey] ?: error("step: $nextKey is not found") } private fun prepareDestinations(input: List<String>): Map<String, Node> { val destinations = mutableMapOf<String, Node>() input .drop(2) .map { parseLineIntoNode(it) } .onEach { destinations[it.data] = it } return destinations } fun main() { fun part1(input: List<String>): Int { val destinations = prepareDestinations(input) val firstLine = input.first() return countStepsUntilFound( destinations = destinations, directions = firstLine, initNode = destinations["AAA"]!!, isFound = { it == "ZZZ" } ) } fun part2(input: List<String>): Long { val destinations = prepareDestinations(input) val directionsLine = input.first() val allFoundCounts = destinations.values .filter { it.data.endsWith("A") } .map { node -> countStepsUntilFound( destinations = destinations, directions = directionsLine, initNode = node, isFound = { cur -> cur.endsWith("Z") } ) .also { printlnDebug { "node $node count = $it" } } } .map { it.toLong() } return allFoundCounts.fold(allFoundCounts.first()) { acc, i -> lcm(acc, i) } } // test if implementation meets criteria from the description, like: val input = readInput("Day$CURRENT_DAY") // Part 1 val part1 = part1(input) println(part1) check(part1 == 19951) // Part 2 val part2 = part2(input) println(part2) check(part2 == 16342438708751) }
0
Kotlin
0
5
c0f36ec0e2ce5d65c35d408dd50ba2ac96363772
3,363
KotlinAdventOfCode
Apache License 2.0
src/main/kotlin/g1801_1900/s1895_largest_magic_square/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g1801_1900.s1895_largest_magic_square // #Medium #Array #Matrix #Prefix_Sum #2023_06_22_Time_202_ms_(100.00%)_Space_36.7_MB_(100.00%) class Solution { fun largestMagicSquare(grid: Array<IntArray>): Int { val m = grid.size val n = grid[0].size val rows = Array(m) { IntArray(n + 1) } val cols = Array(m + 1) { IntArray(n) } for (i in 0 until m) { for (j in 0 until n) { // cumulative sum for each row rows[i][j + 1] = rows[i][j] + grid[i][j] // cumulative sum for each column cols[i + 1][j] = cols[i][j] + grid[i][j] } } // start with the biggest side possible for (side in Math.min(m, n) downTo 2) { // check every square for (i in 0..m - side) { for (j in 0..n - side) { // checks if a square with top left [i, j] and side length is magic if (magic(grid, rows, cols, i, j, side)) { return side } } } } return 1 } private fun magic( grid: Array<IntArray>, rows: Array<IntArray>, cols: Array<IntArray>, r: Int, c: Int, side: Int ): Boolean { val sum = rows[r][c + side] - rows[r][c] var d1 = 0 var d2 = 0 for (k in 0 until side) { d1 += grid[r + k][c + k] d2 += grid[r + side - 1 - k][c + k] // check each row and column if (rows[r + k][c + side] - rows[r + k][c] != sum || cols[r + side][c + k] - cols[r][c + k] != sum ) { return false } } // checks both diagonals return d1 == sum && d2 == sum } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,858
LeetCode-in-Kotlin
MIT License
scripts/Day15.kts
matthewm101
573,325,687
false
{"Kotlin": 63435}
import java.io.File import kotlin.math.absoluteValue data class Interval(val a: Int, val b: Int) { val size = b - a + 1 fun tryMerge(other: Interval): Interval? { if (a <= other.a && other.b <= b) return this if (other.a <= a && b <= other.b) return other if (other.a in a..b) return Interval(a, other.b) if (other.b in a..b) return Interval(other.a, b) return null } fun inside(c: Int) = c in a..b } data class Reading(val x: Int, val y: Int, val bx: Int, val by: Int) { val dist = (x - bx).absoluteValue + (y - by).absoluteValue fun getRowDeadZone(row: Int): Interval? { val rowDist = (y - row).absoluteValue if (rowDist > dist) return null val radius = dist - rowDist return Interval(x - radius, x + radius) } } fun getRowDeadZones(row: Int): Set<Interval> { val deadZones = readings.mapNotNull { it.getRowDeadZone(row) }.toMutableSet() while (true) { val dzList = deadZones.toList() var foundA: Interval = dzList[0] var foundB: Interval = dzList[0] var foundAB: Interval? = null outer@ for (i in dzList.indices) { foundA = dzList[i] for (j in i+1 until dzList.size) { foundB = dzList[j] foundAB = foundA.tryMerge(foundB) if (foundAB != null) break@outer } } if (foundAB != null) { deadZones.remove(foundA) deadZones.remove(foundB) deadZones.add(foundAB) } else break } return deadZones } fun checkForGap(dzs: Set<Interval>, end: Int): Int? { var potentialGap = 0 while (true) { var changed = false for (dz in dzs) { if (dz.inside(potentialGap)) { potentialGap = dz.b + 1 changed = true } } if (potentialGap > end) return null if (!changed) return potentialGap } } val readings = File("../inputs/15.txt").readLines().map { line -> val splits = line.split("Sensor at x=", ", y=", ": closest beacon is at x=").filter { it.isNotEmpty() } Reading(splits[0].toInt(), splits[1].toInt(), splits[2].toInt(), splits[3].toInt()) } val targetRow = 2000000 val targetRowDeadZones = getRowDeadZones(targetRow) val totalDeadZoneSize = targetRowDeadZones.sumOf { it.size } val beaconsInDeadZone = readings.map { Pair(it.bx,it.by) }.toSet().count { (x,y) -> y == targetRow && targetRowDeadZones.any { it.inside(x) } } val totalDefiniteNonBeacons = totalDeadZoneSize - beaconsInDeadZone println("There are $totalDefiniteNonBeacons positions in row $targetRow that cannot contain a beacon.") val end = 4000000 var gapX = 0 var gapY = 0 for (row in 0..end) { val maybeGap = checkForGap(getRowDeadZones(row), end) if (maybeGap != null) { gapX = maybeGap gapY = row break } } println("The distress signal is at ($gapX,$gapY) with tuning frequency ${gapX.toLong() * 4000000L + gapY.toLong()}.")
0
Kotlin
0
0
bbd3cf6868936a9ee03c6783d8b2d02a08fbce85
3,127
adventofcode2022
MIT License
src/Day02.kt
yeung66
574,904,673
false
{"Kotlin": 8143}
fun main() { val winRelations = hashMapOf(0 to 2, 1 to 0, 2 to 1) fun part1(input: List<Pair<Int, Int>>): Int { return input.sumOf { val (theirs, yours) = it val score = when (theirs) { yours -> 3 winRelations[yours]!! -> 6 else -> 0 } score + yours + 1 } } fun part2(input: List<Pair<Int, Int>>): Int { return input.sumOf { val (theirs, strategy) = it val yours = when (strategy) { 0 -> winRelations[theirs]!! 1 -> theirs else -> 3 - theirs - winRelations[theirs]!! } yours + 1 + strategy * 3 } } fun parseInput(input: List<String>): List<Pair<Int, Int>> { return input.map { val chars = it.toCharArray() val theirs = chars[0] val yours = chars[2] Pair<Int, Int>(theirs - 'A', yours - 'X') }.toList(); } val input = parseInput(readInputLines("2")) println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
554217f83e81021229759bccc8b616a6b270902c
1,129
advent-of-code-2022-kotlin
Apache License 2.0
src/main/kotlin/aoc/year2023/Day08.kt
SackCastellon
573,157,155
false
{"Kotlin": 62581}
package aoc.year2023 import aoc.Puzzle import kotlin.math.abs /** * [Day 8 - Advent of Code 2023](https://adventofcode.com/2023/day/8) */ object Day08 : Puzzle<Int, Long> { override fun solvePartOne(input: String): Int { val (instructions, network) = processInput(input) return instructions.asInfiniteSequence() .runningFold("AAA") { node, instruction -> val (left, right) = network.getValue(node) when (instruction) { 'L' -> left 'R' -> right else -> error("Unexpected instruction $instruction") } } .takeWhile { it != "ZZZ" } .count() } override fun solvePartTwo(input: String): Long { val (instructions, network) = processInput(input) fun getSteps(start: String): Int { return instructions.asInfiniteSequence() .runningFold(start) { node, instruction -> val (left, right) = network.getValue(node) when (instruction) { 'L' -> left 'R' -> right else -> error("Unexpected instruction $instruction") } } .takeWhile { !it.endsWith('Z') } .count() } return network.keys.filter { it.endsWith('A') }.map(::getSteps).map(Int::toLong).reduce(::lcm) } private fun processInput(input: String): Pair<String, Map<String, Pair<String, String>>> { val lines = input.lines() val instructions = lines.first() val network = lines.drop(2).associate { val (source, targets) = it.split(" = ") val (left, right) = targets.removeSurrounding("(", ")").split(", ") source to (left to right) } return instructions to network } private fun String.asInfiniteSequence(): Sequence<Char> = sequence { while (true) this.yieldAll(asSequence()) } private fun lcm(a: Long, b: Long): Long = abs(a) * (abs(b) / gcd(a, b)) private tailrec fun gcd(a: Long, b: Long): Long = if (b == 0L) a else gcd(b, a.rem(b)) }
0
Kotlin
0
0
75b0430f14d62bb99c7251a642db61f3c6874a9e
2,214
advent-of-code
Apache License 2.0
src/com/kingsleyadio/adventofcode/y2023/Day18.kt
kingsleyadio
435,430,807
false
{"Kotlin": 134666, "JavaScript": 5423}
package com.kingsleyadio.adventofcode.y2023 import com.kingsleyadio.adventofcode.util.readInput import kotlin.math.absoluteValue fun main() { val input = readInput(2023, 18).readLines() part1(input) part2(input) } private fun part1(input: List<String>) { evaluate(input) { entry -> val (direction, value) = entry.split(" ") direction[0] to value.toInt() } } private fun part2(input: List<String>) { val directions = charArrayOf('R', 'D', 'L', 'U') evaluate(input) { entry -> val encoded = entry.substringAfterLast("#").dropLast(1) val value = encoded.dropLast(1).toInt(16) directions[encoded.last().digitToInt()] to value } } private inline fun evaluate(input: List<String>, splitter: (String) -> Pair<Char, Int>) { val moves = arrayListOf<Int>() val coordinates = buildList<Index> { add(Index(0, 0)) input.forEach { entry -> val previous = last() val (direction, value) = splitter(entry) val next = when (direction) { 'R' -> Index(previous.x + value, previous.y) 'D' -> Index(previous.x, previous.y + value) 'L' -> Index(previous.x - value, previous.y) 'U' -> Index(previous.x, previous.y - value) else -> error("Invalid direction") } add(next) moves.add(value) } } val a = coordinates.zipWithNext { a, b -> (b.x - a.x) * a.y.toLong() }.sum().absoluteValue val p = moves.sumOf { it.toLong() } println(a + p / 2 + 1) }
0
Kotlin
0
1
9abda490a7b4e3d9e6113a0d99d4695fcfb36422
1,597
adventofcode
Apache License 2.0
src/Day24.kt
syncd010
324,790,559
false
null
import kotlin.math.sqrt class Day24: Day { private fun convert(input: List<String>) : IntArray { return input.map { line -> line.mapNotNull { c -> when (c) { '.', '?' -> 0; '#' -> 1; else -> null } }.toIntArray() }.reduce { acc, ints -> acc + ints } } override fun solvePartOne(input: List<String>): Long { fun countAdjacentBugs(board: IntArray, pos: Int): Int { val sz = sqrt(board.size.toFloat()).toInt() return (if (pos - sz >= 0) board[pos - sz] else 0) + (if (pos + sz < board.size) board[pos + sz] else 0) + (if (pos % sz > 0) board[pos - 1] else 0) + (if (pos % sz < sz - 1) board[pos + 1] else 0) } fun evolve(source: IntArray, dest: IntArray) { for (i in dest.indices) { dest[i] = when { source[i] == 1 -> if (countAdjacentBugs(source, i) == 1) 1 else 0 else -> if (countAdjacentBugs(source, i) in 1..2) 1 else 0 } } } fun boardRating(board: IntArray): Long { return board.foldIndexed(0L, { index, acc, i -> acc + i * 2.pow(index) }) } var source = convert(input) var dest = source.copyOf() val seen = mutableListOf<Long>() var rating = boardRating(source) while (rating !in seen) { seen.add(rating) evolve(source, dest) rating = boardRating(dest) val tmp = source; source = dest; dest = tmp } return rating } override fun solvePartTwo(input: List<String>): Int { val board = convert(input) val emptyBoard = IntArray(board.size) { 0 } val sz = sqrt(board.size.toFloat()).toInt() val mid = board.size / 2 val firstRowIdx = 0 until sz val lastRowIdx = (board.size - sz) until board.size val firstColIdx = 0 until board.size step sz val lastColIdx = (sz - 1) until board.size step sz fun countAdjacentBugs(board: List<IntArray>, lvl: Int, pos: Int): Int { return when { (pos in firstRowIdx) -> if (lvl - 1 >= 0) board[lvl - 1][mid - sz] else 0 (pos == mid + sz) -> if (lvl + 1 < board.size) board[lvl + 1].slice(lastRowIdx).sum() else 0 else -> board[lvl][pos - sz] } + when { (pos in lastRowIdx) -> if (lvl - 1 >= 0) board[lvl - 1][mid + sz] else 0 (pos == mid - sz) -> if (lvl + 1 < board.size) board[lvl + 1].slice(firstRowIdx).sum() else 0 else -> board[lvl][pos + sz] } + when { (pos in firstColIdx) -> if (lvl - 1 >= 0) board[lvl - 1][mid - 1] else 0 (pos == mid + 1) -> if (lvl + 1 < board.size) board[lvl + 1].slice(lastColIdx).sum() else 0 else -> board[lvl][pos - 1] } + when { (pos in lastColIdx) -> if (lvl - 1 >= 0) board[lvl - 1][mid + 1] else 0 (pos == mid - 1) -> if (lvl + 1 < board.size) board[lvl + 1].slice(firstColIdx).sum() else 0 else -> board[lvl][pos + 1] } } fun evolve(source: List<IntArray>, dest: List<IntArray>) { for (lvl in source.indices) { for (pos in source[lvl].indices) { if (pos == source[lvl].size / 2) continue dest[lvl][pos] = when { source[lvl][pos] == 1 -> if (countAdjacentBugs(source, lvl, pos) == 1) 1 else 0 else -> if (countAdjacentBugs(source, lvl, pos) in 1..2) 1 else 0 } } } } board[board.size / 2] = 0 var source = mutableListOf(board) var dest = mutableListOf(board.copyOf()) for (m in 0 until 200) { // Add empty boards at beggining/end if there's a chance of evolving bugs there // in the next iteration. Make sure that dest has the same size if (source.first().any { it == 1 }) source.add(0, emptyBoard.copyOf()) if (source.last().any { it == 1 }) source.add(emptyBoard.copyOf()) for (i in 0 until source.size - dest.size) dest.add(emptyBoard.copyOf()) evolve(source, dest) val tmp = source; source = dest; dest = tmp } return source.sumBy { it.sum() } } }
0
Kotlin
0
0
11c7c7d6ccd2488186dfc7841078d9db66beb01a
4,756
AoC2019
Apache License 2.0
src/Day04.kt
baghaii
573,918,961
false
{"Kotlin": 11922}
fun main() { fun part1(input: List<String>): Int { var overlap = 0 input.forEach{ line -> val ranges = line.split(",") val firstAssignment = ranges[0].split("-").map{it.toInt()} val secondAssignment = ranges[1].split("-").map{it.toInt()} if (firstAssignment[0] < secondAssignment[0]) { if (firstAssignment[1] >= secondAssignment[1]) { overlap += 1 } } else if (firstAssignment[0] == secondAssignment[0]) { overlap += 1 } else if (secondAssignment[1] >= firstAssignment[1]) { overlap += 1 } } return overlap } fun part2(input: List<String>): Int { var overlap = 0 input.forEach {line -> val ranges = line.split(",","-").map { it.toInt() } val firstRange = ranges.subList(0,2) val secondRange = ranges.subList(2,4) if (firstRange[0] <= secondRange[0] && firstRange[1] >= secondRange[0]) { overlap += 1 } else if (secondRange[0] <= firstRange[0] && secondRange[1] >= firstRange[0]) { overlap +=1 } } return overlap } // test if implementation meets criteria from the description, like: val testInput = readInput("Day04_test") check(part1(testInput) == 2) check(part2(testInput) == 4) val input = readInput("Day04") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
8c66dae6569f4b269d1cad9bf901e0a686437469
1,542
AdventOfCode2022
Apache License 2.0
src/day01/Day01.kt
AbolfaZlRezaEe
574,383,383
false
null
package day01 import readInput fun main() { fun part01(lines: List<String>): Int { var sumOfCalories = 0 var finalResult = 0 lines.forEach { line -> if (line.isEmpty()) { if (sumOfCalories > finalResult) { finalResult = sumOfCalories } sumOfCalories = 0 } else { sumOfCalories += line.toInt() } } return finalResult } fun part02(lines: List<String>): Int { val topThreeCalories = mutableListOf<Int>() var sumOfCalories = 0 lines.forEachIndexed { index, line -> if (line.isNotEmpty()) { sumOfCalories += line.toInt() } if (line.isEmpty() || index == lines.size - 1) { if (topThreeCalories.size < 3) { topThreeCalories.add(sumOfCalories) } else { // Check and replace if needed val clone = topThreeCalories.toMutableList() val minimumNumber = clone.min() if (sumOfCalories > minimumNumber) { topThreeCalories.remove(minimumNumber) topThreeCalories.add(sumOfCalories) } } sumOfCalories = 0 } } return topThreeCalories.sum() } check(part01(readInput(targetDirectory = "day01", name = "Day01FakeData")) == 24000) check(part02(readInput(targetDirectory = "day01", name = "Day01FakeData")) == 45000) val topCalorie = part01(readInput(targetDirectory = "day01", name = "Day01RealData")) val sumOfTopThreeCalories = part02(readInput(targetDirectory = "day01", name = "Day01RealData")) println("Top calorie is-> $topCalorie") println("Sum of top three calories is-> $sumOfTopThreeCalories") }
0
Kotlin
0
0
798ff23eaa9f4baf25593368b62c2f671dc2a010
1,906
AOC-With-Me
Apache License 2.0
src/Day03.kt
xabgesagtx
572,139,500
false
{"Kotlin": 23192}
fun main() { fun part1(input: List<String>): Int { return input.map { it.splitInHalf() } .flatMap { commonCharacters(it.first, it.second) } .sumOf { it.priority } } fun part2(input: List<String>): Int { return input .chunked(3) .flatMap { commonCharacters(*it.toTypedArray()) } .sumOf { it.priority } } // 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)) } private fun String.splitInHalf() = substring(0, length/2) to substring(length/2) private val Char.priority get() = if (isLowerCase()) this - 'a' + 1 else this - 'A' + 27 private fun commonCharacters(vararg texts: String): Set<Char> = texts.map { it.toSet() } .reduce { acc, text -> acc intersect text }
0
Kotlin
0
0
976d56bd723a7fc712074066949e03a770219b10
1,019
advent-of-code-2022
Apache License 2.0
src/Day21.kt
astrofyz
572,802,282
false
{"Kotlin": 124466}
fun main() { class Monkey(var num: Long? = null, var operation: String? = null, var operLeft: String? = null, var operRight: String? = null){} fun Monkey.print(){ println("num: ${this.num}") println("${this.operLeft} ${this.operation} ${this.operRight}") } fun Monkey.update(mapMonkeys: MutableMap<String, Monkey>): Long { // println("${mapMonkeys[this.operLeft]?.num} ${this.operation} ${mapMonkeys[this.operRight]?.num}") when (this.operation){ "+" -> return mapMonkeys[this.operLeft]?.num?.let { mapMonkeys[this.operRight]?.num?.plus(it) } ?: 0 "-" -> return mapMonkeys[this.operRight]?.num?.let { mapMonkeys[this.operLeft]?.num?.minus(it) } ?: 0 "/" -> return (mapMonkeys[this.operLeft]?.num?:0) / (mapMonkeys[this.operRight]?.num?:1) "*" -> return (mapMonkeys[this.operLeft]?.num?:0) * (mapMonkeys[this.operRight]?.num?: 0) else -> {println("Error in operation"); return 0} } } // fun Monkey.updateInverse(flag:String, operand: Long?, res: Long?): Long { //// println("${mapMonkeys[this.operLeft]?.num} ${this.operation} ${mapMonkeys[this.operRight]?.num}") // if (flag == "left"){ // when (this.operation){ // "+" -> return (res!! - operand!!) ?: 0 // "-" -> return (res!! + mapMonkeys[this.operRight]?.num!!) ?: 0 // "/" -> return (res!! * mapMonkeys[this.operRight]?.num!!) ?: 0 // "*" -> return (res!! / mapMonkeys[this.operRight]?.num!!) ?: 0 // else -> {println("Error in operation"); return 0} // } // } // else{ // when (this.operation){ // "+" -> return (res - mapMonkeys[this.operLeft]?.num!!) ?: 0 // "-" -> return (mapMonkeys[this.operLeft]?.num!! - res) ?: 0 // "/" -> return (mapMonkeys[this.operLeft]?.num!! / res) ?: 0 // "*" -> return (res / mapMonkeys[this.operLeft]?.num!!) ?: 0 // else -> {println("Error in operation"); return 0} // } // } // } fun parseMonkeys(input: List<String>): MutableMap<String, Monkey> { var mapMonkeys = mutableMapOf<String, Monkey>() for (line in input){ if (line.map { it.isDigit() }.count { it } > 0){ mapMonkeys[line.split(":")[0]] = Monkey(num=line.split(": ")[1].toLong()) } else{ var (operLeft, operation, operRight) = line.split(": ")[1].split(" ") mapMonkeys[line.split(":")[0]] = Monkey(operation = operation, operLeft = operLeft, operRight = operRight) } } return mapMonkeys } fun part1(input: List<String>):Long{ var mapMonkeys = parseMonkeys(input) var initNumbers = mapMonkeys.filterValues { it.num != null } var nextMonkeys = mapMonkeys .filterValues { (it.operRight in initNumbers.keys)&&(it.operLeft in initNumbers.keys)&&(it.num == null) } while (true){ for (monk in nextMonkeys){ mapMonkeys[monk.key]?.num = mapMonkeys[monk.key]?.update(mapMonkeys) } initNumbers = mapMonkeys.filterValues { it.num != null } nextMonkeys = mapMonkeys .filterValues { (it.operRight in initNumbers.keys)&&(it.operLeft in initNumbers.keys)&&(it.num == null) } if ("root" in initNumbers.map { it.key }) break } return mapMonkeys["root"]?.num ?: 0 } fun part2(input: List<String>):Long{ var mapMonkeys = parseMonkeys(input) mapMonkeys["humn"]?.num = null var initNumbers = mapMonkeys.filterValues { it.num != null } var nextMonkeys = mapMonkeys .filterValues { (it.operRight in initNumbers.keys)&&(it.operLeft in initNumbers.keys)&&(it.num == null) } while (true){ for (monk in nextMonkeys){ if (monk.key == "humn") continue mapMonkeys[monk.key]?.num = mapMonkeys[monk.key]?.update(mapMonkeys) } initNumbers = mapMonkeys.filterValues { it.num != null } nextMonkeys = mapMonkeys .filterValues { (it.operRight in initNumbers.keys)&&(it.operLeft in initNumbers.keys)&&(it.num == null) } if ((mapMonkeys[mapMonkeys["nrvt"]?.operRight]?.num != null)||(mapMonkeys[mapMonkeys["nrvt"]?.operRight]?.num != null)) break } println("${mapMonkeys["nrvt"]?.operLeft} ${mapMonkeys[mapMonkeys["nrvt"]?.operLeft]?.num}") println("${mapMonkeys["nrvt"]?.operRight} ${mapMonkeys[mapMonkeys["nrvt"]?.operRight]?.num}") println("last unknown") println("${mapMonkeys["root"]?.operLeft} ${mapMonkeys[mapMonkeys["root"]?.operLeft]?.num}") println("${mapMonkeys["root"]?.operRight} ${mapMonkeys[mapMonkeys["root"]?.operRight]?.num}") println("root unknown") var a = 1.0.toDouble() var b = 0.0.toDouble() var nextX = "humn" // println(mapMonkeys.filterValues { it.operLeft == nextX || it.operRight == nextX }.keys.first()) // while (true){ var monk = mapMonkeys.filterValues { it.operLeft == nextX || it.operRight == nextX }.keys.first() if (mapMonkeys[monk]?.operRight == nextX && mapMonkeys[mapMonkeys[monk]?.operLeft]?.num != null) { // println("${mapMonkeys[monk]?.operLeft}, ${mapMonkeys[mapMonkeys[monk]?.operLeft]?.num}") // println("${mapMonkeys[monk]?.operRight}, ${mapMonkeys[mapMonkeys[monk]?.operRight]?.num}") when(mapMonkeys[monk]?.operation){ "+" -> b += mapMonkeys[mapMonkeys[monk]?.operLeft]?.num!! "-" -> {b = mapMonkeys[mapMonkeys[monk]?.operLeft]?.num!! - b; a *= -1L} "*" -> {b *= mapMonkeys[mapMonkeys[monk]?.operLeft]?.num!!; a *= mapMonkeys[mapMonkeys[monk]?.operLeft]?.num!!} "/" -> {println("x in denominator:(")} } nextX = monk // println("a = $a; b = $b") if (nextX == "dcsn") {break} } else if (mapMonkeys[monk]?.operLeft == nextX && mapMonkeys[mapMonkeys[monk]?.operRight]?.num != null) { // println("${mapMonkeys[monk]?.operLeft}, ${mapMonkeys[mapMonkeys[monk]?.operLeft]?.num}") // println("${mapMonkeys[monk]?.operRight}, ${mapMonkeys[mapMonkeys[monk]?.operRight]?.num}") when(mapMonkeys[monk]?.operation){ "+" -> b += mapMonkeys[mapMonkeys[monk]?.operRight]?.num!! "-" -> {b -= mapMonkeys[mapMonkeys[monk]?.operRight]?.num!!} "*" -> {b *= mapMonkeys[mapMonkeys[monk]?.operRight]?.num!!; a *= mapMonkeys[mapMonkeys[monk]?.operRight]?.num!!} "/" -> {b /= mapMonkeys[mapMonkeys[monk]?.operRight]?.num!!.toDouble(); a /= mapMonkeys[mapMonkeys[monk]?.operRight]?.num!!.toDouble()} } nextX = monk // println("a = $a; b = $b") if (nextX == "dcsn") {break} } else{ // println("${mapMonkeys[monk]?.operLeft}, ${mapMonkeys[mapMonkeys[monk]?.operLeft]?.num}") // println("${mapMonkeys[monk]?.operRight}, ${mapMonkeys[mapMonkeys[monk]?.operRight]?.num}") } } println("a = $a") println("b = $b") var nextOperand: String? var flag = "left" if (mapMonkeys[mapMonkeys["root"]?.operLeft]?.num == null){ nextOperand = mapMonkeys["root"]?.operLeft flag = "left" mapMonkeys[nextOperand]?.num = mapMonkeys[mapMonkeys["root"]?.operRight]?.num } else { nextOperand = mapMonkeys["root"]?.operRight flag = "right" mapMonkeys[nextOperand]?.num = mapMonkeys[mapMonkeys["root"]?.operLeft]?.num } while (true){ println(nextOperand) mapMonkeys[nextOperand]?.print() println("..................") if (mapMonkeys[mapMonkeys[nextOperand]?.operLeft]?.num == null && mapMonkeys[mapMonkeys[nextOperand]?.operRight]?.num != null){ var res = mapMonkeys[nextOperand]?.num // println(res) var operand = mapMonkeys[mapMonkeys[nextOperand]?.operRight]?.num // println("$res, $operand") var operation = mapMonkeys[nextOperand]?.operation nextOperand = mapMonkeys[nextOperand]?.operLeft when (operation) { "+" -> mapMonkeys[nextOperand]?.num = (res!! - operand!!) ?: 0 "-" -> mapMonkeys[nextOperand]?.num = (res!! + operand!!) ?: 0 "/" -> mapMonkeys[nextOperand]?.num = (res!! * operand!!) ?: 0 "*" -> mapMonkeys[nextOperand]?.num = (res!! / operand!!) ?: 0 } } else if (mapMonkeys[mapMonkeys[nextOperand]?.operRight]?.num == null && mapMonkeys[mapMonkeys[nextOperand]?.operLeft]?.num != null) { var res = mapMonkeys[nextOperand]?.num // println(res) var operand = mapMonkeys[mapMonkeys[nextOperand]?.operLeft]?.num // println("$res, $operand") var operation = mapMonkeys[nextOperand]?.operation nextOperand = mapMonkeys[nextOperand]?.operRight when (operation) { "+" -> mapMonkeys[nextOperand]?.num = (res!! - operand!!) ?: 0 "-" -> mapMonkeys[nextOperand]?.num = (operand!! - res!!) ?: 0 "/" -> mapMonkeys[nextOperand]?.num = (operand!! / res!!) ?: 0 "*" -> mapMonkeys[nextOperand]?.num = (res!! / operand!!) ?: 0 } } else { nextOperand = mapMonkeys[nextOperand]?.operRight } if (nextOperand == "humn") {println(mapMonkeys[nextOperand]?.num); break} } return mapMonkeys["root"]?.num ?: 0 } val testInput = readInput("Day21") // println(part1(testInput)) part2(testInput) }
0
Kotlin
0
0
a0bc190b391585ce3bb6fe2ba092fa1f437491a6
10,234
aoc22
Apache License 2.0
2021/kotlin/src/main/kotlin/com/pietromaggi/aoc2021/day20/Day20.kt
pfmaggi
438,378,048
false
{"Kotlin": 113883, "Zig": 18220, "C": 7779, "Go": 4059, "CMake": 386, "Awk": 184}
/* * Copyright 2021 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.pietromaggi.aoc2021.day20 import com.pietromaggi.aoc2021.readInput var conversion = "" fun evolve(previous: List<CharArray>, even: Boolean) : List<CharArray> { var image = listOf<CharArray>() val background = if (conversion[0] == '#') if (even) '#' else '.' else '.' fun compute(i: Int, j: Int): Char { fun convert(line: List<Char>): Char { val index = line.map { if (it == '.') '0' else '1' }.map(Char::digitToInt).joinToString("").toInt(radix = 2) return conversion[index] } val list = mutableListOf<Char>() for (idx1 in -1..1) for (idx2 in -1..1) list += image.getOrNull(i+idx1)?.getOrNull(j+idx2) ?: background return convert(list) } fun expand(oldArray: List<CharArray>, oldSize: Int) : List<CharArray> { return buildList { val empty = CharArray(oldSize+2) { background } add(empty) oldArray.forEach { add(charArrayOf(background) + it + charArrayOf(background)) } add(empty) } } image = expand(previous, previous.size) val temp = buildList { image.forEach { line -> add(line.toList().joinToString("").toCharArray()) } } for (i in image.indices) { for (j in image.indices) { temp[i][j] = compute(i, j) } } return temp } fun part1(input: List<String>): Int { conversion = input[0] var inputMap = input.drop(2) .takeWhile(String::isNotEmpty) .map(String::toCharArray) inputMap = evolve(inputMap, false) inputMap = evolve(inputMap, true) return inputMap.sumOf { line -> line.count { char -> char == '#' } } } fun part2(input: List<String>, iteration: Int): Int { conversion = input[0] var inputMap = input.drop(2) .takeWhile(String::isNotEmpty) .map(String::toCharArray) repeat(iteration) { count -> inputMap = evolve(inputMap, (1 == count % 2)) } return inputMap.sumOf { line -> line.count { char -> char == '#' } } } fun main() { val input = readInput("Day20") println(""" AoC2021 - Day20 - Kotlin ======================== How many pixels are lit in the resulting image? --> ${part2(input, 2)} How many pixels are lit in the resulting image? --> ${part2(input, 50)} """) }
0
Kotlin
0
0
7c4946b6a161fb08a02e10e99055a7168a3a795e
2,991
AdventOfCode
Apache License 2.0
src/main/kotlin/year2021/day-22.kt
ppichler94
653,105,004
false
{"Kotlin": 182859}
package year2021 import lib.aoc.Day import lib.aoc.Part import lib.splitLines import kotlin.math.max import kotlin.math.min fun main() { Day(22, 2021, PartA22(), PartB22()).run() } open class PartA22(private val limit: Int = 50) : Part() { private enum class Command { On, Off } private data class Step(val command: Command, val cube: Cube) private data class Cube( val xMin: Long, val xMax: Long, val yMin: Long, val yMax: Long, val zMin: Long, val zMax: Long ) { val volume get() = (xMax - xMin + 1) * (yMax - yMin + 1) * (zMax - zMin + 1) fun intersections(cubes: List<Cube>): List<Cube> { return cubes.mapNotNull { val xMinIntersect = max(xMin, it.xMin) val xMaxIntersect = min(xMax, it.xMax) val yMinIntersect = max(yMin, it.yMin) val yMaxIntersect = min(yMax, it.yMax) val zMinIntersect = max(zMin, it.zMin) val zMaxIntersect = min(zMax, it.zMax) if (xMinIntersect <= xMaxIntersect && yMinIntersect <= yMaxIntersect && zMinIntersect <= zMaxIntersect) { Cube(xMinIntersect, xMaxIntersect, yMinIntersect, yMaxIntersect, zMinIntersect, zMaxIntersect) } else { null } } } fun withinLimit(limit: Int): Boolean { return xMin > -limit && yMin > -limit && zMin > -limit && xMax < limit && yMax < limit && zMax < limit } } private fun Command(text: String): Command { return when (text) { "on " -> Command.On "off" -> Command.Off else -> error("Unknown command $text") } } private lateinit var steps: List<Step> override fun parse(text: String) { steps = text.splitLines() .map { val command = Command(it.take(3)) val values = """-?\d+""".toRegex().findAll(it).map { v -> v.value.toLong() }.toList() val cube = Cube(values[0], values[1], values[2], values[3], values[4], values[5]) Step(command, cube) } } override fun compute(): String { val cubes = mutableListOf<Cube>() val cubesNegative = mutableListOf<Cube>() for ((command, cube) in steps) { if (limit > 0 && !cube.withinLimit(limit)) { continue } val newCubesNegative = cube.intersections(cubes) val newCubes = cube.intersections(cubesNegative) if (command == Command.On) { cubes.add(cube) } cubes.addAll(newCubes) cubesNegative.addAll(newCubesNegative) } return (cubes.sumOf { it.volume } - cubesNegative.sumOf { it.volume }).toString() } override val exampleAnswer: String get() = "39" } class PartB22 : PartA22(0)
0
Kotlin
0
0
49dc6eb7aa2a68c45c716587427353567d7ea313
3,170
Advent-Of-Code-Kotlin
MIT License
src/main/kotlin/Problem21.kt
jimmymorales
496,703,114
false
{"Kotlin": 67323}
import kotlin.math.floor import kotlin.math.sqrt /** * Amicable numbers * * Let d(n) be defined as the sum of proper divisors of n (numbers less than n which divide evenly into n). * If d(a) = b and d(b) = a, where a ≠ b, then a and b are an amicable pair and each of a and b are called amicable * numbers. * * For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110; therefore d(220) = 284. The * proper divisors of 284 are 1, 2, 4, 71 and 142; so d(284) = 220. * * Evaluate the sum of all the amicable numbers under 10000. * * https://projecteuler.net/problem=21 */ fun main() { println(220.sumOfProperDivisors()) println(284.sumOfProperDivisors()) println(sumOfAmicables(10_000)) } private fun sumOfAmicables(n: Int): Int { var sum = 0 val amicables = mutableSetOf<Int>() for (a in 2 until n) { if (a in amicables) continue val b = a.sumOfProperDivisors() if (b > a && a == b.sumOfProperDivisors()) { sum += a + b amicables.add(b) } } return sum } fun Int.sumOfProperDivisors(): Int { var sum = 1 var start = 2 var step = 1 var r = floor(sqrt(toDouble())).toInt() if (r * r == this) { sum += r r-- } if (this % 2 != 0) { start = 3 step = 2 } for (i in start..r step step) { if (this % i == 0) { sum += i + (this / i) } } return sum }
0
Kotlin
0
0
e881cadf85377374e544af0a75cb073c6b496998
1,482
project-euler
MIT License
src/day02/Day02.kt
ubuntudroid
571,771,936
false
{"Kotlin": 7845}
package day02 import day02.Result.* import day02.Result.Companion.toResult import day02.Shape.Companion.toShape import ensureBlankLastItem import readInput fun main() { val input = readInput("Day02") println(part1(input)) println(part2(input)) } fun part1(input: List<String>): Int = input .map { it.split(" ") } .map { it[0].toShape() to it[1].toShape() } .sumOf { (opponentShape, myShape) -> myShape.fight(opponentShape).points + myShape.points } fun part2(input: List<String>): Int = input .map { it.split(" ") } .map { it[0].toShape() to it[1].toResult() } .sumOf { (opponentShape, result) -> result.points + opponentShape.getShapeFor(result).points } sealed class Shape(val points: Int) { object Rock : Shape(1) object Paper : Shape(2) object Scissors : Shape(3) fun fight(opponent: Shape): Result = if (this > opponent) Win else if (this < opponent) Lose else Draw operator fun compareTo(other: Shape): Int = when (this) { Rock -> when (other) { Rock -> 0 Paper -> -1 Scissors -> 1 } Paper -> when (other) { Rock -> 1 Paper -> 0 Scissors -> -1 } Scissors -> when (other) { Rock -> -1 Paper -> 1 Scissors -> 0 } } fun getShapeFor(result: Result): Shape = when (result) { Win -> values().first { it > this } Lose -> values().first { it < this } Draw -> this } companion object { fun values(): Array<Shape> = arrayOf(Rock, Paper, Scissors) fun String.toShape(): Shape = when (this) { "A", "X" -> Rock "B", "Y" -> Paper "C", "Z" -> Scissors else -> throw IllegalArgumentException("Unknown shape: $this") } } } sealed class Result(val points: Int) { object Win : Result(6) object Draw : Result(3) object Lose : Result(0) companion object { fun values(): Array<Result> = arrayOf(Win, Draw, Lose) fun String.toResult(): Result = when (this) { "X" -> Lose "Y" -> Draw "Z" -> Win else -> throw IllegalArgumentException("No object Result.$this") } } }
0
Kotlin
0
0
fde55dcf7583aac6571c0f6fc2d323d235337c27
2,280
advent-of-code-2022
Apache License 2.0
src/Day14.kt
mikemac42
573,071,179
false
{"Kotlin": 45264}
import java.io.File fun main() { val testInput = """498,4 -> 498,6 -> 496,6 503,4 -> 502,4 -> 502,9 -> 494,9""" val realInput = File("src/Day14.txt").readText() val part1TestOutput = unitsOfSandToAbyss(testInput) println("Part 1 Test Output: $part1TestOutput") check(part1TestOutput == 24) val part1RealOutput = unitsOfSandToAbyss(realInput) println("Part 1 Real Output: $part1RealOutput") val part2TestOutput = unitsOfSandToAbyss(testInput, useFloor = true) println("Part 2 Test Output: $part2TestOutput") check(part2TestOutput == 93) val part2RealOutput = unitsOfSandToAbyss(realInput, useFloor = true) println("Part 2 Real Output: $part2RealOutput") } fun unitsOfSandToAbyss(input: String, useFloor: Boolean = false): Int { val grid = makeGrid(input, useFloor) var sandCount = 0 while (grid.addSand() != null) { sandCount++ } println(grid.toString()) return sandCount } private fun makeGrid(input: String, useFloor: Boolean): Grid { val structures = input.lines().map { line -> line.split(" -> ").map { coordinates -> val numbers = coordinates.split(',').map { it.toInt() } Point(numbers[0], numbers[1]) } }.toMutableList() if (useFloor) { val points = structures.flatten() val maxY = points.maxOf { it.y } + 2 val entryPoint = Point(500, 0) val floor = listOf(Point(entryPoint.x - maxY - 1, maxY), Point(entryPoint.x + maxY + 1, maxY)) structures.add(floor) } return structures.toGrid() } private fun List<Structure>.toGrid(): Grid { val entryPoint = Point(500, 0) val points = this.flatten() + entryPoint val minPoint = Point(points.minOf { it.x }, points.minOf { it.y }) val maxPoint = Point(points.maxOf { it.x }, points.maxOf { it.y }) val materials = Array(maxPoint.x - minPoint.x + 1) { x -> Array(maxPoint.y - minPoint.y + 1) { y -> if (x == entryPoint.x - minPoint.x && y == entryPoint.y - minPoint.y) { Material.ENTRY } else { Material.AIR } } } this.forEach { structure -> structure.forEachIndexed { index, point -> if (index > 0) { val start = structure[index - 1] - minPoint val end = point - minPoint if (start.x == end.x) { (minOf(start.y, end.y)..maxOf(start.y, end.y)).forEach { y -> materials[start.x][y] = Material.ROCK } } else { (minOf(start.x, end.x)..maxOf(start.x, end.x)).forEach { x -> materials[x][start.y] = Material.ROCK } } } } } return Grid(materials, entryPoint - minPoint) } private data class Grid(val materials: Array<Array<Material>>, val entryPoint: Point) { fun addSand(): Point? { if (materials[entryPoint.x][entryPoint.y] == Material.SAND) return null var sand = entryPoint while (true) { sand = if (sand.y == materials[0].lastIndex) { return null } else if (materials[sand.x][sand.y + 1] == Material.AIR) { Point(sand.x, sand.y + 1) } else if (sand.x == 0) { return null } else if (materials[sand.x - 1][sand.y + 1] == Material.AIR) { Point(sand.x - 1, sand.y + 1) } else if (materials[sand.x + 1][sand.y + 1] == Material.AIR) { Point(sand.x + 1, sand.y + 1) } else { break } } materials[sand.x][sand.y] = Material.SAND return sand } override fun toString(): String { val stringBuilder = StringBuilder() materials.first().indices.forEach { y -> materials.indices.forEach { x -> stringBuilder.append(materials[x][y].char) } stringBuilder.appendLine() } return stringBuilder.toString() } } private typealias Structure = List<Point> private enum class Material(val char: Char) { AIR('.'), ROCK('#'), SAND('o'), ENTRY('+') }
0
Kotlin
1
0
909b245e4a0a440e1e45b4ecdc719c15f77719ab
3,816
advent-of-code-2022
Apache License 2.0
src/day13/Day13.kt
maxmil
578,287,889
false
{"Kotlin": 32792}
package day13 import println import readInputAsText data class Position(val x: Int, val y: Int) data class Fold(val axis: Char, val position: Int) typealias Paper = Set<Position> fun String.parse(): Pair<Paper, List<Fold>> { val (coords, foldLines) = split("\n\n") val paper = coords.split("\n") .map { line -> line.split(",").let { Position(it.first().toInt(), it.last().toInt()) } } .toSet() val folds = foldLines.split("\n") .map { foldLine -> foldLine.split("=").let { Fold( it.first().split(" ").last().first(), it.last().toInt() ) } } return Pair(paper, folds) } fun Paper.fold(fold: Fold) = if (fold.axis == 'y') { map { if (it.y < fold.position) it else it.copy(y = 2 * fold.position - it.y) }.toSet() } else { map { if (it.x < fold.position) it else it.copy(x = 2 * fold.position - it.x) }.toSet() } fun part1(input: String): Int { val (paper, folds) = input.parse() return paper.fold(folds[0]).size } fun part2(input: String) { var (paper, folds) = input.parse() folds.forEach { paper = paper.fold(it) } println() for (y in 0..paper.maxOf { it.y }) { for (x in 0..paper.maxOf { it.x }) { print(if (paper.contains(Position(x, y))) "#" else " ") } println() } println() } fun main() { val testInput = readInputAsText("day13/input_test") check(part1(testInput) == 17) part2(testInput) val input = readInputAsText("day13/input") part1(input).println() part2(input) }
0
Kotlin
0
0
246353788b1259ba11321d2b8079c044af2e211a
1,625
advent-of-code-2021
Apache License 2.0
src/Day05.kt
fasfsfgs
573,562,215
false
{"Kotlin": 52546}
data class ProcedureStep(val src: Int, val dest: Int, val times: Int) fun getProcedure(strProcedure: String): List<ProcedureStep> = strProcedure .lines() .map { it.toProcedureStep() } fun String.toProcedureStep() = run { val times = getInstructionPart(this, "move") val src = getInstructionPart(this, "from") val dest = getInstructionPart(this, "to") ProcedureStep(src, dest, times) } fun getInstructionPart(strInstruction: String, part: String): Int = strInstruction .substringAfter("$part ") .takeWhile { it.isLetterOrDigit() } .toInt() fun getStacks(strStacks: String): List<ArrayDeque<Char>> { val numberOfStacks = strStacks .lines() .last() // stack numbers .trim() .chunked(4) .map { it.trim().toInt() } .last() val stacks = (1..numberOfStacks).map { ArrayDeque<Char>() } strStacks .lines() .reversed() .drop(1) // stack numbers .map { getStackRow(it) } .forEach { stackRow -> stackRow.forEachIndexed { index, c -> if (c.isLetterOrDigit()) stacks[index].addLast(c) } } return stacks } fun getStackRow(strStackRow: String): List<Char> = strStackRow .chunked(4) .map { it[1] } fun operateOverStacks(stacks: List<ArrayDeque<Char>>, procedure: List<ProcedureStep>) = procedure .forEach { step -> repeat(step.times) { stacks[step.dest - 1].addLast(stacks[step.src - 1].removeLast()) } } fun operateOverStacksWithCrateMover9001(stacks: List<ArrayDeque<Char>>, procedure: List<ProcedureStep>) = procedure .forEach { step -> (1..step.times) .map { stacks[step.src - 1].removeLast() } .reversed() .forEach { stacks[step.dest - 1].addLast(it) } } fun List<ArrayDeque<Char>>.topCrates() = map { it.last() }.joinToString("") fun main() { fun part1(input: String): String { val (strStacks, strProcedure) = input.split("\n\n") val procedure = getProcedure(strProcedure) val stacks = getStacks(strStacks) operateOverStacks(stacks, procedure) return stacks.topCrates() } fun part2(input: String): String { val (strStacks, strProcedure) = input.split("\n\n") val procedure = getProcedure(strProcedure) val stacks = getStacks(strStacks) operateOverStacksWithCrateMover9001(stacks, procedure) return stacks.topCrates() } // test if implementation meets criteria from the description, like: val testInput = readInputAsString("Day05_test") check(part1(testInput) == "CMZ") check(part2(testInput) == "MCD") val input = readInputAsString("Day05") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
17cfd7ff4c1c48295021213e5a53cf09607b7144
2,779
advent-of-code-2022
Apache License 2.0
src/year2023/day16/Day.kt
tiagoabrito
573,609,974
false
{"Kotlin": 73752}
package year2023.day16 import java.util.LinkedList import java.util.Queue import year2023.solveIt enum class Direction { RIGHT, LEFT, UP, DOWN } data class Position(val line: Int, val column: Int) { fun nav(other: Position): Position = Position(line + other.line, column + other.column) fun nav(direction: Direction): Position = when (direction) { Direction.RIGHT -> Position(line, column + 1) Direction.LEFT -> Position(line, column - 1) Direction.UP -> Position(line - 1, column) Direction.DOWN -> Position(line + 1, column) } fun isBounded(maxLine: Int, maxColumn: Int) = line in 0 until maxLine && column in 0 until maxColumn } fun main() { val day = "16" val expectedTest1 = 46L val expectedTest2 = 51L val navigateRIGHT: Map<Char, Sequence<Direction>> = mapOf( '\\' to sequenceOf(Direction.DOWN), '/' to sequenceOf(Direction.UP), '|' to sequenceOf(Direction.UP, Direction.DOWN), '-' to sequenceOf(Direction.RIGHT), '.' to sequenceOf(Direction.RIGHT), ) val navigateLEFT: Map<Char, Sequence<Direction>> = mapOf( '\\' to sequenceOf(Direction.UP), '/' to sequenceOf(Direction.DOWN), '|' to sequenceOf(Direction.UP, Direction.DOWN), '-' to sequenceOf(Direction.LEFT), '.' to sequenceOf(Direction.LEFT), ) val navigateUP: Map<Char, Sequence<Direction>> = mapOf( '\\' to sequenceOf(Direction.LEFT), '/' to sequenceOf(Direction.RIGHT), '-' to sequenceOf(Direction.LEFT, Direction.RIGHT), '|' to sequenceOf(Direction.UP), '.' to sequenceOf(Direction.UP), ) val navigateDOWN: Map<Char, Sequence<Direction>> = mapOf( '\\' to sequenceOf(Direction.RIGHT), '/' to sequenceOf(Direction.LEFT), '-' to sequenceOf(Direction.LEFT, Direction.RIGHT), '|' to sequenceOf(Direction.DOWN), '.' to sequenceOf(Direction.DOWN), ) val navMap = mapOf( Direction.RIGHT to navigateRIGHT, Direction.LEFT to navigateLEFT, Direction.UP to navigateUP, Direction.DOWN to navigateDOWN ) fun navigate(map: List<String>, p: Position, direction: Direction): Sequence<Pair<Position, Direction>> { val current = map[p.line][p.column] val sequence = navMap[direction]!![current]!! return sequence.map { p.nav(it) to it }.filter { it.first.isBounded(map.size, map[0].length) } } fun getLightened(input: List<String>, start: Position, startDirection: Direction): Long { val navigatedMap = mapOf( Direction.RIGHT to mutableSetOf<Position>(), Direction.LEFT to mutableSetOf(), Direction.UP to mutableSetOf(), Direction.DOWN to mutableSetOf() ) val toNavigate: Queue<Pair<Position, Direction>> = LinkedList() toNavigate.add(start to startDirection) while (toNavigate.isNotEmpty()) { val (position, direction) = toNavigate.remove() if (navigatedMap[direction]?.add(position) == true) { navigate(input, position, direction).forEach { toNavigate.add(it) } } } return navigatedMap.values.flatten().distinct().count().toLong() } fun part1(input: List<String>): Long { return getLightened(input, Position(0, 0), Direction.RIGHT) } fun part2(input: List<String>): Long { return listOf(input.indices.map { i -> Position(i, 0) to Direction.RIGHT }, input.indices.map { i -> Position(i, input[0].length - 1) to Direction.LEFT }, input[0].indices.map { i -> Position(0, i) to Direction.DOWN }, input[0].indices.map { i -> Position(input.size - 1, i) to Direction.UP }).flatten() .maxOfOrNull { getLightened(input, it.first, it.second) }?:0; } solveIt(day, ::part1, expectedTest1, ::part2, expectedTest2, "test") }
0
Kotlin
0
0
1f9becde3cbf5dcb345659a23cf9ff52718bbaf9
3,938
adventOfCode
Apache License 2.0
src/Day02.kt
GreyWolf2020
573,580,087
false
{"Kotlin": 32400}
/*enum class RockPaperScissorsPermutation(val result: Int) { `A X`(3 + 1), `A Y`(6 + 2), `A Z`(0 + 3), `B X`(0 + 1), `B Y`(3 + 2), `B Z`(6 + 3), `C X`(6 + 1), `C Y`(0 + 2), `C Z`(3 + 3) }*/ val RoPaScPermutations = mapOf<String, Int>( "A X" to 3 + 1, "A Y" to 6 + 2, "A Z" to 0 + 3, "B X" to 0 + 1, "B Y" to 3 + 2, "B Z" to 6 + 3, "C X" to 6 + 1, "C Y" to 0 + 2, "C Z" to 3 + 3 ) val RoPaScPermElfStrategy = mapOf<String, Int>( "A X" to 0 + 3, "A Y" to 3 + 1, "A Z" to 6 + 2, "B X" to 0 + 1, "B Y" to 3 + 2, "B Z" to 6 + 3, "C X" to 0 + 2, "C Y" to 3 + 3, "C Z" to 6 + 1 ) fun main() { fun part1(input: List<String>): Int = input.foldRight(0) { singlePlayResult, acc -> acc + RoPaScPermutations.getOrDefault(singlePlayResult, 0) } fun part2(input: List<String>): Int = input.foldRight(0) { singlePlayResult, acc -> acc + RoPaScPermElfStrategy.getOrDefault(singlePlayResult, 0) } // 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
498da8861d88f588bfef0831c26c458467564c59
1,243
aoc-2022-in-kotlin
Apache License 2.0
2023/src/day11/day11.kt
Bridouille
433,940,923
false
{"Kotlin": 171124, "Go": 37047}
package day11 import GREEN import RESET import printTimeMillis import readInput import kotlin.math.abs data class Point(val x: Int, val y: Int) private fun calculateDistances( galaxies: List<Point>, emptyColumns: List<Int>, emptyRows: List<Int>, stretchFactor: Int ): Long { var distance = 0L for (i in 0 until galaxies.lastIndex) { for (j in i + 1..galaxies.lastIndex) { val a = galaxies[i] val b = galaxies[j] val aXOffset = emptyColumns.count { it < a.x } * (stretchFactor - 1) val bXOffset = emptyColumns.count { it < b.x } * (stretchFactor - 1) val aYOffset = emptyRows.count { it < a.y } * (stretchFactor - 1) val bYOffset = emptyRows.count { it < b.y } * (stretchFactor - 1) distance += abs((b.x + bXOffset) - (a.x + aXOffset)) + abs((b.y + bYOffset) - (a.y + aYOffset)) } } return distance } private fun getEmptyRowsIdx(input: List<String>) = buildList { for (y in input.indices) { if (input[y].all { it == '.' }) add(y) } } private fun getEmptyColumnsIdx(input: List<String>) = buildList { for (x in input[0].indices) { var hasGalaxy = false for (y in input.indices) { if (input[y][x] == '#') { hasGalaxy = true } } if (!hasGalaxy) { add(x) } } } private fun getGalaxies(input: List<String>) = buildList { for (y in input.indices) { for (x in input[y].indices) { if (input[y][x] == '#') { add(Point(x, y)) } } } } fun part1(input: List<String>): Long { return calculateDistances( getGalaxies(input), getEmptyColumnsIdx(input), getEmptyRowsIdx(input), 2 ) } fun part2(input: List<String>): Long { return calculateDistances( getGalaxies(input), getEmptyColumnsIdx(input), getEmptyRowsIdx(input), 1_000_000 ) } fun main() { val testInput = readInput("day11_example.txt") printTimeMillis { print("part1 example = $GREEN" + part1(testInput) + RESET) } printTimeMillis { print("part2 example = $GREEN" + part2(testInput) + RESET) } val input = readInput("day11.txt") printTimeMillis { print("part1 input = $GREEN" + part1(input) + RESET) } printTimeMillis { print("part2 input = $GREEN" + part2(input) + RESET) } }
0
Kotlin
0
2
8ccdcce24cecca6e1d90c500423607d411c9fee2
2,447
advent-of-code
Apache License 2.0
src/day04/Day04.kt
JakubMosakowski
572,993,890
false
{"Kotlin": 66633}
package day04 import readInput /** * Space needs to be cleared before the last supplies can be unloaded from the ships, * and so several Elves have been assigned the job of cleaning up sections of the camp. * Every section has a unique ID number, and each Elf is assigned a range of section IDs. * However, as some of the Elves compare their section assignments with each other, they've noticed that many of the assignments overlap. To try to quickly find overlaps and reduce duplicated effort, the Elves pair up and make a big list of the section assignments for each pair (your puzzle input). * * For example, consider the following list of section assignment pairs: * * 2-4,6-8 * 2-3,4-5 * 5-7,7-9 * 2-8,3-7 * 6-6,4-6 * 2-6,4-8 * For the first few pairs, this list means: * * Within the first pair of Elves, the first Elf was assigned sections 2-4 (sections 2, 3, and 4), * while the second Elf was assigned sections 6-8 (sections 6, 7, 8). * The Elves in the second pair were each assigned two sections. * The Elves in the third pair were each assigned three sections: one got sections 5, 6, and 7, * while the other also got 7, plus 8 and 9. * This example list uses single-digit section IDs to make it easier to draw; * your actual list might contain larger numbers. Visually, these pairs of section assignments look like this: * * .234..... 2-4 * .....678. 6-8 * * .23...... 2-3 * ...45.... 4-5 * * ....567.. 5-7 * ......789 7-9 * * .2345678. 2-8 * ..34567.. 3-7 * * .....6... 6-6 * ...456... 4-6 * * .23456... 2-6 * ...45678. 4-8 * Some of the pairs have noticed that one of their assignments fully contains the other. * For example, 2-8 fully contains 3-7, and 6-6 is fully contained by 4-6. * In pairs where one assignment fully contains the other, * one Elf in the pair would be exclusively cleaning sections their partner will already be cleaning, * so these seem like the most in need of reconsideration. In this example, there are 2 such pairs. * * In how many assignment pairs does one range fully contain the other? * * PART 2: * It seems like there is still quite a bit of duplicate work planned. * Instead, the Elves would like to know the number of pairs that overlap at all. * * In the above example, the first two pairs (2-4,6-8 and 2-3,4-5) don't overlap, * while the remaining four pairs (5-7,7-9, 2-8,3-7, 6-6,4-6, and 2-6,4-8) do overlap: * * 5-7,7-9 overlaps in a single section, 7. * 2-8,3-7 overlaps all of the sections 3 through 7. * 6-6,4-6 overlaps in a single section, 6. * 2-6,4-8 overlaps in sections 4, 5, and 6. * So, in this example, the number of overlapping assignment pairs is 4. * * In how many assignment pairs do the ranges overlap? */ private fun main() { fun part1(input: List<String>): Int = input.sumOf { line -> val (firstElf, secondElf) = line.split(",") val firstElfRange = firstElf.toRange() val secondElfRange = secondElf.toRange() val firstContain = firstElfRange.contains(secondElfRange) val secondContain = secondElfRange.contains(firstElfRange) if (firstContain || secondContain) 1L else 0L }.toInt() fun part2(input: List<String>): Int = input.sumOf { line -> val (firstElf, secondElf) = line.split(",") val firstElfRange = firstElf.toRange() val secondElfRange = secondElf.toRange() val firstContain = firstElfRange.containsStart(secondElfRange) || firstElfRange.containsEnd(secondElfRange) val secondContain = secondElfRange.containsStart(firstElfRange) || secondElfRange.containsEnd(firstElfRange) if (firstContain || secondContain) 1L else 0L }.toInt() 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 IntRange.containsStart(range: IntRange): Boolean = first in range private fun IntRange.containsEnd(range: IntRange): Boolean = last in range private fun IntRange.contains(range: IntRange): Boolean = containsStart(range) && containsEnd(range) private fun String.toRange(): IntRange = split("-").map { it.toInt() }.let { it[0]..it[1] }
0
Kotlin
0
0
f6e9a0b6c2b66c28f052d461c79ad4f427dbdfc8
4,288
advent-of-code-2022
Apache License 2.0
src/Day20.kt
dragere
440,914,403
false
{"Kotlin": 62581}
import java.io.File import java.lang.Integer.max fun main() { val debug = false fun getEnhanced(alg: String, img: HashMap<Pair<Int, Int>, Char>, round: Int, pos: Pair<Int, Int>): Char { val algIdx = pos.neighbors(center = true).map { if (img.getOrElse(pos) { '.' //todo } == '#') '1' else '0' }.joinToString("").toInt(2) return ' ' } fun part1(input: Pair<String, HashMap<Pair<Int, Int>, Char>>): Int { var (alg, img) = input for (round in 0 until 2) { val nextImg = HashMap<Pair<Int, Int>, Char>() val iRange = img.minOf { (k, _) -> k.first } - 1..img.maxOf { (k, _) -> k.first } + 1 for (i in iRange) { val jRange = img.minOf { (k, _) -> k.second } - 1..img.maxOf { (k, _) -> k.second } + 1 for (j in jRange) { val pos = Pair(i, j) nextImg[pos] = getEnhanced(alg, img, round, pos) } } img = nextImg } return img.count { it.value == '#' } } fun part2(input: List<String>): Int { return 0 } fun preprocessing(input: String): Pair<String, HashMap<Pair<Int, Int>, Char>> { val (alg, imgString) = input.split("\r\n\r\n") val img = HashMap<Pair<Int, Int>, Char>() imgString.split("\r\n").forEachIndexed { i, s -> s.forEachIndexed { j, c -> img[Pair(i, j)] = c } } return Pair(alg, img) } // val realInp = read_testInput("real20") val testInp = read_testInput("test20") // val testInp = "" println("Test 1: ${part1(preprocessing(testInp))}") // println("Real 1: ${part1(preprocessing(realInp))}") // println("-----------") // println("Test 2: ${part2(preprocessing(testInp))}") // println("Real 2: ${part2(preprocessing(realInp))}") }
0
Kotlin
0
0
3e33ab078f8f5413fa659ec6c169cd2f99d0b374
1,902
advent_of_code21_kotlin
Apache License 2.0
src/main/kotlin/solutions/day07/Day7.kt
Dr-Horv
570,666,285
false
{"Kotlin": 115643}
package solutions.day07 import solutions.Solver enum class FileType { DIRECTORY, FILE } data class Node( val name: String, val type: FileType, val children: MutableList<Node>, val size: Int, var explored: Boolean, val parent: Node? ) class Day7 : Solver { private fun isCommand(s: String): Boolean = s.startsWith("\$") override fun solve(input: List<String>, partTwo: Boolean): String { val terminalOutput = input.toMutableList() val root = Node( name = "/", type = FileType.DIRECTORY, children = mutableListOf(), size = 0, explored = false, parent = null ) var curr: Node? = null while (terminalOutput.isNotEmpty()) { val line = terminalOutput.removeFirst(); println("output: " + line) if (line.startsWith("\$ cd")) { val name = line.removePrefix("\$ cd").trim() curr = when (name) { ".." -> curr!!.parent "/" -> root else -> curr!!.children.find { it.name == name } } println("location " + curr!!.name) } if (line.startsWith("\$ ls") && !curr!!.explored) { while (terminalOutput.isNotEmpty() && !isCommand(terminalOutput[0])) { val parts = terminalOutput.removeFirst().split(" ").map(String::trim) val name = parts[1] if (parts[0] == "dir") { val n = Node( name = name, type = FileType.DIRECTORY, children = mutableListOf(), size = 0, explored = false, parent = curr ) curr!!.children.add(n) } else { val size = parts[0].toInt() val n = Node( name = name, type = FileType.FILE, children = mutableListOf(), size = size, explored = false, parent = curr ) curr!!.children.add(n) } } println(curr.name + " children: " + curr.children.joinToString(",") { it.name }) curr.explored = true } } if(!partTwo) { val matches = mutableListOf<Node>() findMatches(root, matches) { it < 100_000 } println(matches.map { it.name }) return matches.sumOf { calculateSize(it) }.toString() } else { val AVAILABLE = 70000000 val NEEDED = 30000000 val UNUSED = AVAILABLE - calculateSize(root) val LEFT = NEEDED - UNUSED val matches = mutableListOf<Node>() findMatches(root, matches) { it >= LEFT } println(matches.map { it.name }) val smallest = matches.minBy { calculateSize(it) } return calculateSize(smallest).toString() } } private fun findMatches(n: Node, matches: MutableList<Node>, sizeCondition: (Int) -> Boolean) { if(n.type == FileType.DIRECTORY && sizeCondition(calculateSize(n))) { matches.add(n) } n.children.forEach { findMatches(it, matches, sizeCondition) } } private fun calculateSize(n: Node): Int = if (n.type === FileType.FILE) { n.size } else { n.children.sumOf { calculateSize(it) } } }
0
Kotlin
0
2
6c9b24de2fe2a36346cb4c311c7a5e80bf505f9e
3,781
Advent-of-Code-2022
MIT License
src/Day15.kt
illarionov
572,508,428
false
{"Kotlin": 108577}
import java.lang.Integer.max import java.lang.Integer.min import kotlin.LazyThreadSafetyMode.NONE import kotlin.math.abs fun main() { // test if implementation meets criteria from the description, like: val testInput = readInput("Day15_test") .parseField() val part1TestResult = part1(testInput, 10) check(part1TestResult == 26) val input = readInput("Day15") .parseField() val part1Result = part1(input, 2000000) println(part1Result) val part2TestResult = part2(testInput, XY(20, 20)) println(part2TestResult) check(part2TestResult == 56000011L) val part2Result = part2(input, XY(4000000, 4000000)) println(part2Result) } private data class XY(val x: Int, val y: Int) private data class SensorData(val sensor: XY, val beacon: XY) { val distance: Int = let { abs(it.sensor.x - it.beacon.x) + abs(it.sensor.y - it.beacon.y) } val leftTop: XY = XY(x = sensor.x - distance, sensor.y - distance) val rightBottom: XY = XY(x = sensor.x + distance, sensor.y + distance) fun getCoverageAt(y: Int): IntRange { val d = distance - abs(y - sensor.y) if (d < 0) return IntRange.EMPTY val left = sensor.x - d val right = sensor.x + d return left..right } } private class Area( val sensors: List<SensorData> ) { val xRange: IntRange = let { f -> val minX = f.sensors.minOf { it.leftTop.x } val maxX = f.sensors.maxOf { it.rightBottom.x } minX..maxX } val yRange: IntRange = let { f -> val minY = f.sensors.minOf { it.leftTop.y } val maxY = f.sensors.maxOf { it.rightBottom.y } minY..maxY } val beacons: Set<XY> by lazy(NONE) { sensors.map(SensorData::beacon).toSet() } fun getCoveragesAt(y: Int): List<IntRange> { return sensors .map { r -> r.getCoverageAt(y) } .filter { !it.isEmpty() } } } private fun part1(area: Area, y: Int): Int { val coverages = area.getCoveragesAt(y) return (area.xRange) .count { i -> coverages.any { i in it && XY(i, y) !in area.beacons } } } private fun part2(area: Area, max: XY): Long { val xMin = max(area.xRange.first, 0) val xMax = min(area.xRange.last, max.x) val yMin = max(area.yRange.first, 0) val yMax = min(area.yRange.last, max.y) var y = yMin while (y <= yMax) { var x = xMin val coverages = area.getCoveragesAt(y) while (x <= xMax) { val c = coverages.find { x in it } if (c != null) { x = c.last + 1 } else { println("x: $x, y: $y") return x * 4_000_000L + y } } y += 1 } return -1 } private fun List<String>.parseField(): Area { return Area(sensors = this.map(String::parseReport)) } private val reportStringRegex = """Sensor at x=([+-]?\d+), y=([+-]?\d+): closest beacon is at x=([+-]?\d+), y=([+-]?\d+)""".toRegex() private fun String.parseReport(): SensorData { val (x, y, bx, by) = reportStringRegex.matchEntire(this) ?.groupValues ?.drop(1) ?.map(String::toInt) ?: error("Can not parse $this") return SensorData( sensor = XY(x, y), beacon = XY(bx, by) ) }
0
Kotlin
0
0
3c6bffd9ac60729f7e26c50f504fb4e08a395a97
3,345
aoc22-kotlin
Apache License 2.0
src/main/kotlin/day11.kt
gautemo
725,273,259
false
{"Kotlin": 79259}
import shared.Input import shared.XYMap fun main() { val input = Input.day(11) println(day11A(input)) println(day11B(input)) } fun day11A(input: Input): Long { val map = XYMap(input) { if(it == '#') it else null } return sumGalaxyPairDistance(map) } fun day11B(input: Input, emptySize: Long = 1000000): Long { val map = XYMap(input) { if(it == '#') it else null } return sumGalaxyPairDistance(map, emptySize) } private fun sumGalaxyPairDistance(map: XYMap<Char>, emptySize: Long = 2): Long { val pairs = map.all().keys.mapIndexed { index, galaxy1 -> map.all().keys.drop(index + 1).map { Pair(galaxy1, it)} }.flatten() return pairs.sumOf { pair -> val xRange = minOf(pair.first.x, pair.second.x) ..< maxOf(pair.first.x, pair.second.x) val yRange = minOf(pair.first.y, pair.second.y) ..< maxOf(pair.first.y, pair.second.y) val emptyHorizontal = xRange.count { x -> map.all().keys.none { it.x == x } } val emptyVertical = yRange.count { y -> map.all().keys.none { it.y == y } } val emptyLines = emptyHorizontal + emptyVertical xRange.count() + yRange.count() + emptyLines * emptySize - emptyLines } }
0
Kotlin
0
0
6862b6d7429b09f2a1d29aaf3c0cd544b779ed25
1,242
AdventOfCode2023
MIT License
src/com/kingsleyadio/adventofcode/y2023/Day16.kt
kingsleyadio
435,430,807
false
{"Kotlin": 134666, "JavaScript": 5423}
package com.kingsleyadio.adventofcode.y2023 import com.kingsleyadio.adventofcode.util.readInput fun main() { val grid = readInput(2023, 16).readLines() part1(grid) part2(grid) } private fun part1(grid: List<String>) { val energized = energize(grid, Index(0, 0), Index(1, 0)) println(energized) } private fun part2(grid: List<String>) { val top = grid[0].indices.maxOf { x -> energize(grid, Index(x, 0), Index(0, 1)) } val left = grid.indices.maxOf { y -> energize(grid, Index(0, y), Index(1, 0)) } val bottom = grid[0].indices.maxOf { x -> energize(grid, Index(x, grid.lastIndex), Index(0, -1)) } val right = grid.indices.maxOf { y -> energize(grid, Index(grid[0].lastIndex, y), Index(-1, 0)) } val max = listOf(top, left, bottom, right).max() println(max) } private fun energize(grid: List<String>, start: Index, startDirection: Index): Int { val queue = ArrayDeque<Pair<Index, Index>>() val energized = List(grid.size) { BooleanArray(grid[0].length) } val visited = hashSetOf<Pair<Index, Index>>() queue.addLast(start to startDirection) while (queue.isNotEmpty()) { val visitId = queue.removeFirst() val (current, direction) = visitId if (current.y !in grid.indices || current.x !in grid[0].indices || visitId in visited) continue energized[current.y][current.x] = true visited.add(visitId) val cell = grid[current.y][current.x] if (cell == '-') { if (direction.y == 0) { // horizontal, do nothing special queue.addLast(current + direction to direction) } else { queue.addLast(current + Index(1, 0) to Index(1, 0)) queue.addLast(current + Index(-1, 0) to Index(-1, 0)) } } else if (cell == '|') { if (direction.x == 0) { // vertical, do nothing special queue.addLast(current + direction to direction) } else { queue.addLast(current + Index(0, 1) to Index(0, 1)) queue.addLast(current + Index(0, -1) to Index(0, -1)) } } else if (cell == '/') { val newDirection = if (direction.x == 1) Index(0, -1) else if (direction.x == -1) Index(0, 1) else if (direction.y == 1) Index(-1, 0) else Index(1, 0) queue.addLast(current + newDirection to newDirection) } else if (cell == '\\') { val newDirection = if (direction.x == 1) Index(0, 1) else if (direction.x == -1) Index(0, -1) else if (direction.y == 1) Index(1, 0) else Index(-1, 0) queue.addLast(current + newDirection to newDirection) } else { queue.addLast(current + direction to direction) } } return energized.sumOf { it.count { active -> active } } }
0
Kotlin
0
1
9abda490a7b4e3d9e6113a0d99d4695fcfb36422
2,885
adventofcode
Apache License 2.0
src/Day07.kt
TheGreatJakester
573,222,328
false
{"Kotlin": 47612}
import utils.string.asLines import utils.readInputAsText import utils.runSolver private typealias SolutionType = Int private val dayNumber: String = "07" private val testSolution1: SolutionType = 95437 private val testSolution2: SolutionType? = 24933642 interface ElfItem { val size: Int } class ElfFile(val name: String, override val size: Int) : ElfItem class ElfDir(val name: String, val parent: ElfDir? = null, val contents: MutableList<ElfItem> = mutableListOf()) : ElfItem { override val size: Int get() = contents.sumOf { it.size } fun fillWithSmall(maxSize: Int, dirSet: MutableSet<ElfDir> = mutableSetOf()): Set<ElfDir> { val all = contents.filterIsInstance<ElfDir>() val smalls = all.filter { it.size < maxSize } dirSet.addAll(smalls) all.forEach { it.fillWithSmall(maxSize, dirSet) } return dirSet } fun fillWith(dirSet: MutableSet<ElfDir> = mutableSetOf()): Set<ElfDir> { val all = contents.filterIsInstance<ElfDir>() dirSet.addAll(all) all.forEach { it.fillWith(dirSet) } return dirSet } fun addDir(name: String) { contents.add(ElfDir(name, this)) } fun addFile(name: String, size: Int) { contents.add(ElfFile(name, size)) } } private fun part1(input: String): SolutionType { val commandsInput = input.asLines() val commands = commandsInput.subList(1, commandsInput.size) val startDir = ElfDir("/") var currentDir = startDir commands.forEach { if (it == "$ ls") { // No op? } else if (it.contains("dir")) { val (_, dirName) = it.split(" ") currentDir.addDir(dirName) } else if (it.contains("cd")) { val (_, _, destination) = it.split(" ") currentDir = if (destination == "..") { currentDir.parent!! } else { currentDir.contents .filterIsInstance<ElfDir>() .first { it.name == destination } } } else { // must be a file val (fileSize, fileName) = it.split(" ") currentDir.addFile(fileName, fileSize.toInt()) } } val smalls = startDir.fillWithSmall(100000) return smalls.sumOf { it.size } } private fun part2(input: String): SolutionType { val commandsInput = input.asLines() val commands = commandsInput.subList(1, commandsInput.size) val startDir = ElfDir("/") var currentDir = startDir commands.forEach { if (it == "$ ls") { // No op? } else if (it.contains("dir")) { val (_, dirName) = it.split(" ") currentDir.addDir(dirName) } else if (it.contains("cd")) { val (_, _, destination) = it.split(" ") currentDir = if (destination == "..") { currentDir.parent!! } else { currentDir.contents .filterIsInstance<ElfDir>() .first { it.name == destination } } } else { // must be a file val (fileSize, fileName) = it.split(" ") currentDir.addFile(fileName, fileSize.toInt()) } } val totalSize = startDir.size val neededSpace = 30_000_000 - (70_000_000 - totalSize) val all = startDir.fillWith() return all.sortedBy { it.size }.first { it.size > neededSpace }.size } fun main() { runSolver("Test 1", readInputAsText("Day${dayNumber}_test"), testSolution1, ::part1) runSolver("Test 2", readInputAsText("Day${dayNumber}_test"), testSolution2, ::part2) runSolver("Part 1", readInputAsText("Day${dayNumber}"), null, ::part1) runSolver("Part 2", readInputAsText("Day${dayNumber}"), null, ::part2) }
0
Kotlin
0
0
c76c213006eb8dfb44b26822a44324b66600f933
3,788
2022-AOC-Kotlin
Apache License 2.0
src/main/kotlin/day10_syntax_scoring/SyntaxScoring.kt
barneyb
425,532,798
false
{"Kotlin": 238776, "Shell": 3825, "Java": 567}
package day10_syntax_scoring import java.util.* /** * "Chunks contain ... other chunks" means recursion is the name of the game, * and that means a stack. Some lookup tables for matching delimiters and scores * will be needed too. Since we're again interpreting the input (not treating it * as data), this will be a parser-heavy task. * * Turns out part one also partitioned the input lines into corrupt and * incomplete halves (you noticed "all of them" for which lines had errors, * right?). Now instead of using the stacks to find mismatches, we need to use * what is left on the stacks to compute a score. Comprehending a collection is * a cinch. Phew. */ fun main() { util.solve(290691, ::partOne) // 240.165μs initially // 243.996μs with "pattern" types util.solve(2768166558, ::partTwo) // 213.655μs initially // 199.046μs with "pattern" types } fun partOne(input: String) = input .lineSequence() .map(String::toSyntaxScore) .sumOf { when (it) { is Corrupt -> it.score else -> 0 } } private interface Score private class Corrupt(val score: Long) : Score private class Incomplete(val score: Long) : Score private class Legal : Score private fun String.toSyntaxScore(): Score { val stack: Deque<Char> = ArrayDeque() forEach { when (it) { '(' -> stack.addFirst(')') '[' -> stack.addFirst(']') '{' -> stack.addFirst('}') '<' -> stack.addFirst('>') ')' -> if (stack.removeFirst() != ')') return Corrupt(3) ']' -> if (stack.removeFirst() != ']') return Corrupt(57) '}' -> if (stack.removeFirst() != '}') return Corrupt(1197) '>' -> if (stack.removeFirst() != '>') return Corrupt(25137) else -> throw IllegalArgumentException("Unknown char '$it'") } } if (stack.isEmpty()) return Legal() return Incomplete(stack.map { when (it) { ')' -> 1 ']' -> 2 '}' -> 3 '>' -> 4 else -> throw IllegalArgumentException("Unknown stacked char '$it'") } } .fold(0L) { sum, n -> sum * 5 + n }) } fun partTwo(input: String) = input .lineSequence() .map(String::toSyntaxScore) .map { when (it) { is Incomplete -> it.score else -> -1 } } .filter { it > 0 } .sorted() .toList() .let { it[it.size / 2] }
0
Kotlin
0
0
a8d52412772750c5e7d2e2e018f3a82354e8b1c3
2,658
aoc-2021
MIT License
2022/kotlin/app/src/main/kotlin/day04/Day04.kt
jghoman
726,228,039
false
{"Kotlin": 15309, "Rust": 14555, "Scala": 1804, "Shell": 737}
package day04 data class Range(val start: Int, val end: Int) { fun span() = end - start } data class Assignments(val first: Range, val second: Range) fun parseLine(line: String): Assignments { val first = line.split(",")[0] val second = line.split(",")[1] fun parseRange(r: String): Range { val start = r.split("-")[0] val end = r.split("-")[1] return Range(Integer.valueOf(start), Integer.valueOf(end)) } return Assignments(parseRange(first), parseRange(second)) } fun entirelyContains(a: Assignments): Boolean { val (larger, smaller) = if (a.first.span() > a.second.span()) Pair(a.first, a.second) else Pair(a.second, a.first) return (larger.start <= smaller.start) && (larger.end >= smaller.end) } fun anyOverlap(a: Assignments): Boolean { val (first, second) = if (a.first.start < a.second.start) Pair(a.first, a.second) else Pair(a.second, a.first) return first.end >= second.start } fun part1(input: String): Int { return input .split("\n") .map { parseLine(it) } .count { entirelyContains(it) } //.forEach { println(it) } // 490 } fun part2(input: String): Int { return input .split("\n") .map { parseLine(it) } .count { anyOverlap(it) } //.forEach{println("$it -> ${anyOverlap(it)}")}; // 921 } fun main() { val input = util.readFileUsingGetResource("day-4-input.txt") //println("Number of entirely contained assignments: ${part1(input)}") println("Number of any overlapping assignments: ${part2(input)}") }
0
Kotlin
0
0
2eb856af5d696505742f7c77e6292bb83a6c126c
1,576
aoc
Apache License 2.0
src/year_2021/day_05/Day05.kt
scottschmitz
572,656,097
false
{"Kotlin": 240069}
package year_2021.day_05 import readInput data class Point( val x: Int, val y: Int ) data class LineSegment( val pointA: Point, val pointB: Point ) { val allHorizontalAndVerticalPoints: List<Point> get() { return when { pointA.x == pointB.x -> { // vertical val (start, end) = if (pointA.y < pointB.y) { pointA to pointB } else { pointB to pointA } (start.y..end.y).map { y -> Point( x = pointA.x, y = y ) } } pointA.y == pointB.y -> { // horizontal val (start, end) = if (pointA.x < pointB.x) { pointA to pointB } else { pointB to pointA } (start.x..end.x).map { x -> Point( x = x, y = pointA.y ) } } else -> { emptyList() } } } val allPoints: List<Point> get() { return when { pointA.x == pointB.x -> { // vertical val (start, end) = if (pointA.y < pointB.y) { pointA to pointB } else { pointB to pointA } (start.y..end.y).map { y -> Point( x = pointA.x, y = y ) } } pointA.y == pointB.y -> { // horizontal val (start, end) = if (pointA.x < pointB.x) { pointA to pointB } else { pointB to pointA } (start.x..end.x).map { x -> Point( x = x, y = pointA.y ) } } pointA.x > pointB.x && pointA.y > pointB.y -> { // left up (pointB.x..pointA.x).mapIndexed { index, x -> Point( x = x, y = pointB.y + index ) } } pointA.x > pointB.x -> { // left down (pointB.x..pointA.x).mapIndexed { index, x -> Point( x = x, y = pointB.y - index ) } } pointA.y > pointB.y -> { // right up (pointA.x..pointB.x).mapIndexed { index, x -> Point( x = x, y = pointA.y - index ) } } else -> { // right down (pointA.x..pointB.x).mapIndexed { index, x -> Point( x = x, y = pointA.y + index ) } } } } } object Day05 { /** * @return */ fun solutionOne(text: List<String>): Int { return parseLines(text) .flatMap { lineSegment -> lineSegment.allHorizontalAndVerticalPoints } .groupBy { it } .filter { (_, points) -> points.size > 1 } .count() } /** * @return */ fun solutionTwo(text: List<String>): Int { return parseLines(text) .flatMap { lineSegment -> lineSegment.allPoints } .groupBy { it } .filter { (_, points) -> points.size > 1 } .count() } private fun parseLines(text: List<String>): List<LineSegment> { return text.map { line -> val points = line .split(" -> ") .map { pointText -> val points = pointText.split(",").map { it.toInt() } Point( x = points[0], y = points[1] ) } LineSegment( pointA = points[0], pointB = points[1], ) } } } fun main() { val inputText = readInput("year_2021/day_05/Day06.txt") val solutionOne = Day05.solutionOne(inputText) println("Solution 1: $solutionOne") val solutionTwo = Day05.solutionTwo(inputText) println("Solution 2: $solutionTwo") }
0
Kotlin
0
0
70efc56e68771aa98eea6920eb35c8c17d0fc7ac
4,596
advent_of_code
Apache License 2.0
src/main/kotlin/de/startat/aoc2023/Day2.kt
Arondc
727,396,875
false
{"Kotlin": 194620}
package de.startat.aoc2023 data class D2Play(val shownRed: Int, val shownGreen: Int, val shownBlue: Int) data class Game(val id: Int, val plays: List<D2Play>) fun isValid(game : Game, maxRed: Int, maxGreen: Int, maxBlue: Int): Boolean = game.plays.all { play -> play.shownRed <= maxRed && play.shownGreen <= maxGreen && play.shownBlue <= maxBlue } fun leastCubes(game: Game): Triple<Int, Int, Int> { return Triple(game.plays.maxOf { it.shownRed }, game.plays.maxOf { it.shownGreen }, game.plays.maxOf { it.shownBlue }) } val gameId = Regex("Game (\\d*): ") val reds = Regex("(\\d*) red") val greens = Regex("(\\d*) green") val blues = Regex("(\\d*) blue") fun String.parseGame(): Game { val id: Int = gameId.find(this).let { it?.groupValues?.get(1)?.toInt() ?: -1 } val plays = this.dropWhile { it != ':' }.drop(1).split(";").map { it.parsePlay() }.toList() return Game(id, plays) } fun String.parsePlay(): D2Play { val red = reds.find(this).let { it?.groupValues?.get(1)?.toInt() ?: 0 } val green = greens.find(this).let { it?.groupValues?.get(1)?.toInt() ?: 0 } val blue = blues.find(this).let { it?.groupValues?.get(1)?.toInt() ?: 0 } return D2Play(red, green, blue) } class Day2 { fun star1() { val result = day2Input.lines().map { it.parseGame() }.filter { isValid(it,12, 13, 14) } .fold(0) { acc, game -> acc + game.id } println("Lösung für Stern 1: $result") } fun star2() { val result = day2Input.lines().map { leastCubes(it.parseGame()) } .fold(0) { acc, (maxRed,maxGreen,maxBlue) -> acc + maxRed * maxGreen * maxBlue } println("Lösung für Stern 2: $result") } } val day2testInput = """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 day2Input = """Game 1: 1 red, 5 blue, 10 green; 5 green, 6 blue, 12 red; 4 red, 10 blue, 4 green Game 2: 2 green, 1 blue; 1 red, 2 green; 3 red, 1 blue; 2 blue, 1 green, 8 red; 1 green, 10 red; 10 red Game 3: 14 red, 9 green, 5 blue; 2 green, 5 red, 7 blue; 1 blue, 14 green; 6 green, 2 red Game 4: 2 green, 3 blue, 9 red; 1 red, 1 green; 4 red, 4 blue; 1 blue, 19 red; 7 red Game 5: 1 green, 10 blue, 4 red; 15 green, 4 red, 5 blue; 14 blue, 14 green, 2 red; 15 green, 7 blue, 1 red; 2 red, 9 green, 17 blue Game 6: 2 red, 2 blue, 4 green; 3 red, 13 blue, 9 green; 1 red, 14 blue, 3 green; 9 green, 11 blue, 3 red; 6 blue, 2 green Game 7: 11 green, 6 blue, 6 red; 2 blue, 3 red, 9 green; 3 red, 5 blue, 5 green; 6 red, 5 green, 3 blue; 9 red, 6 blue Game 8: 11 blue, 3 red; 3 blue, 2 green, 13 red; 11 red, 7 blue, 1 green Game 9: 2 green, 1 blue, 3 red; 9 green, 4 red; 7 red, 5 green; 4 red, 1 blue; 11 green, 16 red; 2 red, 6 green Game 10: 1 red, 4 blue, 1 green; 7 green, 3 red, 1 blue; 5 blue, 7 red Game 11: 1 red, 11 blue, 7 green; 6 green, 2 blue, 12 red; 8 blue, 7 green, 5 red Game 12: 11 red, 5 blue, 4 green; 8 blue, 15 red, 5 green; 9 blue, 11 green, 1 red; 6 blue, 3 red, 9 green; 5 red, 2 blue, 1 green Game 13: 5 red, 2 blue, 7 green; 1 red, 8 green; 6 green, 4 red Game 14: 1 green, 2 blue, 2 red; 5 red, 1 blue, 2 green; 4 red, 1 blue Game 15: 6 green, 1 red; 4 red, 5 blue, 6 green; 1 green, 3 blue, 4 red; 5 green, 8 red Game 16: 16 red, 10 blue, 3 green; 9 blue, 13 green, 5 red; 14 green, 2 blue, 2 red; 3 blue, 1 green, 1 red; 2 green, 4 blue, 8 red; 1 blue, 17 red, 9 green Game 17: 6 red, 1 blue, 15 green; 5 red, 5 green; 16 green, 5 red, 4 blue; 5 red, 8 green, 2 blue; 12 blue, 13 green, 3 red Game 18: 17 green, 5 blue; 2 green, 14 red; 10 green, 9 red, 10 blue; 6 red, 11 green, 6 blue Game 19: 12 green, 2 blue, 4 red; 1 blue, 16 red; 8 green, 2 blue, 14 red Game 20: 1 red, 4 green; 5 red, 4 green; 4 green, 1 red; 5 red, 1 blue, 3 green Game 21: 15 red, 5 blue, 12 green; 10 green, 12 red, 1 blue; 9 red, 14 blue, 1 green; 2 green, 13 red, 7 blue; 12 blue, 11 red, 12 green Game 22: 8 blue, 3 red; 2 green, 4 red, 3 blue; 1 blue, 2 red, 1 green; 13 blue, 4 red, 2 green Game 23: 3 blue, 5 green, 3 red; 4 green, 9 red; 3 red, 2 green; 2 blue, 3 green, 2 red; 2 green, 3 blue, 5 red Game 24: 15 red, 1 green; 1 blue, 14 red, 1 green; 5 green, 14 red; 4 blue, 1 red, 3 green; 1 blue, 4 green, 3 red Game 25: 3 green, 3 red; 8 green, 1 red, 2 blue; 1 blue, 11 green Game 26: 3 red, 12 green, 15 blue; 15 blue, 2 red, 2 green; 2 red, 18 blue; 3 red, 14 blue, 7 green Game 27: 6 green, 15 red, 10 blue; 6 green, 7 red, 4 blue; 14 blue, 12 red, 7 green; 8 red, 14 blue, 17 green; 15 red, 14 blue, 4 green; 5 red, 1 blue, 5 green Game 28: 5 blue, 3 green; 3 green, 2 blue, 4 red; 8 green, 6 red; 4 red, 2 green, 5 blue; 1 blue, 5 red, 5 green; 1 red, 4 blue, 9 green Game 29: 4 blue, 9 red, 12 green; 2 red, 14 blue, 13 green; 2 red, 10 green; 5 green, 14 blue, 9 red Game 30: 3 red, 3 blue, 13 green; 2 blue, 10 green, 4 red; 2 blue, 5 green, 4 red Game 31: 13 green, 3 red, 8 blue; 15 green; 4 blue, 1 red; 8 red, 4 green, 2 blue; 18 blue, 4 red, 9 green Game 32: 3 blue, 8 red, 16 green; 2 blue, 13 red, 18 green; 8 red, 9 green Game 33: 1 red, 7 green, 3 blue; 10 green, 10 red, 10 blue; 5 blue, 8 red, 14 green; 10 blue, 5 green, 2 red; 10 green, 10 red, 16 blue Game 34: 3 blue, 1 green, 6 red; 2 blue, 5 red; 3 blue, 2 red, 9 green Game 35: 5 blue, 2 green, 1 red; 7 blue, 3 red, 7 green; 13 green, 4 blue, 3 red; 1 blue, 9 green; 1 red, 13 green, 3 blue Game 36: 1 red, 1 blue, 13 green; 1 green; 2 blue, 16 green; 3 blue, 17 green, 1 red; 4 blue, 1 red; 5 blue, 1 red Game 37: 5 red, 8 green, 1 blue; 16 blue, 2 red; 7 blue, 7 red, 6 green; 2 blue, 6 green, 4 red; 4 green, 3 red, 5 blue; 3 green, 9 blue, 3 red Game 38: 7 green, 3 red, 2 blue; 1 blue, 1 green, 1 red; 15 blue; 4 red, 11 blue; 1 red, 1 green, 2 blue Game 39: 20 red, 4 blue, 7 green; 11 red, 16 green, 7 blue; 7 red, 15 green, 11 blue; 10 red, 9 blue, 13 green; 12 red, 12 blue, 17 green Game 40: 5 blue, 4 green; 1 red, 1 blue, 9 green; 9 green, 6 blue, 1 red; 6 blue, 4 green, 1 red Game 41: 2 blue; 2 blue, 1 green; 4 green, 2 red, 1 blue Game 42: 7 blue, 12 green, 1 red; 8 blue, 3 green, 1 red; 3 red, 1 blue, 10 green; 7 green, 15 blue Game 43: 3 blue, 19 green, 7 red; 14 blue, 8 green, 8 red; 2 red, 1 green, 5 blue; 8 red, 8 blue, 17 green; 1 blue, 10 red, 18 green; 4 green, 11 red, 8 blue Game 44: 12 blue, 4 green; 9 blue, 1 green, 2 red; 2 red, 3 blue, 3 green; 1 red, 4 green, 14 blue Game 45: 2 red, 1 blue, 7 green; 5 red, 5 green, 1 blue; 2 blue, 6 red, 5 green; 3 green, 2 blue; 6 red, 1 blue; 5 green, 4 red, 1 blue Game 46: 2 blue, 3 green, 2 red; 1 blue, 4 green, 5 red; 4 green, 3 blue, 6 red Game 47: 10 green, 12 blue; 3 red, 8 blue, 8 green; 1 green, 10 blue, 2 red; 4 blue, 4 green Game 48: 5 green, 11 blue, 4 red; 2 blue, 5 green, 7 red; 16 red, 2 green, 5 blue; 2 red, 1 green, 10 blue Game 49: 11 blue, 5 red, 7 green; 15 green, 9 blue; 3 red, 4 green, 6 blue; 2 green, 14 blue, 6 red; 2 red, 11 green, 4 blue; 12 blue, 10 green Game 50: 1 red, 13 blue, 4 green; 2 green, 1 red, 6 blue; 6 green, 14 blue Game 51: 5 blue, 9 green, 1 red; 17 blue, 1 red; 11 green, 13 blue; 7 green, 13 blue; 2 blue, 4 green; 7 blue, 5 green Game 52: 17 green, 3 blue; 15 green, 5 blue, 1 red; 12 green, 1 red, 4 blue; 1 red, 10 blue, 16 green; 12 green, 6 blue, 1 red Game 53: 4 red; 2 green, 5 blue, 5 red; 3 red, 5 blue Game 54: 5 red, 1 green; 16 green, 14 blue, 10 red; 1 red, 15 blue, 15 green Game 55: 5 green, 14 red; 9 red, 6 green, 1 blue; 9 green, 4 red, 1 blue; 3 green, 1 blue, 7 red; 1 blue, 1 red, 2 green Game 56: 2 red, 2 blue; 8 red, 5 blue; 6 blue, 1 green, 4 red Game 57: 1 blue, 1 red; 2 green, 8 red; 7 red, 2 green; 2 blue, 5 green, 5 red Game 58: 18 blue, 1 red, 6 green; 1 red, 8 green; 5 blue, 7 green; 4 blue, 2 green; 8 blue, 4 green Game 59: 10 red, 3 blue; 10 red, 3 green, 4 blue; 3 blue, 1 green; 4 red, 3 green, 6 blue; 5 red, 3 green, 5 blue Game 60: 8 red, 7 green; 11 green, 14 red; 11 red, 1 blue, 7 green; 1 blue, 18 red; 10 red, 12 green, 1 blue Game 61: 11 blue, 6 green, 1 red; 6 red, 12 green, 6 blue; 14 blue, 6 red; 11 blue, 3 red, 6 green Game 62: 7 blue, 4 green, 5 red; 2 green, 4 red, 7 blue; 4 red; 1 blue, 5 red Game 63: 7 green, 10 blue, 11 red; 13 red, 19 blue; 11 green, 11 red; 8 green, 18 blue, 4 red; 5 green, 19 blue, 12 red; 10 green, 6 blue, 2 red Game 64: 1 green, 5 red; 4 green, 13 blue, 6 red; 5 green, 2 red, 13 blue Game 65: 1 blue, 2 green, 5 red; 13 red, 4 green, 3 blue; 8 red; 3 green, 1 red; 6 red, 4 green, 2 blue Game 66: 2 green, 15 red; 3 green, 12 red; 2 blue, 2 green, 4 red; 4 blue, 8 red; 1 green, 4 blue, 14 red; 2 blue, 2 green, 6 red Game 67: 3 green, 5 blue, 1 red; 5 green, 6 red, 3 blue; 13 red, 9 green, 8 blue; 11 green, 15 red, 3 blue; 16 red, 8 blue, 17 green; 8 green, 5 red Game 68: 1 red, 3 green; 1 blue; 2 green; 3 red, 1 blue; 1 green, 3 red, 2 blue Game 69: 2 red, 13 green, 3 blue; 3 red, 2 blue, 7 green; 2 blue, 3 red, 9 green; 7 blue, 1 red, 4 green; 6 red, 14 blue, 2 green; 1 green, 2 red, 14 blue Game 70: 5 blue, 2 green, 1 red; 1 blue, 6 red, 4 green; 4 red, 2 blue, 6 green; 4 red, 2 blue, 8 green; 4 green, 1 blue Game 71: 7 green, 3 blue; 2 red, 4 green, 6 blue; 2 red, 5 blue; 1 blue, 5 green Game 72: 20 green, 4 red; 13 green, 12 blue, 7 red; 15 blue, 16 red, 7 green; 14 green, 13 red, 2 blue; 11 green, 6 red, 8 blue; 10 green, 13 red Game 73: 10 blue, 13 green, 3 red; 3 red, 16 green, 7 blue; 5 blue, 6 green, 2 red; 4 green, 1 blue, 2 red Game 74: 2 green, 7 red, 1 blue; 8 red, 10 green; 5 red, 5 blue Game 75: 4 green, 13 blue, 5 red; 1 red, 2 green, 3 blue; 2 red, 7 green, 14 blue; 1 red, 2 green, 2 blue; 13 blue, 5 red Game 76: 10 blue, 3 green, 6 red; 12 blue, 1 red, 3 green; 13 green, 16 blue, 4 red Game 77: 7 green, 4 red, 4 blue; 6 red; 6 red, 4 green, 9 blue; 1 red, 2 blue Game 78: 3 blue, 11 green; 12 green; 10 green, 4 red, 6 blue Game 79: 8 green, 12 red, 9 blue; 4 green, 6 blue, 1 red; 9 blue, 4 green; 6 blue, 7 green, 11 red; 11 blue, 18 red, 7 green; 4 green, 11 red, 1 blue Game 80: 9 green, 1 red, 7 blue; 3 red, 15 blue, 9 green; 3 blue, 1 red, 5 green; 10 red, 15 blue, 3 green Game 81: 2 red, 3 blue, 2 green; 1 green, 4 blue, 5 red; 7 red, 8 blue; 2 green, 2 blue, 8 red Game 82: 6 blue, 4 red, 1 green; 1 green, 4 red, 9 blue; 3 green, 8 blue; 3 red, 3 blue; 8 blue, 2 green Game 83: 2 red, 1 green, 3 blue; 6 blue, 3 red; 2 red, 1 green, 4 blue Game 84: 1 blue, 10 green; 13 red, 8 green, 4 blue; 7 red, 1 green, 4 blue Game 85: 7 red, 7 green, 1 blue; 1 red, 5 green, 2 blue; 16 red, 10 green, 4 blue; 1 blue, 12 green, 3 red Game 86: 15 red, 7 blue, 1 green; 19 blue, 3 red; 2 blue, 1 green, 4 red Game 87: 9 green; 5 red, 8 green, 1 blue; 1 blue, 5 red, 7 green Game 88: 16 red, 3 green, 2 blue; 1 blue, 6 green, 14 red; 12 blue, 17 red; 11 blue, 13 red, 5 green; 2 blue, 20 red, 3 green; 9 red, 8 blue, 2 green Game 89: 7 green, 3 blue, 6 red; 4 green, 7 blue, 5 red; 6 green, 3 red, 7 blue; 5 green, 3 red, 8 blue; 6 red, 9 blue, 11 green Game 90: 11 green, 4 red, 5 blue; 7 green, 2 red, 1 blue; 4 red, 1 green, 8 blue Game 91: 2 green, 7 red, 5 blue; 18 red, 3 green, 3 blue; 6 red, 2 blue, 5 green; 6 red, 5 blue, 3 green; 7 green, 6 blue, 8 red Game 92: 4 red; 3 red, 5 green, 1 blue; 3 red, 2 blue, 2 green Game 93: 2 green, 15 red, 10 blue; 3 red, 8 blue; 20 red, 5 blue, 2 green; 11 blue, 2 green, 20 red; 7 blue, 18 red Game 94: 1 red, 4 green, 2 blue; 7 green, 9 red, 2 blue; 3 red, 3 green, 1 blue; 8 red, 2 blue, 2 green; 2 red, 8 green, 2 blue; 5 green, 8 red Game 95: 2 blue, 4 red; 1 blue, 3 green, 4 red; 5 green, 3 red, 4 blue; 1 green, 4 red, 6 blue Game 96: 1 green, 1 blue, 2 red; 1 red, 13 blue, 4 green; 3 red, 14 blue, 15 green Game 97: 3 green, 7 red; 2 red, 3 green, 1 blue; 4 green, 1 blue, 4 red; 1 red Game 98: 9 blue, 8 red, 3 green; 10 blue, 3 red; 7 blue, 2 green, 7 red; 4 red, 11 blue, 3 green; 8 red, 9 blue, 2 green Game 99: 5 green, 8 blue; 3 blue, 4 red, 16 green; 1 green, 5 red, 6 blue Game 100: 6 blue, 9 green; 3 green, 6 blue; 5 blue, 1 red"""
0
Kotlin
0
0
660d1a5733dd533aff822f0e10166282b8e4bed9
12,312
AOC2023
Creative Commons Zero v1.0 Universal
day09/main.kt
LOZORD
441,007,912
false
{"Kotlin": 29367, "Python": 963}
import java.util.Scanner data class Position(val row: Int, val col: Int) fun findLowPoints(grid: Array<IntArray>): Set<Position> { val lowPoints = HashSet<Position>() fun visit(i: Int, j: Int) { if (getNeighbors(grid, i, j).all { grid[i][j] < grid[it.row][it.col] }) { lowPoints.add(Position(row=i,col=j)) } } for ((i, row) in grid.withIndex()) { for ((j, _) in row.withIndex()) { visit(i, j) } } return lowPoints } fun lavaFloodBasinSize(grid: Array<IntArray>, lowPoint: Position): Int { // Share the same instance of the HashMap so that each level of recursion // has the same view of visited positions. return recurseFlood(grid, lowPoint, hashSetOf()) } fun recurseFlood(grid: Array<IntArray>, p: Position, visited: HashSet<Position>): Int { if (grid[p.row][p.col] == 9) { return 0 // Base case: maximum height of basin. } if (visited.contains(p)) { return 0 // Base case: already visited this position. } visited.add(p) return 1 + getNeighbors(grid, p) .map { recurseFlood(grid, it, visited) } .sum() } fun getNeighbors(grid: Array<IntArray>, p: Position): Set<Position> { return getNeighbors(grid, p.row, p.col) } fun getNeighbors(grid: Array<IntArray>, i: Int, j: Int): Set<Position> { val neighbors = HashSet<Position>(4) if (i - 1 >= 0) { neighbors.add(Position(row=i-1, col=j)) } if (i + 1 < grid.size) { neighbors.add(Position(row=i+1, col=j)) } if (j - 1 >= 0) { neighbors.add(Position(row=i, col=j-1)) } if (j + 1 < grid[0].size) { neighbors.add(Position(row=i, col=j+1)) } return neighbors } fun main(args: Array<String>) { val rows = ArrayList<IntArray>() val input = Scanner(System.`in`) while (input.hasNextLine()) { val scanned = input.nextLine() rows.add(scanned .trim() .toCharArray() .map { it.digitToInt() } .toIntArray()) } val grid = rows.toTypedArray() val lowPoints = findLowPoints(grid) if (args.contains("--part1")) { val risk = lowPoints .map { grid[it.row][it.col] + 1 } .sum() println("RISK: $risk") return } val product = lowPoints .map { lavaFloodBasinSize(grid, it) } .sortedDescending() .take(3) .reduce { acc, n -> acc * n } println("PRODUCT: $product") }
0
Kotlin
0
0
17dd266787acd492d92b5ed0d178ac2840fe4d57
2,522
aoc2021
MIT License
src/Day12.kt
sitamshrijal
574,036,004
false
{"Kotlin": 34366}
fun main() { fun parse(input: List<String>): List<List<HillPosition>> = buildList { input.forEach { row -> val list = mutableListOf<HillPosition>() row.forEach { char -> val elevation = char.toElevation() list += HillPosition(elevation, Type.parse(char)) } add(list) } } fun bfs( heightmap: List<List<HillPosition>>, start: HillPosition, isGoal: (HillPosition) -> Boolean, canMove: (HillPosition, HillPosition) -> Boolean ): Int { val xRange = heightmap.indices val yRange = heightmap[0].indices val directions = listOf(-1 to 0, 1 to 0, 0 to 1, 0 to -1) heightmap.forEachIndexed { x, row -> row.forEachIndexed { y, position -> val adjacentList = mutableListOf<HillPosition>() directions.forEach { (dx, dy) -> if (x + dx in xRange && y + dy in yRange) { adjacentList += heightmap[x + dx][y + dy] } } position.adjacentPositions = adjacentList } } val end = heightmap.flatten().first { it.type == Type.END } val queue = mutableListOf<HillPosition>() queue.add(start) while (queue.isNotEmpty()) { val vertex = queue.removeFirst() if (isGoal(vertex)) { break } vertex.adjacentPositions.forEach { if (it.color == Color.WHITE && canMove(vertex, it)) { it.color = Color.GRAY it.distance = vertex.distance + 1 queue.add(it) } } vertex.color = Color.BLACK } return if (start.type == Type.END) { heightmap.flatten().filter { it.elevation == 0 && it.distance != 0 } .minOf { it.distance } } else { end.distance } } fun part1(input: List<String>): Int { val heightmap = parse(input) val start = heightmap.flatten().first { it.type == Type.START } return bfs( heightmap, start, { it.type == Type.END }, { from, to -> to.elevation - from.elevation <= 1 } ) } fun part2(input: List<String>): Int { val heightmap = parse(input) // Start at the end val start = heightmap.flatten().first { it.type == Type.END } return bfs( heightmap, start, { it.elevation == 0 }, { from, to -> from.elevation - to.elevation <= 1 } ) } val input = readInput("input12") println(part1(input)) println(part2(input)) } enum class Type { START, END, OTHER; companion object { fun parse(char: Char): Type = when (char) { 'S' -> START 'E' -> END else -> OTHER } } } enum class Color { WHITE, GRAY, BLACK } data class HillPosition( val elevation: Int, val type: Type, var color: Color = Color.WHITE, var distance: Int = 0 ) { var adjacentPositions = mutableListOf<HillPosition>() } fun Char.toElevation(): Int = when (this) { 'S' -> 0 'E' -> 25 else -> this - 'a' }
0
Kotlin
0
0
fd55a6aa31ba5e3340be3ea0c9ef57d3fe9fd72d
3,355
advent-of-code-2022
Apache License 2.0
src/Day12.kt
armandmgt
573,595,523
false
{"Kotlin": 47774}
import java.util.* import kotlin.math.abs fun main() { data class Node(val x: Int, val y: Int, val height: Int) data class Puzzle(val start: Node, val end: Node, val nodes: List<List<Node>>) fun parse(input: List<String>): Puzzle { var start: Node? = null var end: Node? = null val nodes = mutableListOf<List<Node>>() input.forEachIndexed { y, line -> val lineNodes = mutableListOf<Node>() line.forEachIndexed { x, c -> when (c) { 'S' -> { start = Node(x, y, 0) lineNodes.add(start!!) } 'E' -> { end = Node(x, y, 25) lineNodes.add(end!!) } else -> lineNodes.add(Node(x, y, c - 'a')) } } nodes.add(lineNodes) } return Puzzle(start!!, end!!, nodes) } fun manhattanDist(n1: Node, end: Node): Int { return abs(end.x - n1.x) + abs(end.y - n1.y) } fun reconstructPath(cameFrom: Map<Node, Node>, current: Node): List<Node> { var cur = current val totalPath = mutableListOf(cur) while (cameFrom.containsKey(cur)) { cur = cameFrom[cur]!! totalPath.add(cur) } return totalPath } fun validNeighbours(current: Node, puzzle: Puzzle): List<Node> { return arrayOf( Pair(current.x, current.y - 1), Pair(current.x + 1, current.y), Pair(current.x, current.y + 1), Pair(current.x - 1, current.y) ).mapNotNull { (x, y) -> if (y < 0 || y > puzzle.nodes.size - 1) return@mapNotNull null if (x < 0 || x > puzzle.nodes[0].size - 1) return@mapNotNull null if (puzzle.nodes[y][x].height <= current.height + 1) puzzle.nodes[y][x] else null } } fun aStar(puzzle: Puzzle): List<Node> { val cameFrom = mutableMapOf<Node, Node>() val gScore = mutableMapOf<Node, Int>() gScore[puzzle.start] = 0 val fScore = mutableMapOf<Node, Int>() fScore[puzzle.start] = manhattanDist(puzzle.start, puzzle.end) val openSet = PriorityQueue<Node>(1) { n1, n2 -> compareValuesBy(n1, n2) { fScore.getOrDefault(it, Int.MAX_VALUE) } } openSet.add(puzzle.start) while (!openSet.isEmpty()) { val current = openSet.remove() if (current.equals(puzzle.end)) { return reconstructPath(cameFrom, current) } for (neighbour in validNeighbours(current, puzzle)) { val tentativeGScore = gScore.getOrDefault(current, Int.MAX_VALUE) + 1 if (tentativeGScore < gScore.getOrDefault(neighbour, Int.MAX_VALUE)) { cameFrom[neighbour] = current gScore[neighbour] = tentativeGScore fScore[neighbour] = tentativeGScore + manhattanDist(neighbour, puzzle.end) if (!openSet.contains(neighbour)) { openSet.add(neighbour) } } } } return emptyList() } fun part1(input: List<String>): Int { val puzzle = parse(input) return aStar(puzzle).size - 1 } fun part2(input: List<String>): Int { val puzzle = parse(input) return puzzle.nodes.fold(emptyList<Node>()) { acc, nodes -> acc + nodes.filter { it.height == 0 } }.minOf { start -> aStar(puzzle.copy(start = start)).let { if (it.isEmpty()) Int.MAX_VALUE else it.size - 1 } } } // test if implementation meets criteria from the description, like: val testInput = readInput("resources/Day12_test") check(part1(testInput) == 31) val input = readInput("resources/Day12") println(part1(input)) check(part2(testInput) == 29) println(part2(input)) }
0
Kotlin
0
1
0d63a5974dd65a88e99a70e04243512a8f286145
4,073
advent_of_code_2022
Apache License 2.0
src/day05/Day05.kt
xxfast
572,724,963
false
{"Kotlin": 32696}
package day05 import readText typealias Crate = Char typealias Stack = MutableList<Crate> data class Instruction(val count: Int, val fromIndex: Int, val toIndex: Int) data class Crane(val stacks: List<Stack>, val instructions: List<Instruction>) // Parsing is long 🤮 fun Crane(input: String): Crane { val lines: List<String> = input.lines() fun String.filterSpaces(): String = filter { it != ' ' } val stackDescriptionIndex: Int = lines.indexOfFirst { line -> line.filterSpaces().all { it.isDigit() } } val stackDescription: String = lines[stackDescriptionIndex] val stackIndexes: Map<Int, Int> = stackDescription .mapIndexed { index, char -> char to index } .filter { (char, _) -> char.isDigit() } .associate { (char, index) -> char.digitToInt() to index } val width: Int = stackDescription.filterSpaces().map { char -> char.digitToInt() }.max() val height: Int = stackDescriptionIndex val stackDescriptions: List<String> = lines.subList(0, height) val stacks: MutableList<MutableList<Char>> = MutableList(width) { mutableListOf() } for (rowIndex in height - 1 downTo 0) { val row = stackDescriptions[rowIndex] for (columnIndex in 0 until width) { val charIndex = stackIndexes[columnIndex + 1]!! val char = row.getOrNull(charIndex) if (char != null && char.isLetter()) { stacks[columnIndex].add(char) } } } val instructions: List<Instruction> = lines .drop(stackDescriptionIndex + 2) .dropLast(1) .map { line -> val (count, from, to) = line .split(" ") .filter { word -> word.all { it.isDigit() } } .map { number -> number.toInt() } Instruction(count, from, to) } return Crane(stacks, instructions) } fun Crane.stackTops(): List<Crate> = stacks.map { it.last() } fun Crane.move(operation: (count: Int, from: Stack, to: Stack) -> Unit): Crane = apply { instructions.forEach { (count, fromIndex, toIndex) -> val from: Stack = stacks[fromIndex - 1] val to: Stack = stacks[toIndex - 1] operation(count, from, to) } } // TODO: Why is this not on stdlib 🤯 fun <E> MutableList<E>.removeLast(count: Int): List<E> { val last: List<E> = takeLast(count) repeat(count) { removeLast() } return last } fun main() { fun part1(input: String): String = Crane(input) .move { count, from, to -> repeat(count) { val crate: Crate = from.removeLast() to.add(crate) } } .stackTops() .joinToString("") fun part2(input: String): String = Crane(input) .move { count, from, to -> val crates: List<Crate> = from.removeLast(count) to.addAll(crates) } .stackTops() .joinToString("") // test if implementation meets criteria from the description, like: val testInput: String = readText("day05/test.txt") val input: String = readText("day05/input.txt") check(part1(testInput) == "CMZ") check(part2(testInput) == "MCD") println(part1(input)) println(part2(input)) }
0
Kotlin
0
1
a8c40224ec25b7f3739da144cbbb25c505eab2e4
3,003
advent-of-code-22
Apache License 2.0
src/Day03.kt
hijst
572,885,261
false
{"Kotlin": 26466}
fun main() { val itemTypePriorities: Map<Char, Int> = ( (('a'..'z').toList() + ('A'..'Z').toList()) .zip(1..52) ) .toMap() fun Char.toPriority(): Int = itemTypePriorities.getOrDefault(this, 0) fun String.splitInHalves() = substring(0, (length / 2)) to substring(length / 2) fun Pair<String, String>.findCommonItem(): Char = first .first { char -> second.contains(char) } fun List<String>.findBadge(): Char = first() .first { char -> 2 < sumOf { rucksack -> rucksack.contains(char).compareTo(false) } } fun part1(input: List<String>): Int = input .sumOf { items -> items.splitInHalves() .findCommonItem() .toPriority() } fun part2(input: List<String>): Int = input .chunked(3) .sumOf { group -> group.findBadge() .toPriority() } val testInput = readInputLines("Day03_test") check(part1(testInput) == 157) check(part2(testInput) == 70) val input = readInputLines("Day03_input") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
2258fd315b8933642964c3ca4848c0658174a0a5
1,166
AoC-2022
Apache License 2.0
src/main/kotlin/day02/Day02.kt
Malo-T
575,370,082
false
null
package day02 class Day02 { enum class Play(val points: Int) { ROCK(1) { override fun scoreAgainst(other: Play) = when (other) { ROCK -> Result.DRAW PAPER -> Result.LOSS SCISSORS -> Result.WIN }.points + points }, PAPER(2) { override fun scoreAgainst(other: Play) = when (other) { ROCK -> Result.WIN PAPER -> Result.DRAW SCISSORS -> Result.LOSS }.points + points }, SCISSORS(3) { override fun scoreAgainst(other: Play) = when (other) { ROCK -> Result.LOSS PAPER -> Result.WIN SCISSORS -> Result.DRAW }.points + points }; abstract fun scoreAgainst(other: Play): Int } enum class Result(val points: Int) { LOSS(0), DRAW(3), WIN(6) } enum class OpponentPlay(val play: Play) { A(Play.ROCK), B(Play.PAPER), C(Play.SCISSORS) } enum class ResponsePlay(val play: Play) { X(Play.ROCK), Y(Play.PAPER), Z(Play.SCISSORS) } enum class ExpectedResult(val result: Result) { X(Result.LOSS) { override fun expectedResponse(opponentPlay: Play) = when (opponentPlay) { Play.ROCK -> Play.SCISSORS Play.PAPER -> Play.ROCK Play.SCISSORS -> Play.PAPER } }, Y(Result.DRAW) { override fun expectedResponse(opponentPlay: Play) = opponentPlay }, Z(Result.WIN) { override fun expectedResponse(opponentPlay: Play) = when (opponentPlay) { Play.ROCK -> Play.PAPER Play.PAPER -> Play.SCISSORS Play.SCISSORS -> Play.ROCK } }; abstract fun expectedResponse(opponentPlay: Play): Play } fun parse1(input: String): List<Pair<OpponentPlay, ResponsePlay>> = input.split("\n") .map { it.split(" ") .let { pair -> OpponentPlay.valueOf(pair[0]) to ResponsePlay.valueOf(pair[1]) } } fun part1(parsed: List<Pair<OpponentPlay, ResponsePlay>>): Int = parsed.sumOf { (opponent, response) -> response.play.scoreAgainst(opponent.play) } fun parse2(input: String): List<Pair<OpponentPlay, ExpectedResult>> = input.split("\n") .map { it.split(" ") .let { pair -> OpponentPlay.valueOf(pair[0]) to ExpectedResult.valueOf(pair[1]) } } fun part2(parsed: List<Pair<OpponentPlay, ExpectedResult>>): Int = parsed.sumOf { (opponent, expectedResult) -> expectedResult.expectedResponse(opponent.play).scoreAgainst(opponent.play) } }
0
Kotlin
0
0
f4edefa30c568716e71a5379d0a02b0275199963
2,929
AoC-2022
Apache License 2.0
src/main/kotlin/_2022/Day18.kt
novikmisha
572,840,526
false
{"Kotlin": 145780}
package _2022 import readInput fun main() { fun getNearCoords(coord: Triple<Int, Int, Int>): Set<Triple<Int, Int, Int>> { return setOf( Triple(coord.first + 1, coord.second, coord.third), Triple(coord.first - 1, coord.second, coord.third), Triple(coord.first, coord.second + 1, coord.third), Triple(coord.first, coord.second - 1, coord.third), Triple(coord.first, coord.second, coord.third + 1), Triple(coord.first, coord.second, coord.third - 1), ) } fun part1(input: List<String>): Int { val coords = input.map { val (x, y, z) = it.split(",") .map(String::toInt) Triple(x, y, z) }.toSet() var result = 0 for (coord in coords) { result += 6 - getNearCoords(coord).intersect(coords).size } return result } fun part2(input: List<String>): Int { val coords = input.map { val (x, y, z) = it.split(",") .map(String::toInt) Triple(x, y, z) }.toSet() val maxX = coords.maxOf { it.first + 1 } val maxY = coords.maxOf { it.second + 1 } val maxZ = coords.maxOf { it.third + 1 } val minX = coords.minOf { it.first - 1 } val minY = coords.minOf { it.second - 1 } val minZ = coords.minOf { it.third - 1 } var result = 0 val queue = ArrayDeque<Triple<Int, Int, Int>>() val visited = mutableSetOf<Triple<Int, Int, Int>>() queue.add(Triple(minX, minY, minZ)) while (queue.isNotEmpty()) { val coord = queue.removeFirst() getNearCoords(coord) .filter { it.first in minX..maxX && it.second in minY..maxY && it.third in minZ..maxZ }.forEach { if (coords.contains(it)) { result++ } else if (!visited.contains(it)) { queue.remove(it) queue.add(it) } } visited.add(coord) } return result } // test if implementation meets criteria from the description, like: val testInput = readInput("Day18_test") println(part1(testInput)) println(part2(testInput)) val input = readInput("Day18") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
0c78596d46f3a8bf977bf356019ea9940ee04c88
2,512
advent-of-code
Apache License 2.0
day 02/Wouter - kotlin/solution.kts
AE-nv
420,076,649
false
{"Python": 254337, "Java": 180867, "C#": 167466, "F#": 114222, "Clojure": 88016, "C++": 45744, "HTML": 22679, "TypeScript": 19433, "Go": 16626, "JavaScript": 10488, "Assembly": 8364, "Rust": 6671, "Kotlin": 3264, "Scala": 2328, "CSS": 252}
data class Position(val depth: Int, val horizontal: Int, val aim:Int) { fun execute(command: Command) = when(command.direction) { "forward" -> Position(depth, horizontal+command.amount, aim) "down" -> Position(depth+command.amount, horizontal, aim) "up" -> Position(depth-command.amount, horizontal, aim) else -> this } fun execute2(command: Command) = when(command.direction) { "forward" -> Position(depth + aim * command.amount, horizontal + command.amount, aim) "down" -> Position(depth, horizontal, aim + command.amount) "up" -> Position(depth, horizontal, aim - command.amount) else -> this } fun result() = depth * horizontal } data class Command(val direction: String, val amount: Int) fun solve(input: List<String>) = input.map { it.split(" ") } .map { Command(it[0], it[1].toInt()) } .fold(Position(0,0,0)) { acc, command -> acc.execute(command) } .result() fun solve2(input: List<String>) = input.map { it.split(" ") } .map { Command(it[0], it[1].toInt()) } .fold(Position(0,0,0)) { acc, command -> acc.execute2(command) } .result() val testInput = """ forward 5 down 5 forward 8 up 3 down 8 forward 2 """.trimIndent().split("\n") println("Part 1: ${solve(testInput)}") println("Part 2: ${solve2(testInput)}")
0
Python
1
1
e9c803dc5fab3c51a2acbbaade56b71d4f5ce7d2
1,367
aedvent-code-2021
MIT License
2021/src/main/kotlin/day4_imp.kt
madisp
434,510,913
false
{"Kotlin": 388138}
import utils.IntGrid import utils.Parser import utils.Solution fun main() { Day4Imp.run() } object Day4Imp : Solution<Pair<List<Int>, List<IntGrid>>>() { override val name = "day4" override val parser = Parser.compoundList(Parser.ints, IntGrid.table) override fun part1(input: Pair<List<Int>, List<IntGrid>>): Int { val (numbers, boards) = input return boardWinTimes(numbers, boards).minByOrNull { it.first }!!.second } override fun part2(input: Pair<List<Int>, List<IntGrid>>): Int { val (numbers, boards) = input return boardWinTimes(numbers, boards).maxByOrNull { it.first }!!.second } // given a list of numbers and a list of boards calculates the turn win times and winning scores for each board private fun boardWinTimes(numbers: List<Int>, boards: List<IntGrid>): List<Pair<Int, Int>> { val takenNumbers = mutableSetOf<Int>() val boardsList = mutableListOf(*boards.toTypedArray()) val winningBoards = mutableListOf<Pair<Int, Int>>() numbers.forEachIndexed { index, number -> takenNumbers.add(number) val iterator = boardsList.listIterator() while (iterator.hasNext()) { val board = iterator.next() if (board.winning(takenNumbers)) { iterator.remove() winningBoards.add(index + 1 to board.score(takenNumbers)) } } } return winningBoards } private fun IntGrid.winning(marked: Set<Int>): Boolean { return rows.any { row -> row.values.all { it in marked } } || columns.any { col -> col.values.all { it in marked } } } private fun IntGrid.score(marked: Set<Int>): Int { return (values.toSet() - marked).sum() * marked.last() } }
0
Kotlin
0
1
3f106415eeded3abd0fb60bed64fb77b4ab87d76
1,684
aoc_kotlin
MIT License
src/day12/Day12.kt
armanaaquib
572,849,507
false
{"Kotlin": 34114}
package day12 import readInput import kotlin.math.min fun main() { fun parseInput(input: List<String>) = input.map { it.toCharArray().toList() } fun findStart(heightMap: List<List<Char>>): Pair<Int, Int> { for (i in heightMap.indices) { for (j in heightMap[0].indices) { if (heightMap[i][j] == 'S') { return Pair(i, j) } } } throw Error("Start not found") } fun isMovable(heightMap: List<List<Char>>, sp: Pair<Int, Int>, dp: Pair<Int, Int>): Boolean { val dest = if (heightMap[dp.first][dp.second] == 'E') 'z' else heightMap[dp.first][dp.second] val source = if (heightMap[sp.first][sp.second] == 'S') 'a' else heightMap[sp.first][sp.second] return dest - source <= 1 } fun findNextPositions(heightMap: List<List<Char>>, step: Pair<Int, Int>): List<Pair<Int, Int>> { val i = step.first val j = step.second val steps = mutableListOf<Pair<Int, Int>>() if (j - 1 >= 0 && isMovable(heightMap, step, Pair(i, j - 1))) { steps.add(Pair(i, j - 1)) } if (i - 1 >= 0 && isMovable(heightMap, step, Pair(i - 1, j))) { steps.add(Pair(i - 1, j)) } if (j + 1 <= heightMap[i].lastIndex && isMovable(heightMap, step, Pair(i, j + 1))) { steps.add(Pair(i, j + 1)) } if (i + 1 <= heightMap.lastIndex && isMovable(heightMap, step, Pair(i + 1, j))) { steps.add(Pair(i + 1, j)) } return steps } fun findFewestSteps(start: Pair<Int, Int>, heightMap: List<List<Char>>): Int { val queue = ArrayDeque<Pair<Int, Int>>() queue.add(start) var steps = 0 val visited = mutableSetOf(start) while (queue.isNotEmpty()) { val n = queue.size for (i in 1..n) { val pos = queue.removeFirst() if (heightMap[pos.first][pos.second] == 'E') return steps for (p in findNextPositions(heightMap, pos)) { if (!visited.contains(p)) { queue.addLast(p) visited.add(p) } } } steps++ } return Int.MAX_VALUE } fun part1(input: List<String>): Int { val heightMap = parseInput(input) val start = findStart(heightMap) return findFewestSteps(start, heightMap) } fun findStarts(heightMap: List<List<Char>>): List<Pair<Int, Int>> { val starts = mutableListOf<Pair<Int, Int>>() for (i in heightMap.indices) { for (j in heightMap[0].indices) { if (heightMap[i][j] == 'S' || heightMap[i][j] == 'a') { starts.add(Pair(i, j)) } } } return starts } fun part2(input: List<String>): Int { val heightMap = parseInput(input) var fewestSteps = Int.MAX_VALUE for (start in findStarts(heightMap)) { fewestSteps = min(fewestSteps, findFewestSteps(start, heightMap)) } return fewestSteps } // test if implementation meets criteria from the description, like: check(part1(readInput("Day12_test")) == 31) println(part1(readInput("Day12"))) check(part2(readInput("Day12_test")) == 29) println(part2(readInput("Day12"))) }
0
Kotlin
0
0
47c41ceddacb17e28bdbb9449bfde5881fa851b7
3,461
aoc-2022
Apache License 2.0
src/main/kotlin/_2022/Day11.kt
novikmisha
572,840,526
false
{"Kotlin": 145780}
package _2022 import readGroupedInput import java.math.BigInteger fun main() { fun getNewItemLvl(item: BigInteger, operation: String): BigInteger { val (first, operationChar, second) = operation.replace("old", item.toString()) .split(" ") when (operationChar) { "+" -> return first.toBigInteger() + second.toBigInteger() "-" -> return first.toBigInteger() - second.toBigInteger() "*" -> return first.toBigInteger() * second.toBigInteger() "/" -> return first.toBigInteger() / second.toBigInteger() } return BigInteger.ZERO } fun parseMonkey( unparsedMonkey: List<String>, monkeyMap: MutableMap<Int, Monkey>, monkeyIndex: Int ) { val items = ArrayDeque<BigInteger>() var operation = "" var divisible = 0 var testTrueMonkeyNumber = 0 var testFalseMonkeyNumber = 0 unparsedMonkey.forEachIndexed { index, line -> when (index) { 1 -> items.addAll(line.replace("Starting items: ", "") .replace(",", "") .split(" ") .filter { it.isNotEmpty() } .map { it.trim().toBigInteger() }) 2 -> { operation = line.replace(" Operation: new = ", "") .trim() } 3 -> { divisible = line.split(" ") .firstNotNullOf { it.toIntOrNull() } } 4 -> { testTrueMonkeyNumber = line.split(" ") .firstNotNullOf { it.toIntOrNull() } } 5 -> { testFalseMonkeyNumber = line.split(" ") .firstNotNullOf { it.toIntOrNull() } } } } val monkey = Monkey(items, operation, divisible, testTrueMonkeyNumber, testFalseMonkeyNumber) monkeyMap[monkeyIndex] = monkey } fun catchMonkeysItems( input: List<List<String>>, rounds: Int, newItemLevelModificator: (BigInteger, BigInteger) -> BigInteger ): BigInteger { val monkeyMap = mutableMapOf<Int, Monkey>() input.mapIndexed { monkeyIndex, unparsedMonkey -> parseMonkey(unparsedMonkey, monkeyMap, monkeyIndex) } val inspectMap = mutableMapOf<Int, BigInteger>() val divisor = monkeyMap.values.map { it.divisible }.reduce(Int::times).toBigInteger() for (round in 0 until rounds) { monkeyMap.forEach { (index, monkey) -> while (monkey.items.isNotEmpty()) { val item = monkey.items.removeFirst() inspectMap.merge(index, BigInteger.ONE, BigInteger::plus) val newItemLvl = newItemLevelModificator.invoke(getNewItemLvl(item, monkey.operation), divisor) if (newItemLvl.mod(monkey.divisible.toBigInteger()).compareTo(BigInteger.ZERO) == 0) { monkeyMap[monkey.testTrueMonkeyNumber]?.items?.addLast(newItemLvl) } else { monkeyMap[monkey.testFalseMonkeyNumber]?.items?.addLast(newItemLvl) } } } } return inspectMap.values.sortedDescending().take(2).reduce(BigInteger::times) } fun part1(input: List<List<String>>): BigInteger { return catchMonkeysItems(input, 20) { itemLvl, _ -> itemLvl.divide(BigInteger("3")) } } fun part2(input: List<List<String>>): BigInteger { return catchMonkeysItems(input, 10000) { itemLvl, divisor -> itemLvl.remainder(divisor) } } // test if implementation meets criteria from the description, like: val testInput = readGroupedInput("Day11_test") println(part1(testInput)) println(part2(testInput)) val input = readGroupedInput("Day11") println(part1(input)) println(part2(input)) } data class Monkey( val items: ArrayDeque<BigInteger>, val operation: String, val divisible: Int, val testTrueMonkeyNumber: Int, val testFalseMonkeyNumber: Int )
0
Kotlin
0
0
0c78596d46f3a8bf977bf356019ea9940ee04c88
4,226
advent-of-code
Apache License 2.0
src/main/kotlin/biz/koziolek/adventofcode/year2022/day02/day2.kt
pkoziol
434,913,366
false
{"Kotlin": 715025, "Shell": 1892}
package biz.koziolek.adventofcode.year2022.day02 import biz.koziolek.adventofcode.findInput fun main() { val inputFile = findInput(object {}) val encryptedGuide = parseRockPaperScissorsGuide(inputFile.bufferedReader().readLines()) val guessedMoves = decodeGuessedMoves(encryptedGuide) println("Total score: ${totalScore(guessedMoves)}") val actualMoves = decodeActualMoves(encryptedGuide) println("Total score: ${totalScore(actualMoves)}") } enum class RoundOutcome(val points: Int) { VICTORY(points = 6), DEFEAT(points = 0), DRAW(points = 3), } enum class Shape(val points: Int) { ROCK(points = 1), PAPER(points = 2), SCISSORS(points = 3); val winsOver: Shape get() = when (this) { ROCK -> SCISSORS PAPER -> ROCK SCISSORS -> PAPER } val losesTo: Shape get() = values().first { it.winsOver == this } } data class Round(val opponents: Shape, val my: Shape) { val outcome = when { my.winsOver == opponents -> RoundOutcome.VICTORY my.losesTo == opponents -> RoundOutcome.DEFEAT else -> RoundOutcome.DRAW } val score = my.points + outcome.points } fun parseRockPaperScissorsGuide(lines: Iterable<String>): List<Pair<Char, Char>> = lines.map { line -> line[0] to line[2] } fun decodeGuessedMoves(guide: List<Pair<Char, Char>>): List<Round> = guide.map { (opponents, my) -> Round( opponents = decodeOpponentsShape(opponents), my = decodeMyShape(my) ) } fun decodeActualMoves(guide: List<Pair<Char, Char>>): List<Round> = guide .map { (opponents, outcome) -> decodeOpponentsShape(opponents) to decodeExpectedOutcome(outcome) } .map { (opponents, outcome) -> Round( opponents = opponents, my = when (outcome) { RoundOutcome.VICTORY -> opponents.losesTo RoundOutcome.DEFEAT -> opponents.winsOver RoundOutcome.DRAW -> opponents } ) } fun decodeOpponentsShape(shape: Char): Shape = when (shape) { 'A' -> Shape.ROCK 'B' -> Shape.PAPER 'C' -> Shape.SCISSORS else -> throw IllegalArgumentException("Illegal opponent's shape: $shape") } fun decodeMyShape(shape: Char): Shape = when (shape) { 'X' -> Shape.ROCK 'Y' -> Shape.PAPER 'Z' -> Shape.SCISSORS else -> throw IllegalArgumentException("Illegal my shape: $shape") } fun decodeExpectedOutcome(outcome: Char): RoundOutcome = when (outcome) { 'X' -> RoundOutcome.DEFEAT 'Y' -> RoundOutcome.DRAW 'Z' -> RoundOutcome.VICTORY else -> throw IllegalArgumentException("Illegal expected outcome: $outcome") } fun totalScore(moves: List<Round>): Int = moves.sumOf { it.score }
0
Kotlin
0
0
1b1c6971bf45b89fd76bbcc503444d0d86617e95
2,907
advent-of-code
MIT License
src/main/aoc2022/Day24.kt
nibarius
154,152,607
false
{"Kotlin": 963896}
package aoc2022 import Pos import Search class Day24(input: List<String>) { private val width = input[0].length - 2 private val height = input.size - 2 private val map = parseInput(input) private fun parseInput(input: List<String>): Map<Pos, Char> { return buildMap { for (y in 1 until input.size - 1) { for (x in 1 until input[y].length - 1) { this[Pos(x - 1, y - 1)] = input[y][x] } } } } private data class State(val time: Int, val pos: Pos) private class Graph(val map: Map<Pos, Char>, val mapWidth: Int, val mapHeight: Int) : Search.WeightedGraph<State> { private fun Pos.isStartOrGoal() = this in setOf(Pos(0, -1), Pos(mapWidth - 1, mapHeight)) // Check, in each direction if there is a blizzard that will end up on this spot at the given time. private fun Pos.isASafeSpot(atTime: Int): Boolean { return this in map && map[Pos((x - atTime).mod(mapWidth), y)] != '>' && map[Pos((x + atTime).mod(mapWidth), y)] != '<' && map[Pos(x, (y - atTime).mod(mapHeight))] != 'v' && map[Pos(x, (y + atTime).mod(mapHeight))] != '^' } override fun neighbours(id: State): List<State> { return (mutableListOf(id.pos) + id.pos.allNeighbours()) // either stay or move .filter { it.isStartOrGoal() || it.isASafeSpot(id.time + 1) } .map { State(id.time + 1, it) } } override fun cost(from: State, to: State) = 1f } private val graph = Graph(map, width, height) /** * Walk through the valley avoiding blizzards. Returns the current time when reaching the goal. */ private fun dodgeBlizzards(initialTime: Int, from: Pos, to: Pos): Int { val (last, _) = Search.aStar( graph, start = State(initialTime, from), goalFn = { it.pos == to }, heuristic = { it.pos.distanceTo(to).toFloat() }) return last.time } fun solvePart1(): Int { return dodgeBlizzards(0, Pos(0, -1), Pos(width - 1, height)) } fun solvePart2(): Int { val goal = Pos(width - 1, height) val start = Pos(0, -1) val first = dodgeBlizzards(0, start, goal) val second = dodgeBlizzards(first, goal, start) return dodgeBlizzards(second, start, goal) } }
0
Kotlin
0
6
f2ca41fba7f7ccf4e37a7a9f2283b74e67db9f22
2,476
aoc
MIT License
y2020/src/main/kotlin/adventofcode/y2020/Day08.kt
Ruud-Wiegers
434,225,587
false
{"Kotlin": 503769}
package adventofcode.y2020 import adventofcode.io.AdventSolution fun main() = Day08.solve() object Day08 : AdventSolution(2020, 8, "Handheld Halting") { override fun solvePartOne(input: String): Int { val instructions = parseInstructions(input) return Program(0, instructions).run().first } override fun solvePartTwo(input: String): Int { val instructions = parseInstructions(input) return instructions.indices .asSequence() .filter { instructions[it].op != Operation.Acc } .map { val mod = instructions.toMutableList() mod[it]= mod[it].copy(op = when (mod[it].op) { Operation.Acc -> Operation.Acc Operation.Nop -> Operation.Jmp Operation.Jmp -> Operation.Nop }) mod } .map{Program(0,it).run()} .first { it.second==Status.End } .first } private fun parseInstructions(input: String) = input.lines().map { val (opStr, vStr) = it.split(' ') val op = when (opStr) { "acc" -> Operation.Acc "jmp" -> Operation.Jmp else -> Operation.Nop } val v = vStr.toInt() Instruction(op, v) } } private class Program(var acc: Int, val instructions: List<Instruction>) { var pc = 0 val visited = instructions.map { false }.toMutableList() fun step(): Status { if (pc !in instructions.indices) return Status.End if (visited[pc]) return Status.Loop visited[pc] = true val (op, v) = instructions[pc] when (op) { Operation.Acc -> acc += v Operation.Jmp -> pc += v - 1 Operation.Nop -> { } } pc++ return Status.Run } fun run(): Pair<Int, Status> { var status = Status.Run while (status == Status.Run) { status = step() } return acc to status } } private data class Instruction(val op: Operation, val v: Int) private enum class Operation { Acc, Jmp, Nop } private enum class Status { Run, Loop, End }
0
Kotlin
0
3
fc35e6d5feeabdc18c86aba428abcf23d880c450
2,278
advent-of-code
MIT License
src/main/kotlin/cloud/dqn/leetcode/CombinationSumKt.kt
aviuswen
112,305,062
false
null
package cloud.dqn.leetcode /** * https://leetcode.com/problems/combination-sum/description/ Given a set of candidate numbers (C) (without duplicates) and a target number (T), find all unique combinations in C where the candidate numbers sums to T. The same repeated number may be chosen from C unlimited number of times. Note: All numbers (including target) will be positive integers. The solution set must not contain duplicate combinations. For example, given candidate set [2, 3, 6, 7] and target 7, A solution set is: [ [7], [2, 2, 3] ] */ class CombinationSumKt { class Factor(val multiple: Int, val value: Int) { fun total(): Int = multiple * value companion object { fun factory(value: Int, maxValueInclusive: Int): ArrayList<Factor> { val res = ArrayList<Factor>() (1..(maxValueInclusive / value)).forEach { res.add(Factor(it, value)) } return res } } fun toArray(): IntArray? { if (multiple > 0) { return IntArray(multiple, { value }) } return null } } class FactorCollection { val list: ArrayList<Factor> = ArrayList() var total: Int = 0 fun add(factor: Factor, maxValueInclusive: Int) { if (factor.total() + total <= maxValueInclusive && factor.multiple != 0) { list.add(factor) total += factor.total() } } fun toList(): ArrayList<Int> { val res = ArrayList<Int>() list.forEach { it.toArray()?.let { it.forEach { res.add(it) } } } return res } } fun combinationSum(candidates: IntArray, target: Int): List<List<Int>> { val listFactorCollection = ArrayList<FactorCollection>() candidates.forEach { factor -> val subFactor = Factor.factory(factor, target) val appendList = ArrayList<FactorCollection>() listFactorCollection.forEach { factorCollection -> subFactor.forEach { if (factorCollection.total + it.total() <= target) { val newFactorCollection = FactorCollection() newFactorCollection.add(it, target) factorCollection.list.forEach { newFactorCollection.add(it, target) } appendList.add(newFactorCollection) } } } appendList.forEach { listFactorCollection.add(it) } subFactor.forEach { val factorCollection = FactorCollection() factorCollection.add(it, target) listFactorCollection.add(factorCollection) } } val result = ArrayList<ArrayList<Int>>() listFactorCollection.forEach { factorCollection -> if (factorCollection.total == target) { result.add( factorCollection.toList() ) } } return result } }
0
Kotlin
0
0
23458b98104fa5d32efe811c3d2d4c1578b67f4b
3,269
cloud-dqn-leetcode
No Limit Public License
src/com/ncorti/aoc2023/Day02.kt
cortinico
723,409,155
false
{"Kotlin": 76642}
package com.ncorti.aoc2023 import kotlin.math.max data class Game(val id: Int, val sets : List<Triple<Int, Int, Int>>) { companion object { fun from(input: String): Game { val gameId = input.substringBefore(":").substringAfter(" ").toInt() val sets = input.substringAfter(":").split(";") .map { set -> val red = if ("red" in set) { set.substringBefore(" red").substringAfterLast(" ").toInt() } else { 0 } val green = if ("green" in set) { set.substringBefore(" green").substringAfterLast(" ").toInt() } else { 0 } val blue = if ("blue" in set) { set.substringBefore(" blue").substringAfterLast(" ").toInt() } else { 0 } Triple(red, green, blue) } return Game(gameId, sets) } } } fun main() { fun part1() = getInputAsText("02") { split("\n").filter(String::isNotBlank).map { Game.from(it) } }.sumOf { game -> if (game.sets.any { (red, green, blue) -> red > 12 || green > 13 || blue > 14 }) { 0 } else { game.id } } fun part2() = getInputAsText("02") { split("\n").filter(String::isNotBlank).map { Game.from(it) } }.sumOf { it -> val maxRed = it.sets.maxBy { (red, _, _) -> red }.first.toLong() val maxGreen = it.sets.maxBy { (_, green, _) -> green }.second.toLong() val maxBlue = it.sets.maxBy { (_, _, blue) -> blue }.third.toLong() maxRed * maxGreen * maxBlue } println(part1()) println(part2()) }
1
Kotlin
0
1
84e06f0cb0350a1eed17317a762359e9c9543ae5
1,868
adventofcode-2023
MIT License
solutions/aockt/y2016/Y2016D04.kt
Jadarma
624,153,848
false
{"Kotlin": 435090}
package aockt.y2016 import io.github.jadarma.aockt.core.Solution object Y2016D04 : Solution { /** The actual value of a room, containing its real name and location. */ private data class Room(val name: String, val sector: Int) { init { require(sector > 0) { "Invalid sector; must be positive." } require(name.all { it in "abcdefghijklmnopqrstuvwxyz " }) { "Invalid name; illegal character." } require(checksum.length == 5) { "Invalid name; not enough distinct characters." } } /** The encrypted [name], obtained by shifting by [sector] positions. */ private val encryptedName: String get() = name.shift(-sector) /** The checksum of the [encryptedName], the top 5 letters sorted by occurrences, then alphabetically*/ private val checksum: String get() = encryptedName .groupBy { it } .mapValues { it.value.count() } .filter { it.key != '-' } .entries.sortedWith(compareByDescending<Map.Entry<Char, Int>> { it.value }.thenBy { it.key }) .take(5) .joinToString(separator = "") { it.key.toString() } override fun toString() = "$encryptedName-$sector[$checksum]" companion object { private val inputRegex = Regex("""([a-z-]+)-(\d+)\[([a-z]{5})]""") /** * Creates a string obtained by shifting every character by [shiftBy] positions, cyclically. * Accepts only lowercase letters, spaces, and dashes. * For the latter two, they are swapped around instead. */ private fun String.shift(shiftBy: Int): String = map { char -> when (char) { ' ' -> '-' '-' -> ' ' in 'a'..'z' -> 'a' + Math.floorMod((char - 'a') + shiftBy, 26) else -> throw IllegalArgumentException("Can only rotate lowercase letters, dashes, and spaces.") } }.joinToString("") /** Returns the original room of the encrypted [input] or null if it is invalid. */ fun parseOrNull(input: String): Room? = runCatching { val (encryptedName, sectorRaw, _) = inputRegex.matchEntire(input)!!.destructured val sector = sectorRaw.toInt() val name = encryptedName.shift(sector) return Room(name, sector).takeIf { it.toString() == input } }.getOrNull() } } /** Parses the [input], returning only the valid [Room]s it contains. */ private fun parseInput(input: String) = input.lineSequence().mapNotNull { Room.parseOrNull(it) } override fun partOne(input: String) = parseInput(input).sumOf { it.sector } override fun partTwo(input: String) = parseInput(input).first { it.name == "northpole object storage" }.sector }
0
Kotlin
0
3
19773317d665dcb29c84e44fa1b35a6f6122a5fa
2,971
advent-of-code-kotlin-solutions
The Unlicense
src/aoc2022/Day07.kt
dayanruben
433,250,590
false
{"Kotlin": 79134}
package aoc2022 import readInputText fun main() { val (year, day) = "2022" to "Day07" fun directorySizes(input: String): List<Int> { var currentDir = Directory("/") val directories = mutableListOf(currentDir) input.split("$ ").drop(2).forEach { entry -> val details = entry.split("\n").filter { it.isNotBlank() } when (val command = details.first()) { "ls" -> { if (!currentDir.visited) { currentDir.visited = true details.drop(1).map { it.split(" ") }.forEach { (a, b) -> when (a) { "dir" -> { with(Directory(name = b, parent = currentDir)) { directories.add(this) currentDir.directories.add(this) } } else -> currentDir.files.add(File(name = b, size = a.toInt())) } } } } else -> { val (_, dirName) = command.split(" ") currentDir = when (dirName) { ".." -> currentDir.parent ?: currentDir else -> currentDir.directories.first { it.name == dirName } } } } } return directories.map { it.size } } fun part1(input: String) = directorySizes(input).filter { it <= 100000 }.sum() fun part2(input: String): Int { val sizes = directorySizes(input) val needed = 30000000 - (70000000 - sizes.maxOf { it }) return sizes.filter { it >= needed }.minOf { it } } val testInput = readInputText(name = "${day}_test", year = year) val input = readInputText(name = day, year = year) check(part1(testInput) == 95437) println(part1(input)) check(part2(testInput) == 24933642) println(part2(input)) } data class Directory( val name: String, val parent: Directory? = null, val directories: MutableList<Directory> = mutableListOf(), val files: MutableList<File> = mutableListOf(), var visited: Boolean = false ) { val size: Int get() = files.sumOf { it.size } + directories.sumOf { it.size } override fun toString() = "name=$name size=$size" } data class File(val name: String, val size: Int)
1
Kotlin
2
30
df1f04b90e81fbb9078a30f528d52295689f7de7
2,555
aoc-kotlin
Apache License 2.0
src/main/kotlin/day11.kt
bfrengley
318,716,410
false
null
package aoc2020.day11 import aoc2020.util.* enum class Seat { EMPTY, FLOOR, OCCUPIED; companion object { fun parse(chr: Char): Seat = when (chr) { '#' -> OCCUPIED '.' -> FLOOR 'L' -> EMPTY else -> throw IllegalArgumentException("Invalid value: $chr") // whatever } } } data class SeatState( val seats: List<List<Seat>>, val threshold: Int, val useExpandedSearch: Boolean ) { fun nextState() = seats.indices.map { x -> seats[x].indices.map { y -> when (val seat = seats[x][y]) { Seat.FLOOR -> seat else -> { val occupied = occupiedNeighbours(x, y) if (seat == Seat.EMPTY && occupied == 0) { Seat.OCCUPIED } else if (seat == Seat.OCCUPIED && occupied >= threshold) { Seat.EMPTY } else { seat } } } } }.let { SeatState(it, threshold, useExpandedSearch) } private fun occupiedNeighbours(x: Int, y: Int): Int = listOf( Pair(-1, -1), Pair(-1, 0), Pair(-1, 1), Pair(0, -1), Pair(0, 1), Pair(1, -1), Pair(1, 0), Pair(1, 1) ) .map { (xOff, yOff) -> if (useExpandedSearch) { val xs = generateSequence(x + xOff) { it + xOff } val ys = generateSequence(y + yOff) { it + yOff } xs.zip(ys) .map { (x_, y_) -> seats.getOrNull(x_)?.getOrNull(y_) } .firstOrNull { it != Seat.FLOOR } } else { seats.getOrNull(x + xOff)?.getOrNull(y + yOff) } }.count { it == Seat.OCCUPIED } fun runToSteadyState(): SeatState { var state = this while (true) { val next = state.nextState() if (next == state) { break } state = next } return state } } fun main(args: Array<String>) { val seats = loadTextResource("/day11.txt").lines().map { line -> line.map(Seat::parse) } print("Part 1: ") println( SeatState(seats, 4, false) .runToSteadyState() .seats .map { it.count { it == Seat.OCCUPIED } } .sum() ) print("Part 1: ") println( SeatState(seats, 5, true) .runToSteadyState() .seats .map { it.count { it == Seat.OCCUPIED } } .sum() ) }
0
Kotlin
0
0
088628f585dc3315e51e6a671a7e662d4cb81af6
2,805
aoc2020
ISC License
src/day18/Day18.kt
kerchen
573,125,453
false
{"Kotlin": 137233}
package day18 import readInput import java.lang.Math.abs data class Point(val x: Int, val y: Int, val z: Int) fun parseCubes(input: List<String>): List<Point> { var returnList = MutableList<Point>(0){ Point(0, 0, 0) } for (cube in input) { val components = cube.split(",") if (components.size == 3) { returnList.add( Point( components[0].trim().toInt(), components[1].trim().toInt(), components[2].trim().toInt() ) ) } } return returnList } fun areAdjacent(p1: Point, p2: Point): Boolean { if (p1 == p2) return false val dx = abs(p1.x - p2.x) if (dx > 1) return false val dy = abs(p1.y - p2.y) if (dy > 1) return false val dz = abs(p1.z - p2.z) if (dz > 1) return false if (dx + dy + dz > 1) return false return true } class AdjacencyMatrix(cubes: List<Point>) { var neighborMap: MutableMap<Point, MutableList<Point>> = mutableMapOf() init { for (i in IntRange(0, cubes.size - 1)) { for (j in IntRange(i+1, cubes.size - 1)) { if (areAdjacent(cubes[i], cubes[j])) { if (! neighborMap.containsKey(cubes[i])) { neighborMap[cubes[i]] = mutableListOf() } neighborMap[cubes[i]]?.add(cubes[j]) if (! neighborMap.containsKey(cubes[j])) { neighborMap[cubes[j]] = mutableListOf() } neighborMap[cubes[j]]?.add(cubes[i]) } } } } } fun computeSurfaceArea(cubes: List<Point>): Int { var surfaceArea = 0 val adjacencyMatrix = AdjacencyMatrix(cubes) for (c in cubes) { surfaceArea += 6 - (adjacencyMatrix.neighborMap[c]?.size ?: 0) } return surfaceArea } class Bounds(val minimum: Point, val maximum: Point) { fun inBounds(pt: Point): Boolean { return (pt.x in (minimum.x..maximum.x) && pt.y in (minimum.y..maximum.y) && pt.z in (minimum.z..maximum.z)) } } fun computeBounds(cubes: Set<Point>): Bounds { var minX = Int.MAX_VALUE var minY = Int.MAX_VALUE var minZ = Int.MAX_VALUE var maxX = Int.MIN_VALUE var maxY = Int.MIN_VALUE var maxZ = Int.MIN_VALUE for (cube in cubes) { minX = (cube.x - 1).coerceAtMost(minX) minY = (cube.y - 1).coerceAtMost(minY) minZ = (cube.z - 1).coerceAtMost(minZ) maxX = (cube.x + 1).coerceAtLeast(maxX) maxY = (cube.y + 1).coerceAtLeast(maxY) maxZ = (cube.z + 1).coerceAtLeast(maxZ) } return Bounds(Point(minX, minY, minZ), Point(maxX, maxY, maxZ)) } fun computeExteriorSurfaceArea(cubes: Set<Point>): Int { var surfaceArea = 0 val bounds = computeBounds(cubes) var cellsToVisit = mutableSetOf(bounds.minimum.copy()) var visitedCells = mutableSetOf<Point>() fun visit(cell: Point, cellsToVisit: MutableSet<Point>, visitedCells: MutableSet<Point>) { cellsToVisit.remove(cell) visitedCells.add(cell.copy()) val adjacentPoints = listOf(cell.copy(x=cell.x+1), cell.copy(x=cell.x-1), cell.copy(y=cell.y+1), cell.copy(y=cell.y-1), cell.copy(z=cell.z+1), cell.copy(z=cell.z-1)) for (pt in adjacentPoints) { if (bounds.inBounds(pt) && !visitedCells.contains(pt)) { if (cubes.contains(pt)) { surfaceArea += 1 } else { cellsToVisit.add(pt.copy()) } } } } while(!cellsToVisit.isEmpty()) { visit(cellsToVisit.last(), cellsToVisit, visitedCells) } return surfaceArea } fun main() { fun part1(input: List<String>): Int = computeSurfaceArea(parseCubes(input)) fun part2(input: List<String>): Int = computeExteriorSurfaceArea(parseCubes(input).toSet()) val testInput = readInput("Day18_test") check(part1(testInput) == 64) check(part2(testInput) == 58) val input = readInput("Day18") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
dc15640ff29ec5f9dceb4046adaf860af892c1a9
4,187
AdventOfCode2022
Apache License 2.0
src/Day05.kt
wooodenleg
572,658,318
false
{"Kotlin": 30668}
data class Instruction( val quantity: Int, val sourceStackId: Int, val targetStackId: Int ) fun String.asInstruction(): Instruction { val (quantity, source, target) = split(" ") .filter { text -> text.all(Char::isDigit) } .map(String::toInt) return Instruction(quantity, source, target) } class CrateStack( columnInput: String ) { private val crates = ArrayDeque<Char>() .apply { columnInput.trim().forEach(::add) } fun pop(): Char = crates.removeFirst() fun push(char: Char) = crates.addFirst(char) } fun initStacks(input: String): Map<Int, CrateStack> { val sanitizedColumns = input.columns() .filter { column -> // remove blank lines if '[' and ']' are considered blank characters column.replace(Regex("[\\[\\]]"), " ").isNotBlank() } return buildMap { sanitizedColumns.forEachIndexed { index, column -> val id = index + 1 val stackValues = column.dropLast(1) // drop last character (stack ID) set(id, CrateStack(stackValues)) } } } fun Map<Int, CrateStack>.applyCrateMover9000Instruction(instruction: Instruction) { val source = get(instruction.sourceStackId) ?: error("Stack with id ${instruction.sourceStackId} does not exist") val target = get(instruction.targetStackId) ?: error("Stack with id ${instruction.targetStackId} does not exist") repeat(instruction.quantity) { target.push(source.pop()) } } fun Map<Int, CrateStack>.applyCrateMover9001Instruction(instruction: Instruction) { val source = get(instruction.sourceStackId) ?: error("Stack with id ${instruction.sourceStackId} does not exist") val target = get(instruction.targetStackId) ?: error("Stack with id ${instruction.targetStackId} does not exist") val crates = buildString { repeat(instruction.quantity) { append(source.pop()) } }.reversed() crates.forEach(target::push) } fun main() { fun prepare(input: String): Pair<Map<Int, CrateStack>, List<Instruction>> { val (initialStateInput, instructionsInput) = input.lines() .let { lines -> val separatorIndex = lines.indexOfFirst(String::isBlank) lines.subList(0, separatorIndex) to lines.subList(separatorIndex + 1, lines.size) } val stacks = initStacks(initialStateInput.joinToString("\n")) val instructions = instructionsInput.map(String::asInstruction) return stacks to instructions } fun part1(input: String): String { val (stacks, instructions) = prepare(input) instructions.forEach(stacks::applyCrateMover9000Instruction) return buildString { for (stack in stacks.values) append(stack.pop()) } } fun part2(input: String): String { val (stacks, instructions) = prepare(input) instructions.forEach(stacks::applyCrateMover9001Instruction) return buildString { for (stack in stacks.values) append(stack.pop()) } } val testInput = readInput("Day05_test") check(part1(testInput) == "CMZ") check(part2(testInput) == "MCD") val input = readInput("Day05") println(part1(input)) println(part2(input)) }
0
Kotlin
0
1
ff1f3198f42d1880e067e97f884c66c515c8eb87
3,297
advent-of-code-2022
Apache License 2.0
y2021/src/main/kotlin/adventofcode/y2021/Day03.kt
Ruud-Wiegers
434,225,587
false
{"Kotlin": 503769}
package adventofcode.y2021 import adventofcode.io.AdventSolution object Day03 : AdventSolution(2021, 3, "Binary Diagnostic") { override fun solvePartOne(input: String): Int { val lines = input.lines() return lines[0].indices.map(lines::mostFrequentDigitAt) .joinToString("") .toInt(2) .let { it * (lines[0].replace('0', '1').toInt(2) xor it) } } override fun solvePartTwo(input: String): Int { val generator = findRating(input) { d, mostFrequent -> d == mostFrequent } val scrubber = findRating(input) { d, mostFrequent -> d != mostFrequent } return generator * scrubber } } private inline fun findRating(input: String, crossinline matchCriteria: (d: Char, mostFrequent: Char) -> Boolean) = generateSequence(0, Int::inc) .scan(input.lines()) { candidates, index -> val mfd = candidates.mostFrequentDigitAt(index) candidates.filter { candidate -> matchCriteria(candidate[index], mfd) } } .firstNotNullOf { it.singleOrNull() } .toInt(radix = 2) //verborgen shenanigans met het geval dat er evenveel nullen als enen zijn private fun List<String>.mostFrequentDigitAt(index: Int): Char = (if (count { it[index] == '1' } >= (size + 1) / 2) '1' else '0')
0
Kotlin
0
3
fc35e6d5feeabdc18c86aba428abcf23d880c450
1,309
advent-of-code
MIT License
src/Day15.kt
matusekma
572,617,724
false
{"Kotlin": 119912, "JavaScript": 2024}
import java.util.SortedSet import kotlin.math.abs class PositionLong(val x: Long, val y: Long) { val posKey: String get() = "${this.x},${this.y}" } fun PositionLong.getManhattanDistance(otherPos: PositionLong) = abs(this.x - otherPos.x) + abs(this.y - otherPos.y) class Day15 { val occupiedPositionLongsInRow = mutableSetOf<String>() val maxCoord = 4_000_000 fun part1(input: List<String>, row: Long): Long { for (line in input) { val (sensor, beacon) = parseLine(line) val distance = sensor.getManhattanDistance(beacon) val yDistanceFromRow = abs(sensor.y - row) if (yDistanceFromRow <= distance) { for (x in 0..distance - yDistanceFromRow) { occupiedPositionLongsInRow.add(PositionLong(sensor.x + x, row).posKey) occupiedPositionLongsInRow.add(PositionLong(sensor.x - x, row).posKey) } } occupiedPositionLongsInRow.remove(sensor.posKey) // remove sensor occupiedPositionLongsInRow.remove(beacon.posKey) // remove beacon } return occupiedPositionLongsInRow.size.toLong() } fun part2(input: List<String>): Long { val sensorsWithDistance = mutableMapOf<PositionLong, Long>() for (line in input) { val (sensor, beacon) = parseLine(line) val distance = sensor.getManhattanDistance(beacon) sensorsWithDistance[sensor] = distance } for ((sensor, distance) in sensorsWithDistance.entries) { val searchedDistance = distance + 1 // it must be in distance + 1 for (x in 0..searchedDistance) { val y = searchedDistance - x val positions = listOf( PositionLong(sensor.x + x, sensor.y + y), PositionLong(sensor.x - x, sensor.y + y), PositionLong(sensor.x + x, sensor.y - y), PositionLong(sensor.x - x, sensor.y - y) ) for (position in positions) { if(position.x !in 0..maxCoord || position.y !in 0..maxCoord) continue var foundPositionLong = true for ((otherSensor, otherDistance) in sensorsWithDistance.entries) { if (otherSensor.getManhattanDistance(position) <= otherDistance) { foundPositionLong = false; } } if (foundPositionLong) { println(position.x) println(position.y) return position.x * 4_000_000 + position.y } } } } return -1 } fun parseLine(line: String): List<PositionLong> { val destructuredRegex = "Sensor at x=(-?[0-9]+), y=(-?[0-9]+): closest beacon is at x=(-?[0-9]+), y=(-?[0-9]+)".toRegex() return destructuredRegex.matchEntire(line) ?.destructured ?.let { (sensorX, sensorY, beaconX, beaconY) -> listOf( PositionLong(sensorX.toLong(), sensorY.toLong()), PositionLong(beaconX.toLong(), beaconY.toLong()) ) } ?: throw IllegalArgumentException("Bad input '$line'") } } fun main() { val input = readInput("input15_1") // println(Day15().part1(input, 2000000)) println(Day15().part2(input)) }
0
Kotlin
0
0
744392a4d262112fe2d7819ffb6d5bde70b6d16a
3,546
advent-of-code
Apache License 2.0
src/day5/day5.kt
bienenjakob
573,125,960
false
{"Kotlin": 53763}
package day5 import inputTextOfDay fun parseInput(input: String): Pair<MutableList<MutableList<Char>>, List<List<Int>>> { return input.split("\r\n\r\n").let { (_, second) -> getStacks() to parseInstructions(second) } } fun getStacks(): MutableList<MutableList<Char>> { val s1 = listOf('N', 'R', 'J', 'T', 'Z', 'B', 'D', 'F') val s2 = listOf('H', 'J', 'N', 'S', 'R') val s3 = listOf('Q', 'F', 'Z', 'G', 'J', 'N', 'R', 'C') val s4 = listOf('Q', 'T', 'R', 'G', 'N', 'V', 'F') val s5 = listOf('F', 'Q', 'T', 'L') val s6 = listOf('N', 'G', 'R', 'B', 'Z', 'W', 'C', 'Q') val s7 = listOf('M', 'H', 'N', 'S', 'L', 'C', 'F') val s8 = listOf('J', 'T', 'M', 'Q', 'N', 'D') val s9 = listOf('S', 'G', 'P') return listOf(s1, s2, s3, s4, s5, s6, s7, s8, s9).map { it.reversed().toMutableList() }.toMutableList() } fun parseInstructions(second: String): List<List<Int>> { return second.lines().map { line -> line.split("move ", " from ", " to ").mapNotNull { it.toIntOrNull() } } } fun part1(text: String): String { val (stack, instructions) = parseInput(text) instructions.forEach { (amount, source, dest) -> repeat(amount) { stack[dest - 1].add(stack[source - 1].removeLast()) } } return stack.map { it.last() }.joinToString("") } fun part2(text: String): String { val (stack, instructions) = parseInput(text) instructions.forEach { (amount, source, dest) -> val lifted = mutableListOf<Char>() repeat(amount) { lifted.add(stack[source - 1].removeLast()) } repeat(amount) { stack[dest - 1].add(lifted.removeLast()) } } return stack.map { it.last() }.joinToString("") } fun main() { val day = 5 // val testInput = testTextOfDay(day) // check(part1(testInput) == 5) val input = inputTextOfDay(day) println(part1(input)) check(part1(input) == "QNNTGTPFN") println(part2(input)) check(part2(input) == "GGNPJBTTR") }
0
Kotlin
0
0
6ff34edab6f7b4b0630fb2760120725bed725daa
2,016
aoc-2022-in-kotlin
Apache License 2.0
src/Day14.kt
asm0dey
572,860,747
false
{"Kotlin": 61384}
import kotlin.math.max import kotlin.math.min fun main() { operator fun Pair<Int, Int>.rangeTo(other: Pair<Int, Int>): Set<Pair<Int, Int>> { val minX = min(first, other.first) val maxX = max(first, other.first) val minY = min(second, other.second) val maxY = max(second, other.second) return buildSet { for (i in minX..maxX) { for (j in minY..maxY) { add(i to j) } } } } fun Pair<Int, Int>.tryMove(occupied: HashSet<Pair<Int, Int>>): Pair<Int, Int> { val down = copy(second = second + 1) return if (!occupied.contains(down)) down else { val downLeft = copy(first = first - 1, second = second + 1) if (!occupied.contains(downLeft)) downLeft else { val downRight = copy(first = first + 1, second = second + 1) if (!occupied.contains(downRight)) downRight else this } } } fun List<String>.buildMap(): HashSet<Pair<Int, Int>> { return map { it.split(Regex(",| -> ")).chunked(2).map { (a, b) -> a.toInt() to b.toInt() } } .flatMap { it.windowed(2).flatMap { (a, b) -> a..b } } .toHashSet() } fun part1(input: List<String>): Int { val occupied = input.buildMap() val bottomLine = occupied.maxBy { it.second }.second var counter = 0 outer@ while (true) { counter++ var grain = 500 to 0 while (true) { val next = grain.tryMove(occupied) if (next == grain) { occupied.add(next) break } else if (next.second > bottomLine) { counter-- break@outer } else { grain = next } } } return counter } fun part2(input: List<String>): Int { val occupied = input.buildMap() val bottomLine = occupied.maxBy { it.second }.second var counter = 0 val start = 500 to 0 outer@ while (true) { counter++ var grain = start while (true) { val next = grain.tryMove(occupied) if (next == grain) { occupied.add(next) if (next == start) break@outer break } else if (next.second > bottomLine) { occupied.add(next) break } else { grain = next } } } return counter } val testInput = readInput("Day14_test") check(part1(testInput) == 24) val input = readInput("Day14") println(part1(input)) check(part2(testInput) == 93) println(part2(input)) }
1
Kotlin
0
1
f49aea1755c8b2d479d730d9653603421c355b60
2,942
aoc-2022
Apache License 2.0
src/Day07.kt
jimmymorales
572,156,554
false
{"Kotlin": 33914}
fun main() { fun parseDir(input: List<String>, node: TreeNode, currentIndex: Int = 1): Int { var index = currentIndex while (index < input.count()) { val parts = input[index].split(' ') val (op1, op2) = parts when { op1 == "$" && op2 == "ls" -> {} op1 == "$" && op2 == "cd" -> { val dir = parts[2] if (dir == "..") { return index } else { index = parseDir(input, node.getDir(dir), index + 1) } } op1 == "dir" -> node.addDir(op2) else -> node.addFile(op1.toInt()) } index++ } return index } fun flattenDir(node: TreeNode): List<TreeNode> = buildList { addAll(node.children) node.children.forEach { addAll(flattenDir(it)) } } fun part1(input: List<String>): Int { val root = TreeNode("/") parseDir(input, root, currentIndex = 1) return flattenDir(root) .map(TreeNode::calculateTotalSize) .filter { it <= 100_000 } .sum() } fun part2(input: List<String>): Int { val root = TreeNode("/") parseDir(input, root, currentIndex = 1) val totalUsedSpace = root.calculateTotalSize() val neededSpace = 30_000_000 - (70_000_000 - totalUsedSpace) return flattenDir(root) .map(TreeNode::calculateTotalSize) .sorted() .first { it > neededSpace } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day07_test") check(part1(testInput) == 95437) cache.clear() val input = readInput("Day07") println(part1(input)) // part 2 cache.clear() check(part2(testInput) == 24933642) cache.clear() println(part2(input)) } data class TreeNode(val value: String) { private val _children: MutableList<TreeNode> = mutableListOf() val children: List<TreeNode> get() = _children.toList() private var sizeOfFiles = 0 fun addFile(size: Int) { sizeOfFiles += size } fun addDir(name: String) { _children.add(TreeNode("$value/$name")) } fun getDir(name: String): TreeNode { return _children.first { it.value == "$value/$name" } } fun calculateTotalSize(): Int { if (value in cache) { return cache[value]!! } var totalSize = sizeOfFiles for (child in children) { totalSize += if (child.value in cache) cache[child.value]!! else child.calculateTotalSize() } cache[value] = totalSize return totalSize } } private val cache = mutableMapOf<String, Int>()
0
Kotlin
0
0
fb72806e163055c2a562702d10a19028cab43188
2,886
advent-of-code-2022
Apache License 2.0
src/main/kotlin/tr/emreone/adventofcode/days/Day12.kt
EmRe-One
568,569,073
false
{"Kotlin": 166986}
package tr.emreone.adventofcode.days import tr.emreone.kotlin_utils.math.Point2D object Day12 { class Area(private val width: Int, private val height: Int) { private val squares = Array<Array<Char>>(height) { Array(width) { ' ' } } lateinit var startPosition: Point2D lateinit var endPosition: Point2D fun parseSquares(rows: List<String>) { rows.forEachIndexed { y, row -> row.forEachIndexed { x, char -> when(char) { 'S' -> { this.squares[y][x] = 'a' startPosition = Point2D(x.toLong(), y.toLong()) } 'E' -> { this.squares[y][x] = 'z' endPosition = Point2D(x.toLong(), y.toLong()) } else -> { this.squares[y][x] = char } } } } } private fun getSignalStrengthAt(coord: Point2D): Char { return this.squares[coord.y.toInt()][coord.x.toInt()] } private fun getValidNeighbors(from: Point2D): List<Point2D> { val neighbors = mutableListOf<Point2D>() val (x, y) = from.x to from.y if ((x - 1) in 0 until this.width) neighbors.add(Point2D(x - 1, y)) if ((x + 1) in 0 until this.width) neighbors.add(Point2D(x + 1, y)) if ((y - 1) in 0 until this.height) neighbors.add(Point2D(x, y - 1)) if ((y + 1) in 0 until this.height) neighbors.add(Point2D(x, y + 1)) val currentSignalStrength = this.getSignalStrengthAt(from) return neighbors .filter { this.getSignalStrengthAt(it) <= currentSignalStrength + 1 } } fun findSignalStrength(signalStrength: Char): List<Point2D> { val result = mutableListOf<Point2D>() this.squares.forEachIndexed { y, row -> row.forEachIndexed { x, char -> if (char == signalStrength) { result.add(Point2D(x.toLong(), y.toLong())) } } } return result } fun bfs(start: Point2D, target: Point2D): Int { val queue = mutableListOf(start) val dist = queue .associateWith { 0 } .toMutableMap() while (queue.isNotEmpty()) { val currentSquare = queue.removeFirst() this.getValidNeighbors(currentSquare) .filter {neighbor -> !dist.contains(neighbor) } .forEach {neighbor -> dist[neighbor] = dist[currentSquare]!! + 1 queue.add(neighbor) } } return dist[target] ?: Int.MAX_VALUE } } fun part1(input: List<String>): Int { val area = Area(input.first().length, input.size) area.parseSquares(input) return area.bfs(area.startPosition, area.endPosition) } fun part2(input: List<String>): Int { val area = Area(input.first().length, input.size) area.parseSquares(input) return area.findSignalStrength('a').minOf { coord -> area.bfs(coord, area.endPosition) } } }
0
Kotlin
0
0
a951d2660145d3bf52db5cd6d6a07998dbfcb316
3,535
advent-of-code-2022
Apache License 2.0