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/g2901_3000/s2911_minimum_changes_to_make_k_semi_palindromes/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g2901_3000.s2911_minimum_changes_to_make_k_semi_palindromes
// #Hard #String #Dynamic_Programming #Two_Pointers
// #2023_12_27_Time_216_ms_(100.00%)_Space_37.2_MB_(100.00%)
import kotlin.math.min
class Solution {
private val divisors = getDivisors()
private lateinit var cs: CharArray
private lateinit var cost: Array<IntArray>
private lateinit var dp: Array<IntArray>
fun minimumChanges(s: String, k: Int): Int {
cs = s.toCharArray()
val n = cs.size
cost = Array(n - 1) { IntArray(n + 1) }
dp = Array(n + 1) { IntArray(k + 1) }
return calc(n, k) - k
}
private fun calc(i: Int, k: Int): Int {
if (k == 1) {
return change(0, i)
}
if (dp[i][k] > 0) {
return dp[i][k]
}
var min = INF
for (j in (k - 1) * 2 until (i - 1)) {
min = min(min.toDouble(), (calc(j, k - 1) + change(j, i)).toDouble()).toInt()
}
dp[i][k] = min
return min
}
private fun change(start: Int, end: Int): Int {
if (cost[start][end] > 0) {
return cost[start][end]
}
var min = INF
var divisor = divisors[end - start]
while (divisor != null) {
val d = divisor.value
var count = 0
for (i in 0 until d) {
var left = start + i
var right = end - d + i
while (left + d <= right) {
if (cs[left] != cs[right]) {
count++
}
left += d
right -= d
}
}
if (count < min) {
min = count
}
divisor = divisor.next
}
cost[start][end] = min + 1
return min + 1
}
private fun getDivisors(): Array<Divisor?> {
val list = arrayOfNulls<Divisor>(200 + 1)
for (d in 1..199) {
var len = d + d
while (len < 200 + 1) {
list[len] = Divisor(d, list[len])
len += d
}
}
return list
}
private class Divisor(var value: Int, var next: Divisor?)
companion object {
private const val INF = 200
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 2,297 | LeetCode-in-Kotlin | MIT License |
src/Day08_2.kt | rbraeunlich | 573,282,138 | false | {"Kotlin": 63724} | import kotlin.math.max
fun main() {
fun visilityInRow(columnIndex: Int, rowIndex: Int, row: IntArray): Int {
// check left side
val left = (columnIndex - 1) downTo 0
var leftScore = 0
for (leftIndex in left) {
if (row[leftIndex] < row[columnIndex]) {
leftScore++
} else {
leftScore++
break
}
}
val right = (columnIndex + 1)..(row.size - 1)
var rightScore = 0
for (rightIndex in right) {
if (row[rightIndex] < row[columnIndex]) {
rightScore++
} else {
rightScore++
break
}
}
return leftScore * rightScore
}
fun visibilityInColumn(columnIndex: Int, rowIndex: Int, treeGrid: Array<IntArray?>): Int {
// check top
val top = (rowIndex - 1) downTo 0
var topScore = 0
for (topIndex in top) {
if (treeGrid[topIndex]!![columnIndex] < treeGrid[rowIndex]!![columnIndex]) {
topScore++
} else {
topScore++
break
}
}
// check bottom
val bottom = (rowIndex + 1)..(treeGrid.size - 1)
var bottomScore = 0
for (bottomIndex in bottom) {
if (treeGrid[bottomIndex]!![columnIndex] < treeGrid[rowIndex]!![columnIndex]) {
bottomScore++
} else {
bottomScore++
break
}
}
return topScore * bottomScore
}
fun treeVisibility(columnIndex: Int, rowIndex: Int, tree: Int, rowSize: Int, treeGrid: Array<IntArray?>): Int {
val rowScore = visilityInRow(columnIndex, rowIndex, treeGrid[rowIndex]!!)
val columnScore = visibilityInColumn(
columnIndex,
rowIndex,
treeGrid
)
val result = rowScore * columnScore
return result
}
fun part2(input: List<String>): Int {
val treeGrid = arrayOfNulls<IntArray>(input.size)
input.forEachIndexed { index, row ->
val currentRow = row.map { it.toString().toInt() }.toIntArray()
treeGrid[index] = currentRow
}
var maxVisibility = 0
treeGrid.forEachIndexed { rowIndex, treeRow ->
treeRow!!.forEachIndexed { columnIndex, tree ->
val treeVisibility: Int = treeVisibility(columnIndex, rowIndex, tree, treeRow.size, treeGrid)
maxVisibility = max(maxVisibility, treeVisibility)
}
}
return maxVisibility
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day08_test")
println(part2(testInput))
check(part2(testInput) == 8)
// 2169 too high
val input = readInput("Day08")
println(part2(input))
}
| 0 | Kotlin | 0 | 1 | 3c7e46ddfb933281be34e58933b84870c6607acd | 2,913 | advent-of-code-2022 | Apache License 2.0 |
src/day03/Day03.kt | ignazio-castrogiovanni | 434,481,121 | false | {"Kotlin": 8657} | package day03
import readInput
import kotlin.math.roundToInt
fun main() {
val exampleInput = listOf(
"00100", "11110", "10110", "10111", "10101", "01111",
"00111", "11100", "10000", "11001", "00010", "01010")
val input = readInput("Day03_test", "day03")
println(part1(exampleInput))
println(part1(input))
println(part2(exampleInput))
println(part2(input))
}
fun part1(input: List<String>): Int {
// binary string length of 12
val binaryOnes = mutableListOf<Int>()
for (i in input[0].indices) {
binaryOnes.add(0)
}
var numberOfLines = 0
input.forEach {
numberOfLines++
for (i in it.indices) {
if (it[i] == '1') {
binaryOnes[i]++
}
}
}
var binaryGamma = ""
var binaryEpsilon = ""
for (i in binaryOnes.indices) {
val currentGamma = if (binaryOnes[i] > numberOfLines / 2) { "1" } else { "0" }
val currentEpsilon = if (binaryOnes[i] > numberOfLines / 2) { "0" } else { "1" }
binaryGamma += currentGamma
binaryEpsilon += currentEpsilon
}
val gamma = binaryGamma.toInt(2)
val epsilon = binaryEpsilon.toInt(2)
return gamma * epsilon
}
fun part2(input: List<String>): Int {
val oxygen = createBinaryString(input, true)
val co2 = createBinaryString(input, false)
val co2Value = co2[0].toInt(2)
val oxygenValue = oxygen[0].toInt(2)
return co2Value * oxygenValue
}
fun onlyOnes(it: String, currentCharacter: Int) = it[currentCharacter] == '1'
fun onlyZeros(it: String, currentCharacter: Int) = it[currentCharacter] == '0'
fun createBinaryString(list: List<String>, isOxygen: Boolean): List<String> {
var variableList = list.toList()
for (currentCharacter in variableList.indices) {
if (variableList.size == 1) {
break
}
var onesCounter = 0
variableList.forEach {
if (it[currentCharacter] == '1') {
onesCounter++
}
}
variableList = filterList(isOxygen, onesCounter, variableList, currentCharacter)
}
return variableList
}
private fun filterList(
isOxygen: Boolean,
onesCounter: Int,
variableList: List<String>,
currentCharacter: Int
) = if (isOxygen) {
if (onesCounter >= (variableList.size / 2.0).roundToInt()) {
variableList.filter { onlyOnes(it, currentCharacter) }
} else {
variableList.filter { onlyZeros(it, currentCharacter) }
}
} else {
if (onesCounter >= (variableList.size / 2.0).roundToInt()) {
variableList.filter { onlyZeros(it, currentCharacter) }
} else {
variableList.filter { onlyOnes(it, currentCharacter) }
}
} | 0 | Kotlin | 0 | 0 | 5ce48ba58da7ec5f5c8b05e4430a652710a0b4b9 | 2,745 | advent_of_code_kotlin | Apache License 2.0 |
src/day12/second/Solution.kt | verwoerd | 224,986,977 | false | null | package day12.second
import day12.first.applyGravity
import day12.first.readPlanetCoordinates
import tools.timeSolution
fun main() = timeSolution {
val scan = readPlanetCoordinates().map { it.first }
val xSteps = calculateLoop(scan.map { it.x })
val ySteps = calculateLoop(scan.map { it.y })
val zSteps = calculateLoop(scan.map { it.z })
println("Found orbits are repeating for scan x=$xSteps y=$ySteps z=$zSteps")
println(lcm(xSteps, lcm(ySteps, zSteps)))
}
fun calculateLoop(startLocation: List<Int>) =
generateSequence(Triple(0L, startLocation.toList(), listOf(0, 0, 0, 0))) { (steps, locations, velocity) ->
val nextVelocity = velocity.zip(locations.map { location ->
locations.map { applyGravity(location, it) }.sum()
}, Int::plus)
val nextLocations = locations.zip(nextVelocity, Int::plus)
Triple(steps + 1, nextLocations, nextVelocity)
}.drop(1).first { (_, locations, velocity) -> velocity.all { it == 0 } && locations == startLocation }.first
fun lcm(a: Long, b: Long) = (a * b) / gcd(a, b)
fun gcd(a: Long, b: Long): Long = when (b) {
0L -> a
else -> gcd(b, a % b)
}
| 0 | Kotlin | 0 | 0 | 554377cc4cf56cdb770ba0b49ddcf2c991d5d0b7 | 1,127 | AoC2019 | MIT License |
src/day4/Day04.kt | armanaaquib | 572,849,507 | false | {"Kotlin": 34114} | package day4
import readInput
fun main() {
fun parseInput(input: List<String>) =
input.map { pair -> pair.split(",").map { sections -> sections.split("-").map { it.toInt() } } }
fun isCover(range1: List<Int>, range2: List<Int>): Boolean {
return range2[0] >= range1[0] && range2[1] <= range1[1]
}
fun part1(input: List<String>): Int {
val data = parseInput(input)
var overlappingPairs = 0
for (pair in data) {
if(isCover(pair[0], pair[1]) || isCover(pair[1], pair[0])) {
overlappingPairs++
}
}
return overlappingPairs
}
fun isOverlap(range1: List<Int>, range2: List<Int>): Boolean {
return range2[0] >= range1[0] && range2[0] <= range1[1]
}
fun part2(input: List<String>): Int {
val data = parseInput(input)
var overlappingPairs = 0
for (pair in data) {
if(isOverlap(pair[0], pair[1]) || isOverlap(pair[1], pair[0])) {
overlappingPairs++
}
}
return overlappingPairs
}
// test if implementation meets criteria from the description, like:
check(part1(readInput("Day04_test")) == 2)
println(part1(readInput("Day04")))
check(part2(readInput("Day04_test")) == 4)
println(part2(readInput("Day04")))
}
| 0 | Kotlin | 0 | 0 | 47c41ceddacb17e28bdbb9449bfde5881fa851b7 | 1,350 | aoc-2022 | Apache License 2.0 |
src/Day05.kt | inssein | 573,116,957 | false | {"Kotlin": 47333} | fun main() {
fun Array<ArrayDeque<Char>>.topOfStack() = this.mapNotNull { it.firstOrNull() }.joinToString("")
fun move(command: String, list: Array<ArrayDeque<Char>>, oneAtATime: Boolean = true) {
// could use a regex like "move ([0-9]*) from ([0-9]*) to ([0-9]*)", but prefer split
val parts = command.split(" ")
val num = parts[1].toInt()
val from = parts[3].toInt()
val to = parts[5].toInt()
val items = (1..num).map { list[from - 1].removeFirst() }
list[to - 1].addAll(0, if (oneAtATime) items.reversed() else items)
}
fun buildStacks(input: List<String>, moveOneAtATime: Boolean = true): Array<ArrayDeque<Char>> {
// cheat, based on the input we know it's up to a max of 10 stacks, so we pre-create them
return input.fold(Array(10) { ArrayDeque() }) { stacks, line ->
if (line.startsWith("move")) {
// instruction
move(line, stacks, moveOneAtATime)
} else if (line.isEmpty() || line.startsWith(" 1")) {
// ignore empty line or line with stack numbers
} else {
// stack definition, grab all letters
for (i in 1..line.length step 4) {
val char = line[i]
if (char.isLetter()) {
stacks[i / 4].add(char)
}
}
}
stacks
}
}
fun part1(input: List<String>): String {
return buildStacks(input, true).topOfStack()
}
fun part2(input: List<String>): String {
return buildStacks(input, false).topOfStack()
}
val testInput = readInput("Day05_test")
check(part1(testInput) == "CMZ")
check(part2(testInput) == "MCD")
val input = readInput("Day05")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 095d8f8e06230ab713d9ffba4cd13b87469f5cd5 | 1,887 | advent-of-code-2022 | Apache License 2.0 |
src/aoc2023/Day13.kt | dayanruben | 433,250,590 | false | {"Kotlin": 79134} | package aoc2023
import checkValue
import readInputText
fun main() {
val (year, day) = "2023" to "Day13"
fun parseInput(input: String): List<Pair<List<Int>, List<Int>>> {
return input.split("\n\n").map { line ->
val pattern = line.split("\n")
fun List<Char>.toBinInt() = this.map { if (it == '#') '1' else '0' }.joinToString("").toInt(radix = 2)
val rows = pattern.first().indices.map { colIndex -> pattern.map { it[colIndex] }.toBinInt() }
val cols = pattern.map { row -> row.map { it }.toBinInt() }
rows to cols
}
}
fun countDiffBits(n1: Int, n2: Int) = (n1 xor n2).countOneBits()
fun List<Int>.reflectionIndex(hasFix: Boolean) = indices.filter { it != this.size - 1 }.firstOrNull { index ->
val interval = 0..minOf(index, this.size - 2 - index)
if (!hasFix) {
interval.all { this[index - it] == this[index + 1 + it] }
} else {
interval.sumOf { countDiffBits(this[index - it], this[index + 1 + it]) } == 1
}
} ?: -1
fun sumNotes(input: String, hasFix: Boolean) = parseInput(input).sumOf { (rows, cols) ->
maxOf(rows.reflectionIndex(hasFix) + 1, (cols.reflectionIndex(hasFix) + 1) * 100)
}
fun part1(input: String) = sumNotes(input, hasFix = false)
fun part2(input: String) = sumNotes(input, hasFix = true)
val testInput = readInputText(name = "${day}_test", year = year)
val input = readInputText(name = day, year = year)
checkValue(part1(testInput), 405)
println(part1(input))
checkValue(part2(testInput), 400)
println(part2(input))
} | 1 | Kotlin | 2 | 30 | df1f04b90e81fbb9078a30f528d52295689f7de7 | 1,651 | aoc-kotlin | Apache License 2.0 |
src/Day14.kt | ZiomaleQ | 573,349,910 | false | {"Kotlin": 49609} | import kotlin.math.min
fun main() {
fun part1(input: List<String>): Int {
val lines = input.flatMap {
it.split("->")
.map { segment ->
segment.trim().split(',').let { numbers -> Cords(numbers[0].toInt(), numbers[1].toInt()) }
}
.toMutableList().groupEvery()
}
val points = List(1000) { BooleanArray(500) { false } }
for (drawLine in lines) {
val start = drawLine[0]
val end = drawLine[1]
//Find same axis
when (start.axis(end)) {
Axis.EQ -> points[start.x][start.y] = true
Axis.X -> {
val x = start.x
val startingY = start.y
val endingY = end.y
val stepDown = min(startingY, endingY) == endingY
val range = if (stepDown) endingY..startingY else startingY..endingY
for (y in range) {
points[x][y] = true
}
}
Axis.Y -> {
val y = start.y
val startingX = start.x
val endingX = end.x
val stepDown = min(startingX, endingX) == endingX
val range = if (stepDown) endingX..startingX else startingX..endingX
for (x in range) {
points[x][y] = true
}
}
Axis.None -> println("Welp fuck")
}
}
return simulateSand(points)
}
fun part2(input: List<String>): Int {
val lines = input.flatMap {
it.split("->")
.map { segment ->
segment.trim().split(',').let { numbers -> Cords(numbers[0].toInt(), numbers[1].toInt()) }
}
.toMutableList().groupEvery()
}
val highestY = lines.flatten().maxOf { it.y } + 2
val points = List(1000) { BooleanArray(500) { it == highestY } }
for (drawLine in lines) {
val start = drawLine[0]
val end = drawLine[1]
//Find same axis
when (start.axis(end)) {
Axis.EQ -> points[start.x][start.y] = true
Axis.X -> {
val x = start.x
val startingY = start.y
val endingY = end.y
val stepDown = min(startingY, endingY) == endingY
val range = if (stepDown) endingY..startingY else startingY..endingY
for (y in range) {
points[x][y] = true
}
}
Axis.Y -> {
val y = start.y
val startingX = start.x
val endingX = end.x
val stepDown = min(startingX, endingX) == endingX
val range = if (stepDown) endingX..startingX else startingX..endingX
for (x in range) {
points[x][y] = true
}
}
Axis.None -> println("Welp fuck")
}
}
//Add one to include starting point
return simulateSand2(points) + 1
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day14_test")
part1(testInput).also { println(it); check(it == 24) }
part2(testInput).also { println(it);check(it == 93) }
val input = readInput("Day14")
println(part1(input))
println(part2(input))
}
private fun Cords.axis(other: Cords): Axis = when {
this.x == other.x && this.y == other.y -> Axis.EQ
this.x == other.x -> Axis.X
this.y == other.y -> Axis.Y
else -> Axis.None
}
private fun simulateSand(points: List<BooleanArray>): Int {
var count = 0
while (nextPosition(points) != null) {
// if (count % 5 == 0) {
//
// println(count)
//
// for (line in points.subList(496, 505)) {
// println(line.joinToString("") { if (it) "*" else " " })
// }
//
// println()
// }
count++
}
return count
}
private fun simulateSand2(points: List<BooleanArray>): Int {
var count = 0
while (nextPosition(points) != Cords(500, 0)) {
count++
}
return count
}
private fun nextPosition(points: List<BooleanArray>): Cords? {
var x = 500
var y = 0
while (true) {
try {
if (!points[x][y + 1]) {
y++
} else {
if (!points[x - 1][y + 1]) {
x--
y++
} else {
if (!points[x + 1][y + 1]) {
x++
y++
} else {
points[x][y] = true
return Cords(x, y)
}
}
}
} catch (err: IndexOutOfBoundsException) {
return null
}
}
} | 0 | Kotlin | 0 | 0 | b8811a6a9c03e80224e4655013879ac8a90e69b5 | 5,178 | aoc-2022 | Apache License 2.0 |
src/commonMain/kotlin/advent2020/day12/Day12Puzzle.kt | jakubgwozdz | 312,526,719 | false | null | package advent2020.day12
import advent2020.day12.Action.*
import kotlin.math.absoluteValue
enum class Action { N, S, E, W, L, R, F }
data class Command(val action: Action, val count: Int) {
constructor(s: String) : this(Action.valueOf(s.take(1)), s.drop(1).toInt())
}
internal fun parseAsSequence(input: String) =
input.trim().lineSequence().map(::Command)
data class Vector(val dx: Int, val dy: Int) {
operator fun plus(that: Vector) = Vector(dx + that.dx, dy + that.dy)
operator fun times(count: Int) = Vector(dx * count, dy * count)
operator fun unaryMinus() = Vector(-dx, -dy)
fun rotateLeft(count: Int) = when (count % 360) {
0 -> this
90 -> Vector(-dy, dx)
180 -> -this
270 -> Vector(dy, -dx)
else -> error("can't rotate $count")
}
fun rotateRight(count: Int) = when (count % 360) {
0 -> this
90 -> Vector(dy, -dx)
180 -> -this
270 -> Vector(-dy, dx)
else -> error("can't rotate $count")
}
}
data class Position(val x: Int, val y: Int) {
operator fun plus(v: Vector) = Position(x + v.dx, y + v.dy)
val manhattan get() = x.absoluteValue + y.absoluteValue
}
fun direction(action: Action) = when (action) {
N -> Vector(0, 1)
S -> Vector(0, -1)
E -> Vector(1, 0)
W -> Vector(-1, 0)
else -> error("`$action` is not a direction")
}
data class State(val position: Position, val waypoint: Vector)
fun State.part1Command(command: Command) = when (command.action) {
N, S, E, W -> copy(position = position + direction(command.action) * command.count)
L -> copy(waypoint = waypoint.rotateLeft(command.count))
R -> copy(waypoint = waypoint.rotateRight(command.count))
F -> copy(position = position + waypoint * command.count)
}
fun part1(input: String): String {
val commands = parseAsSequence(input)
val start = State(Position(0, 0), Vector(1, 0))
val end = commands.fold(start, State::part1Command)
val manhattan = end.position.manhattan
return manhattan.toString()
}
fun State.part2Command(command: Command) = when (command.action) {
N, S, E, W -> copy(waypoint = waypoint + direction(command.action) * command.count)
L -> copy(waypoint = waypoint.rotateLeft(command.count))
R -> copy(waypoint = waypoint.rotateRight(command.count))
F -> copy(position = position + waypoint * command.count)
}
fun part2(input: String): String {
val commands = parseAsSequence(input)
val start = State(Position(0, 0), Vector(10, 1))
val end = commands.fold(start, State::part2Command)
val manhattan = end.position.manhattan
return manhattan.toString()
}
| 0 | Kotlin | 0 | 2 | e233824109515fc4a667ad03e32de630d936838e | 2,665 | advent-of-code-2020 | MIT License |
src/Day14.kt | andrikeev | 574,393,673 | false | {"Kotlin": 70541, "Python": 18310, "HTML": 5558} | fun main() {
fun part1(input: List<String>): Int {
val grid = RocksGrid.parse(input)
var counter = 0
while (grid.addSandUnit()) {
counter++
}
return counter
}
fun part2(input: List<String>): Int {
val grid = RocksGrid.parse(input)
var counter = 0
while (grid.addSandUnit2()) {
counter++
}
return counter
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day14_test")
check(part1(testInput).also { println("part1 test: $it") } == 24)
check(part2(testInput).also { println("part2 test: $it") } == 93)
val input = readInput("Day14")
println(part1(input))
println(part2(input))
}
private class RocksGrid(
val blocked: MutableSet<Pair<Int, Int>>,
private val floorLevel: Int,
) {
fun addSandUnit(): Boolean {
var pos = Pair(500, 0)
fun hasBottom(): Boolean = blocked.any { it -> it.first == pos.first && it.second > pos.second }
fun canFall(): Boolean {
return !blocked.contains(Pair(pos.first, pos.second + 1)) ||
!blocked.contains(Pair(pos.first - 1, pos.second + 1)) ||
!blocked.contains(Pair(pos.first + 1, pos.second + 1))
}
while (canFall()) {
if (!hasBottom()) return false
val newPos = when {
!blocked.contains(Pair(pos.first, pos.second + 1)) -> Pair(pos.first, pos.second + 1)
!blocked.contains(Pair(pos.first - 1, pos.second + 1)) -> Pair(pos.first - 1, pos.second + 1)
!blocked.contains(Pair(pos.first + 1, pos.second + 1)) -> Pair(pos.first + 1, pos.second + 1)
else -> error("not possible")
}
pos = newPos
}
blocked.add(pos)
return true
}
fun addSandUnit2(): Boolean {
var pos = Pair(500, 0)
fun canFall(): Boolean {
return (pos.second < floorLevel - 1) &&
(!blocked.contains(Pair(pos.first, pos.second + 1)) ||
!blocked.contains(Pair(pos.first - 1, pos.second + 1)) ||
!blocked.contains(Pair(pos.first + 1, pos.second + 1)))
}
if (blocked.contains(pos)) {
return false
}
while (canFall()) {
val newPos = when {
!blocked.contains(Pair(pos.first, pos.second + 1)) -> Pair(pos.first, pos.second + 1)
!blocked.contains(Pair(pos.first - 1, pos.second + 1)) -> Pair(pos.first - 1, pos.second + 1)
!blocked.contains(Pair(pos.first + 1, pos.second + 1)) -> Pair(pos.first + 1, pos.second + 1)
else -> error("not possible")
}
pos = newPos
}
blocked.add(pos)
return true
}
companion object {
fun parse(input: List<String>): RocksGrid {
val rocks = mutableSetOf<Pair<Int, Int>>()
var floorLevel = 0
input.forEach { line ->
val points = line
.split(" -> ")
.map { it.split(",").map(String::toInt).let { (x, y) -> Pair(x, y) } }
for (i in 1..points.lastIndex) {
val start = points[i - 1]
val end = points[i]
for (x in minOf(start.first, end.first)..maxOf(start.first, end.first)) {
for (y in minOf(start.second, end.second)..maxOf(start.second, end.second)) {
rocks.add(Pair(x, y))
}
}
val maxLevel = maxOf(start.second, end.second) + 2
if (maxLevel > floorLevel) {
floorLevel = maxLevel
}
}
}
return RocksGrid(rocks, floorLevel)
}
}
}
| 0 | Kotlin | 0 | 1 | 1aedc6c61407a28e0abcad86e2fdfe0b41add139 | 3,973 | aoc-2022 | Apache License 2.0 |
problems/2020adventofcode11b/submissions/accepted/Stefan.kt | stoman | 47,287,900 | false | {"C": 169266, "C++": 142801, "Kotlin": 115106, "Python": 76047, "Java": 68331, "Go": 46428, "TeX": 27545, "Shell": 3428, "Starlark": 2165, "Makefile": 1582, "SWIG": 722} | import java.util.*
enum class Seat { EMPTY, OCCUPIED, FLOOR }
data class WaitingArea(val seats: List<List<Seat>>) {
private val neighbors =
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))
fun people(): Int = seats.sumOf { it.count { cell -> cell == Seat.OCCUPIED } }
fun next(): WaitingArea {
val r = List(seats.size) { MutableList(seats[0].size) {Seat.FLOOR} }
for (i in seats.indices) {
for (j in seats[i].indices) {
var peopleAround = 0
for (n in neighbors) {
var x = i + n.first
var y = j + n.second
while (x in seats.indices && y in seats[x].indices && seats[x][y] == Seat.FLOOR) {
x += n.first
y += n.second
}
if (x in seats.indices && y in seats[x].indices && seats[x][y] == Seat.OCCUPIED) {
peopleAround++
}
}
r[i][j] = when {
seats[i][j] == Seat.EMPTY && peopleAround == 0 -> Seat.OCCUPIED
seats[i][j] == Seat.OCCUPIED && peopleAround >= 5 -> Seat.EMPTY
else -> seats[i][j]
}
}
}
return WaitingArea(r)
}
}
fun main() {
val s = Scanner(System.`in`)
val input = mutableListOf<List<Seat>>()
while (s.hasNext()) {
input.add(s.next().map { if (it == 'L') Seat.EMPTY else Seat.FLOOR })
}
var wait = WaitingArea(input)
var last: WaitingArea
do {
last = wait
wait = wait.next()
} while (last != wait)
println(wait.people())
}
| 0 | C | 1 | 3 | ee214c95c1dc1d5e9510052ae425d2b19bf8e2d9 | 1,528 | CompetitiveProgramming | MIT License |
src/questions/FirstBadVersion.kt | realpacific | 234,499,820 | false | null | package questions
import _utils.UseCommentAsDocumentation
import utils.shouldBe
abstract class VersionControl(open val badVersion: Int) {
fun isBadVersion(version: Int): Boolean {
return version >= badVersion
}
abstract fun firstBadVersion(n: Int): Int
}
/**
* Suppose you have n versions [1, 2, ..., n] and you want to find out the first bad one,
* which causes all the following ones to be bad.
*
* You are given an API bool isBadVersion(version) which returns whether version is bad.
* Implement a function to find the first bad version. You should minimize the number of calls to the API.
*
*
* Constraint `1 <= bad <= n <= 2^31 - 1`
*
* [Source](https://leetcode.com/problems/first-bad-version/)
*/
@UseCommentAsDocumentation
class Solution(override val badVersion: Int) : VersionControl(badVersion) {
override fun firstBadVersion(n: Int): Int {
// This is basically a binary search problem
return binarySearch(0, n)
}
private fun binarySearch(low: Int, high: Int): Int {
if (high < low) {
return -1
}
// HERE: high can go as far as (2^31 - 1) so need to use Long to accommodate
val mid = ((low.toLong() + high.toLong()) / 2).toInt()
val midElement = mid + 1
return if (isBadVersion(midElement)) {
if (mid == 0 || (mid > 0 && !isBadVersion(midElement - 1))) { // also check for previous element
// if previous element is not a bad version, then this is for sure the bad version
mid + 1
} else {
// previous element was not bad version so continue checking
binarySearch(low, mid - 1)
}
} else {
binarySearch(mid + 1, high)
}
}
}
fun main() {
run {
Solution(badVersion = 1702766719).firstBadVersion(n = 2126753390) shouldBe 1702766719
}
run {
Solution(badVersion = 4).firstBadVersion(n = 5) shouldBe 4
}
}
| 4 | Kotlin | 5 | 93 | 22eef528ef1bea9b9831178b64ff2f5b1f61a51f | 2,002 | algorithms | MIT License |
src/Day03.kt | Jenner-Zhl | 576,294,907 | false | {"Kotlin": 8369} | fun main() {
fun findCommonTypes(s: String): Set<Char> {
val res = HashSet<Char>()
val size = s.length
val compartmentSize = size / 2
val firstSet = HashSet<Char>(compartmentSize)
for (i in 0 until compartmentSize) {
val c = s[i]
firstSet.add(c)
}
for (i in compartmentSize until size) {
val c = s[i]
if (firstSet.contains(c)) {
res.add(c)
}
}
return res
}
fun scoreOf(type: Char): Int {
val res = if (type.isUpperCase()) {
type - 'A' + 27
} else {
type - 'a' + 1
}
println("$type : $res")
return res
}
fun part1(input: List<String>): Int {
var totalScore = 0
input.forEach {
println(it)
findCommonTypes(it).forEach {type ->
totalScore += scoreOf(type)
}
}
return totalScore
}
fun findCommonType(s: String, s1: String, s2: String): Char {
val firstSet = hashSetOf<Char>()
s.forEach {
firstSet.add(it)
}
firstSet.forEach {
if (s1.contains(it) && s2.contains(it)) {
return it
}
}
throw IllegalArgumentException()
}
fun part2(input: List<String>): Int {
var totalScore = 0
for (i in 0 until input.size / 3) {
val j = i * 3
val type = findCommonType(input[j], input[j + 1], input[j + 2])
totalScore += scoreOf(type)
}
return totalScore
}
// 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 | 0 | 5940b844155069e020d1859bb2d3fb06cb820981 | 1,924 | aoc | Apache License 2.0 |
year2023/src/cz/veleto/aoc/year2023/Day18.kt | haluzpav | 573,073,312 | false | {"Kotlin": 164348} | package cz.veleto.aoc.year2023
import cz.veleto.aoc.core.AocDay
import cz.veleto.aoc.core.Pos
import cz.veleto.aoc.core.plus
class Day18(config: Config) : AocDay(config) {
override fun part1(): String {
val startState = State()
val endState = input
.map { line ->
val (rawDirection, rawStepCount, _) = line.split(' ')
val direction = when (rawDirection.single()) {
'U' -> Direction.Up
'R' -> Direction.Right
'D' -> Direction.Down
'L' -> Direction.Left
else -> error("unknown direction $rawDirection")
}
direction to rawStepCount.toInt()
}
.fold(startState) { directionState, (direction, stepCount) ->
(0..<stepCount).fold(directionState) { repeatState, _ ->
val newPos = repeatState.pos + direction
check(repeatState.pos !in repeatState.directions)
State(newPos, repeatState.directions + (repeatState.pos to direction))
}
}
check(endState.pos == startState.pos)
val lines = endState.directions.entries
.groupBy { (pos, _) -> pos.first }
.values
.map { posDirections ->
posDirections
.sortedBy { (pos, _) -> pos.second }
.associate { (pos, direction) -> pos.second to direction }
}
val lineCounts = lines
.map { posDirections ->
(posDirections.keys.first()..posDirections.keys.last())
.fold(State2()) { state, columnIndex ->
val direction = posDirections[columnIndex]
when {
!state.counting && direction != null -> state.copy(
counting = true, startDirection = direction, counted = state.counted + 1,
)
state.counting -> when (direction) {
Direction.Up -> {
lines[]
}
null -> state.copy(counted = state.counted + 1)
else -> error("unknown direction $direction")
}
else -> state
}
}
.counted
}
return lineCounts
.sum()
.toString()
}
override fun part2(): String {
// TODO
return ""
}
object Direction {
val Up = -1 to 0
val Right = 0 to 1
val Down = 1 to 0
val Left = 0 to -1
}
data class State(
val pos: Pos = 0 to 0,
val directions: Map<Pos, Pos> = emptyMap(),
)
data class State2(
val counting: Boolean = false,
val startDirection: Pos? = null,
val counted: Int = 0,
)
}
| 0 | Kotlin | 0 | 1 | 32003edb726f7736f881edc263a85a404be6a5f0 | 3,095 | advent-of-pavel | Apache License 2.0 |
src/main/kotlin/dev/paulshields/aoc/Day7.kt | Pkshields | 433,609,825 | false | {"Kotlin": 133840} | /**
* Day 7: The Treachery of Whales
*/
package dev.paulshields.aoc
import dev.paulshields.aoc.common.readFileAsString
import kotlin.math.abs
fun main() {
println(" ** Day 7: The Treachery of Whales ** \n")
val crabPositions = readFileAsString("/Day7CrabPositions.txt").split(",").mapNotNull { it.toIntOrNull() }
val naiveFuelUsed = naivelyCalculateFuelUsageToAlignCrabs(crabPositions)
println("Naively, the crabs would have to use a combined total of $naiveFuelUsed fuel to line up.")
val actualFuelUsed = correctlyCalculateFuelUsageToAlignCrabs(crabPositions)
println("The crabs would actually have to use a combined total of $actualFuelUsed fuel to line up.")
}
fun naivelyCalculateFuelUsageToAlignCrabs(crabPositions: List<Int>): Int {
val medianPosition = crabPositions.sorted()[crabPositions.size / 2]
return crabPositions.sumOf { abs(it - medianPosition) }
}
fun correctlyCalculateFuelUsageToAlignCrabs(crabPositions: List<Int>): Int {
val lastPossiblePosition = crabPositions.sorted().maxOrNull() ?: 0
return (0 until lastPossiblePosition).map { possiblePosition ->
crabPositions.sumOf {
val distanceToTravel = abs(it - possiblePosition)
sumNumbersUpTo(distanceToTravel)
}
}.sorted().minOrNull() ?: 0
}
private fun sumNumbersUpTo(number: Int) = (number * (number + 1)) / 2
| 0 | Kotlin | 0 | 0 | e3533f62e164ad72ec18248487fe9e44ab3cbfc2 | 1,377 | AdventOfCode2021 | MIT License |
2022/src/day13/day13.kt | Bridouille | 433,940,923 | false | {"Kotlin": 171124, "Go": 37047} | package day13
import GREEN
import RESET
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.jsonArray
import printTimeMillis
import readInput
enum class Result { RIGHT, WRONG, PROCEED }
fun rightOrWrong(leftStr: String, rightStr: String): Result {
val left = Json.parseToJsonElement(leftStr).jsonArray.toList()
val right = Json.parseToJsonElement(rightStr).jsonArray.toList()
val ileft = left.iterator()
val iright = right.iterator()
while (ileft.hasNext() && iright.hasNext()) {
val l = ileft.next()
val r = iright.next()
val lDigit = l.toString().toIntOrNull()
val rDigit = r.toString().toIntOrNull()
val ret = when {
lDigit != null && rDigit != null -> when { // both are valid digits
lDigit > rDigit -> Result.WRONG
lDigit < rDigit -> Result.RIGHT
else -> Result.PROCEED
}
lDigit != null -> rightOrWrong("[$lDigit]", r.toString())
rDigit != null -> rightOrWrong(l.toString(), "[$rDigit]")
else -> rightOrWrong(l.toString(), r.toString()) // both are lists
}
if (ret != Result.PROCEED) return ret
}
return when {
!ileft.hasNext() && !iright.hasNext() -> Result.PROCEED // Both ran out of items, Proceed
!ileft.hasNext() && iright.hasNext() -> Result.RIGHT // Left ran out of items, Correct order
else -> Result.WRONG // Right ran out of items, Wrong order
}
}
fun part1(input: List<String>) = input.windowed(2, 2) {
when (rightOrWrong(it[0], it[1])) {
Result.RIGHT -> input.indexOf(it[0]) / 2 + 1
Result.WRONG -> 0
else -> throw IllegalStateException("Oh no :(")
}
}.sum()
fun part2(input: List<String>) = input.sortedWith { o1, o2 ->
when (rightOrWrong(o1, o2)) {
Result.RIGHT -> -1
Result.WRONG -> 1
else -> throw IllegalStateException("Oh no :(")
}
}.let { (it.indexOf("[[2]]") + 1) * (it.indexOf("[[6]]") + 1) }
fun main() {
val testInput = readInput("day13_example.txt")
printTimeMillis { print("part1 example = $GREEN" + part1(testInput) + RESET) }
printTimeMillis { print("part2 example = $GREEN" + part2(testInput) + RESET) }
val input = readInput("day13.txt") // 5675
printTimeMillis { print("part1 input = $GREEN" + part1(input) + RESET) }
printTimeMillis { print("part2 input = $GREEN" + part2(input) + RESET) }
}
| 0 | Kotlin | 0 | 2 | 8ccdcce24cecca6e1d90c500423607d411c9fee2 | 2,468 | advent-of-code | Apache License 2.0 |
src/main/kotlin/solutions/day17/Day17.kt | Dr-Horv | 570,666,285 | false | {"Kotlin": 115643} | package solutions.day17
import solutions.Solver
import utils.Coordinate
import utils.Direction
import utils.plus
import utils.step
import kotlin.math.abs
data class Rock(val position: Coordinate, val parts: List<Coordinate>) {
fun partsAbsolutePositions(): List<Coordinate> = parts.map { position.plus(it) }
}
val FIRST_SHAPE = listOf(
Coordinate(0, 0), Coordinate(1, 0), Coordinate(2, 0), Coordinate(3, 0)
)
val SECOND_SHAPE = listOf(
Coordinate(1, 0),
Coordinate(0, 1), Coordinate(1, 1), Coordinate(2, 1),
Coordinate(1, 2)
)
val THIRD_SHAPE = listOf(
Coordinate(2, 0),
Coordinate(2, 1),
Coordinate(0, 2),
Coordinate(1, 2),
Coordinate(2, 2),
)
val FOURTH_SHAPE = listOf(
Coordinate(0, 0),
Coordinate(0, 1),
Coordinate(0, 2),
Coordinate(0, 3),
)
val FIFTH_SHAPE = listOf(
Coordinate(0, 0), Coordinate(1, 0),
Coordinate(0, 1), Coordinate(1, 1),
)
data class CircularList<T>(val list: List<T>) {
private var index = 0
fun next(): T = list[(index++) % list.size]
}
enum class RoomTile {
ROCK,
EMPTY
}
fun RoomTile.toPrint(): String = when (this) {
RoomTile.ROCK -> "#"
RoomTile.EMPTY -> "."
}
class Day17 : Solver {
override fun solve(input: List<String>, partTwo: Boolean): String {
val shapes = CircularList(listOf(FIRST_SHAPE, SECOND_SHAPE, THIRD_SHAPE, FOURTH_SHAPE, FIFTH_SHAPE))
val jetstream = CircularList(input.first().map {
when (it) {
'<' -> Direction.LEFT
'>' -> Direction.RIGHT
else -> throw Error("Unexpected Stream char: '$it'")
}
})
var highestRockInRoom = 0
val room = mutableMapOf<Coordinate, RoomTile>().withDefault { coordinate ->
when {
coordinate.x < 0 || coordinate.x >= 7 -> RoomTile.ROCK
else -> RoomTile.EMPTY
}
}
for (x in 0 until 7) {
room[Coordinate(x, 0)] = RoomTile.ROCK
}
val rocksToSimulate = if (!partTwo) {
2022
} else {
1000000000000
}
val diffs = mutableListOf<Int>()
for (r in 1..6_850) {
val shape = shapes.next()
var fallingRock = Rock(Coordinate(2, highestRockInRoom - 4 - shape.maxOf { it.y }), shape)
while (true) {
fallingRock = jetstreamPush(fallingRock, jetstream, room)
val beforePos = fallingRock.position
fallingRock = fall(fallingRock, room)
if (beforePos == fallingRock.position) {
fallingRock.partsAbsolutePositions().forEach { room[it] = RoomTile.ROCK }
val oldHighest = highestRockInRoom
highestRockInRoom = room.keys.minOf { it.y }
val diff = abs(highestRockInRoom - oldHighest)
diffs += diff
break
}
}
}
val cycle = findCycle(diffs)!!
val diffsBeforeFirstCycle = diffs.slice(IntRange(0, cycle.first - 1))
val heightBeforeFirstCycle = diffsBeforeFirstCycle.sum()
val rocksLeft = rocksToSimulate - diffsBeforeFirstCycle.size
val cycleHeight = diffs.slice(cycle).sum()
val completeCycles = rocksLeft / cycle.count()
val rocksLeftAfterCompleteCycles = rocksLeft % cycle.count()
val rest = diffs.slice(IntRange(cycle.first, cycle.first + rocksLeftAfterCompleteCycles.toInt() - 1)).sum()
val totalHeight = heightBeforeFirstCycle + (cycleHeight * completeCycles) + rest
return totalHeight.toString()
}
fun findCycle(diffs: List<Int>): IntRange? {
val startPoint = diffs.size / 2
for (size in 1 until diffs.size / 4) {
val rangeToCheck = (0 until size).map { Pair(it, it + size) }
if (rangeToCheck.all { diffs[startPoint + it.first] == diffs[startPoint + it.second] }) {
val foundSize = rangeToCheck.size
for (i in diffs.indices) {
val rangeToCheckAgain = (0 until foundSize).map { Pair(it, it + foundSize) }
if (rangeToCheckAgain.all { diffs[i + it.first] == diffs[i + it.second] }) {
return IntRange(i, i + foundSize - 1)
}
}
}
}
return null
}
private fun printRoom(rock: Rock, room: Map<Coordinate, RoomTile>) {
val currMap = room.toMutableMap().withDefault { coordinate ->
when {
coordinate.x < 0 || coordinate.x >= 7 -> RoomTile.ROCK
else -> RoomTile.EMPTY
}
}
rock.partsAbsolutePositions().forEach { currMap[it] = RoomTile.ROCK }
val falling = rock.partsAbsolutePositions().toSet()
val minY = currMap.keys.minOf { it.y }
val maxY = currMap.keys.maxOf { it.y }
var s = ""
for (y in minY until maxY) {
for (x in -1..7) {
s += if (x == -1 || x == 7) {
"|"
} else if (falling.contains(Coordinate(x, y))) {
"@"
} else {
currMap.getValue(Coordinate(x, y)).toPrint()
}
}
s += "\n"
}
s += "+-------+\n"
println(s)
}
private fun fall(fallingRock: Rock, room: Map<Coordinate, RoomTile>): Rock {
val nextState = fallingRock.copy(position = fallingRock.position.plus(Coordinate(0, 1)))
return if (nextState.partsAbsolutePositions().all { room.getValue(it) == RoomTile.EMPTY }) {
nextState
} else {
fallingRock
}
}
private fun jetstreamPush(
fallingRock: Rock,
jetstream: CircularList<Direction>,
room: Map<Coordinate, RoomTile>
): Rock {
val d = jetstream.next()
val nextState = fallingRock.copy(position = fallingRock.position.step(d))
return if (nextState.partsAbsolutePositions().all { room.getValue(it) == RoomTile.EMPTY }) {
nextState
} else {
fallingRock
}
}
}
| 0 | Kotlin | 0 | 2 | 6c9b24de2fe2a36346cb4c311c7a5e80bf505f9e | 6,221 | Advent-of-Code-2022 | MIT License |
src/main/kotlin/com/colinodell/advent2023/Day13.kt | colinodell | 726,073,391 | false | {"Kotlin": 114923} | package com.colinodell.advent2023
class Day13(input: String) {
private val patterns = input.split("\n\n").map { it.split("\n") }
private fun findHorizontalLineOfSymmetry(lines: List<String>, desiredCharDifference: Int = 0) = lines
.indices
.drop(1)
.firstOrNull { calculateSymmetry(lines, it) == desiredCharDifference }
.default(0)
// We can just rotate the text 90 degrees and use the same logic as above
private fun findVerticalLineOfSymmetry(lines: List<String>, desiredCharDifference: Int = 0) = findHorizontalLineOfSymmetry(rotate(lines), desiredCharDifference)
// Rotates the text 90 degrees
private fun rotate(lines: List<String>): List<String> {
val lineLength = lines[0].length
val rotated = StringBuilder()
for (i in 0 until lineLength) {
for (j in lines.indices.reversed()) {
rotated.append(lines[j][i])
}
rotated.append("\n")
}
return rotated.toString().trim().split("\n")
}
// Calculates how many characters are different between the two halves
private fun calculateSymmetry(lines: List<String>, pos: Int) = mirror(lines, pos)
// Zip the two halves together, ignoring the longer part
.let { (top, bottom) -> top.zip(bottom) }
// Sum the number of...
.sumOf { (a, b) ->
// Differing characters on each comparison line
a.zip(b).count { (c1, c2) -> c1 != c2 }
}
// Splits the text into two halves, mirroring one side
private fun mirror(lines: List<String>, across: Int) = lines.subList(0, across).reversed() to lines.subList(across, lines.size)
private fun summarizeReflectionLines(desiredCharDifference: Int = 0) = patterns.sumOf { p -> findVerticalLineOfSymmetry(p, desiredCharDifference) + 100 * findHorizontalLineOfSymmetry(p, desiredCharDifference) }
fun solvePart1() = summarizeReflectionLines()
fun solvePart2() = summarizeReflectionLines(desiredCharDifference = 1)
}
| 0 | Kotlin | 0 | 0 | 97e36330a24b30ef750b16f3887d30c92f3a0e83 | 2,037 | advent-2023 | MIT License |
src/main/kotlin/day13.kt | Gitvert | 433,947,508 | false | {"Kotlin": 82286} | fun day13() {
val lines: List<String> = readFile("day13.txt")
day13part1(lines)
day13part2(lines)
}
fun day13part1(lines: List<String>) {
var paper = getPaper(lines)
val foldInstructions = getFoldInstructions(lines)
paper = fold(paper, foldInstructions[0])
val answer = paper.map { row -> row.filter { it == '#' } }.flatten().size
println("13a: $answer")
}
fun day13part2(lines: List<String>) {
var paper = getPaper(lines)
val foldInstructions = getFoldInstructions(lines)
foldInstructions.forEach {
paper = fold(paper, it)
}
println("13b:")
printPaper(paper)
}
fun printPaper(paper: Array<CharArray>) {
paper.forEach { row ->
println(row.map { it.toString() }.reduce { acc, c -> acc+ c})
}
}
fun fold(paper: Array<CharArray>, foldInstruction: Pair<Char, Int>): Array<CharArray> {
return if (foldInstruction.first == 'y') {
for (x in paper.indices) {
for (y in 0 until paper[0].size) {
if (x > foldInstruction.second && paper[x][y] == '#') {
paper[kotlin.math.abs(paper.size - 1 - x)][y] = '#'
}
}
}
paper.slice(0 until foldInstruction.second).toTypedArray()
} else {
for (x in paper.indices) {
for (y in 0 until paper[0].size) {
if (y > foldInstruction.second && paper[x][y] == '#') {
paper[x][kotlin.math.abs(paper[0].size -1 - y)] = '#'
}
}
}
paper.map { it.slice(0 until foldInstruction.second).toCharArray() }.toTypedArray()
}
}
fun getPaper(lines: List<String>): Array<CharArray> {
val dotLocations = lines
.filter { it.isNotEmpty() && it[0].isDigit() }
.map { Pair(Integer.valueOf(it.split(",")[0]), Integer.valueOf(it.split(",")[1])) }
val xSize = dotLocations.map { it.first }.maxOf { it } + 1
val ySize = dotLocations.map { it.second }.maxOf { it } + 1
val paper = Array(ySize) { CharArray(xSize) { ' ' } }
dotLocations.forEach {
paper[it.second][it.first] = '#'
}
return paper
}
fun getFoldInstructions(lines: List<String>): List<Pair<Char, Int>> {
return lines
.filter { it.isNotEmpty() && it.startsWith("fold") }
.map { Pair(it.split("=")[0].lastOrNull()!!, Integer.valueOf(it.split("=")[1])) }
} | 0 | Kotlin | 0 | 0 | 02484bd3bcb921094bc83368843773f7912fe757 | 2,393 | advent_of_code_2021 | MIT License |
src/Day11.kt | mrugacz95 | 572,881,300 | false | {"Kotlin": 102751} | private data class Monkey(
val id: Int,
var items: MutableList<Int>,
var part2Items: MutableList<Item>,
val operation: (Int) -> Int,
val testDivisibleBy: Int,
val testTrueMonkey: Int,
val testFalseMonkey: Int
)
private object Patterns {
val monkey = "Monkey (?<id>\\d+):".toRegex()
val startingItems = " +Starting items: ".toRegex()
val operation = " +Operation: new = old (?<sign>[+*]) (?<id>\\d+|old)".toRegex()
val divisible = " +Test: divisible by (?<divider>\\d+)".toRegex()
val testTrue = " +If true: throw to monkey (?<id>\\d+)".toRegex()
val testFalse = " +If false: throw to monkey (?<id>\\d+)".toRegex()
}
private fun String.getValue(pattern: Regex, id: String): String {
val match = pattern.matchEntire(this)
val groups = match?.groups
groups ?: throw Exception("Cant parse `$this` with `$pattern`")
return groups[id]?.value ?: throw Exception("Id not found in regex")
}
private fun lowerWorryLevel(worry: Int): Int {
return worry / 3
}
data class Item(
var monkeysValues: MutableList<Int>
) {
constructor(value: Int, monkeys: Int) : this(MutableList<Int>(monkeys) {value} )
}
private fun makeOperationsForAllMonkeys(monkeys: List<Monkey>, item: Item, operation: (Int) -> Int) : Item{
val newMonkeyValues = monkeys.map { it.testDivisibleBy }.zip(item.monkeysValues) {
divider, monkeyValue ->
operation(monkeyValue) % divider
}.toMutableList()
return Item(
newMonkeyValues
)
}
fun main() {
fun List<String>.parse(): List<Monkey> {
val allMonkeys = joinToString("\n").split("\n\n")
return allMonkeys.map { monkeyString ->
val monkeyDesc = monkeyString.split("\n")
val id = monkeyDesc[0].getValue(Patterns.monkey, "id").toInt()
val items = monkeyDesc[1].replace(Patterns.startingItems, "")
.split(", ")
.map { it.toInt() }
.toMutableList()
val part2Items = items.map { Item(it, allMonkeys.size) }.toMutableList()
val operationSign = monkeyDesc[2].getValue(Patterns.operation, "sign")
val operationItem = monkeyDesc[2].getValue(Patterns.operation, "id")
val operation: (Int) -> Int = if (operationItem == "old") {
when (operationSign) {
"+" -> { v -> v + v }
"*" -> { v -> v * v }
else -> throw Exception("Unknown operation")
}
} else {
val operationId = operationItem.toInt()
when (operationSign) {
"+" -> { v -> v + operationId }
"*" -> { v -> v * operationId }
else -> throw Exception("Unknown operation")
}
}
val divisible = monkeyDesc[3].getValue(Patterns.divisible, "divider").toInt()
val testTrue = monkeyDesc[4].getValue(Patterns.testTrue, "id").toInt()
val testFalse = monkeyDesc[5].getValue(Patterns.testFalse, "id").toInt()
Monkey(
id = id,
items = items,
operation = operation,
testDivisibleBy = divisible,
testTrueMonkey = testTrue,
testFalseMonkey = testFalse,
part2Items = part2Items
)
}
}
fun part1(input: List<String>): Int {
val monkeys = input.parse()
var round = 0
val monkeyBusiness = MutableList(monkeys.size) { 0 }
var monkeyId = 0
while (round != 20) {
val monkey = monkeys[monkeyId]
for (item in monkey.items) {
monkeyBusiness[monkey.id] += 1
var newWorryLvl = monkey.operation(item)
newWorryLvl = lowerWorryLevel(newWorryLvl)
val nextMonkeyId = when (newWorryLvl % monkey.testDivisibleBy == 0) {
true -> monkey.testTrueMonkey
false -> monkey.testFalseMonkey
}
monkeys[nextMonkeyId].items.add(newWorryLvl)
}
monkey.items = mutableListOf()
if (monkeyId + 1 == monkeys.size) {
round += 1
}
monkeyId = (monkeyId + 1) % monkeys.size
}
return monkeyBusiness.sorted().reversed().slice(0..1).reduce { acc, it -> acc * it }
}
fun part2(input: List<String>): Long {
val monkeys = input.parse()
var round = 0
val monkeyBusiness = MutableList(monkeys.size) { 0L }
var monkeyId = 0
while (round != 10000) {
val monkey = monkeys[monkeyId]
for (item in monkey.part2Items) {
monkeyBusiness[monkey.id] = monkeyBusiness[monkey.id] + 1
val newWorryLvl = makeOperationsForAllMonkeys(monkeys, item, monkey.operation)
val nextMonkeyId = when (newWorryLvl.monkeysValues[monkeyId] % monkey.testDivisibleBy == 0) {
true -> monkey.testTrueMonkey
false -> monkey.testFalseMonkey
}
monkeys[nextMonkeyId].part2Items.add(newWorryLvl)
}
monkey.part2Items = mutableListOf()
if (monkeyId + 1 == monkeys.size) {
round += 1
}
monkeyId = (monkeyId + 1) % monkeys.size
}
return monkeyBusiness.sorted().reversed().slice(0..1).reduce { acc, it -> acc * it }
}
val testInput = readInput("Day11_test")
val input = readInput("Day11")
assert(part1(testInput), 10605)
println(part1(input))
assert(part2(testInput), 2713310158)
println(part2(input))
}
// Time: 01:36
| 0 | Kotlin | 0 | 0 | 29aa4f978f6507b182cb6697a0a2896292c83584 | 5,755 | advent-of-code-2022 | Apache License 2.0 |
src/nativeMain/kotlin/com.qiaoyuang.algorithm/round1/Questions41.kt | qiaoyuang | 100,944,213 | false | {"Kotlin": 338134} | package com.qiaoyuang.algorithm.round1
import com.qiaoyuang.algorithm.round0.exchange
fun test41() {
val sequence = sequence {
repeat(80) {
yield(it)
}
}
printMedian(sequence)
}
private fun printMedian(sequence: Sequence<Int>) {
val heapMax = IntArray(50)
var maxIndex = 0
val heapMin = IntArray(50)
var minIndex = 0
sequence.forEachIndexed { index, i ->
val realIndex = index + 1
val isAddMax = realIndex % 2 == 1
if (isAddMax) {
heapMax[++maxIndex] = i
heapMax.swimMax(maxIndex)
} else {
heapMin[++minIndex] = i
heapMin.swimMin(minIndex)
}
if (maxIndex > 0 && minIndex > 0 && heapMax[1] > heapMin[1]) {
val temp = heapMax[1]
heapMax[1] = heapMin[1]
heapMin[1] = temp
}
printlnMedian(heapMax, heapMin, maxIndex, minIndex)
}
}
private fun IntArray.swimMax(i: Int) {
var k = i
while (k > 1 && this[k / 2] < this[k]) {
exchange(k / 2, k)
k /= 2
}
}
private fun IntArray.swimMin(i: Int) {
var k = i
while (k > 1 && this[k / 2] > this[k]) {
exchange(k / 2, k)
k /= 2
}
}
private fun printlnMedian(heapMax: IntArray, heapMin: IntArray, heapMaxRealIndex: Int, heapMinRealIndex: Int) {
val elements = buildList {
if (heapMaxRealIndex > 0)
for (i in 1..heapMaxRealIndex)
add(heapMax[i])
if (heapMinRealIndex > 0)
for (i in 1..heapMinRealIndex)
add(heapMin[i])
}
val median = when {
heapMaxRealIndex > heapMinRealIndex -> heapMax[1]
heapMaxRealIndex < heapMinRealIndex -> heapMin[1]
else -> (heapMax[1] + heapMin[1]) / 2
}
println("The median of sequence: $elements is: $median")
}
| 0 | Kotlin | 3 | 6 | 66d94b4a8fa307020d515d4d5d54a77c0bab6c4f | 1,863 | Algorithm | Apache License 2.0 |
src/Day05.kt | mrugacz95 | 572,881,300 | false | {"Kotlin": 102751} | import java.util.Stack
fun main() {
fun parse(input: List<String>): Pair<MutableList<Stack<Char>>, List<Triple<Int, Int, Int>>> {
val crates = mutableListOf<Stack<Char>>()
val cratesInput = input.subList(0, input.indexOf(""))
val movesInputs = input.subList(input.indexOf("") + 1, input.size )
for (x in cratesInput.last().indices){
if (cratesInput.last()[x] != ' '){
val stack = Stack<Char>()
for (y in cratesInput.size - 2 downTo 0){
if (x > cratesInput[y].length){
break
}
if (cratesInput[y][x] != ' '){
stack.add(cratesInput[y][x])
}
}
crates.add(stack)
}
}
val pattern = "move (?<num>\\d+) from (?<from>\\d+) to (?<to>\\d+)".toRegex()
val parsedMoves = movesInputs.map{ line ->
val groups = pattern.matchEntire(line)
val num = groups?.groups?.get("num")?.value?.toInt() ?: throw Exception("Cant parse")
val from = groups.groups["from"]?.value?.toInt() ?: throw Exception("Cant parse")
val to = groups.groups["to"]?.value?.toInt() ?: throw Exception("Cant parse")
Triple(num, from - 1, to - 1)
}
return Pair(crates, parsedMoves)
}
fun part1(input: List<String>): String {
val (crates, moves) = parse(input)
for ((num, from, to) in moves){
for (i in 0 until num){
val top = crates[from].pop()
crates[to].add(top)
}
}
return crates.joinToString(separator = "") { it.pop().toString() }
}
fun part2(input: List<String>): String {
val (crates, moves) = parse(input)
for ((num, from, to) in moves){
val batch = Stack<Char>()
for (i in 0 until num){
batch.add(crates[from].pop())
}
crates[to].addAll(batch.reversed())
}
return crates.joinToString(separator = "") { it.pop().toString() }
}
val testInput = readInput("Day05_test")
assert(part1(testInput), "CMZ")
assert(part2(testInput), "MCD")
val input = readInput("Day05")
println(part1(input))
println(part2(input))
}
// Time: 00:30
| 0 | Kotlin | 0 | 0 | 29aa4f978f6507b182cb6697a0a2896292c83584 | 2,367 | advent-of-code-2022 | Apache License 2.0 |
src/Day05.kt | bigtlb | 573,081,626 | false | {"Kotlin": 38940} | fun main() {
val move = """move (\d+) from (\d+) to (\d+)""".toRegex()
fun playInstructions(input: List<String>, allAtOnce: Boolean = false): String {
val state = mutableListOf<ArrayDeque<Char>>()
input.takeWhile { !it.startsWith(" 1 ") }.map {
while (state.size < Math.floorDiv((it.length - 1), 4) + 1) {
state.add(ArrayDeque())
}
it.filterIndexed { index, _ -> (index - 1) % 4 == 0 }.mapIndexed { index, c -> state[index].add(c) }
}
state.forEach {
it.removeIf(Char::isWhitespace)
it.reverse()
}
input.takeLastWhile { it.isNotBlank() }
.forEach {
move.matchEntire(it)?.let {
it.groupValues.drop(1).map { group -> group.trim().toInt() }
.let { (move, from, to) ->
if (allAtOnce) {
state[to - 1].addAll(state[from - 1].takeLast(move))
(1..move).forEach { _ -> state[from - 1].removeLast() }
} else {
(1..move).forEach { _ -> state[to - 1].add(state[from - 1].removeLast()) }
}
}
}
}
return String(state.map { it.last() }.toCharArray())
}
fun part1(input: List<String>): String = playInstructions(input)
fun part2(input: List<String>): String = playInstructions(input, true)
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day05_test")
check(part1(testInput) == "CMZ")
check(part2(testInput) == "MCD")
val input = readInput("Day05")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | d8f76d3c75a30ae00c563c997ed2fb54827ea94a | 1,817 | aoc-2022-demo | Apache License 2.0 |
src/Day04.kt | f1qwase | 572,888,869 | false | {"Kotlin": 33268} | private fun parseLine(line: String): Pair<Pair<Int, Int>, Pair<Int, Int>> {
val (left, right)= line.split(",")
.map {
val (start, end) = it.split("-")
.map(String::toInt)
start to end
}
return left to right
}
fun main() {
fun part1(input: List<String>): Int = input.count { line ->
val (left, right) = parseLine(line)
(left.first >= right.first && left.second <= right.second) ||
(left.first <= right.first && left.second >= right.second)
}
fun part2(input: List<String>): Int = input.count { line ->
val (left, right) = parseLine(line)
!(left.second < right.first || right.second < left.first )
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day04_test")
check(part1(testInput) == 2) { part1(testInput) }
val input = readInput("Day04")
println(part1(input))
check(part2(testInput) == 4) { part2(testInput) }
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 3fc7b74df8b6595d7cd48915c717905c4d124729 | 1,050 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/problems/Day13.kt | PedroDiogo | 432,836,814 | false | {"Kotlin": 128203} | package problems
class Day13(override val input: String) : Problem {
override val number: Int = 13
private val dots = input
.split("\n\n")
.first()
.lines()
.map { line -> line.split(",") }
.map { (x, y) -> Pair(x.toInt(), y.toInt()) }
.toSet()
private val folds = input
.split("\n\n")[1]
.lines()
.map { line -> line.replace("fold along ", "") }
.map { line -> line.split("=") }
.map { (type, position) -> Pair(type, position.toInt()) }
override fun runPartOne(): String {
return fold(dots, folds.first())
.count()
.toString()
}
override fun runPartTwo(): String {
val imagePoints = folds.fold(dots) { dots, fold ->
fold(dots, fold)
}
return printPoints(imagePoints)
}
private fun fold(points: Set<Pair<Int, Int>>, fold: Pair<String, Int>): Set<Pair<Int, Int>> {
return when (fold.first) {
"y" -> foldVertical(points, fold.second)
else -> foldHorizontal(points, fold.second)
}
}
private fun foldVertical(points: Set<Pair<Int, Int>>, foldPosition: Int): Set<Pair<Int, Int>> {
val (down, up) = points.partition { (_, y) -> y <= foldPosition }
val newUp = up
.map { (x, y) -> Pair(x, 2 * foldPosition - y) }
return down.toSet() + newUp.toSet()
}
private fun foldHorizontal(points: Set<Pair<Int, Int>>, foldPosition: Int): Set<Pair<Int, Int>> {
val (left, right) = points.partition { (x, _) -> x <= foldPosition }
val newRight = right
.map { (x, y) -> Pair(2 * foldPosition - x, y) }
return left.toSet() + newRight.toSet()
}
private fun printPoints(points: Set<Pair<Int, Int>>): String {
val maxX = points.maxOf { (x, _) -> x }
val maxY = points.maxOf { (_, y) -> y }
val image = MutableList(maxY + 1) { MutableList(maxX + 1) { ' ' } }
for ((x, y) in points) {
image[y][x] = '█'
}
return image.joinToString(separator = "\n") { line -> line.joinToString(separator = "") }
}
} | 0 | Kotlin | 0 | 0 | 93363faee195d5ef90344a4fb74646d2d26176de | 2,175 | AdventOfCode2021 | MIT License |
src/main/kotlin/com/ginsberg/advent2022/Day23.kt | tginsberg | 568,158,721 | false | {"Kotlin": 113322} | /*
* Copyright (c) 2022 by <NAME>
*/
/**
* Advent of Code 2022, Day 23 - Unstable Diffusion
* Problem Description: http://adventofcode.com/2022/day/23
* Blog Post/Commentary: https://todd.ginsberg.com/post/advent-of-code/2022/day23/
*/
package com.ginsberg.advent2022
class Day23(input: List<String>) {
private val startingPositions = parseInput(input)
private val nextTurnOffsets: List<List<Point2D>> = createOffsets()
fun solvePart1(): Int {
val locations = (0 until 10).fold(startingPositions) { carry, round -> carry.playRound(round) }
val gridSize = ((locations.maxOf { it.x } - locations.minOf { it.x }) + 1) * ((locations.maxOf { it.y } - locations.minOf { it.y }) + 1)
return gridSize - locations.size
}
fun solvePart2(): Int {
var thisTurn = startingPositions
var roundId = 0
do {
val previousTurn = thisTurn
thisTurn = previousTurn.playRound(roundId++)
} while (previousTurn != thisTurn)
return roundId
}
private fun Set<Point2D>.playRound(roundNumber: Int): Set<Point2D> {
val nextPositions = this.toMutableSet()
val movers: Map<Point2D, Point2D> = this
.filter { elf -> elf.neighbors().any { it in this } }
.mapNotNull { elf ->
nextTurnOffsets.indices.map { direction -> nextTurnOffsets[(roundNumber + direction) % 4] }
.firstNotNullOfOrNull { offsets ->
if (offsets.none { offset -> (elf + offset) in this }) elf to (elf + offsets.first())
else null
}
}.toMap()
val safeDestinations = movers.values.groupingBy { it }.eachCount().filter { it.value == 1 }.keys
movers
.filter { (_, target) -> target in safeDestinations }
.forEach { (source, target) ->
nextPositions.remove(source)
nextPositions.add(target)
}
return nextPositions
}
private fun createOffsets(): List<List<Point2D>> =
listOf(
listOf(Point2D(0, -1), Point2D(-1, -1), Point2D(1, -1)), // N
listOf(Point2D(0, 1), Point2D(-1, 1), Point2D(1, 1)), // S
listOf(Point2D(-1, 0), Point2D(-1, -1), Point2D(-1, 1)), // W
listOf(Point2D(1, 0), Point2D(1, -1), Point2D(1, 1)), // E
)
private fun parseInput(input: List<String>): Set<Point2D> =
input.flatMapIndexed { y, row ->
row.mapIndexedNotNull { x, char ->
if (char == '#') Point2D(x, y) else null
}
}.toSet()
}
| 0 | Kotlin | 2 | 26 | 2cd87bdb95b431e2c358ffaac65b472ab756515e | 2,648 | advent-2022-kotlin | Apache License 2.0 |
src/Day03.kt | kenyee | 573,186,108 | false | {"Kotlin": 57550} |
fun main() { // ktlint-disable filename
fun getPriorityScore(priority: Char) = if (priority.isUpperCase()) {
priority - 'A' + 27
} else {
priority - 'a' + 1
}
fun calcPriority(line: String): Int {
val rucksacks = line.chunked(line.length / 2)
val priority = rucksacks[0].toCharArray().intersect(rucksacks[1].toSet()).first()
return getPriorityScore(priority)
}
fun part1(input: List<String>): Int {
val totalPriority = input.sumOf { line ->
calcPriority(line.trim())
}
return totalPriority
}
fun calcBadges(input: List<String>): Int {
return input.chunked(3).sumOf { rucksacks ->
getPriorityScore(
rucksacks[0].toCharArray()
.intersect(rucksacks[1].toSet())
.intersect(rucksacks[2].toSet()).first()
)
}
}
fun part2(input: List<String>): Int {
return calcBadges(input)
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day03_test")
println("test result priority total: ${part1(testInput)}")
check(part1(testInput) == 157)
println("test result badge priority total is: ${part2(testInput)}")
check(part2(testInput) == 70)
val input = readInput("Day03_input")
println("Priority total is: ${part1(input)}")
println("Badge priority total is: ${part2(input)}")
}
| 0 | Kotlin | 0 | 0 | 814f08b314ae0cbf8e5ae842a8ba82ca2171809d | 1,472 | KotlinAdventOfCode2022 | Apache License 2.0 |
y2022/src/main/kotlin/adventofcode/y2022/Day02.kt | Ruud-Wiegers | 434,225,587 | false | {"Kotlin": 503769} | package adventofcode.y2022
import adventofcode.io.AdventSolution
object Day02 : AdventSolution(2022, 2, "Rock Paper Scissors") {
override fun solvePartOne(input: String) = input
.lines()
.map { line -> line.first().toRps() to line.last().toRps() }
.sumOf { (opp, play) -> play.score + score(play, opp) }
override fun solvePartTwo(input: String): Any {
return input.lines()
.map { line -> line.first().toRps() to line.last().toOutcome() }
.map { (opp, strat) -> opp to strategize(opp, strat) }
.sumOf { (opp, play) -> play.score + score(play, opp) }
}
}
private fun score(play: RPS, opponent: RPS) = when (opponent) {
play.losesTo() -> 0
play.draws() -> 3
else -> 6
}
private enum class RPS(
val score: Int
) {
Rock(1), Paper(2), Scissors(3);
fun beats() = when (this) {
Rock -> Scissors
Paper -> Rock
Scissors -> Paper
}
fun draws() = this
fun losesTo() = beats().beats()
}
private fun Char.toRps() = when (this) {
'A', 'X' -> RPS.Rock
'B', 'Y' -> RPS.Paper
'C', 'Z' -> RPS.Scissors
else -> throw IllegalArgumentException()
}
private enum class Outcome { Lose, Draw, Win }
private fun Char.toOutcome() = when (this) {
'X' -> Outcome.Lose
'Y' -> Outcome.Draw
'Z' -> Outcome.Win
else -> throw IllegalArgumentException()
}
private fun strategize(opponent: RPS, outcome: Outcome): RPS = when (outcome) {
Outcome.Lose -> opponent.beats()
Outcome.Draw -> opponent.draws()
Outcome.Win -> opponent.losesTo()
} | 0 | Kotlin | 0 | 3 | fc35e6d5feeabdc18c86aba428abcf23d880c450 | 1,604 | advent-of-code | MIT License |
src/main/kotlin/ca/kiaira/advent2023/day8/Day8.kt | kiairatech | 728,913,965 | false | {"Kotlin": 78110} | package ca.kiaira.advent2023.day8
import ca.kiaira.advent2023.Puzzle
/**
* Solution for Day 8 of the Advent of Code challenge.
* It involves navigating a network of nodes based on a sequence of left/right instructions.
*
* @author <NAME> <<EMAIL>>
* @since December 8th, 2023
*/
object Day8 : Puzzle<Pair<List<Day8.Direction>, Map<String, Pair<String, String>>>>(8) {
/**
* Enumeration for directions.
*/
enum class Direction { LEFT, RIGHT }
/**
* Parses the input data for the Day 8 puzzle.
*
* @param input The input data as a sequence of strings.
* @return A pair of a list of directions (List<Direction>) and a map of node connections (Map<String, Pair<String, String>>).
*/
override fun parse(input: Sequence<String>): Pair<List<Direction>, Map<String, Pair<String, String>>> {
val lines = input.toList() // Convert the sequence to a list
val directions = lines.first().map { if (it == 'L') Direction.LEFT else Direction.RIGHT }
val entries = lines.drop(1) // Drop the first line (directions)
.filter { it.isNotBlank() }.associate { line ->
val instruction = line.split(" = ")
val (left, right) = instruction.last().split("(", ")", ", ").filter(String::isNotBlank)
instruction.first() to (left to right)
}
return directions to entries
}
/**
* Solves Part 1 of the Day 8 puzzle.
* Navigates through the node network, starting from node 'AAA', and follows the sequence
* of left/right instructions until reaching the node 'ZZZ'.
*
* @param input The parsed input data consisting of directions and node connections.
* @return The number of steps (Long) to reach node 'ZZZ'.
*/
override fun solvePart1(input: Pair<List<Direction>, Map<String, Pair<String, String>>>): Long {
return countSteps("AAA", { it == "ZZZ" }, input).toLong()
}
/**
* Solves Part 2 of the Day 8 puzzle.
* It starts from all nodes ending with 'A' and follows the sequence of instructions
* until all paths reach nodes ending with 'Z'.
*
* @param input The parsed input data consisting of directions and node connections.
* @return The number of steps (Long) taken until all nodes being navigated end with 'Z'.
*/
override fun solvePart2(input: Pair<List<Direction>, Map<String, Pair<String, String>>>): Long {
return input.second
.filter { it.key.endsWith('A') }
.map { entry -> countSteps(entry.key, { it.endsWith('Z') }, input) }
.map(Int::toBigInteger)
.reduce { acc, steps -> acc * steps / acc.gcd(steps) }
.toLong()
}
/**
* Counts the number of steps required to navigate from a starting node to a target condition.
*
* @param from The starting node as a string.
* @param until A lambda function defining the condition to meet the target node.
* @param network A pair of list of directions and a map of node connections.
* @return The number of steps (Int) required to reach the target condition.
*/
private fun countSteps(
from: String,
until: (String) -> Boolean,
network: Pair<List<Direction>, Map<String, Pair<String, String>>>,
): Int {
val (directions, entries) = network
var current = from
var steps = 0
while (!until(current)) {
val next = entries[current]!!
val dir = directions[steps % directions.size]
current = if (dir == Direction.LEFT) next.first else next.second
steps++
}
return steps
}
}
| 0 | Kotlin | 0 | 1 | 27ec8fe5ddef65934ae5577bbc86353d3a52bf89 | 3,367 | kAdvent-2023 | Apache License 2.0 |
src/Day09.kt | inssein | 573,116,957 | false | {"Kotlin": 47333} | import kotlin.math.absoluteValue
import kotlin.math.sign
fun main() {
data class Position(val x: Int, val y: Int) {
fun move(direction: Char): Position {
return when (direction) {
'U' -> copy(y = y - 1)
'D' -> copy(y = y + 1)
'L' -> copy(x = x - 1)
'R' -> copy(x = x + 1)
else -> error("Invalid move.")
}
}
fun moveTowardsHead(head: Position): Position {
val xDelta = head.x - x
val yDelta = head.y - y
if (xDelta.absoluteValue <= 1 && yDelta.absoluteValue <= 1) {
return this
}
return Position(xDelta.sign + x, yDelta.sign + y)
}
}
fun countTailPositions(input: List<String>, knots: Int): Int {
val visited = mutableSetOf<Position>()
val nodes = Array(knots) { Position(0, 0) }
input.forEach { line ->
val direction = line[0]
val moves = line.substring(2).toInt()
repeat(moves) {
nodes[knots - 1] = nodes[knots - 1].move(direction)
for (j in knots - 2 downTo 0) {
nodes[j] = nodes[j].moveTowardsHead(nodes[j + 1])
}
visited.add(nodes[0])
}
}
return visited.count()
}
fun part1(input: List<String>): Int {
return countTailPositions(input, 2)
}
fun part2(input: List<String>): Int {
return countTailPositions(input, 10)
}
val testInput = readInput("Day09_test")
check(part1(testInput) == 13)
check(part2(testInput) == 1)
val input = readInput("Day09")
println(part1(input)) // 6030
println(part2(input)) // 2545
}
| 0 | Kotlin | 0 | 0 | 095d8f8e06230ab713d9ffba4cd13b87469f5cd5 | 1,783 | advent-of-code-2022 | Apache License 2.0 |
src/year2022/day13/Day.kt | tiagoabrito | 573,609,974 | false | {"Kotlin": 73752} | package year2022.day13
import readInput
sealed class Data {
data class Integer(val value: Int) : Data()
data class ListData(val data: List<Data> = listOf()) : Data()
}
fun String.findClosingBracketFromPos(openBracketPos: Int): Int {
var closedBracketPos = openBracketPos
var counter = 1
while (counter > 0) {
when (this[++closedBracketPos]) {
']' -> counter--
'[' -> counter++
}
}
return closedBracketPos
}
fun String.parseLine(): Data {
if (isEmpty()) return Data.ListData(listOf())
val list = mutableListOf<Data>()
var index = 0
while (index < count()) {
when (val char = this[index]) {
'[' -> {
val closedPos = this.findClosingBracketFromPos(index)
val sub = substring(startIndex = index + 1, endIndex = closedPos)
list.add(sub.parseLine())
index = closedPos
}
',' -> {}
else -> {
var digitToParse = ""
var curr = char
while (curr.isDigit()) {
digitToParse += curr
index++
if (index == count()) {
break
}
curr = this[index]
continue
}
list.add(Data.Integer(digitToParse.toInt()))
}
}
index++
}
return Data.ListData(list)
}
fun main() {
val day = "13"
val expectedTest1 = 13
val expectedTest2 = 1
fun checkIt(left: String, right: String): Boolean {
//return left.parseLine() == ""
return false
}
fun part1(input: List<String>): Int {
val sum = input.chunked(3)
.mapIndexed { index, strings ->
when (checkIt(strings[0], strings[1])) {
true -> index + 1
false -> 0
}
}
.sum()
return sum
}
fun part2(input: List<String>): Int {
return input.size
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("year2022/day$day/test")
val part1Test = part1(testInput)
check(part1Test == expectedTest1) { "expected $expectedTest1 but was $part1Test" }
val input = readInput("year2022/day$day/input")
println(part1(input))
val part2Test = part2(testInput)
check(part2Test == expectedTest2) { "expected $expectedTest2 but was $part2Test" }
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 1f9becde3cbf5dcb345659a23cf9ff52718bbaf9 | 2,599 | adventOfCode | Apache License 2.0 |
src/main/kotlin/be/seppevolkaerts/day1/Day1.kt | Cybermaxke | 727,453,020 | false | {"Kotlin": 35118} | package be.seppevolkaerts.day1
fun part1CalibrationValue(value: String): Int {
val firstDigit = value.first { it.isDigit() }
val lastDigit = value.last { it.isDigit() }
return "$firstDigit$lastDigit".toInt()
}
fun part1SumOfCalibrationValues(iterable: Iterable<String>): Int {
return iterable.sumOf { part1CalibrationValue(it) }
}
private val valueMapping = (0..9).associateBy { "$it" } +
mapOf("one" to 1, "two" to 2, "three" to 3, "four" to 4, "five" to 5, "six" to 6, "seven" to 7, "eight" to 8, "nine" to 9)
private fun String.findDigit(last: Boolean): Int {
var closestValue = 0
var closestIndex = -1
valueMapping.forEach { (key, value) ->
val currentIndex = if (last) lastIndexOf(key) else indexOf(key)
if (currentIndex != -1 && (closestIndex == -1 || (!last && currentIndex < closestIndex) || (last && currentIndex > closestIndex))) {
closestIndex = currentIndex
closestValue = value
}
}
return closestValue
}
fun calibrationValue(value: String): Int {
val firstDigit = value.findDigit(false)
val lastDigit = value.findDigit(true)
return "$firstDigit$lastDigit".toInt()
}
fun sumOfCalibrationValues(iterable: Iterable<String>): Int {
return iterable.sumOf { calibrationValue(it) }
}
| 0 | Kotlin | 0 | 1 | 56ed086f8493b9f5ff1b688e2f128c69e3e1962c | 1,248 | advent-2023 | MIT License |
src/main/kotlin/com/nibado/projects/advent/y2020/Day17.kt | nielsutrecht | 47,550,570 | false | null | package com.nibado.projects.advent.y2020
import com.nibado.projects.advent.*
object Day17 : Day {
private val grid = resourceLines(2020, 17)
.mapIndexed { y, s -> s.mapIndexedNotNull { x, c -> if (c == '#') listOf(x, y, 0) else null } }
.flatten().toSet()
override fun part1() = solve(grid)
override fun part2() = solve(grid.map { it + 0 }.toSet())
private fun solve(input: Set<List<Int>>): Any {
var points = input
val neighbors = neighbors(points.first().size)
fun neighbors(list: List<Int>) = neighbors.map { n -> list.mapIndexed { i, v -> n[i] + v } }
repeat(6) {
val map = points.flatMap { neighbors(it) }.fold(mutableMapOf<List<Int>, Int>()) { map, p ->
map[p] = map.getOrDefault(p, 0) + 1
map
}
points = map.filter { (p, c) -> (p in points && c in 2..3) || (p !in points && c == 3) }
.map { it.key }.toSet()
}
return points.size
}
private fun neighbors(dim: Int) = (1 until dim).fold((-1..1).map { listOf(it) }) { points, _ ->
points.flatMap { p -> (-1..1).map { p + it } }
}.filterNot { it.all { it == 0 } }
}
| 1 | Kotlin | 0 | 15 | b4221cdd75e07b2860abf6cdc27c165b979aa1c7 | 1,223 | adventofcode | MIT License |
src/Day04.kt | inssein | 573,116,957 | false | {"Kotlin": 47333} | fun main() {
fun String.toRange(): IntRange = this.split('-')
.let { (first, second) -> first.toInt()..second.toInt() }
fun String.toRanges(): Pair<IntRange, IntRange> = this.split(',')
.let { (first, second) -> first.toRange() to second.toRange() }
fun IntRange.fullyOverlaps(other: IntRange) = first <= other.first && last >= other.last
fun IntRange.overlaps(other: IntRange) = first <= other.last && other.first <= last
fun part1(input: List<String>): Int {
return input.count {
it.toRanges().let { (firstElf, secondElf) ->
firstElf.fullyOverlaps(secondElf) || secondElf.fullyOverlaps(firstElf)
}
}
}
fun part2(input: List<String>): Int {
return input.count {
it.toRanges().let { (firstElf, secondElf) ->
firstElf.overlaps(secondElf)
}
}
}
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 | 095d8f8e06230ab713d9ffba4cd13b87469f5cd5 | 1,109 | advent-of-code-2022 | Apache License 2.0 |
src/day07/Day07.kt | TheRishka | 573,352,778 | false | {"Kotlin": 29720} | package day07
import readInput
import java.util.*
fun main() {
val input = readInput("day07/Day07")
val rootFolder = Folder(
name = "/",
files = mutableMapOf(),
folders = mutableMapOf(),
totalSize = 0L
)
var currentFolder: Stack<Folder> = Stack<Folder>().apply { add(rootFolder) }
input.forEach { terminalInput ->
val command = if (terminalInput.startsWith("$")) terminalInput else null
val commandOutput = if (command.isNullOrEmpty()) terminalInput else null
command?.let {
when (it) {
"$ cd /" -> Unit
"$ ls" -> {
// Listing data for CURRENT FOLDER
// Do nothing as currentFolder should be set
}
"$ cd .." -> {
currentFolder.pop()
}
else -> {
// CD somewhere?
val folderName = command?.drop(5)
if (currentFolder.peek().folders.containsKey(folderName).not()) {
println("ERRORR NO SUCH FOLDER!!!!!")
} else {
currentFolder.push(
currentFolder.peek().folders[folderName]
)
}
}
}
}
commandOutput?.let { output ->
when {
output.startsWith("dir") -> {
val dirName = output.drop(4)
currentFolder.peek().folders =
currentFolder.peek().folders.toMutableMap().apply {
put(
dirName, Folder(
name = dirName,
files = mutableMapOf(),
folders = mutableMapOf(),
totalSize = 0,
)
)
}
}
output.first().isDigit() -> {
// It's a file with filesize
val fileSize = output.filter {
it.isDigit()
}.toLong()
val fileName = output.filter {
it.isDigit().not()
}.trim()
currentFolder.peek().addFile(fileSize, fileName)
}
}
}
}
println(part1(currentFolder[0]))
println(part2(currentFolder[0]))
}
fun calculateFolderTotalSize(
folder: Folder,
calculationsCallback: (Folder, Long) -> Unit
): Long {
var size = folder.totalSize
folder.folders.forEach {
size += calculateFolderTotalSize(it.value, calculationsCallback)
}
calculationsCallback(folder, size)
return size
}
fun part1(inputRootFolder: Folder): Long {
val listOfDirsWithSizeThreshold = mutableListOf<Pair<String, Long>>()
calculateFolderTotalSize(inputRootFolder) { folder, size ->
if (size <= 100000) {
listOfDirsWithSizeThreshold.add(
folder.name to size
)
}
}
return listOfDirsWithSizeThreshold.sumOf {
it.second
}
}
fun part2(inputRootFolder: Folder): Long {
val diskAvailable = 70000000
val requiredAtLeast = 30000000
val listOfDirsWithSizes = mutableListOf<Pair<String, Long>>()
inputRootFolder.totalSize = calculateFolderTotalSize(inputRootFolder) { folder, size ->
listOfDirsWithSizes.add(
folder.name to size
)
}
val totalOccupiedSpace = inputRootFolder.totalSize
val diskRequiredToBeFreed = totalOccupiedSpace - requiredAtLeast
val dirThatFit = listOfDirsWithSizes.filter {
diskAvailable - (totalOccupiedSpace - it.second) >= requiredAtLeast
}.minBy {
it.second
}
return dirThatFit.second
}
//1117448
data class FileInfo(
var name: String,
var size: Long,
)
data class Folder(
var name: String,
var files: MutableMap<String, FileInfo>,
var folders: MutableMap<String, Folder>,
var totalSize: Long
) {
fun addFile(size: Long, fileName: String) {
files[fileName] = FileInfo(
name = fileName,
size = size
)
totalSize += size
}
} | 0 | Kotlin | 0 | 1 | 54c6abe68c4867207b37e9798e1fdcf264e38658 | 4,380 | AOC2022-Kotlin | Apache License 2.0 |
src/Day07.kt | AndreiShilov | 572,661,317 | false | {"Kotlin": 25181} | import java.util.Stack
fun main() {
fun getSizesMap(input: List<String>): Map<String, Long> {
val mutableMapOf = mutableMapOf<String, Long>()
val folders = Stack<String>()
for (line in input) {
if (line.startsWith("$ cd") && !line.startsWith("$ cd ..")) {
val dirName = line.substring(5)
val dir = folders.elements().asSequence().plus(dirName).joinToString("_")
folders.push(dir)
continue
}
if (line.startsWith("$ ls") || line.startsWith("dir")) {
continue
}
if (line.startsWith("$ cd ..")) {
folders.pop()
continue
}
val toLong = line.split(" ")[0].toLong()
folders.elements().toList().forEach {
val orPut = mutableMapOf.getOrPut(it) { 0 }
mutableMapOf[it] = orPut + toLong
}
}
return mutableMapOf
}
fun part1(input: List<String>): Long {
return getSizesMap(input).filter { it.value < 100000 }.map { it.value }.sum()
}
fun part2(input: List<String>): Long {
val sizesMap = getSizesMap(input)
val root = sizesMap.getOrDefault("/", 0)
val available = 70000000 - root
println("Available $available")
val needToFreeUp = 30000000 - available
println("Need to free up $needToFreeUp")
return sizesMap.filter { it.value > needToFreeUp }.map { it.value }.min()
}
// test if implementation meets criteria from the description, like:
check(part1(readInput("Day07_test")) == 95437L)
println(part2(readInput("Day07_test")))
check(part2(readInput("Day07_test")) == 24933642L)
val input = readInput("Day07")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 852b38ab236ddf0b40a531f7e0cdb402450ffb9a | 1,868 | aoc-2022 | Apache License 2.0 |
src/day23/Day23.kt | dakr0013 | 572,861,855 | false | {"Kotlin": 105418} | package day23
import day23.Direction.*
import kotlin.test.assertEquals
import readInput
fun main() {
fun part1(input: List<String>): Int {
val grove = Grove.parse(input)
grove.simulate(10)
return grove.emptyGroundTiles()
}
fun part2(input: List<String>): Int {
val grove = Grove.parse(input)
return grove.firstRoundWhereNoElfMoves()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day23_test")
assertEquals(110, part1(testInput))
assertEquals(20, part2(testInput))
val input = readInput("Day23")
println(part1(input))
println(part2(input))
}
class Grove(private val elves: List<Elf>) {
private val directions = mutableListOf(NORTH, SOUTH, WEST, EAST)
fun simulate(rounds: Int) {
repeat(rounds) { simulateRound() }
}
private fun simulateRound(): Int {
val elvesWhichCanProposeMove = elves.filter { it.hasAdjacentElf() }
val elvesWhichProposedMove = elvesWhichCanProposeMove.mapNotNull { it.proposeMove() }
val elvesToMove =
elvesWhichProposedMove
.groupBy { it.proposedPosition }
.values
.filter { it.size == 1 }
.flatten()
elvesToMove.forEach { it.move() }
directions.add(directions.removeFirst())
return elvesToMove.size
}
fun firstRoundWhereNoElfMoves(): Int {
var round = 1
while (simulateRound() != 0) {
round++
}
return round
}
fun emptyGroundTiles(): Int {
val minX = elves.minOf { it.currentPosition.x }
val maxX = elves.maxOf { it.currentPosition.x }
val minY = elves.minOf { it.currentPosition.y }
val maxY = elves.maxOf { it.currentPosition.y }
val width = maxX - minX + 1
val height = maxY - minY + 1
return width * height - elves.size
}
private fun Elf.hasAdjacentElf(): Boolean {
val adjacentPositions =
listOf(
Vector2D(0, -1),
Vector2D(1, -1),
Vector2D(1, 0),
Vector2D(1, 1),
Vector2D(0, 1),
Vector2D(-1, 1),
Vector2D(-1, 0),
Vector2D(-1, -1),
)
.map { this.currentPosition + it }
return adjacentPositions.any { adjacentPosition ->
elves.any { elf -> elf.currentPosition == adjacentPosition }
}
}
private fun Elf.proposeMove(): Elf? {
for (direction in directions) {
if (this.canMoveIn(direction)) {
return this.apply { proposedPosition = currentPosition + direction.moveTo }
}
}
return null
}
private fun Elf.canMoveIn(direction: Direction): Boolean {
return direction.toCheck
.map { this.currentPosition + it }
.all { positionToCheck -> elves.all { it.currentPosition != positionToCheck } }
}
companion object {
fun parse(input: List<String>): Grove {
var elfCount = 0
val elves =
input
.mapIndexed { y, s ->
s.mapIndexed { x, c ->
if (c == '#') {
Elf(elfCount++, Vector2D(x, y), Vector2D(x, y))
} else null
}
.filterNotNull()
}
.flatten()
return Grove(elves)
}
}
}
data class Elf(val number: Int, var currentPosition: Vector2D, var proposedPosition: Vector2D) {
fun move() {
currentPosition = proposedPosition
}
}
enum class Direction(val moveTo: Vector2D, val toCheck: Set<Vector2D>) {
NORTH(Vector2D(0, -1), setOf(Vector2D(-1, -1), Vector2D(0, -1), Vector2D(1, -1))),
SOUTH(Vector2D(0, 1), setOf(Vector2D(-1, 1), Vector2D(0, 1), Vector2D(1, 1))),
WEST(Vector2D(-1, 0), setOf(Vector2D(-1, -1), Vector2D(-1, 0), Vector2D(-1, 1))),
EAST(Vector2D(1, 0), setOf(Vector2D(1, -1), Vector2D(1, 0), Vector2D(1, 1))),
}
data class Vector2D(val x: Int, val y: Int) {
operator fun plus(other: Vector2D) = Vector2D(x + other.x, y + other.y)
}
| 0 | Kotlin | 0 | 0 | 6b3adb09f10f10baae36284ac19c29896d9993d9 | 3,976 | aoc2022 | Apache License 2.0 |
advent-of-code-2021/src/main/kotlin/eu/janvdb/aoc2021/day23/Day23.kt | janvdbergh | 318,992,922 | false | {"Java": 1000798, "Kotlin": 284065, "Shell": 452, "C": 335} | package eu.janvdb.aoc2021.day23
import eu.janvdb.aocutil.kotlin.Move
import eu.janvdb.aocutil.kotlin.findShortestPath
import eu.janvdb.aocutil.kotlin.point2d.Point2D
import eu.janvdb.aocutil.kotlin.readLines
import eu.janvdb.aocutil.kotlin.runWithTimer
import kotlin.math.abs
const val FILENAME = "input23.txt"
val costs = listOf(1, 10, 100, 1000)
fun main() {
val game = Game()
val cost = runWithTimer("Game") { game.solve() }
println(cost)
}
class Game {
private val lines = readLines(2021, FILENAME)
private val numberOfTypes = (lines[1].length - 4) / 2
private val corridorSize = lines[1].length - 2 - numberOfTypes
private val numberPerType = lines.size - 3
private val locations = generateLocations()
private val corridorIndicesPerX = locations.filter { it.type == null }.associate { Pair(it.position.x, it.index) }
private val startState = parseStartState()
private val endState = generateEndState()
private fun generateLocations(): List<Location> {
val result = mutableListOf<Location>()
for (i in 1 until lines[1].length - 1)
if (i < 3 || i > numberOfTypes * 2 + 1 || i % 2 == 0)
result.add(Location(result.size, Point2D(i, 0), null, null))
for (number in 0 until numberPerType)
for (type in 0 until numberOfTypes)
result.add(Location(result.size, Point2D(type * 2 + 3, number + 1), type, number))
return result
}
private fun parseStartState(): State {
val result = IntArray(corridorSize + numberOfTypes * numberPerType) { -1 }
for (y in lines.indices) {
for (x in lines[y].indices) {
if (lines[y][x] != '.') {
val location = locations.find { it.position.x == x && it.position.y == y - 1 }
if (location != null) result[location.index] = lines[y][x] - 'A'
}
}
}
return State(result)
}
private fun generateEndState(): State {
val result = IntArray(corridorSize + numberOfTypes * numberPerType) { -1 }
for (it in corridorSize until result.size) {
result[it] = (it - corridorSize) % numberOfTypes
}
return State(result)
}
fun solve(): Int? {
return findShortestPath(startState, endState, State::getSteps, State::estimateRemainingCost)
}
data class Location(val index: Int, val position: Point2D, val type: Int?, val number: Int?)
inner class State(val value: IntArray) {
fun getSteps(): Sequence<Move<State>> {
return locations
.asSequence()
.filter { value[it.index] != -1 }
.flatMap { generateMovesFrom(it) }
}
private fun generateMovesFrom(location: Location): Sequence<Move<State>> {
// Handle moves from corridor later
if (location.type == null) return sequenceOf()
// Do not move if this one and all ones behind it are in the correct place
val allCorrect = IntRange(location.number!!, numberPerType - 1)
.all { value[indexOfHome(location.type, it)] == location.type }
if (allCorrect) return sequenceOf()
// Do not move if route to corridor not empty
val routeToCorridorEmpty = IntRange(0, location.number - 1)
.all { value[indexOfHome(location.type, it)] == -1 }
if (!routeToCorridorEmpty) return sequenceOf()
// Try to move left and right
val toLocations = mutableListOf<Location>()
for (index in corridorIndicesPerX[location.position.x - 1]!! downTo 0) {
if (value[index] != -1) break
toLocations.add(locations[index])
}
for (index in corridorIndicesPerX[location.position.x + 1]!! until corridorSize) {
if (value[index] != -1) break
toLocations.add(locations[index])
}
// Try the moves
return toLocations.asSequence().map { createMove(location, it) }
}
private fun createMove(from: Location, to: Location): Move<State> {
// Do the move
val newValue = value.clone()
var totalCost = 0
fun move(from: Location, to: Location) {
newValue[to.index] = newValue[from.index]
newValue[from.index] = -1
totalCost += costs[newValue[to.index]] * from.position.manhattanDistanceTo(to.position)
}
fun homeCanBeOccupied(type: Int): Boolean {
return IntRange(0, numberPerType - 1).map { newValue[indexOfHome(type, it)] }
.all { it == -1 || it == type }
}
fun homeLastFreeIndex(type: Int): Int {
return (numberPerType - 1 downTo 0).map { indexOfHome(type, it) }.first { newValue[it] == -1 }
}
move(from, to)
// See if we can move back home
var checkMoveHome = true
while (checkMoveHome) {
checkMoveHome = false
for (type in 0 until numberOfTypes) {
if (homeCanBeOccupied(type)) {
// Try to move left and right
val xOfHome = xOfHome(type)
for (index in corridorIndicesPerX[xOfHome - 1]!! downTo 0) {
if (newValue[index] == type) {
move(locations[index], locations[homeLastFreeIndex(type)])
checkMoveHome = true
} else if (newValue[index] != -1) {
break
}
}
for (index in corridorIndicesPerX[xOfHome + 1]!! until corridorSize) {
if (newValue[index] == type) {
move(locations[index], locations[homeLastFreeIndex(type)])
checkMoveHome = true
} else if (newValue[index] != -1) {
break
}
}
}
}
}
val state = State(newValue)
return Move(state, totalCost)
}
private fun xOfHome(type: Int) = type * 2 + 3
private fun indexOfHome(type: Int, number: Int) = corridorSize + number * numberOfTypes + type
fun estimateRemainingCost(): Int {
val result = value.mapIndexed { index, ch ->
val type = value[index]
val location = locations[index]
val correctX = 2 * type + 3
if (type == -1 || location.position.x == correctX)
0
else
10000 + costs[type] * (numberPerType + location.position.y + abs(location.position.x - correctX))
}.sum()
return result
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as State
return value.contentEquals(other.value)
}
override fun hashCode(): Int {
return value.hashCode()
}
override fun toString() = value
.map { if (it == -1) '.' else 'A' + it }
.foldIndexed("") { index, acc, ch ->
acc + (if (index >= corridorSize && (index - corridorSize) % numberOfTypes == 0) "|" else "") + ch
}
}
} | 0 | Java | 0 | 0 | 78ce266dbc41d1821342edca484768167f261752 | 6,212 | advent-of-code | Apache License 2.0 |
src/commonMain/kotlin/advent2020/day16/Day16Puzzle.kt | jakubgwozdz | 312,526,719 | false | null | package advent2020.day16
data class Field(val name: String, val range1: LongRange, val range2: LongRange) {
operator fun contains(v: Long) = v in range1 || v in range2
}
val fieldRegex by lazy { """(.+): (\d+)-(\d+) or (\d+)-(\d+)""".toRegex() }
private fun fields(lines: Sequence<String>): List<Field> = lines
.takeWhile { it.isNotBlank() }
.map { fieldRegex.matchEntire(it)?.destructured ?: error("invalid line `$it`") }
.map { (name, start1, end1, start2, end2) ->
Field(name,
start1.toLong()..end1.toLong(),
start2.toLong()..end2.toLong())
}
.toList()
fun part1(input: String): String {
val lines = input.trim().lineSequence()
val fields = fields(lines)
val result = lines.drop(fields.size + 5).map { nearby ->
nearby.split(',').map { it.toLong() }
.filterNot { v -> fields.any { v in it } }
.sum()
}.sum()
return result.toString()
}
fun part2(input: String): String {
val lines = input.trim().lineSequence()
val fields = fields(lines)
val myTicket = lines.drop(fields.size + 2).first().split(',').map { it.toLong() }
// .also { println("my Ticket: $it") }
val fieldIndices = fields.map { it.name }.associateWith { fields.indices.toMutableSet() }
lines.drop(fields.size + 5)
.map { it.split(',').map(String::toLong) }
.filter { nearby -> nearby.all { v -> fields.any { v in it } } }
.forEach { ticket ->
ticket.forEachIndexed { index, v ->
fields.filterNot { v in it }
.map { it.name }
.forEach {
// println("`$it` can't be at $index because of $ticket")
fieldIndices[it]!! -= index
}
}
}
// display(fieldIndices)
while (doSearchStep(fieldIndices)) {
// display(fieldIndices)
}
return fields.asSequence()
.map { it.name }
.filter { it.startsWith("departure") }
.map { fieldIndices[it]!!.single() }
.map { myTicket[it] }
.fold(1L) { a, b -> a * b }.toString()
}
fun doSearchStep(fieldIndices: Map<String, MutableSet<Int>>): Boolean {
var changed = false
val lastIndex = fieldIndices.size - 1
val fieldsWithOneIndex = fieldIndices
.filterValues { it.size == 1 }
.map { (f, v) -> f to v.single() }
val indicesWithOneField = (0..lastIndex)
.mapNotNull { index ->
fieldIndices.entries
.singleOrNull { (_, v) -> index in v }
?.let { (f, _) -> f to index }
}
val newFieldsWithOneIndex = fieldsWithOneIndex - indicesWithOneField
val newIndicesWithOneField = indicesWithOneField - fieldsWithOneIndex
newFieldsWithOneIndex.forEach { (f, i) ->
// println("`$f` can be only at $i")
fieldIndices.forEach { (f1, s) -> if (f1 != f && i in s) s -= i.also { changed = true } }
}
newIndicesWithOneField.forEach { (f, i) ->
// println("at $i can be only `$f`")
fieldIndices.forEach { (f1, s) -> if (f1 == f && s.size > 1) s.retainAll(setOf(i)).also { changed = true } }
}
return changed
}
fun display(m: Map<String, Set<Int>>) {
println()
val lastIndex = m.size - 1
println("${": ".padStart(32)}${(0..lastIndex).map { i -> "$i".padStart(2) }}")
m.forEach { (f, s) ->
println("${f.padStart(30)}: ${
(0..lastIndex).map { i -> if (i in s) "><" else " " }
}")
}
}
| 0 | Kotlin | 0 | 2 | e233824109515fc4a667ad03e32de630d936838e | 3,542 | advent-of-code-2020 | MIT License |
src/Day03.kt | alexaldev | 573,318,666 | false | {"Kotlin": 10807} | fun main() {
val priorities = ('a'..'z').zip( (1..26))
.toMap(hashMapOf()).apply { putAll(('A'..'Z').zip((27..52)).toMap()) }
fun part1(input: List<String>): Int {
var acc = 0
input.forEach { line ->
val compartments = line.splitInHalf()
val first = compartments.first().toCharArray().toSet()
val second = compartments[1].toCharArray().toSet()
val commonChars = first.intersect(second)
commonChars.forEach { c -> acc += priorities[c]!! }
}
return acc
}
fun part2(input: List<String>): Int {
val typesPerGroup = mutableListOf<Char>()
val ruckackArrays: List<List<CharArray>> = input
.windowed(3, step = 3) { strings ->
strings.map { it.toCharArray() }
.sortedBy { it.size }
}
ruckackArrays.forEach {
try {
it.first().first { smallListChar ->
(smallListChar in it[1]) && (smallListChar in it[2])
}.let { typeFound -> typesPerGroup.add(typeFound) }
} catch (e: NoSuchElementException) { }
}
return typesPerGroup.sumOf { priorities[it]!! }
}
val testInput = readInput("In03.txt")
print(part1(testInput))
}
fun String.splitInHalf() : List<String> {
return listOf(
this.substring(0, this.length / 2),
this.substring(this.length / 2, this.length)
)
} | 0 | Kotlin | 0 | 0 | 5abf10b2947e1c6379d179a48f1bdcc719e7062b | 1,484 | advent-of-code-2022-kotlin | Apache License 2.0 |
src/main/kotlin/at/mpichler/aoc/solutions/year2022/Day19.kt | mpichler94 | 656,873,940 | false | {"Kotlin": 196457} | package at.mpichler.aoc.solutions.year2022
import at.mpichler.aoc.lib.Day
import at.mpichler.aoc.lib.PartSolution
import at.mpichler.aoc.lib.ShortestPaths
import kotlin.math.min
open class Part19A : PartSolution() {
protected lateinit var blueprints: List<Blueprint>
override fun parseInput(text: String) {
val lines = text.trim().split("\n")
val blueprints = mutableListOf<Blueprint>()
val pattern =
Regex("Blueprint (\\d+): Each ore robot costs (\\d+) ore\\. Each clay robot costs (\\d+) ore\\. Each obsidian robot costs (\\d+) ore and (\\d+) clay\\. Each geode robot costs (\\d+) ore and (\\d+) obsidian\\.")
for (line in lines) {
val result = pattern.find(line)!!
val id = result.groupValues[1].toInt()
val oreRobot = result.groupValues[2].toInt()
val clayRobot = result.groupValues[3].toInt()
val obsidianRobotOreCost = result.groupValues[4].toInt()
val obsidianRobotClayCost = result.groupValues[5].toInt()
val geodeRobotOreCost = result.groupValues[6].toInt()
val geodeRobotObsidianCost = result.groupValues[7].toInt()
val costs = listOf(
Costs(oreRobot),
Costs(clayRobot),
Costs(obsidianRobotOreCost, obsidianRobotClayCost, 0, 0),
Costs(geodeRobotOreCost, 0, geodeRobotObsidianCost)
)
blueprints.add(Blueprint(id, costs))
}
this.blueprints = blueprints
}
override fun compute(): Int {
val qualityLevels = mutableListOf<Int>()
for (blueprint in blueprints) {
qualityLevels.add(blueprint.produce(24) * blueprint.id)
}
return qualityLevels.sum()
}
override fun getExampleAnswer(): Int {
return 33
}
override fun getExampleInput(): String? {
return """
Blueprint 1: Each ore robot costs 4 ore. Each clay robot costs 2 ore. Each obsidian robot costs 3 ore and 14 clay. Each geode robot costs 2 ore and 7 obsidian.
Blueprint 2: Each ore robot costs 2 ore. Each clay robot costs 3 ore. Each obsidian robot costs 3 ore and 8 clay. Each geode robot costs 3 ore and 12 obsidian.
""".trimIndent()
}
enum class RobotType(val idx: Int) {
ORE(0), CLAY(1), OBSIDIAN(2), GEODE(3)
}
data class Costs(val ore: Int = 0, val clay: Int = 0, val obsidian: Int = 0, val geode: Int = 0) {
operator fun plus(other: Costs): Costs {
return Costs(ore + other.ore, clay + other.clay, obsidian + other.obsidian, geode + other.geode)
}
operator fun minus(other: Costs): Costs {
return Costs(ore - other.ore, clay - other.clay, obsidian - other.obsidian, geode - other.geode)
}
operator fun times(factor: Int): Costs {
return Costs(ore * factor, clay * factor, obsidian * factor, geode * factor)
}
operator fun get(type: RobotType): Int {
return when (type) {
RobotType.ORE -> ore
RobotType.CLAY -> clay
RobotType.OBSIDIAN -> obsidian
RobotType.GEODE -> geode
}
}
fun allLessEqual(other: Costs): Boolean {
return ore <= other.ore && clay <= other.clay && obsidian <= other.obsidian && geode <= other.geode
}
fun inc(type: RobotType): Costs {
return when (type) {
RobotType.ORE -> Costs(ore + 1, clay, obsidian, geode)
RobotType.CLAY -> Costs(ore, clay + 1, obsidian, geode)
RobotType.OBSIDIAN -> Costs(ore, clay, obsidian + 1, geode)
RobotType.GEODE -> Costs(ore, clay, obsidian, geode + 1)
}
}
}
data class Blueprint(val id: Int, private val costs: List<Costs>) {
private val maxRobots = costs.reduce { acc, c -> max(acc, c) }
fun produce(minutes: Int): Int {
fun nextEdges(node: Node, traversal: ShortestPaths<Node>): Sequence<Pair<Node, Int>> {
val minutesRemaining = minutes - traversal.depth
if (minutesRemaining == 1) {
return sequenceOf()
}
return sequence {
val newMaterials = node.materials + node.producing
var robotsBuild = 0
for (robotId in RobotType.entries) {
if (robotId != RobotType.GEODE && node.producing[robotId] >= maxRobots[robotId]) {
continue
}
if (costs[robotId].allLessEqual(node.materials)) {
robotsBuild += 1
val weight = if (robotId == RobotType.GEODE) 0 else minutesRemaining
yield(Pair(Node(newMaterials - costs[robotId], node.producing.inc(robotId)), weight))
}
}
if (robotsBuild < 4) {
val maxMaterials = node.materials + node.producing * minutesRemaining
var robotsBuildable = 0
for (robotId in RobotType.entries) {
if (costs[robotId].allLessEqual(maxMaterials)) {
robotsBuildable += 1
}
}
if (robotsBuildable > 0) {
yield(Pair(Node(newMaterials, node.producing), minutesRemaining))
}
}
}
}
val traversal = ShortestPaths(::nextEdges)
traversal.startFrom(Node(Costs(), Costs(1)))
for (node in traversal) {
if (traversal.depth == minutes - 1) {
return node.materials.geode + node.producing.geode
}
}
error("Should not reach")
}
private fun max(first: Costs, other: Costs): Costs {
return Costs(kotlin.math.max(first.ore, other.ore), kotlin.math.max(first.clay, other.clay), kotlin.math.max(first.obsidian, other.obsidian), kotlin.math.max(first.geode, other.geode))
}
operator fun <T>List<T>.get(type: RobotType): T {
return get(type.idx)
}
}
private data class Node(val materials: Costs, val producing: Costs)
}
class Part19B : Part19A() {
override fun compute(): Int {
val geodes = mutableListOf<Int>()
for (i in 0..<min(2, blueprints.size)) {
val blueprint = blueprints[i]
geodes.add(blueprint.produce(32))
}
return geodes.reduce(Int::times)
}
override fun getExampleAnswer(): Int {
return 3472
}
}
fun main() {
Day(2022, 19, Part19A(), Part19B())
} | 0 | Kotlin | 0 | 0 | 69a0748ed640cf80301d8d93f25fb23cc367819c | 6,913 | advent-of-code-kotlin | MIT License |
src/main/kotlin/se/brainleech/adventofcode/aoc2021/Aoc2021Day17.kt | fwangel | 435,571,075 | false | {"Kotlin": 150622} | package se.brainleech.adventofcode.aoc2021
import se.brainleech.adventofcode.compute
import se.brainleech.adventofcode.readText
import se.brainleech.adventofcode.verify
import kotlin.math.abs
import kotlin.math.sign
class Aoc2021Day17 {
companion object {
private const val debug = false
private const val PARSE_EXPRESSION = "target area: x=(-?\\d+)\\.\\.(-?\\d+), y=(-?\\d+)\\.\\.(-?\\d+)"
}
data class Area(val xAxis: IntRange, val yAxis: IntRange)
data class Trajectory(
var x: Int = 0,
var y: Int = 0,
var dx: Int = 0,
var dy: Int = 0
) {
var steps: Int = 0
var maxY: Int = Int.MIN_VALUE
fun step(): Trajectory {
x += dx
y += dy
dx += -dx.sign
dy -= 1
maxY = maxOf(maxY, y)
steps++
return this
}
fun isSuccess(targetArea: Area): Boolean = targetArea.xAxis.contains(x) && targetArea.yAxis.contains(y)
}
data class Solution(val dx: Int, val dy: Int, val maxY: Int, val steps: Int)
data class Result(
val solutions: List<Solution>,
val maxY: Int,
val minDx: Int,
val maxDx: Int,
val minDy: Int,
val maxDy: Int,
val maxSteps: Int
)
data class Probe(val targetArea: Area) {
private fun List<Solution>.asResult(): Result {
val maxY = this.maxOf { it.maxY }
val minDx = this.minOf { it.dx }
val maxDx = this.maxOf { it.dx }
val minDy = this.minOf { it.dy }
val maxDy = this.maxOf { it.dy }
val maxSteps = this.maxOf { it.steps }
if (debug) println("Found ${this.size} solution(s):\n $this")
if (debug) println(" max y = $maxY, min dx=$minDx, max dx=$maxDx, min dy=$minDy, max dy=$maxDy, max steps=$maxSteps")
return Result(this, maxY, minDx, maxDx, minDy, maxDy, maxSteps)
}
fun solve(): Result {
if (debug) println("Target area=$targetArea")
val validSolutions = mutableListOf<Solution>()
for (dx in 0..targetArea.xAxis.last) {
for (dy in -abs(targetArea.yAxis.first * 2)..abs(targetArea.yAxis.last * 2)) {
val trajectory = Trajectory(0, 0, dx, dy)
for (attempt in 1..500) {
trajectory.step()
if (trajectory.isSuccess(targetArea)) {
validSolutions.add(Solution(dx, dy, trajectory.maxY, trajectory.steps))
break
}
}
}
}
return validSolutions.asResult()
}
}
private fun IntRange.toSortedRange(): IntRange {
return minOf(this.first, this.last)..maxOf(this.first, this.last)
}
private fun String.toProbe(): Probe {
val (x1, x2, y1, y2) = Regex(PARSE_EXPRESSION).find(this)!!.destructured.toList().map { it.toInt() }
return Probe(targetArea = Area((x1..x2).toSortedRange(), (y1..y2).toSortedRange()))
}
fun part1(input: String): Int {
return input.toProbe().solve().maxY
}
fun part2(input: String): Int {
return input.toProbe().solve().solutions.size
}
}
fun main() {
val solver = Aoc2021Day17()
val prefix = "aoc2021/aoc2021day17"
val testData = readText("$prefix.test.txt")
val realData = readText("$prefix.real.txt")
verify(45, solver.part1(testData))
compute({ solver.part1(realData) }, "$prefix.part1 = ")
verify(112, solver.part2(testData))
compute({ solver.part2(realData) }, "$prefix.part2 = ")
} | 0 | Kotlin | 0 | 0 | 0bba96129354c124aa15e9041f7b5ad68adc662b | 3,716 | adventofcode | MIT License |
src/main/kotlin/day14/Day14.kt | jakubgwozdz | 571,298,326 | false | {"Kotlin": 85100} | package day14
import Stack
import execute
import readAllText
import wtf
class Cave(val abyss: Int) {
private val data: Array<BooleanArray> = Array(abyss + 2) { BooleanArray(abyss * 2 + 6) }
private val offset: Int = 500 - abyss - 3
operator fun plusAssign(point: Pair<Int, Int>) {
val (x, y) = point
data[y][x - offset] = true
}
operator fun contains(point: Pair<Int, Int>): Boolean {
val (x, y) = point
return y in data.indices && (x - offset) in data[y].indices && data[y][x - offset]
}
}
fun part1(input: String) = input
.let(::buildData)
.let(::simulate)
fun part2(input: String) = input
.let(::buildData)
.also { data ->
val bottom = data.abyss
(500 - bottom - 1..500 + bottom + 1).forEach { data += it to bottom }
}
.let(::simulate)
private fun simulate(data: Cave): Int {
val starts = Stack<Pair<Int, Int>>().apply { offer(500 to 0) }
var count = 0
var abyssHit = false
while (starts.isNotEmpty() && !abyssHit) {
var (x, y) = starts.poll()
var rest = false
while (!rest && !abyssHit) when {
y > data.abyss -> abyssHit = true
x to y + 1 !in data -> {
starts.offer(x to y)
y += 1
}
x - 1 to y + 1 !in data -> {
starts.offer(x to y)
x -= 1; y += 1
}
x + 1 to y + 1 !in data -> {
starts.offer(x to y)
x += 1; y += 1
}
else -> rest = true
}
if (!abyssHit) {
data += x to y
count++
}
}
return count
}
private fun buildData(input: String): Cave = input.lineSequence().filterNot(String::isBlank)
.map { it.split(" -> ").map { s -> s.split(",").let { (x, y) -> (x.toInt() to y.toInt()) } } }
.flatMap { it.windowed(2) }
.map { (s, e) -> s to e }
.toList()
.let { lines ->
val abyss = lines.maxOf { maxOf(it.first.second, it.second.second) } + 2
val result = Cave(abyss)
lines.forEach { (s, e) ->
val (sx, sy) = s
val (ex, ey) = e
when {
sx < ex -> (sx..ex).map { it to ey }
sx > ex -> (sx downTo ex).map { it to ey }
sy < ey -> (sy..ey).map { ex to it }
sy > ey -> (sy downTo ey).map { ex to it }
else -> wtf(s to e)
}.forEach { p -> result += p }
}
result
}
fun main() {
val input = readAllText("local/day14_input.txt")
val test = """
498,4 -> 498,6 -> 496,6
503,4 -> 502,4 -> 502,9 -> 494,9
""".trimIndent()
execute(::part1, test, 24)
execute(::part1, input, 578)
execute(::part2, test, 93)
execute(::part2, input, 24377)
}
| 0 | Kotlin | 0 | 0 | 7589942906f9f524018c130b0be8976c824c4c2a | 2,857 | advent-of-code-2022 | MIT License |
src/Day09.kt | simonbirt | 574,137,905 | false | {"Kotlin": 45762} | import kotlin.math.absoluteValue
import kotlin.math.sign
fun main() {
Day9.printSolutionIfTest(88, 36)
}
object Day9 : Day<Int, Int>(9) {
override fun part1(lines: List<String>) = solveForLength(lines, 1)
override fun part2(lines: List<String>) = solveForLength(lines, 9)
private val moves = mapOf("R" to Pair(1, 0), "L" to Pair(-1, 0), "U" to Pair(0, 1), "D" to Pair(0, -1))
private fun solveForLength(lines: List<String>, length: Int): Int {
val (head, tail) = ropeOfLength(length)
lines.map { it.split(" ") }.forEach { (direction, count) ->
repeat(count.toInt()) {
moves[direction]?.let { (x, y) -> head.move(x, y) }
}
}
return tail.countPositions()
}
private fun ropeOfLength(length: Int) = Knot().let { Pair(it, it.addLength(length))}
class Knot(private var x: Int = 0, private var y: Int = 0) {
private val positions = mutableSetOf(Pair(x, y))
private var next: Knot? = null
fun move(dx: Int, dy: Int) {
x += dx
y += dy
positions.add(Pair(x, y))
next?.follow(this)
}
private fun follow(prior: Knot) {
val xdiff = prior.x - x
val ydiff = prior.y - y
if (xdiff.absoluteValue > 1 || ydiff.absoluteValue > 1) {
move(xdiff.sign, ydiff.sign)
}
}
fun countPositions() = positions.size
fun addLength(count: Int):Knot {
return (1..count).map{ Knot() }.fold(this) { a, b -> a.next = b; b }
}
}
}
| 0 | Kotlin | 0 | 0 | 962eccac0ab5fc11c86396fc5427e9a30c7cd5fd | 1,606 | advent-of-code-2022 | Apache License 2.0 |
src/Day03.kt | mpythonite | 572,671,910 | false | {"Kotlin": 29542} | fun main() {
fun part1(input: List<String>): Int {
var score = 0
for (i in input.indices)
{
val split = input[i].length / 2
val first = input[i].subSequence(0, split).toString().asIterable()
val second = input[i].subSequence(split, input[i].length).toString().asIterable()
val dupe = first.intersect(second.toSet()).first()
score += if (dupe > 'a') {
dupe - 'a' + 1
} else {
dupe - 'A' + 27
}
}
return score
}
fun part2(input: List<String>): Int {
var index = 0
var score = 0
while (index < input.size) {
val first = input[index++].asIterable()
val second = input[index++].asIterable()
val third = input[index++].asIterable()
val dupe = first.intersect(second).intersect(third).first()
score += if (dupe > 'a') {
dupe - 'a' + 1
} else {
dupe - 'A' + 27
}
}
return score
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day03_test")
println(part1(testInput))
check(part1(testInput) == 157)
println(part2(testInput))
check(part2(testInput) == 70)
val input = readInput("Day03")
var split = input[0].length / 2
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | cac94823f41f3db4b71deb1413239f6c8878c6e4 | 1,481 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/de/dikodam/adventofcode2019/days/Day12.kt | dikodam | 225,222,616 | false | null | package de.dikodam.adventofcode2019.days
import de.dikodam.adventofcode2019.utils.*
import kotlin.math.abs
fun main() {
val (moonsInput, setupDuration) = withTimer {
day12input.split("\n")
.map { it.drop(1).dropLast(1) }
.map { line -> inputlineToCoordinates(line) }
.map { coords ->
Moon(
pos = Vector3D(
coords.first,
coords.second,
coords.third
),
vel = Vector3D(0, 0, 0)
)
}
}
// TASK 1
val (totalSystemEnergy, t1duration) = withTimer {
var moons = moonsInput
repeat(1000) {
moons = completeTimeStep(moons)
}
moons.map(Moon::energy).sum()
}
println("Task 1: total energy is $totalSystemEnergy")
// TASK 2
// determine cycle count for each coordinate dimension independently
// determine least common multiple of all three
val (cycleLength, t2duration) = withTimer {
val xCycleLength = moonsInput.determineCycleLengthBy { moon -> Pair(moon.pos.x, moon.vel.x) }
val yCycleLength = moonsInput.determineCycleLengthBy { moon -> Pair(moon.pos.y, moon.vel.y) }
val zCycleLength = moonsInput.determineCycleLengthBy { moon -> Pair(moon.pos.z, moon.vel.z) }
lcm(xCycleLength, lcm(yCycleLength, zCycleLength))
}
println("Task 2: Cycle length is $cycleLength (duration: $t2duration)")
TimingData(setupDuration, t1duration, t2duration).print()
}
private fun <T> List<Moon>.determineCycleLengthBy(selector: (Moon) -> T): Long {
var newMoonState = this
var count = 0L
do {
newMoonState = completeTimeStep(newMoonState)
count++
} while (
!compareEqualsBy(newMoonState, this, selector)
)
return count
}
private fun completeTimeStep(moons: List<Moon>) =
moons.map { moon -> moon.applyGravity(moons) }
.map { moon -> moon.move() }
private fun inputlineToCoordinates(line: String): Triple<Int, Int, Int> {
val coords = line
.split(",")
.map { coordinate ->
coordinate
.split("=")[1]
.toInt()
}
return Triple(coords[0], coords[1], coords[2])
}
data class Vector3D(val x: Int, val y: Int, val z: Int) {
operator fun plus(other: Vector3D): Vector3D =
Vector3D(
this.x + other.x,
this.y + other.y,
this.z + other.z
)
}
data class Moon(val pos: Vector3D, val vel: Vector3D) {
fun move(): Moon = this.copy(pos = pos + vel, vel = vel)
fun applyGravity(moons: Collection<Moon>): Moon {
val totalGravity = moons.map { otherMoon ->
if (otherMoon == this) {
Vector3D(0, 0, 0)
} else {
computeGravity(this.pos, otherMoon.pos)
}
}.reduce(Vector3D::plus)
return this.copy(vel = vel + totalGravity)
}
private fun potentialEnergy(): Int {
val (px, py, pz) = pos
return abs(px) + abs(py) + abs(pz)
}
private fun kineticEnergy(): Int {
val (vx, vy, vz) = vel
return abs(vx) + abs(vy) + abs(vz)
}
fun energy(): Int = potentialEnergy() * kineticEnergy()
}
private fun computeGravity(v1: Vector3D, v2: Vector3D): Vector3D =
Vector3D(
computeGravity(v1.x, v2.x),
computeGravity(v1.y, v2.y),
computeGravity(v1.z, v2.z)
)
private fun computeGravity(v1: Int, v2: Int): Int =
when {
v1 > v2 -> {
-1
}
v1 == v2 -> {
0
}
else -> 1
}
private const val day12input =
"""<x=-14, y=-4, z=-11>
<x=-9, y=6, z=-7>
<x=4, y=1, z=4>
<x=2, y=-14, z=-9>"""
| 0 | Kotlin | 0 | 0 | 6db72123172615f4ba5eb047cc2e1fc39243adc7 | 3,823 | adventofcode2019 | MIT License |
src/day8/Day8.kt | pocmo | 433,766,909 | false | {"Kotlin": 134886} | package day8
import java.io.File
fun find_one_chars(input: List<List<Char>>): List<Char> {
return input.find { it.size == 2 } ?: throw IllegalStateException("One not found")
}
fun find_four_chars(input: List<List<Char>>): List<Char> {
return input.find { it.size == 4 } ?: throw IllegalStateException("Four not found")
}
fun find_seven_chars(input: List<List<Char>>): List<Char> {
return input.find { it.size == 3 } ?: throw IllegalStateException("Seven not found")
}
fun find_eight_chars(input: List<List<Char>>): List<Char> {
return input.find { it.size == 7 } ?: throw IllegalStateException("Seven not found")
}
fun find_nine_chars(input: List<List<Char>>, four: List<Char>): List<Char> {
return input.filter { it.size == 6 }
.find { it.containsAll(four) }
?: throw IllegalStateException("Nine not found")
}
fun find_zero_chars(input: List<List<Char>>, one: List<Char>, nine: List<Char>): List<Char> {
return input
.filter { it.size == 6 }
.filter { it.containsAll(one) }
.firstOrNull() { it != nine } ?: throw IllegalStateException("Zero not found")
}
fun find_six_chars(input: List<List<Char>>, nine: List<Char>, zero: List<Char>): List<Char> {
return input
.filter { it.size == 6 }
.filter { it != nine }
.firstOrNull() { it != zero } ?: throw IllegalStateException("Six not found")
}
fun find_five_chars(input: List<List<Char>>, six: List<Char>): List<Char> {
return input
.filter { it.size == 5 }
.firstOrNull { six.containsAll(it) }?: throw IllegalStateException("Five not found")
}
fun find_three_chars(input: List<List<Char>>, seven: List<Char>): List<Char> {
return input
.filter { it.size == 5 }
.firstOrNull { it.containsAll(seven) } ?: throw IllegalStateException("Three not found")
}
fun find_two_chars(input: List<List<Char>>, threeChars: List<Char>, fiveChars: List<Char>): List<Char> {
return input
.filter { it.size == 5 }
.firstOrNull { it != threeChars && it != fiveChars } ?: throw IllegalStateException("Three not found")
}
fun findMappings(input: List<List<Char>>): Map<List<Char>, Char> {
val oneChars = find_one_chars(input).sorted()
val fourChars = find_four_chars(input).sorted()
val sevenChars = find_seven_chars(input).sorted()
val eightChars = find_eight_chars(input).sorted()
val nineChars = find_nine_chars(input, fourChars).sorted()
val zeroChars = find_zero_chars(input, oneChars, nineChars).sorted()
val sixChars = find_six_chars(input, nineChars, zeroChars).sorted()
val threeChars = find_three_chars(input, sevenChars).sorted()
val fiveChars = find_five_chars(input, sixChars).sorted()
val twoChars = find_two_chars(input, threeChars, fiveChars).sorted()
val map = mapOf(
zeroChars.sorted() to '0',
oneChars.sorted() to '1',
twoChars.sorted() to '2',
threeChars.sorted() to '3',
fourChars.sorted() to '4',
fiveChars.sorted() to '5',
sixChars.sorted() to '6',
sevenChars.sorted() to '7',
eightChars.sorted() to '8',
nineChars.sorted() to '9'
)
if (map.keys.size != 10) {
map.values.sorted().forEach {
println(it)
}
println("3 = " + map[threeChars])
throw IllegalStateException("Map size is not 10")
}
return map
}
fun translate(input: List<List<Char>>, value: List<List<Char>>): List<Char> {
val mappings = findMappings(input)
return value.map { segments ->
mappings[segments.sorted()] ?: '.'
}
}
/*
aa
b c
b c
dd
e f
e f
gg
[x] 0: 6 abcefg
[x] 1: 2 cf
[x] 2: 5 acdeg
[x] 3: 5 acdfg
[x] 4: 4 bcdf
[x] 5: 5 abdfg
[x] 6: 6 abdefg
[x] 7: 3 acf
[x] 8: 7 abcdefg
[x] 9: 6 abcdfg
[x] 1: 2 cf
[x] 7: 3 acf
[x] 4: 4 bcdf
[x] 2: 5 acdeg
[x] 3: 5 acdfg
[x] 5: 5 abdfg
[x] 6: 6 abdefg
[x] 9: 6 abcdfg
[x] 0: 6 abcefg
[x] 8: 7 abcdefg
0: 1: 2: 3: 4:
aaaa .... aaaa aaaa ....
b c . c . c . c b c
b c . c . c . c b c
.... .... dddd dddd dddd
e f . f e . . f . f
e f . f e . . f . f
gggg .... gggg gggg ....
5: 6: 7: 8: 9:
aaaa aaaa aaaa aaaa aaaa
b . b . . c b c b c
b . b . . c b c b c
dddd dddd .... dddd dddd
. f e f . f e f . f
. f e f . f e f . f
gggg gggg .... gggg gggg
*/
fun readInput(filename: String = "day8.txt"): List<Pair<List<List<Char>>, List<List<Char>>>> {
return File(filename)
.readLines()
.map { line ->
val (rawInput, rawValue) = line.split("|")
Pair(
rawInput.trim().split(" ").map { it.toCharArray().toList().sorted() },
rawValue.trim().split(" ").map { it.toCharArray().toList().sorted() },
)
}
}
fun part1() {
val inputs = readInput()
val sum = inputs.map { (input, value) ->
translate(input, value)
}.sumOf {
it.count { character -> character in listOf('1', '4', '7', '8') }
}
println("Digits: $sum")
}
fun part2() {
val inputs = readInput()
val sum = inputs.map { (input, value) ->
translate(input, value)
}.map {
it.joinToString("").toInt()
}.sum()
print(sum)
}
fun part2_debug() {
val inputs = readInput("day8_debug.txt")
inputs.map { (input, value) ->
translate(input, value)
}.forEach { translation ->
println(translation.joinToString(""))
}
}
fun main() {
part2()
} | 0 | Kotlin | 1 | 2 | 73bbb6a41229e5863e52388a19108041339a864e | 5,739 | AdventOfCode2021 | Apache License 2.0 |
src/main/kotlin/day19/Code.kt | fcolasuonno | 317,324,330 | false | null | package day19
import isDebug
import java.io.File
fun main() {
val name = if (isDebug()) "test.txt" else "input.txt"
System.err.println(name)
val dir = ::main::class.java.`package`.name
val input = File("src/main/kotlin/$dir/$name").readLines()
val parsed = parse(input)
part1(parsed)
part2(parsed)
}
private val lineStructure = """(\d+): (?:([0-9 |]+)|"([ab])")""".toRegex()
sealed class Rule {
abstract fun consumeMatch(rules: Map<Int, Rule>, string: String?): String?
data class Terminal(val char: Char) : Rule() {
override fun consumeMatch(rules: Map<Int, Rule>, string: String?) =
if (string?.firstOrNull() == char) string.substring(1) else null
}
data class Composed(val ruleSet: Set<List<Int>>) : Rule() {
override fun consumeMatch(rules: Map<Int, Rule>, string: String?) = ruleSet.mapNotNull { alternateRules ->
alternateRules.map { rules.getValue(it) }.fold(string) { acc, rule ->
acc?.let { rule.consumeMatch(rules, it) }
}
}.firstOrNull()
}
data class Nested(val startRule: Int, val endRule: Int) : Rule() {
override fun consumeMatch(rules: Map<Int, Rule>, string: String?): String? =
rules.getValue(startRule).consumeMatch(rules, string)?.let {
val end = rules.getValue(endRule)
end.consumeMatch(rules, it) ?: end.consumeMatch(rules, consumeMatch(rules, it))
}
}
}
fun parse(input: List<String>) = input.mapNotNull {
lineStructure.matchEntire(it)?.destructured?.let {
val (ruleNum, composed, terminal) = it.toList()
ruleNum.toInt() to when {
terminal.isNotEmpty() -> Rule.Terminal(terminal.single())
else -> Rule.Composed(composed.split(" | ").map {
it.split(" ").map(String::toInt)
}.toSet())
}
}
}.toMap() to input.filter { it.isNotEmpty() && !it.first().isDigit() }
fun part1(input: Pair<Map<Int, Rule>, List<String>>) {
val (rules, tests) = input
val res = tests.count { rules.getValue(0).consumeMatch(rules, it) == "" }
println("Part 1 = $res")
}
fun part2(input: Pair<Map<Int, Rule>, List<String>>) {
val (rules, tests) = input
val r8 = rules.getValue(8)
val r11 = Rule.Nested(42, 31)
val res = tests.count {
generateSequence(it) {
r8.consumeMatch(rules, it)
}.drop(1).any {
r11.consumeMatch(rules, it) == ""
}
}
println("Part 2 = $res")
} | 0 | Kotlin | 0 | 0 | e7408e9d513315ea3b48dbcd31209d3dc068462d | 2,530 | AOC2020 | MIT License |
src/Utils.kt | jwklomp | 572,195,432 | false | {"Kotlin": 65103} | import java.io.File
import java.math.BigInteger
import java.security.MessageDigest
import kotlin.math.abs
import kotlin.math.max
/**
* Extension function to get all index positions of a given element in a collection
*/
fun <E> Iterable<E>.indexesOf(e: E) = mapIndexedNotNull { index, elem -> index.takeIf { elem == e } }
/**
* Reads lines from the given input txt file.
*/
fun readInput(name: String) = File("src", "$name.txt").readLines()
/**
* Converts string to md5 hash.
*/
fun String.md5(): String = BigInteger(1, MessageDigest.getInstance("MD5").digest(toByteArray())).toString(16)
fun findIndex(haystack2D: List<List<String>>, needle: String): MutableList<Int> =
mutableListOf(-1, -1).apply {
haystack2D.forEachIndexed { i, r ->
r.forEachIndexed { j, c ->
if (c == needle) {
this[0] = j
this[1] = i
}
}
}
}
/**
* Dijkstra shortest path algorithm.
* adapted from https://github.com/SebastianAigner/advent-of-code-2021/blob/master/src/main/kotlin/Day15.kt
*/
fun dijkstraSP(
graph: List<Node<Int>>,
source: Node<Int>,
target: Node<Int>,
filterNeighborsFn: (it: Node<Int>, u: Node<Int>) -> Boolean
): ArrayDeque<Node<Int>> {
val q = mutableSetOf<Node<Int>>()
val dist = mutableMapOf<Node<Int>, Int?>()
val prev = mutableMapOf<Node<Int>, Node<Int>?>()
for (vertex in graph) {
dist[vertex] = Int.MAX_VALUE
prev[vertex] = null
q.add(vertex)
}
dist[source] = 0
while (q.isNotEmpty()) {
val u = q.minByOrNull { dist[it]!! }!!
q.remove(u)
if (u == target) break
for (v in q.filter { filterNeighborsFn(it, u) }) {
val alt = dist[u]!! + 1
if (alt < dist[v]!!) {
dist[v] = alt
prev[v] = u
}
}
}
// all found.
val s = ArrayDeque<Node<Int>>()
var u: Node<Int>? = target
if (prev[u] != null || u == source) {
while (u != null) {
s.addFirst(u)
u = prev[u]
}
}
return s
}
/**
* Extension function that is like takeWhile, yet also takes the first element not making the test.
*/
fun <T> Iterable<T>.takeWhileInclusive(
predicate: (T) -> Boolean
): List<T> {
var shouldContinue = true
return takeWhile {
val result = shouldContinue
shouldContinue = predicate(it)
result
}
}
data class Point(val x: Int, val y: Int)
fun manhattanDistance(first: Point, second: Point) = abs(first.x - second.x) + abs(first.y - second.y)
data class Interval(val from: Int, val to: Int)
fun mergeIntervals(intervals: List<Interval>) = intervals
.sortedWith(compareBy { it.from })
.fold(listOf<Interval>()) { sum, item ->
val last = sum.lastOrNull()
if (last != null && last.to >= item.from) {
val old = sum.dropLast(1)
old + Interval(from = last.from, to = max(last.to, item.to))
} else {
sum + item
}
}
inline fun <reified T> transpose(xs: List<List<T>>): List<List<T>> {
val cols = xs[0].size
val rows = xs.size
return List(cols) { j ->
List(rows) { i ->
xs[i][j]
}
}
}
| 0 | Kotlin | 0 | 0 | 1b1121cfc57bbb73ac84a2f58927ab59bf158888 | 3,291 | aoc-2022-in-kotlin | Apache License 2.0 |
src/Day03.kt | sbaumeister | 572,855,566 | false | {"Kotlin": 38905} | import java.lang.IllegalArgumentException
fun mapItemToPriority(item: Char): Int {
return when (item) {
'a' -> 1
'b' -> 2
'c' -> 3
'd' -> 4
'e' -> 5
'f' -> 6
'g' -> 7
'h' -> 8
'i' -> 9
'j' -> 10
'k' -> 11
'l' -> 12
'm' -> 13
'n' -> 14
'o' -> 15
'p' -> 16
'q' -> 17
'r' -> 18
's' -> 19
't' -> 20
'u' -> 21
'v' -> 22
'w' -> 23
'x' -> 24
'y' -> 25
'z' -> 26
'A' -> 27
'B' -> 28
'C' -> 29
'D' -> 30
'E' -> 31
'F' -> 32
'G' -> 33
'H' -> 34
'I' -> 35
'J' -> 36
'K' -> 37
'L' -> 38
'M' -> 39
'N' -> 40
'O' -> 41
'P' -> 42
'Q' -> 43
'R' -> 44
'S' -> 45
'T' -> 46
'U' -> 47
'V' -> 48
'W' -> 49
'X' -> 50
'Y' -> 51
'Z' -> 52
else -> throw IllegalArgumentException()
}
}
fun main() {
fun part1(input: List<String>): Int {
var sum = 0
input.forEach nextRucksack@{ itemStr ->
val items = itemStr.toCharArray()
val firstCompartment = items.take(items.size / 2)
val secondCompartment = items.takeLast(items.size / 2)
firstCompartment.forEach { item ->
val matchedItem = secondCompartment.firstOrNull { item == it }
if (matchedItem != null) {
sum += mapItemToPriority(matchedItem)
return@nextRucksack
}
}
}
return sum
}
fun part2(input: List<String>): Int {
var sum = 0
val groupCount = input.size / 3
(1..groupCount).forEach nextGroup@{ i ->
val startIdx = (i - 1) * 3
val endIdx = (i * 3) - 1
val (firstRucksack, secondRucksack, thirdRucksack) = input.slice(startIdx..endIdx)
val secondRucksackItems = secondRucksack.toCharArray()
val thirdRucksackItems = thirdRucksack.toCharArray()
val firstRucksackItems = firstRucksack.toCharArray()
firstRucksackItems.forEach { item ->
val matchedItem = secondRucksackItems.firstOrNull { item == it }
if (matchedItem != null) {
if (thirdRucksackItems.firstOrNull { item == it } != null) {
sum += mapItemToPriority(matchedItem)
return@nextGroup
}
}
}
}
return sum
}
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 | e3afbe3f4c2dc9ece1da7cf176ae0f8dce872a84 | 2,896 | advent-of-code-2022 | Apache License 2.0 |
src/leetcodeProblem/leetcode/editor/en/MergeSortedArray.kt | faniabdullah | 382,893,751 | false | null | //You are given two integer arrays nums1 and nums2, sorted in non-decreasing
//order, and two integers m and n, representing the number of elements in nums1 and
//nums2 respectively.
//
// Merge nums1 and nums2 into a single array sorted in non-decreasing order.
//
// The final sorted array should not be returned by the function, but instead
//be stored inside the array nums1. To accommodate this, nums1 has a length of m +
//n, where the first m elements denote the elements that should be merged, and the
//last n elements are set to 0 and should be ignored. nums2 has a length of n.
//
//
// Example 1:
//
//
//Input: nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3
//Output: [1,2,2,3,5,6]
//Explanation: The arrays we are merging are [1,2,3] and [2,5,6].
//The result of the merge is [1,2,2,3,5,6] with the underlined elements coming
//from nums1.
//
//
// Example 2:
//
//
//Input: nums1 = [1], m = 1, nums2 = [], n = 0
//Output: [1]
//Explanation: The arrays we are merging are [1] and [].
//The result of the merge is [1].
//
//
// Example 3:
//
//
//Input: nums1 = [0], m = 0, nums2 = [1], n = 1
//Output: [1]
//Explanation: The arrays we are merging are [] and [1].
//The result of the merge is [1].
//Note that because m = 0, there are no elements in nums1. The 0 is only there
//to ensure the merge result can fit in nums1.
//
//
//
// Constraints:
//
//
// nums1.length == m + n
// nums2.length == n
// 0 <= m, n <= 200
// 1 <= m + n <= 200
// -10⁹ <= nums1[i], nums2[j] <= 10⁹
//
//
//
// Follow up: Can you come up with an algorithm that runs in O(m + n) time?
// Related Topics Array Two Pointers Sorting 👍 1680 👎 183
package leetcodeProblem.leetcode.editor.en
class MergeSortedArray {
fun solution() {
}
//below code will be used for submission to leetcode (using plugin of course)
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
fun merge(nums1: IntArray, m: Int, nums2: IntArray, n: Int): Unit {
var indexM = m - 1
var indexN = n - 1
var insertPosition = nums1.size - 1
while (insertPosition >= 0 && indexN >= 0) {
val v1 = nums1.getOrNull(indexM)
val v2 = nums2.getOrNull(indexN)
if (v1 != null && v2 != null && v1 > v2) {
nums1[insertPosition] = v1
indexM--
} else {
nums1[insertPosition] = v2!!
indexN--
}
insertPosition--
}
}
}
//leetcode submit region end(Prohibit modification and deletion)
}
fun main() {
MergeSortedArray.Solution().merge(
intArrayOf(9, 8, 0, 0, 0, 0),
2,
intArrayOf(2, 5, 6, 10),
4
)
}
| 0 | Kotlin | 0 | 6 | ecf14fe132824e944818fda1123f1c7796c30532 | 2,839 | dsa-kotlin | MIT License |
2022/src/Day12.kt | Saydemr | 573,086,273 | false | {"Kotlin": 35583, "Python": 3913} | package src
import kotlin.Double.Companion.POSITIVE_INFINITY
import kotlin.math.min
fun main() {
val mountain = readInput("input12")
.map { it.trim().split("") }
.map { it.filter { it2 -> it2 != "" } }
.map { it.map { it2 -> it2.first() }.toMutableList() }
.toMutableList()
val reach = MutableList(mountain.size) { MutableList(mountain[0].size) { POSITIVE_INFINITY } }
val firstDim = mountain.flatten().indexOf('S') / mountain[0].size
val secondDim = mountain.flatten().indexOf('S') % mountain[0].size
mountain[firstDim][secondDim] = 'a'
println(firstDim)
println(secondDim)
val endX = mountain.flatten().indexOf('E') / mountain[0].size
val endY = mountain.flatten().indexOf('E') % mountain[0].size
mountain[endX][endY] = 'z'
val directions = listOf(Pair(1,0), Pair(-1,0), Pair(0,1), Pair(0,-1))
fun notNeedGear(pos1: Pair<Int,Int>, pos2: Pair<Int,Int>): Boolean {
if (pos2.first < 0 || pos2.first >= mountain.size || pos2.second < 0 || pos2.second >= mountain[0].size)
return false
val first = mountain[pos1.first][pos1.second]
val second = mountain[pos2.first][pos2.second]
return when {
second - first < 2 -> true
else -> false
}
}
val visitedNodes = mutableSetOf<Pair<Int,Int>>()
visitedNodes.add(Pair(firstDim, secondDim))
reach[firstDim][secondDim] = 0.0
// part 2
visitedNodes.addAll(mountain.mapIndexed { index, list ->
list.mapIndexed { index2, c ->
if (c == 'a') {
reach[index][index2] = 0.0;
listOf(Pair(index, index2))
}
else
listOf()
}
}.flatten().flatten())
fun move() {
val nextNodes = mutableSetOf<Pair<Int,Int>>()
for (node in visitedNodes) {
for (direction in directions) {
if (!visitedNodes.contains(Pair(node.first + direction.first, node.second + direction.second)) && notNeedGear(node, Pair(node.first + direction.first, node.second + direction.second))) {
nextNodes.add(Pair(node.first + direction.first, node.second + direction.second))
reach[node.first + direction.first][node.second + direction.second] = min(reach[node.first][node.second] + 1, reach[node.first + direction.first][node.second + direction.second])
if (reach[endX][endY] != POSITIVE_INFINITY)
return
}
}
}
if (nextNodes.isNotEmpty()) {
visitedNodes.addAll(nextNodes)
move()
}
}
move()
println(reach[endX][endY])
} | 0 | Kotlin | 0 | 1 | 25b287d90d70951093391e7dcd148ab5174a6fbc | 2,726 | AoC | Apache License 2.0 |
src/day12/first/Solution.kt | verwoerd | 224,986,977 | false | null | package day12.first
import tools.timeSolution
import java.util.stream.Collectors
import kotlin.math.abs
const val STEPS = 1000
fun main() = timeSolution {
var scan = readPlanetCoordinates()
for (step in 1..STEPS) {
scan = scan.map { (location, velocity) ->
val newVelocity = scan.fold(velocity) { (x, y, z), (nextLocation) ->
PlanetCoordinate(
x + applyGravity(location.x, nextLocation.x),
y + applyGravity(location.y, nextLocation.y),
z + applyGravity(location.z, nextLocation.z)
)
}
applyVelocity(location, newVelocity) to newVelocity
}.toMutableList()
// scan.printReport(step)
}
println(scan.map { (location, velocity) -> location.potentialEnergy() * velocity.potentialEnergy() }.sum())
}
data class PlanetCoordinate(var x: Int, var y: Int, var z: Int) {
fun potentialEnergy() = abs(x) + abs(y) + abs(z)
}
val regex = Regex("<x=(-?\\w+), y=(-?\\w+), z=(-?\\w+)>")
fun readPlanetCoordinates(): MutableList<Pair<PlanetCoordinate, PlanetCoordinate>> =
System.`in`.bufferedReader().lines().map { regex.find(it)!!.groups }.map {
PlanetCoordinate(
it[1]!!.value.toInt(),
it[2]!!.value.toInt(),
it[3]!!.value.toInt()
) to PlanetCoordinate(0, 0, 0)
}.collect(Collectors.toList())
fun applyGravity(base: Int, other: Int) = when {
other > base -> 1
other == base -> 0
other < base -> -1
else -> throw IllegalArgumentException("$base $other")
}
fun applyVelocity(location: PlanetCoordinate, velocity: PlanetCoordinate) =
PlanetCoordinate(location.x + velocity.x, location.y + velocity.y, location.z + velocity.z)
fun MutableList<Pair<PlanetCoordinate, PlanetCoordinate>>.printReport(step: Number) {
println("after $step steps")
this.forEach { (location, velocity) -> println("pos=<x=${location.x}, y=${location.y}, z=${location.z}>, vel=<x=${velocity.x}, y=${velocity.y}, z=${velocity.z}>") }
}
| 0 | Kotlin | 0 | 0 | 554377cc4cf56cdb770ba0b49ddcf2c991d5d0b7 | 1,958 | AoC2019 | MIT License |
src/Day13.kt | fercarcedo | 573,142,185 | false | {"Kotlin": 60181} | import com.beust.klaxon.Klaxon
private val FIRST_DIVIDER = listOf(listOf(2))
private val SECOND_DIVIDER = listOf(listOf(6))
fun <T> MutableList<T>.swap(from: Int, to: Int) {
val temp = this[from]
this[from] = this[to]
this[to] = temp
}
fun main() {
fun inRightOrder(left: Any, right: Any, index: Int, resultsMap: MutableMap<Int, Boolean>) {
if (left is Int && right is Int) {
if (left < right) {
resultsMap.putIfAbsent(index, true)
}
if (left > right) {
resultsMap.putIfAbsent(index, false)
}
} else if (left is List<*> && right is List<*>) {
for (i in 0 until maxOf(left.size, right.size)) {
if (i >= left.size) {
resultsMap.putIfAbsent(index, true)
}
if (i >= right.size) {
resultsMap.putIfAbsent(index, false)
}
if (index !in resultsMap) {
inRightOrder(left[i]!!, right[i]!!, index, resultsMap)
}
}
} else if (left is Int) {
inRightOrder(listOf(left), right, index, resultsMap)
} else {
inRightOrder(left, listOf(right), index, resultsMap)
}
}
fun parsePackets(input: List<String>) = input.filter { it.isNotBlank() }
.map { Klaxon().parseArray<Any>(it)!! }
.toMutableList()
fun part1(input: List<String>): Int {
val pairs = parsePackets(input).chunked(2)
val resultsMap = mutableMapOf<Int, Boolean>()
for ((pairIndex, pair) in pairs.withIndex()) {
inRightOrder(pair[0], pair[1], pairIndex, resultsMap)
}
return resultsMap.filterValues { it }
.map { it.key + 1 }
.sum()
}
fun bubbleSort(packets: MutableList<List<Any>>) {
for (i in 0 until packets.size - 1) {
for (j in 0 until packets.size - i - 1) {
val resultsMap = mutableMapOf<Int, Boolean>()
inRightOrder(packets[j], packets[j + 1], 0, resultsMap)
if (!resultsMap[0]!!) {
packets.swap(j, j + 1)
}
}
}
}
fun part2(input: List<String>): Int {
val packets = parsePackets(input)
packets.add(FIRST_DIVIDER)
packets.add(SECOND_DIVIDER)
bubbleSort(packets)
return (packets.indexOf(FIRST_DIVIDER) + 1) * (packets.indexOf(SECOND_DIVIDER) + 1)
}
val testInput = readInput("Day13_test")
check(part1(testInput) == 13)
check(part2(testInput) == 140)
val input = readInput("Day13")
println(part1(input)) // 6101
println(part2(input)) // 21909
} | 0 | Kotlin | 0 | 0 | e34bc66389cd8f261ef4f1e2b7f7b664fa13f778 | 2,755 | Advent-of-Code-2022-Kotlin | Apache License 2.0 |
src/Day05.kt | alexdesi | 575,352,526 | false | {"Kotlin": 9824} | import java.io.File
fun main() {
val regex = """\s*\[(\w)\]\s*""".toRegex()
fun getStacks(input: List<String>): MutableList<MutableList<Char>> {
val stackSize = (input.first().length + 1) / 4
val stacks: MutableList<MutableList<Char>> = mutableListOf()
repeat(stackSize) {
stacks.add(mutableListOf())
}
val stackLines = input
.dropLastWhile { !it.startsWith(" 1") }
.dropLast(1)
val stackChars = stackLines.map {
it.chunked(4).map { markInBrackets ->
val mark = regex.find(markInBrackets)
if (mark != null)
mark.groupValues[1].first()// .first is to convert string to char
else
null
}
}.reversed()
stackChars.forEach { marksLine ->
marksLine.forEachIndexed { i, mark ->
if (mark != null) stacks[i].add(mark)
}
}
return stacks
}
fun getMoves(input: List<String>): List<List<Int>> {
// count, source, destination
val regex = """\D+(\d+)\D+(\d+)\D+(\d+)""".toRegex()
val moves = input
.dropWhile { !it.startsWith("move") }
.map {
regex.find(it)!!
.groupValues
.drop(1).map {
it.toInt()
}
}
return moves
}
fun part1(input: List<String>): String {
val stacks = getStacks(input)
val moves = getMoves(input)
moves.forEach { (count, source, destination) ->
println("count: $count, source:$source, destination:$destination")
repeat(count) {
println(it)
val el = stacks[source - 1].removeLast()
stacks[destination - 1].add(el)
}
}
return stacks.map {
it.last()
}.joinToString("")
}
fun part2(input: List<String>): String {
val stacks = getStacks(input)
val moves = getMoves(input)
moves.forEach { (count, source, destination) ->
val cratesToMove = stacks[source - 1].takeLast(count)
cratesToMove.forEach { stacks[destination - 1].add(it) }
repeat(count) { stacks[source - 1].removeLast() }
}
return stacks.map {
it.last()
}.joinToString("")
}
// Test if implementation meets criteria from the description:
val testInput = readInput("Day05_test")
check(part1(testInput) == "CMZ")
check(part2(testInput) == "MCD")
val input = readInput("Day05")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 56a6345e0e005da09cb5e2c7f67c49f1379c720d | 2,736 | advent-of-code-kotlin | Apache License 2.0 |
src/main/kotlin/com/jackchapman/codingchallenges/hackerrank/QueensAttack.kt | crepppy | 381,882,392 | false | null | package com.jackchapman.codingchallenges.hackerrank
import kotlin.math.abs
/**
* Problem: [Queen's Attack II](https://www.hackerrank.com/challenges/queens-attack-2/)
*
* Given a chess board and a list of obstacles, find the number of valid moves a queen can make
* @param size The size of the chess board
* @param k The number of obstacles on the board
* @param obstacles An array of obstacles represented as an array of two integers (it's y and x coordinate)
* @return The number of valid moves a queen could make
*/
fun queensAttack(size: Int, k: Int, y: Int, x: Int, obstacles: Array<IntArray>): Int {
val closest = obstacles.asSequence()
.filter { it[0] == y || it[1] == x || abs(it[0] - y) == abs(it[1] - x) }
.groupBy { (if (it[0] > y) 1 else if (it[0] < y) 2 else 0) or (if (it[1] > x) 4 else if (it[1] < x) 8 else 0) }
.mapValues { (dir, arr) ->
when {
dir and 1 != 0 -> arr.minByOrNull { it[0] }!!
dir and 2 != 0 -> arr.maxByOrNull { it[0] }!!
dir and 4 != 0 -> arr.minByOrNull { it[1] }!!
dir and 8 != 0 -> arr.maxByOrNull { it[1] }!!
else -> throw IllegalStateException()
}
}
return arrayOf(1, 2, 4, 5, 6, 8, 9, 10).sumOf {
val obstacle = closest[it] ?: return@sumOf minOf(
if (it and 1 != 0) size - y else Int.MAX_VALUE,
if (it and 2 != 0) y - 1 else Int.MAX_VALUE,
if (it and 4 != 0) size - x else Int.MAX_VALUE,
if (it and 8 != 0) x - 1 else Int.MAX_VALUE,
)
maxOf(abs(obstacle[0] - y), abs(obstacle[1] - x)) - 1
}
} | 0 | Kotlin | 0 | 0 | 9bcfed84a9850c3977ccff229948cc31e319da1b | 1,661 | coding-challenges | The Unlicense |
src/Day02/Day02.kt | G-lalonde | 574,649,075 | false | {"Kotlin": 39626} | package Day02
import readInput
fun main() {
fun part1(input: List<String>): Int {
val shapePoints: HashMap<Char, Int> = hashMapOf(
'A' to 1, // Rock
'B' to 2, // Paper
'C' to 3, // Scissors
'X' to 1, // Rock
'Y' to 2, // Paper
'Z' to 3, // Scissors
)
fun draw(me: Char, over: Char): Boolean {
return when {
me == 'X' && over == 'A' -> true
me == 'Y' && over == 'B' -> true
me == 'Z' && over == 'C' -> true
else -> false
}
}
fun win(me: Char, over: Char): Boolean {
return when {
me == over -> false
me == 'X' && over == 'C' -> true
me == 'Y' && over == 'A' -> true
me == 'Z' && over == 'B' -> true
else -> false
}
}
fun score(other: Char, me: Char): Int {
return when {
draw(me, other) -> 3 + shapePoints[me]!! // draw
win(me, other) -> 6 + shapePoints[me]!! // win
else -> 0 + shapePoints[me]!! // lose
}
}
var score = 0
for (line: String in input) {
if (line.isEmpty()) {
continue
}
val (other, me) = line.split(" ")
score += score(other[0], me[0])
}
return score
}
fun part2(input: List<String>): Int {
val shapePoints: HashMap<Char, Int> = hashMapOf(
'A' to 1, // Rock
'B' to 2, // Paper
'C' to 3, // Scissors
)
val resultPoints: HashMap<Char, Int> = hashMapOf(
'Z' to 6, // win
'Y' to 3, // draw
'X' to 0, // lose
)
val winAgainst: HashMap<Char, Char> = hashMapOf(
'A' to 'B', // Rock
'B' to 'C', // Paper
'C' to 'A', // Scissors
)
val loseAgainst: HashMap<Char, Char> = hashMapOf(
'A' to 'C', // Rock
'B' to 'A', // Paper
'C' to 'B', // Scissors
)
fun shapeToChoose(instruction: Char, over: Char): Char {
return when (instruction) {
'X' -> loseAgainst[over]!! // lose
'Y' -> over // draw
'Z' -> winAgainst[over]!! // win
else -> 'A'
}
}
fun score(other: Char, instruction: Char): Int {
val myShape = shapeToChoose(instruction, other)
val result = resultPoints[instruction]!!
val shape = shapePoints[myShape]!!
return result + shape
}
var score = 0
for (line: String in input) {
if (line.isEmpty()) {
continue
}
val (other, me) = line.split(" ")
score += score(other[0], me[0])
}
return score
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day02/Day02_test")
check(part1(testInput) == 15) { "Got instead : ${part1(testInput)}" }
check(part2(testInput) == 12) { "Got instead : ${part2(testInput)}" }
val input = readInput("Day02/Day02")
println("Answer for part 1 : ${part1(input)}")
println("Answer for part 2 : ${part2(input)}")
}
| 0 | Kotlin | 0 | 0 | 3463c3228471e7fc08dbe6f89af33199da1ceac9 | 3,421 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/aoc/year2021/Day04.kt | SackCastellon | 573,157,155 | false | {"Kotlin": 62581} | package aoc.year2021
import aoc.Puzzle
/**
* [Day 4 - Advent of Code 2021](https://adventofcode.com/2021/day/4)
*/
object Day04 : Puzzle<Int, Int> {
override fun solvePartOne(input: String): Int {
val split = input.split(Regex("(\\r?\\n){2}"))
val boards = split.drop(1)
.map { it.split(Regex("\\s")).mapNotNull(String::toIntOrNull).associateWithTo(linkedMapOf()) { false } }
split.first().splitToSequence(",").map(String::toInt).forEach { n ->
for (b in boards) {
b.computeIfPresent(n) { _, _ -> true } ?: continue
val values = b.values.toList()
if (values.windowed(5, 5).any { row -> row.all { it } } ||
(0 until 5).any { col -> (0 until 5).all { row -> values[col + (row * 5)] } }) {
return b.filterValues { !it }.keys.sum() * n
}
}
}
throw IllegalStateException()
}
override fun solvePartTwo(input: String): Int {
val split = input.split(Regex("(\\r?\\n){2}"))
val boards = split.drop(1)
.map { it.split(Regex("\\s")).mapNotNull(String::toIntOrNull).associateWithTo(linkedMapOf()) { false } }
.toMutableList()
split.first().splitToSequence(",").map(String::toInt).forEach { n ->
val iter = boards.listIterator()
while (iter.hasNext()) {
val b = iter.next()
b.computeIfPresent(n) { _, _ -> true } ?: continue
val values = b.values.toList()
if (values.windowed(5, 5).any { row -> row.all { it } } ||
(0 until 5).any { col -> (0 until 5).all { row -> values[col + (row * 5)] } }) {
if (boards.size == 1) return b.filterValues { !it }.keys.sum() * n
iter.remove()
}
}
}
throw IllegalStateException()
}
}
| 0 | Kotlin | 0 | 0 | 75b0430f14d62bb99c7251a642db61f3c6874a9e | 1,950 | advent-of-code | Apache License 2.0 |
src/Day07.kt | SnyderConsulting | 573,040,913 | false | {"Kotlin": 46459} | fun main() {
fun part1(input: List<String>): Int {
val fileSystem = AOCFileSystem()
fillFileSystem(input, fileSystem)
val nestedDirectories = getNestedDirectories(fileSystem)
return nestedDirectories.map { it.getSize() }.filter { it < 100000 }.sum()
}
fun part2(input: List<String>): Int {
val fileSystem = AOCFileSystem()
fillFileSystem(input, fileSystem)
val nestedDirectories = getNestedDirectories(fileSystem).map { it.getSize() }.sorted()
val systemSpace = 70 * 1000 * 1000
val availableSpaceRequired = 30 * 1000 * 1000
val usedSpace = nestedDirectories.last()
val availableSpace = systemSpace - usedSpace
val amountToFree = availableSpaceRequired - availableSpace
return nestedDirectories.first { it >= amountToFree }
}
val input = readInput("Day07")
println(part1(input))
println(part2(input))
}
fun getNestedDirectories(fileSystem: AOCFileSystem): List<AOCDirectory> {
val directories = mutableListOf(fileSystem.root)
fun checkFolderChildren(directory: AOCDirectory) {
directories.addAll(directory.subDirectories)
if (directory.subDirectories.isNotEmpty()) {
directory.subDirectories.forEach { subDirectory ->
checkFolderChildren(subDirectory)
}
}
}
checkFolderChildren(fileSystem.root)
return directories
}
fun fillFileSystem(input: List<String>, fileSystem: AOCFileSystem) {
input.forEach {
when {
it.contains("$ cd ") -> {
fileSystem.changeDirectory(it.removePrefix("$ cd "))
}
it.contains("$ ") -> {}
else -> {
if (it.contains("dir")) {
fileSystem.addDirectory(it.removePrefix("dir "))
} else {
val (size, name) = it.split(" ")
fileSystem.addFile(AOCFile(name, size.toInt()))
}
}
}
}
}
class AOCFileSystem {
val root = AOCDirectory("/", null)
var currentDirectory = root
fun addFile(file: AOCFile) {
currentDirectory.files.add(file)
}
fun addDirectory(directoryName: String) {
currentDirectory.subDirectories.add(AOCDirectory(path = directoryName, parent = currentDirectory))
}
fun changeDirectory(path: String) {
currentDirectory = when (path) {
".." -> { currentDirectory.parent!! }
"/" -> { root }
else -> { currentDirectory.subDirectories.find { it.path == path }!! }
}
}
}
data class AOCDirectory(
val path: String,
val parent: AOCDirectory?,
val files: MutableList<AOCFile> = mutableListOf(),
val subDirectories: MutableList<AOCDirectory> = mutableListOf()
) {
private fun getSize(currentDirectory: AOCDirectory): Int {
val fileSizes = currentDirectory.files.sumOf { it.size }
if (currentDirectory.subDirectories.isEmpty()) {
return fileSizes
}
return fileSizes + currentDirectory.subDirectories.sumOf {
getSize(it)
}
}
fun getSize(): Int = getSize(this)
}
data class AOCFile(val name: String, val size: Int) | 0 | Kotlin | 0 | 0 | ee8806b1b4916fe0b3d576b37269c7e76712a921 | 3,268 | Advent-Of-Code-2022 | Apache License 2.0 |
src/main/kotlin/dev/paulshields/aoc/day7/HandyHaversacks.kt | Pkshields | 318,658,287 | false | null | package dev.paulshields.aoc.day7
import dev.paulshields.aoc.common.readFileAsStringList
val bagRuleRegex = Regex("(.+?) bags? contain (.+)")
val captureInnerBagDetailsRegex = Regex("(\\d) (.+?) bags?")
fun main() {
println(" ** Day 7: Handy Haversacks ** \n")
val input = readFileAsStringList("/day7/BagRules.txt")
val bagRules = parseBagRules(input)
val bagsThatCanHoldShinyGoldBag = findBagsThatCanHold("shiny gold", bagRules)
println("There are ${bagsThatCanHoldShinyGoldBag.size} bag colors that can hold a shiny gold bag!")
val numberOfBagsWithinShinyGoldBag = countBagsRequiredToBeContainedInsideBag("shiny gold", bagRules)
println("There are $numberOfBagsWithinShinyGoldBag bags within a shiny gold bag!")
}
fun parseBagRules(rawRules: List<String>) = rawRules
.filter { !it.contains("no other bags") }
.mapNotNull(::parseSingleBagRule)
private fun parseSingleBagRule(rawRule: String) = bagRuleRegex
.find(rawRule)
?.let { bagRuleMatch ->
val innerBags = captureInnerBagDetailsRegex
.findAll(bagRuleMatch.groupValues[2])
.map { BagRuleDetails(it.groupValues[2], it.groupValues[1].toInt()) }
.toList()
BagRule(bagRuleMatch.groupValues[1], innerBags)
}
fun findBagsThatCanHold(bag: String, bagRules: List<BagRule>): Set<BagRule> {
val outerBagsThatCanHoldRequestedBag = bagRules
.filter { bagRule -> bagRule.innerBags.any { it.bagColor == bag } }
.toSet()
val bagsThatCanHoldOuterBags = outerBagsThatCanHoldRequestedBag
.flatMap { findBagsThatCanHold(it.outerBag, bagRules) }
return outerBagsThatCanHoldRequestedBag.union(bagsThatCanHoldOuterBags)
}
fun countBagsRequiredToBeContainedInsideBag(bag: String, bagRules: List<BagRule>): Int = bagRules
.firstOrNull { it.outerBag.contains(bag) }
?.let { bagRule ->
val numberOfNestedBags = bagRule
.innerBags
.sumOf { countBagsRequiredToBeContainedInsideBag(it.bagColor, bagRules) * it.count }
numberOfNestedBags + bagRule.innerBags.sumBy { it.count }
} ?: 0
data class BagRule(val outerBag: String, val innerBags: List<BagRuleDetails>)
data class BagRuleDetails(val bagColor: String, val count: Int) | 0 | Kotlin | 0 | 0 | a7bd42ee17fed44766cfdeb04d41459becd95803 | 2,254 | AdventOfCode2020 | MIT License |
src/main/kotlin/_2022/Day12.kt | novikmisha | 572,840,526 | false | {"Kotlin": 145780} | package _2022
import readInput
fun main() {
fun getChar(input: List<String>, vertex: Pair<Int, Int>): Char {
var first = input[vertex.first][vertex.second]
if (first == 'S') {
first = 'a'
} else if (first == 'E') {
first = 'z'
}
return first
}
fun isValidVertex(currentVertex: Pair<Int, Int>, vertex: Pair<Int, Int>, input: List<String>): Boolean {
val maxRow = input.size
val maxColumn = input.first().length
if (vertex.first in (0 until maxRow)
&& vertex.second in (0 until maxColumn)
) {
val first = getChar(input, currentVertex)
val second = getChar(input, vertex)
return first - second >= -1
}
return false
}
fun part1(input: List<String>): Int {
var start = Pair(0, 0)
var end = Pair(0, 0)
input.forEachIndexed { rowIndex, row ->
row.forEachIndexed { columnIndex, char ->
if (char == 'E') {
end = Pair(rowIndex, columnIndex)
} else if (char == 'S') {
start = Pair(rowIndex, columnIndex)
}
}
}
val queue = mutableListOf(start)
val distanceMap = mutableMapOf(start to 0)
while (queue.isNotEmpty()) {
val currentVertex = queue.removeFirst()
val vertexesToVisit = listOf(
Pair(currentVertex.first + 1, currentVertex.second),
Pair(currentVertex.first - 1, currentVertex.second),
Pair(currentVertex.first, currentVertex.second + 1),
Pair(currentVertex.first, currentVertex.second - 1),
)
val validVertexes = vertexesToVisit.filter { isValidVertex(currentVertex, it, input) }
for (vertex in validVertexes) {
val currentDistance = distanceMap.getOrDefault(vertex, Int.MAX_VALUE)
val newDistance = distanceMap[currentVertex]!! + 1
if (newDistance < currentDistance) {
distanceMap[vertex] = newDistance
queue.remove(vertex)
queue.add(vertex)
queue.sortBy { distanceMap[it]!! }
}
}
}
return distanceMap.getOrDefault(end, Int.MAX_VALUE)
}
fun part2(input: List<String>): Int {
val starts = mutableListOf<Pair<Int, Int>>()
var end = Pair(0, 0)
input.forEachIndexed { rowIndex, row ->
row.forEachIndexed { columnIndex, char ->
if (char == 'E') {
end = Pair(rowIndex, columnIndex)
} else if (char == 'S' || char == 'a') {
starts.add(Pair(rowIndex, columnIndex))
}
}
}
val distances = mutableListOf<Int>()
for (start in starts) {
val queue = mutableListOf(start)
val distanceMap = mutableMapOf(start to 0)
while (queue.isNotEmpty()) {
val currentVertex = queue.removeFirst()
val vertexesToVisit = listOf(
Pair(currentVertex.first + 1, currentVertex.second),
Pair(currentVertex.first - 1, currentVertex.second),
Pair(currentVertex.first, currentVertex.second + 1),
Pair(currentVertex.first, currentVertex.second - 1),
)
val validVertexes = vertexesToVisit.filter { isValidVertex(currentVertex, it, input) }
for (vertex in validVertexes) {
val currentDistance = distanceMap.getOrDefault(vertex, Int.MAX_VALUE)
val newDistance = distanceMap[currentVertex]!! + 1
if (newDistance < currentDistance) {
distanceMap[vertex] = newDistance
queue.remove(vertex)
queue.add(vertex)
queue.sortBy { distanceMap[it]!! }
}
}
}
distances.add(distanceMap.getOrDefault(end, Int.MAX_VALUE))
}
return distances.min()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day12_test")
println(part1(testInput))
println(part2(testInput))
val input = readInput("Day12")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 0c78596d46f3a8bf977bf356019ea9940ee04c88 | 4,518 | advent-of-code | Apache License 2.0 |
2020/src/main/kotlin/sh/weller/adventofcode/twentytwenty/Day19Part2.kt | Guruth | 328,467,380 | false | {"Kotlin": 188298, "Rust": 13289, "Elixir": 1833} | package sh.weller.adventofcode.twentytwenty
fun List<String>.day19Part2(): Int {
val ruleMap = this.filter { it.contains(":") }
.associate { rule -> rule.split(":").let { it.first().trim() to it.last().trim() } }
.toMutableMap()
val messages = this.filter { it.contains(":").not() }.filter { it.isNotBlank() }
val rule42 = ruleMap.toRuleList("42")
val rule31 = ruleMap.toRuleList("31")
val chunkSize = rule42.first().length
return messages
.map { it.chunked(chunkSize) }
.count {
if (
rule31.matchesAll(it.takeLast(1)) &&
rule42.matchesAll(it.dropLast(1).takeLast(1)) &&
rule42.matchesAll(it.dropLast(2))
) {
return@count true
} else if (
rule31.matchesAll(it.takeLast(2)) &&
rule42.matchesAll(it.dropLast(2).takeLast(2)) &&
rule42.matchesAll(it.dropLast(4))
) {
return@count true
} else if (
rule31.matchesAll(it.takeLast(3)) &&
rule42.matchesAll(it.dropLast(3).takeLast(3)) &&
rule42.matchesAll(it.dropLast(6))
) {
return@count true
} else if (
rule31.matchesAll(it.takeLast(4)) &&
rule42.matchesAll(it.dropLast(4).takeLast(4)) &&
rule42.matchesAll(it.dropLast(8))
) {
return@count true
} else if (
rule31.matchesAll(it.takeLast(5)) &&
rule42.matchesAll(it.dropLast(5).takeLast(5)) &&
rule42.matchesAll(it.dropLast(10))
) {
return@count true
} else if (
rule31.matchesAll(it.takeLast(6)) &&
rule42.matchesAll(it.dropLast(6).takeLast(6)) &&
rule42.matchesAll(it.dropLast(12))
) {
return@count true
}
return@count false
}
}
private fun List<String>.matchesAll(messageChunks: List<String>): Boolean =
if (messageChunks.isEmpty()) {
false
} else {
messageChunks.all { this.matches(it) }
}
private fun List<String>.matches(messageChunk: String): Boolean =
this.contains(messageChunk)
private fun Map<String, String>.toRuleList(index: String): List<String> {
val ruleToBuild = this[index]
when {
ruleToBuild == null -> throw IllegalArgumentException("Rule does not exist")
ruleToBuild.contains("\"") -> {
return listOf(ruleToBuild.replace("\"", "").trim())
}
ruleToBuild.contains("|") -> {
return ruleToBuild.split("|")
.map { orRule ->
orRule
.trim()
.split(" ").filter { it.isNotBlank() }
.map { this.toRuleList(it) }
.combineRules()
}
.flatten()
}
else -> {
return ruleToBuild
.split(" ").filter { it.isNotBlank() }
.map { this.toRuleList(it) }
.combineRules()
}
}
}
private fun List<List<String>>.combineRules(): List<String> {
var combinations = this.first()
this.drop(1).forEach { ruleToCombine ->
val tmpCombinations = mutableListOf<String>()
ruleToCombine.forEach { subRule ->
combinations.forEach { combination ->
tmpCombinations.add(combination + subRule)
}
}
combinations = tmpCombinations
}
return combinations
}
| 0 | Kotlin | 0 | 0 | 69ac07025ce520cdf285b0faa5131ee5962bd69b | 3,680 | AdventOfCode | MIT License |
src/main/kotlin/aoc2020/day04_passport_processing/PassportProcessing.kt | barneyb | 425,532,798 | false | {"Kotlin": 238776, "Shell": 3825, "Java": 567} | package aoc2020.day04_passport_processing
import util.paragraphs
fun main() {
util.solve(206, ::partOne)
util.solve(123, ::partTwo)
}
private fun String.toKeyMap() =
paragraphs()
.map {
it.split(' ')
.map { it.split(':') }
.associate { (a, b) -> Pair(a, b) }
}
private val RE_EYE_COLOR = "amb|blu|brn|gry|grn|hzl|oth".toRegex()
private val RE_HEX_COLOR = "^#[0-9a-f]{6}$".toRegex()
private val RE_PASSPORT_ID = "^[0-9]{9}$".toRegex()
private val validators = mapOf<String, (String) -> Boolean>(
"byr" to { it.toInt() in 1920..2002 },
"iyr" to { it.toInt() in 2010..2020 },
"eyr" to { it.toInt() in 2020..2030 },
"hgt" to {
when (it.substring(it.length - 2)) {
"cm" -> it.substring(0, it.length - 2).toInt() in 150..193
"in" -> it.substring(0, it.length - 2).toInt() in 59..76
else -> false
}
},
"hcl" to { RE_HEX_COLOR.matches(it) },
"ecl" to { RE_EYE_COLOR.matches(it) },
"pid" to { RE_PASSPORT_ID.matches(it) },
)
fun partOne(input: String) =
input
.toKeyMap()
.count { p ->
validators.keys.all { k ->
p.containsKey(k)
}
}
fun partTwo(input: String) =
input
.toKeyMap()
.count { p ->
validators.all { (k, validator) ->
val v = p[k]
v != null && validator(v)
}
}
| 0 | Kotlin | 0 | 0 | a8d52412772750c5e7d2e2e018f3a82354e8b1c3 | 1,479 | aoc-2021 | MIT License |
src/main/kotlin/day21/Day21.kt | qnox | 575,581,183 | false | {"Kotlin": 66677} | package day21
import readInput
sealed interface Node {
val id: String
}
class Expr(override val id: String, val v1: Node, val v2: Node, val op: String) : Node {
override fun toString(): String = "($v1 $op $v2)"
}
class Num(override val id: String, val v: Long) : Node {
override fun toString(): String = if (id == "humn") {"$$v$"} else { v.toString() }
}
val expr = "(.+): (.+) (.) (.+)".toRegex()
val num = "(.+): (\\d+)".toRegex()
fun parse(input: List<String>): Expr {
val map: Map<String, ((String) -> Node) -> Node> = input.associate { line ->
expr.matchEntire(line)?.let {
it.groups[1]!!.value to { n: (String) -> Node ->
Expr(
it.groups[1]!!.value,
n(it.groups[2]!!.value),
n(it.groups[4]!!.value),
it.groups[3]!!.value
)
}
}
?: num.matchEntire(line)?.let {
it.groups[1]!!.value to { n: (String) -> Node ->
Num(it.groups[1]!!.value, it.groups[2]!!.value.toLong())
}
}
?: error("Failed to parse: $line")
}
val resolver = object : Function1<String, Node> {
override fun invoke(name: String): Node = map[name]!!(this)
}
return map["root"]!!(resolver) as Expr
}
fun calculate(node: Node): Long {
return when (node) {
is Num -> node.v
is Expr -> when (node.op) {
"+" -> calculate(node.v1) + calculate(node.v2)
"-" -> calculate(node.v1) - calculate(node.v2)
"*" -> calculate(node.v1) * calculate(node.v2)
"/" -> calculate(node.v1) / calculate(node.v2)
else -> error("Unknown op: $node.op")
}
}
}
fun containsHumn(node: Node): Boolean {
return node.id == "humn" || when (node) {
is Num -> false
is Expr -> containsHumn(node.v1) || containsHumn(node.v2)
}
}
fun transform(node: Node, v: Node, id: String= "humn"): Node {
return if (node.id == "humn") {
v
} else {
if (node is Expr) {
val isV1 = containsHumn(node.v1)
val expr = when(node.op) {
"+" -> if (isV1) {
Expr(node.id, v, node.v2, "-")
} else {
Expr(node.id, v, node.v1, "-")
}
"-" -> if (isV1) {
Expr(node.id, v, node.v2, "+")
} else {
Expr(node.id, node.v1, v, "-")
}
"*" -> if (isV1) {
Expr(node.id, v, node.v2, "/")
} else {
Expr(node.id, v, node.v1, "/")
}
"/" -> if (isV1) {
Expr(node.id, v, node.v2, "*")
} else {
Expr(node.id, node.v1, v, "/")
}
else -> error("Unknown op: $node.op")
}
return if (isV1) {
transform(node.v1, expr, id)
} else {
transform(node.v2, expr, id)
}
}
error("Only expression nodes are expected")
}
}
fun main() {
fun part1(input: List<String>): Long {
val root = parse(input)
return calculate(root)
}
fun part2(input: List<String>): Long {
val root = parse(input)
val (v, expr) = if (containsHumn(root.v1)) {
calculate(root.v2) to root.v1
} else {
calculate(root.v1) to root.v2
}
val node = transform(expr, Num("root", v))
return calculate(node)
}
val testInput = readInput("day21", "test")
val input = readInput("day21", "input")
val part1 = part1(testInput)
println(part1)
check(part1 == 152L)
println(part1(input))
val part2 = part2(testInput)
println(part2)
check(part2 == 301L)
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 727ca335d32000c3de2b750d23248a1364ba03e4 | 3,972 | aoc2022 | Apache License 2.0 |
src/Day04.kt | Flexicon | 576,933,699 | false | {"Kotlin": 5474} | fun main() {
fun String.toRange(): IntRange = split("-")
.map { it.toInt() }
.let { (from, to) -> from..to }
fun List<String>.toRangePairs() = map {
it.split(",").map { r -> r.toRange() }
}
fun IntRange.contains(other: IntRange): Boolean =
(other.first in this) && (other.last in this)
fun IntRange.overlapsWith(other: IntRange): Boolean =
(other.first in this) || (other.last in this)
fun part1(input: List<String>): Int = input.toRangePairs()
.count { (r1, r2) -> r1.contains(r2) || r2.contains(r1) }
fun part2(input: List<String>): Int = input.toRangePairs()
.count { (r1, r2) -> r1.overlapsWith(r2) || r2.overlapsWith(r1) }
val testInput = readInput("Day04_test")
val part1Result = part1(testInput)
val expected1 = 2
check(part1Result == expected1) { "Part 1: Expected $expected1, actual $part1Result" }
val part2Result = part2(testInput)
val expected2 = 4
check(part2Result == expected2) { "Part 2: Expected $expected2, actual $part2Result" }
val input = readInput("Day04")
part1(input).println()
part2(input).println()
}
| 0 | Kotlin | 0 | 0 | 7109cf333c31999296e1990ce297aa2db3a622f2 | 1,160 | aoc-2022-in-kotlin | Apache License 2.0 |
src/day01/Day01.kt | shiddarthbista | 572,833,784 | false | {"Kotlin": 9985} | package day01
import readInput
fun main() {
fun part1(input: List<String>): Int {
return getCalorieSums(input).maxOrNull() ?: 0
}
fun part2(input: List<String>): Int {
val calorieSums = getCalorieSums(input)
calorieSums.sortDescending()
return calorieSums.subList(0, 3).sum()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day01_test")
check(part1(testInput) == 24000)
val input = readInput("day01")
println(part1(input))
println(part2(input))
}
fun convertWordToNumber(input: String): String {
val wordToNumberMap = mapOf(
"zero" to "0",
"one" to "1",
"two" to "2",
"three" to "3",
"four" to "4",
"five" to "5",
"six" to "6",
"seven" to "7",
"eight" to "8",
"nine" to "9"
)
var result = input
for ((word, number) in wordToNumberMap) {
result = result.replace(word, number)
}
return result
}
fun getCalorieSums(input: List<String>): MutableList<Int> {
val sums = mutableListOf<Int>()
for (calories in input) {
if (calories.isEmpty()) {
sums += 0
} else {
var sum = sums.removeLastOrNull() ?: 0
sum += calories.toInt()
sums += sum
}
}
return sums
}
| 0 | Kotlin | 0 | 0 | ed1b6a132e201e98ab46c8df67d4e9dd074801fe | 1,421 | aoc-2022-kotlin | Apache License 2.0 |
src/day05/Day05.kt | Raibaz | 571,997,684 | false | {"Kotlin": 9423} | package day05
import readInput
typealias Stacks = List<ArrayDeque<Char>>
fun parseInput(input: List<String>): Pair<Stacks, List<Operation>> {
val stacksInput = input.takeWhile { it.contains("[A-Z]".toRegex()) }
val stackCount = input.first { it.contains("[0-9]".toRegex()) }.split(" ").last().toInt()
val operations = input.dropWhile { !it.contains("move") }.map { it.toOperation() }
val stacks = parseStacks(stacksInput, stackCount)
return stacks to operations
}
fun parseStacks(input: List<String>, stackCount: Int) : Stacks {
val stacks = mutableListOf<ArrayDeque<Char>>()
(1..stackCount).forEach { _ ->
stacks.add(ArrayDeque())
}
input.forEach { line ->
var index = 0
(1..stackCount).forEach {
if (index > line.length) {
return@forEach
}
val cell = line.substring(index, index + 3)
if (cell.trim().isNotEmpty()) {
stacks[it - 1].addLast(cell.removePrefix("[").removeSuffix("]")[0])
}
index += 4
}
}
return stacks
}
data class Operation(
val moves: Int,
val from: Int,
val to: Int
)
fun String.toOperation(): Operation {
val regex = "move (\\d+) from (\\d+) to (\\d+)".toRegex()
val match = regex.find(this)
val values = match!!.groupValues
return Operation(values[1].toInt(), values[2].toInt(), values[3].toInt())
}
fun Stacks.processOperationsPart1(operations: List<Operation>): Stacks {
operations.forEach {op ->
val from = this[op.from - 1]
val to = this[op.to - 1]
(0 until op.moves).forEach { _ ->
val value = from.removeFirst()
to.addFirst(value)
}
println(this)
}
return this
}
fun Stacks.processOperationsPart2(operations: List<Operation>): Stacks {
operations.forEach {op ->
val from = this[op.from - 1]
val to = this[op.to - 1]
val tmp = mutableListOf<Char>()
(0 until op.moves).forEach { _ ->
tmp.add(from.removeFirst())
}
tmp.reversed().forEach {
to.addFirst(it)
}
println(this)
}
return this
}
fun Stacks.tops(): String = this.map { it.first() }.joinToString("")
fun main() {
fun part1(input: List<String>): String {
val (stacks, operations) = parseInput(input)
stacks.processOperationsPart1(operations)
return stacks.tops()
}
fun part2(input: List<String>): String {
val (stacks, operations) = parseInput(input)
stacks.processOperationsPart2(operations)
return stacks.tops()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("day05/input_test")
println(part1(testInput))
println(part2(testInput))
val input = readInput("day05/input")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 99d912f661bd3545ca9ff222ac7d93c12682f42d | 2,954 | aoc-22 | Apache License 2.0 |
src/Day05.kt | treegem | 572,875,670 | false | {"Kotlin": 38876} | import common.readInput
fun main() {
fun part1(input: List<String>): String {
val crates = input.getCrates()
input
.getInstructions()
.forEach { it.applyMovingSingleBoxes(crates) }
return crates.readTopCrates()
}
fun part2(input: List<String>): String {
val crates = input.getCrates()
input
.getInstructions()
.forEach { it.applyMovingMultipleBoxes(crates) }
return crates.readTopCrates()
}
val day = "05"
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day${day}_test")
check(part1(testInput) == "CMZ")
check(part2(testInput) == "MCD")
val input = readInput("Day${day}")
println(part1(input))
println(part2(input))
}
private fun List<String>.toInstructions() =
this.map { it.split(' ') }
.map { splitStrings ->
splitStrings.mapNotNull { it.toIntOrNull() }
}
.map {
Instruction(
amount = it[0],
source = it[1] - 1,
target = it[2] - 1
)
}
private fun List<String>.toCrates(): List<MutableList<Char>> {
val informationIndices = (1..this.first().length).step(4)
val crates = List(informationIndices.count()) { mutableListOf<Char>() }
this.forEach { line ->
informationIndices.forEachIndexed { index, informationIndex ->
if (line[informationIndex] != ' ') crates[index].add(line[informationIndex])
}
}
return crates
}
private fun MutableList<Char>.putOneOnTop(char: Char) = this.add(0, char)
private fun MutableList<Char>.putSomeOnTop(chars: List<Char>) =
chars
.reversed()
.forEach { this.add(0, it) }
private fun MutableList<Char>.takeOneFromTop() = this.removeFirst()
private fun MutableList<Char>.takeSomeFromTop(amount: Int) =
this.take(amount)
.also {
repeat(amount) { this.removeFirst() }
}
private fun List<String>.getCrates() =
this.filterNot { it.startsWith('m') }
.filterNot { it.isBlank() }
.filter { it.trim().startsWith('[') }
.toCrates()
private fun List<String>.getInstructions() =
this.filter { it.startsWith('m') }
.toInstructions()
private fun List<MutableList<Char>>.readTopCrates() =
this.map { it.first() }
.joinToString(separator = "")
private class Instruction(
val amount: Int,
val source: Int,
val target: Int,
) {
fun applyMovingSingleBoxes(crates: List<MutableList<Char>>) {
repeat(amount) {
crates[source]
.takeOneFromTop()
.let { crates[target].putOneOnTop(it) }
}
}
fun applyMovingMultipleBoxes(crates: List<MutableList<Char>>) {
crates[source]
.takeSomeFromTop(amount)
.let { crates[target].putSomeOnTop(it) }
}
}
| 0 | Kotlin | 0 | 0 | 97f5b63f7e01a64a3b14f27a9071b8237ed0a4e8 | 2,952 | advent_of_code_2022 | Apache License 2.0 |
2021/src/main/kotlin/alternative/Day04.kt | eduellery | 433,983,584 | false | {"Kotlin": 97092} | package alternative
class Day04(private val input: List<String>) {
private fun prepareBoards(): Pair<List<Int>, List<Board>> {
val numbers = input.first().trim().split(",").map(String::toInt)
val grids = input.drop(1)
val boards = grids.map(Board.Companion::parse)
return Pair(numbers, boards)
}
fun solve1(): Int {
val (numbers, boards) = prepareBoards()
numbers.forEach { n ->
boards.forEach { board ->
board.markNumber(n)
if (board.won()) {
return board.unmarkedNumbers().sum() * n
}
}
}
return 0
}
fun solve2(): Int {
val (numbers, boards) = prepareBoards()
val winningBoards = mutableSetOf<Board>()
numbers.forEach { n ->
boards.forEach { board ->
board.markNumber(n)
if (board.won() && board !in winningBoards) {
winningBoards += board
if (winningBoards.size == boards.size) {
return board.unmarkedNumbers().sum() * n
}
}
}
}
return 0
}
private class Board(private val grid: List<List<Int>>) {
private val seen = mutableSetOf<Int>()
fun markNumber(n: Int) {
seen += n
}
fun unmarkedNumbers(): List<Int> {
return grid.flatMap { row -> row.mapNotNull { field -> if (field !in seen) field else null } }
}
fun won(): Boolean {
val wonRow = grid.any { row -> row.all { it in seen } }
val wonColumn = grid.first().indices.any { column ->
grid.indices.all { row ->
grid[row][column] in seen
}
}
return wonRow || wonColumn
}
companion object {
fun parse(grid: String): Board =
grid.trim().split("\n").map { it.trim().split("\\s+".toRegex()).map(String::toInt) }.let { Board(it) }
}
}
}
| 0 | Kotlin | 0 | 1 | 3e279dd04bbcaa9fd4b3c226d39700ef70b031fc | 2,102 | adventofcode-2021-2025 | MIT License |
src/Day20.kt | davidkna | 572,439,882 | false | {"Kotlin": 79526} | import java.util.LinkedList
fun main() {
fun parseInput(input: List<String>) = LinkedList(input.mapIndexed { idx, n -> idx to n.toLong() })
fun decrypt(out: LinkedList<Pair<Int, Long>>) {
out.indices.forEach { idx ->
val currentItem = out.withIndex().find { it.value.first == idx }!!
val moves = currentItem.value.second
val newIdx = (currentItem.index + moves).mod(out.size - 1)
if (newIdx == currentItem.index) return@forEach
out.removeAt(currentItem.index)
out.add(newIdx, currentItem.value)
}
}
fun calcSolution(list: LinkedList<Pair<Int, Long>>): Long {
val zeroIndex = list.withIndex().find { it.value.second == 0L }!!.index
return (1..3).sumOf { list[(zeroIndex + 1000 * it).mod(list.size)].second }
}
fun part1(input: List<String>): Long {
val list = parseInput(input)
decrypt(list)
return calcSolution(list)
}
fun part2(input: List<String>): Long {
val list = LinkedList(parseInput(input).map { it.first to it.second * 811589153 })
(1..10).forEach { _ -> decrypt(list) }
return calcSolution(list)
}
val testInput = readInput("Day20_test")
check(part1(testInput) == 3L)
check(part2(testInput) == 1623178306L)
val input = readInput("Day20")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | ccd666cc12312537fec6e0c7ca904f5d9ebf75a3 | 1,415 | aoc-2022 | Apache License 2.0 |
src/Day04CampCleanup.kt | zizoh | 573,932,084 | false | {"Kotlin": 13370} | fun main() {
val input: List<String> = readInput("input/day04")
println("total complete overlap: ${getCompleteOverlap(input)}")
println("total partial overlap: ${getPartialOverlap(input)}")
}
private fun getCompleteOverlap(input: List<String>) = input.sumOf {
val reorderedList: List<Int> = getReorderedList(it)
val overlapCount = if (isCompleteOverlap(reorderedList)) 1 else 0
overlapCount
}
private fun getPartialOverlap(input: List<String>) = input.sumOf {
val reorderedList: List<Int> = getReorderedList(it)
val overlapCount = if (isOverlap(reorderedList)) 1 else 0
overlapCount
}
private fun getReorderedList(it: String): List<Int> {
val sections = it.split("-", ",").map { it.toInt() }.toMutableList()
val startOfFirstPair = sections[0]
val endOfFirstPair = sections[1]
val startOfSecondPair = sections[2]
val endOfSecondPair = sections[3]
if (isStartOfFirstSectionSameAsStartOfSecondSection(startOfFirstPair, startOfSecondPair)
&& isEndOfFirstSectionOverlappingStartOfSecondSection(endOfFirstPair, endOfSecondPair)
|| isFirstSectionAfterSecondSection(startOfFirstPair, startOfSecondPair)
) {
sections[0] = startOfSecondPair
sections[1] = endOfSecondPair
sections[2] = startOfFirstPair
sections[3] = endOfFirstPair
}
return sections
}
private fun isFirstSectionAfterSecondSection(
startOfFirstPair: Int,
startOfSecondPair: Int
) = startOfFirstPair > startOfSecondPair
private fun isStartOfFirstSectionSameAsStartOfSecondSection(
startOfFirstPair: Int,
startOfSecondPair: Int
) = startOfFirstPair == startOfSecondPair
fun isCompleteOverlap(sections: List<Int>) =
isEndOfFirstSectionOverlappingStartOfSecondSection(
sections[2], sections[1]
) && isEndOfFirstSectionOverlappingStartOfSecondSection(sections[3], sections[1])
fun isOverlap(sections: List<Int>) = isCompleteOverlap(sections) ||
isEndOfFirstSectionOverlappingStartOfSecondSection(sections[2], sections[1])
private fun isEndOfFirstSectionOverlappingStartOfSecondSection(
endOfFirstPair: Int,
endOfSecondPair: Int
) = endOfFirstPair <= endOfSecondPair | 0 | Kotlin | 0 | 0 | 817017369d257cca648974234f1e4137cdcd3138 | 2,191 | aoc-2022 | Apache License 2.0 |
src/Day07.kt | brunojensen | 572,665,994 | false | {"Kotlin": 13161} | /**
* This method looks terrible, needs a good refactoring!
*/
private fun createDirectoryMap(input: List<String>): Map<String, Int> {
return buildMap {
val directory = mutableListOf<String>()
input.forEach {
val splittedInput = it.split(" ")
when (splittedInput.first()) {
"$" -> when (splittedInput.last()) {
".." -> directory.removeLast()
"ls" -> {}
else -> {
directory.add(it.substringAfterLast(" "))
this[directory.joinToString("/")] = 0
}
}
else -> if (it.first().isDigit()) {
val tmp = directory.toMutableList()
while (tmp.isNotEmpty()) {
val directoryToString = tmp.joinToString("/")
this[directoryToString] = this[directoryToString]!! + it.substringBefore(" ").toInt()
tmp.removeLast()
}
}
}
}
}
}
fun main() {
fun part1(input: List<String>): Int {
val map = createDirectoryMap(input)
return map.values.filter { it < 100_000 }.sumOf { it }
}
fun part2(input: List<String>): Int {
val map = createDirectoryMap(input)
val used: Int = map["/"]!!
return map.values.filter { (70_000_000 - (used - it)) >= 30_000_000 }.min()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day07.test")
check(part1(testInput) == 95437)
check(part2(testInput) == 24933642)
val input = readInput("Day07")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 2707e76f5abd96c9d59c782e7122427fc6fdaad1 | 1,531 | advent-of-code-kotlin-1 | Apache License 2.0 |
src/Day21.kt | weberchu | 573,107,187 | false | {"Kotlin": 91366} | private interface MonkeyJob
private data class NumberJob(
val number: Long
): MonkeyJob
private data class MathsJob(
val left: String,
val right: String,
val operation: String
): MonkeyJob
private val mathsFormat = """(\w+) ([\+\-*/]) (\w+)""".toRegex()
private fun parseJobs(input: List<String>): Map<String, MonkeyJob> {
return input.map {
val split = it.split(": ")
val name = split[0]
name to try {
NumberJob(split[1].toLong())
} catch (e: NumberFormatException) {
val matchResult = mathsFormat.matchEntire(split[1])
MathsJob(
matchResult!!.groupValues[1],
matchResult.groupValues[3],
matchResult.groupValues[2]
)
}
}.toMap()
}
private fun resolve(name: String, jobs: Map<String, MonkeyJob>): Long {
val monkey = jobs[name]!!
if (monkey is NumberJob) {
return monkey.number
} else if (monkey is MathsJob) {
val left = resolve(monkey.left, jobs)
val right = resolve(monkey.right, jobs)
return when (monkey.operation) {
"+" -> left + right
"-" -> left - right
"*" -> left * right
"/" -> left / right
else -> throw IllegalStateException("Unknown operation $monkey")
}
}
throw IllegalStateException("Unknown job $monkey")
}
private fun part1(input: List<String>): Long {
val jobs = parseJobs(input)
return resolve("root", jobs)
}
private fun hasHumn(name: String, jobs: Map<String, MonkeyJob>): Boolean {
if (name == "humn") {
return true
}
val job = jobs[name]
if (job is NumberJob) {
return false
}
job as MathsJob
return hasHumn(job.left, jobs) || hasHumn(job.right, jobs)
}
private fun findHumn(name: String, expectedValue: Long, jobs: Map<String, MonkeyJob>): Long {
if (name == "humn") {
return expectedValue
}
val job = jobs[name] as MathsJob
return if (hasHumn(job.left, jobs)) {
val right = resolve(job.right, jobs)
val leftExpectedValue = when (job.operation) {
"+" -> expectedValue - right
"-" -> expectedValue + right
"*" -> expectedValue / right
"/" -> expectedValue * right
else -> throw IllegalStateException("Unknown operation $job")
}
findHumn(job.left, leftExpectedValue, jobs)
} else {
val left = resolve(job.left, jobs)
val rightExpectedValue = when (job.operation) {
"+" -> expectedValue - left
"-" -> left - expectedValue
"*" -> expectedValue / left
"/" -> left / expectedValue
else -> throw IllegalStateException("Unknown operation $job")
}
findHumn(job.right, rightExpectedValue, jobs)
}
}
private fun part2(input: List<String>): Long {
val jobs = parseJobs(input)
val root = jobs["root"] as MathsJob
return if (hasHumn(root.left, jobs)) {
val expectedValue = resolve(root.right, jobs)
findHumn(root.left, expectedValue, jobs)
} else {
val expectedValue = resolve(root.left, jobs)
findHumn(root.right, expectedValue, jobs)
}
}
fun main() {
val input = readInput("Day21")
// val input = readInput("Test")
println("Part 1: " + part1(input))
println("Part 2: " + part2(input))
}
| 0 | Kotlin | 0 | 0 | 903ff33037e8dd6dd5504638a281cb4813763873 | 3,433 | advent-of-code-2022 | Apache License 2.0 |
src/Day04.kt | Moonpepperoni | 572,940,230 | false | {"Kotlin": 6305} | fun main() {
fun String.sectionPairs() : Pair<IntRange, IntRange> {
val inputPattern = """(\d+)-(\d+),(\d+)-(\d+)""".toRegex()
val (firstStart, firstEnd, secondStart, secondEnd) = inputPattern.matchEntire(this)?.destructured ?: error("Input incorrect")
return firstStart.toInt()..firstEnd.toInt() to secondStart.toInt()..secondEnd.toInt()
}
fun SectionPair.overlapEntirely() : Boolean {
return (second.first in first && second.last in first) || (first.first in second && first.last in second)
}
fun SectionPair.overlapPartly() : Boolean {
return (second.first in first || second.last in first || first.first in second || first.last in second)
}
fun part1(input: List<String>): Int {
return input.map(String::sectionPairs).count(SectionPair::overlapEntirely)
}
fun part2(input: List<String>): Int {
return input.map(String::sectionPairs).count(SectionPair::overlapPartly)
}
// 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))
}
typealias SectionPair = Pair<IntRange,IntRange>
| 0 | Kotlin | 0 | 0 | 946073042a985a5ad09e16609ec797c075154a21 | 1,303 | moonpepperoni-aoc-2022 | Apache License 2.0 |
src/main/kotlin/com/hj/leetcode/kotlin/problem2316/Solution2.kt | hj-core | 534,054,064 | false | {"Kotlin": 619841} | package com.hj.leetcode.kotlin.problem2316
class Solution2 {
/* Complexity:
* Time O(n+E) and Space O(n) where E is the size of edges;
*/
fun countPairs(n: Int, edges: Array<IntArray>): Long {
val nodeUnionFind = UnionFind(n, edges)
val componentSizes = sizesOfConnectedComponents(n, nodeUnionFind)
return numUnreachablePairs(n, componentSizes)
}
private class UnionFind(numNodes: Int, edges: Array<IntArray>) {
private val parent = IntArray(numNodes) { it }
private val rank = IntArray(numNodes)
init {
for ((u, v) in edges) {
union(u, v)
}
}
private fun union(aNode: Int, bNode: Int) {
val aParent = find(aNode)
val bParent = find(bNode)
if (aParent == bParent) return
val aRank = rank[aParent]
val bRank = rank[bParent]
when {
aRank < bRank -> parent[aParent] = bParent
aRank > bRank -> parent[bParent] = aParent
else -> {
parent[bParent] = aParent
rank[aParent]++
}
}
}
tailrec fun find(node: Int): Int {
return if (node == parent[node]) node else find(parent[node])
}
}
private fun sizesOfConnectedComponents(numNodes: Int, nodeUnionFind: UnionFind): List<Int> {
val nodes = 0 until numNodes
return nodes
.groupingBy { nodeUnionFind.find(it) }
.eachCount()
.values
.toList()
}
private fun numUnreachablePairs(numNodes: Int, componentSizes: List<Int>): Long {
var remainingNodes = numNodes.toLong()
var numPairs = 0L
for (size in componentSizes) {
remainingNodes -= size
numPairs += size * remainingNodes
}
return numPairs
}
}
| 1 | Kotlin | 0 | 1 | 14c033f2bf43d1c4148633a222c133d76986029c | 1,942 | hj-leetcode-kotlin | Apache License 2.0 |
src/main/kotlin/days/Day4.kt | hughjdavey | 159,955,618 | false | null | package days
import days.Day4.Record.RecordType.GUARD
import days.Day4.Record.RecordType.SLEEP
import days.Day4.Record.RecordType.WAKE
import java.time.LocalDateTime
class Day4 : Day(4) {
private val sortedRecords: List<Record> = inputList.map { Record(it) }.sortedBy { it.dateTime }
private val guards: Set<Guard> = sortedRecords
.filter { it.type == GUARD }
.fold(setOf()) { guards, record -> guards.plus(Guard(record)) }
private lateinit var currentGuard: Guard
// add all minutes asleep for all guards. do in init as both parts use it
init {
sortedRecords.forEach { record ->
when {
record.type == GUARD -> currentGuard = guards.find { it.id == Guard(record).id }!!
record.type == SLEEP -> currentGuard.minutesAsleep.add(MinuteAsleep(record.dateTime))
record.type == WAKE -> {
val minutesSinceLastWentToSleep = record.dateTime.minute - currentGuard.minutesAsleep.last().minute.toLong()
(minutesSinceLastWentToSleep - 1 downTo 1).forEach {
currentGuard.minutesAsleep.add(MinuteAsleep(record.dateTime.minusMinutes(it)))
}
}
}
}
}
override fun partOne(): Int {
val guardMostMinsAsleep = guards.sortedBy { it.minutesAsleep.size }.last()
val minuteMostAsleep = guardMostMinsAsleep.mostFrequentMinute()?.key
return guardMostMinsAsleep.id * (minuteMostAsleep?:0)
}
override fun partTwo(): Int {
val guardMostFreqAsleep = guards.sortedBy { it.mostFrequentMinute()?.value }.last()
val minuteMostAsleep = guardMostFreqAsleep.mostFrequentMinute()?.key
return guardMostFreqAsleep.id * (minuteMostAsleep?:0)
}
class Record(recordString: String) {
val dateTime = LocalDateTime.parse(recordString.substring(recordString.indexOf('[') + 1, recordString.indexOf(']')).replace(' ', 'T'))
val recordContent = recordString.substring(recordString.indexOf(']') + 2)
val type = if (recordContent.startsWith("Guard")) GUARD else if (recordContent == "falls asleep") SLEEP else WAKE
enum class RecordType {
GUARD, SLEEP, WAKE
}
}
class Guard(record: Record) {
val id = record.recordContent.substring(record.recordContent.indexOf('#') + 1, record.recordContent.indexOf(" begins")).toInt()
val minutesAsleep: MutableSet<MinuteAsleep> = mutableSetOf()
fun mostFrequentMinute(): Map.Entry<Int, Int>? {
return minutesAsleep.groupingBy { it.minute }.eachCount().maxBy { it.value }
}
}
data class MinuteAsleep(val dateTime: LocalDateTime) {
val minute = dateTime.minute
}
}
| 0 | Kotlin | 0 | 0 | 4f163752c67333aa6c42cdc27abe07be094961a7 | 2,821 | aoc-2018 | Creative Commons Zero v1.0 Universal |
src/test/kotlin/io/noobymatze/aoc/y2022/Day11.kt | noobymatze | 572,677,383 | false | {"Kotlin": 90710} | package io.noobymatze.aoc.y2022
import io.noobymatze.aoc.Aoc
import kotlin.test.Test
class Day11 {
data class Monkey(
val items: MutableList<Long>,
val op: (Long) -> Long,
val test: Long,
val then: Int,
val `else`: Int,
var inspections: Long = 0,
)
@Test
fun test() {
val monkeys = Aoc.getInput(11)
.split("\n\n").map { parse(it) }
repeat(20) {
monkeys.forEach { monkey ->
while (monkey.items.isNotEmpty()) {
val next = monkey.items.removeFirst()
val worryLevel = monkey.op(next)
monkey.inspections += 1
val result = worryLevel / 3
if (result % monkey.test == 0L) {
monkeys[monkey.then].items.add(result)
}
else {
monkeys[monkey.`else`].items.add(result)
}
}
}
}
val (a, b) = monkeys.sortedByDescending { it.inspections }.take(2)
println(a.inspections * b.inspections)
}
@Test
fun test2() {
val monkeys = Aoc.getInput(11)
.split("\n\n").map { parse(it) }
// Found this on the solutions reddit, still not quite sure of the mathematics behind it though
val mod = monkeys.map { it.test }.reduce { a, b -> a * b }
repeat(10000) {
monkeys.forEach { monkey ->
while (monkey.items.isNotEmpty()) {
val next = monkey.items.removeFirst()
val result = monkey.op(next) % mod
monkey.inspections += 1
if (result % monkey.test == 0L) {
monkeys[monkey.then].items.add(result)
}
else {
monkeys[monkey.`else`].items.add(result)
}
}
}
}
val (a, b) = monkeys.sortedByDescending { it.inspections }.take(2)
println(a.inspections * b.inspections)
}
fun parse(input: String): Monkey {
val numberRegex = Regex("\\d+")
val lines = input.lines()
val items = numberRegex.findAll(lines[1]).map { it.value.toLong() }.toMutableList()
val operation = lines[2].split(": ")[1].let { parseOperation(it.split(" ")) }
val test = Regex("\\d+").find(lines[3])!!.value.toLong()
val then = Regex("\\d+").find(lines[4])!!.value.toInt()
val `else` = Regex("\\d+").find(lines[5])!!.value.toInt()
return Monkey(items, operation, test, then, `else`)
}
fun parseOperation(
op: List<String>
): (Long) -> Long = { old ->
val a = if (op[2] == "old") old else op[2].toLong()
val b = if (op[4] == "old") old else op[4].toLong()
when {
op[3] == "*" -> a * b
op[3] == "/" -> a / b
op[3] == "-" -> a - b
else -> a + b
}
}
} | 0 | Kotlin | 0 | 0 | da4b9d894acf04eb653dafb81a5ed3802a305901 | 3,058 | aoc | MIT License |
src/Day20.kt | rod41732 | 572,917,438 | false | {"Kotlin": 85344} | fun main() {
fun part1(input: List<String>): Long {
val encryptedCoordinates = input.map { it.toLong() }.withIndex().toMutableList()
encryptedCoordinates.mix()
return encryptedCoordinates.map { it.value }.groveCoordinatesSum()
}
val DECRYPTION_KEY = 811589153L
fun part2(input: List<String>): Long {
val encryptedCoordinates = input.map { it.toLong() * DECRYPTION_KEY }.withIndex().toMutableList()
repeat(10) { encryptedCoordinates.mix() }
return encryptedCoordinates.map { it.value }.groveCoordinatesSum()
}
val testInput = readInput("Day20_test")
println(part1(testInput))
check(part1(testInput) == 3L)
println(part2(testInput))
check(part2(testInput) == 1623178306L)
val input = readInput("Day20")
println("Part 1")
println(part1(input)) // 1591
println("Part 2")
println(part2(input)) // 14579387544492
}
private fun MutableList<IndexedValue<Long>>.mix() {
repeat(size) { i ->
val idx = indexOfFirst { it.index == i }
removeAt(idx).let { item ->
add(index = (idx + item.value).mod(size), item)
}
}
}
private fun List<Long>.groveCoordinatesSum(): Long {
return indexOf(0).let { idx ->
listOf(1000, 2000, 3000).map { this[(idx + it).mod(size)] }
}.sum()
}
| 0 | Kotlin | 0 | 0 | 1d2d3d00e90b222085e0989d2b19e6164dfdb1ce | 1,333 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/Day03.kt | kprow | 573,685,824 | false | {"Kotlin": 23005} | fun main() {
fun priority(fromChar: Char): Int {
return if (fromChar.isLowerCase()) {
fromChar.code - 96
} else {
fromChar.code - 38
}
}
fun part1(input: List<String>): Int {
var commonItems = arrayOf<Char>()
var sumOfPriorities = 0
for (contentsOfRucksack in input) {
val compartments = contentsOfRucksack.chunked(contentsOfRucksack.length / 2)
for(item in compartments[0]) {
if (compartments[1].contains(item)) {
commonItems += item
break
}
}
}
for (item in commonItems) {
sumOfPriorities += priority(item)
}
println(commonItems.contentToString())
return sumOfPriorities
}
fun part2(input: List<String>): Int {
var badges = arrayOf<Char>()
var sumOfPriorities = 0
val groups = input.chunked(3)
for (group in groups) {
for (item in group[0]) {
if (group[1].contains(item) && group[2].contains(item)) {
badges += item
break
}
}
}
for (item in badges) {
sumOfPriorities += priority(item)
}
return sumOfPriorities
}
val testInput = readInput("Day03_test")
check(part1(testInput) == 157)
println("TEST Passed 157 for test input.")
val input = readInput("Day03")
println("Day 3 Part 1: " + part1(input))
check(part2(testInput) == 70)
println("TEST Passed 70 for test input.")
println("Day 3 Part 2: " + part2(input))
} | 0 | Kotlin | 0 | 0 | 9a1f48d2a49aeac71fa948656ae8c0a32862334c | 1,678 | AdventOfCode2022 | Apache License 2.0 |
year2016/src/main/kotlin/net/olegg/aoc/year2016/day20/Day20.kt | 0legg | 110,665,187 | false | {"Kotlin": 511989} | package net.olegg.aoc.year2016.day20
import net.olegg.aoc.someday.SomeDay
import net.olegg.aoc.year2016.DayOf2016
import java.util.TreeSet
/**
* See [Year 2016, Day 20](https://adventofcode.com/2016/day/20)
*/
object Day20 : DayOf2016(20) {
private val PATTERN = "(\\d+)-(\\d+)".toRegex()
override fun first(): Any? {
val banned = createBlacklist()
return if (banned.first().first > 0) 0 else banned.first().last + 1
}
override fun second(): Any? {
val banned = createBlacklist()
return banned.fold((-1L..-1L) to 0L) { acc, range ->
range to acc.second + (range.first - acc.first.last - 1)
}.second +
((1L shl 32) - banned.last().last - 1)
}
private fun createBlacklist(): TreeSet<LongRange> {
val banned = TreeSet<LongRange>(compareBy({ it.first }, { it.last }))
lines
.mapNotNull { line -> PATTERN.find(line)?.groupValues?.let { it[1].toLong()..it[2].toLong() } }
.forEach { mask ->
val join = banned.filter { mask.overlaps(it) } + listOf(mask)
banned.removeAll(join.toSet())
val toBan = join.fold(LongRange.EMPTY) { acc, next ->
if (acc.isEmpty()) {
next
} else {
minOf(acc.first, next.first)..maxOf(acc.last, next.last)
}
}
banned.add(toBan)
}
return banned
}
private fun LongRange.extend(value: Long) = LongRange(start - value, endInclusive + value)
private fun LongRange.overlaps(other: LongRange): Boolean {
return with(extend(1)) {
other.first in this || other.last in this
} || with(other.extend(1)) {
this@overlaps.first in this || this@overlaps.last in this
}
}
}
fun main() = SomeDay.mainify(Day20)
| 0 | Kotlin | 1 | 7 | e4a356079eb3a7f616f4c710fe1dfe781fc78b1a | 1,723 | adventofcode | MIT License |
src/main/java/hes/nonogram/LogicSolver.kt | Hes-Siemelink | 689,215,071 | false | {"Kotlin": 32733} | package hes.nonogram
import hes.nonogram.State.EMPTY
import hes.nonogram.State.UNKNOWN
import io.github.oshai.kotlinlogging.KotlinLogging
class LogicSolver() : PuzzleSolver {
private val log = KotlinLogging.logger {}
override fun solve(puzzle: Puzzle): Puzzle? {
var previousState: Puzzle?
do {
previousState = puzzle.copy()
applyLogic(puzzle)
} while (!puzzle.isSolved() && puzzle != previousState)
return if (puzzle.isSolved()) puzzle else null
}
private fun applyLogic(puzzle: Puzzle) {
(puzzle.rows + puzzle.columns)
.sortedBy { it.score() }
.forEach {
it.applyLogic()
}
log.info { "Applied logic on rows and columns:\n$puzzle\n" }
}
}
//
// Lines
//
fun Line.score(): Int {
return cells.size - hints.sum() - hints.size + 1
}
fun Line.checkSolved(): Boolean {
if (this.isSolved()) {
cells.forEach {
if (it.state == UNKNOWN) {
it.state = EMPTY
}
}
return true
}
return false
}
fun Line.applyLogic() {
if (checkSolved()) {
return
}
// Get a partial solution by selecting all the positions that have the same state across all solutions
// that are possible given the current configuration.
val solution = possibleSolutions(this).reduce { result, next ->
result.zip(next) { current, newState ->
if (current == newState) current else UNKNOWN
}
}
// Apply the solution to the cells of this line
this.cells.zip(solution) { cell, state ->
cell.state = state
}
}
fun possibleSolutions(line: Line): List<LineState> {
val all = allSolutions(line.hints, line.cells.size)
return all.filter { line.isSolvedBy(it) }
}
fun allSolutions(hints: Hints, length: Int): List<LineState> {
return solutionsCache.getOrPut(Pair(hints, length)) {
generateAllSolutions(hints, length)
}
}
val solutionsCache = mutableMapOf<Pair<Hints, Int>, List<LineState>>()
fun generateAllSolutions(hints: Hints, length: Int): List<LineState> {
val hint = hints.head
val restOfHints = hints.tail
val all = mutableListOf<LineState>()
for (i in 0..length - hint) {
val begin = State.EMPTY.times(i) + State.FILLED.times(hint)
if (restOfHints.isEmpty()) {
all.add(begin + State.EMPTY.times(length - begin.size))
} else {
val beginPlus = begin + listOf(State.EMPTY)
val rest = allSolutions(restOfHints, length - beginPlus.size)
rest.forEach {
all.add(beginPlus + it)
}
}
}
return all
}
| 0 | Kotlin | 0 | 0 | 7b96e50eb2973e4e2a906cf20af743909f0ebc8d | 2,729 | Nonogram | MIT License |
src/cn/leetcode/codes/simple101/Simple101.kt | shishoufengwise1234 | 258,793,407 | false | {"Java": 771296, "Kotlin": 68641} | package cn.leetcode.codes.simple101
import cn.leetcode.codes.common.TreeNode
import cn.leetcode.codes.createTreeNode
import cn.leetcode.codes.out
import cn.leetcode.codes.outTreeNote
import java.util.*
fun main() {
// val node = createTreeNode(arrayOf(1,2,2,3,4,4,3))
val node = createTreeNode(arrayOf(9, -42, -42, null, 76, 76, null, null, 13, null, 13))
outTreeNote(node)
val re = isSymmetric(node)
val re2 = isSymmetric2(node)
val re3 = Simple101_2().isSymmetric(node)
val re4 = Simple101_2().isSymmetric2(node)
val re3_1 = Simple101_3().isSymmetric(node)
val re3_2 = Simple101_3().isSymmetric2(node)
out("re = $re")
out("re2 = $re2")
out("re3 = $re3")
out("re4 = $re4")
out("re3_1 = $re3_1")
out("re3_2 = $re3_2")
}
/*
101. 对称二叉树
给定一个二叉树,检查它是否是镜像对称的。
例如,二叉树 [1,2,2,3,4,4,3] 是对称的。
1
/ \
2 2
/ \ / \
3 4 4 3
但是下面这个 [1,2,2,null,3,null,3] 则不是镜像对称的:
1
/ \
2 2
\ \
3 3
进阶:
你可以运用递归和迭代两种方法解决这个问题吗?
*/
fun isSymmetric(root: TreeNode?): Boolean {
return isMirror(root, root)
}
fun isSymmetric2(root: TreeNode?): Boolean {
return check(root, root)
}
//递归形式
fun isMirror(root: TreeNode?, root2: TreeNode?): Boolean {
//都为null 是相同数据
if (root == null && root2 == null) return true
//一个为null 一个不为null 则数据不相同
if (root == null || root2 == null) return false
return root.`val` == root2.`val` && isMirror(root.left, root2.right) && isMirror(root.right, root2.left)
}
//迭代方式
fun check(root: TreeNode?, root2: TreeNode?): Boolean {
//借助队列 将根节点入队两次
val deque = LinkedList<TreeNode?>()
var u = root
var v = root2
deque.offer(u)
deque.offer(v)
while (!deque.isEmpty()) {
u = deque.poll()
v = deque.poll()
if (u == null && v == null) {
continue
}
//两边值不相等
if (u == null || v == null || (u?.`val` != v?.`val`)) {
return false
}
deque.offer(u?.left)
deque.offer(v?.right)
deque.offer(u?.right)
deque.offer(v?.left)
}
return true
} | 0 | Java | 0 | 0 | f917a262bcfae8cd973be83c427944deb5352575 | 2,347 | LeetCodeSimple | Apache License 2.0 |
kotlin/src/main/kotlin/year2023/Day06.kt | adrisalas | 725,641,735 | false | {"Kotlin": 130217, "Python": 1548} | package year2023
fun main() {
val input = readInput("Day06")
Day06.part1(input).println()
Day06.part2(input).println()
}
object Day06 {
fun part1(input: List<String>): Int {
val times = input[0].split(":")[1].split(" ").filter { it.isNotBlank() }
val distances = input[1].split(":")[1].split(" ").filter { it.isNotBlank() }
return times.mapIndexed { i, it ->
val maxTime = it.toInt()
val objective = distances[i].toInt()
var count = 0
for (time in 0..maxTime) {
val distance = (maxTime - time) * time
if (distance > objective) {
count++
}
}
count
}.fold(1) { acc, count ->
acc * count
}
}
fun part2(input: List<String>): Int {
val maxTime = input[0]
.split(":")[1]
.split(" ")
.filter { it.isNotBlank() }
.joinToString(separator = "")
.toLong()
val objective = input[1]
.split(":")[1]
.split(" ")
.filter { it.isNotBlank() }
.joinToString(separator = "")
.toLong()
var count = 0
for (time in 0..maxTime) {
val distance = (maxTime - time) * time
if (distance > objective) {
count++
}
}
return count
}
}
| 0 | Kotlin | 0 | 2 | 6733e3a270781ad0d0c383f7996be9f027c56c0e | 1,448 | advent-of-code | MIT License |
src/aoc22/Day19.kt | mihassan | 575,356,150 | false | {"Kotlin": 123343} | @file:Suppress("PackageDirectoryMismatch")
package aoc22.day19
import lib.Bag
import lib.Solution
import lib.Strings.words
enum class Mineral {
ORE, CLAY, OBSIDIAN, GEODE;
companion object {
fun parse(mineral: String): Mineral = Mineral.values().find { it.name.lowercase() == mineral }
?: error("Bad input for Mineral: $mineral")
}
}
typealias Minerals = Bag<Mineral>
data class Rule(val robot: Mineral, val cost: Minerals) {
companion object {
fun parse(rule: String): Rule {
val (robotPart, costPart) = rule.removePrefix("Each ").removeSuffix(".")
.split(" robot costs ")
val robot = Mineral.parse(robotPart)
val minerals = Bag.of(costPart.split(" and ").associate {
val (amount, mineral) = it.words()
Mineral.parse(mineral) to amount.toInt()
})
return Rule(robot, minerals)
}
}
}
data class Blueprint(val rules: List<Rule>) {
companion object {
fun parse(blueprint: String): Blueprint {
val rules = blueprint.substringAfter(": ").split(". ").map { Rule.parse(it) }
return Blueprint(rules)
}
}
}
typealias Input = List<Blueprint>
typealias Output = Int
private val solution = object : Solution<Input, Output>(2022, "Day19") {
override fun parse(input: String): Input {
return input.lines().map { Blueprint.parse(it) }
}
override fun format(output: Output): String {
return "$output"
}
override fun part1(input: Input): Output {
val totalMinutes = 24
return input.withIndex().sumOf { (index, blueprint) ->
(index + 1) * findMaxGeodes(blueprint, totalMinutes)
}
}
override fun part2(input: Input): Output {
val totalMinutes = 32
return input.take(3).map { blueprint ->
findMaxGeodes(blueprint, totalMinutes)
}.reduce(Int::times)
}
private fun findMaxGeodes(blueprint: Blueprint, totalMinutes: Int): Int {
val rules = blueprint.rules.associate { it.robot to it.cost }
val maxCost = Bag.of(
rules.values
.flatMap { it.entries.toList() }
.groupBy({ it.first }, { it.second })
.mapValues { (_, amounts) -> amounts.max() })
fun step(
robots: Minerals,
minerals: Minerals,
minutesLeft: Int,
skippedRobots: Set<Mineral> = emptySet(),
): Int {
if (minutesLeft <= 0) {
return minerals[Mineral.GEODE]
}
// Find candidates for robots to construct
// 1. Must have enough minerals to construct.
// 2. Must not be a skipped robot. This is an optimization where if we skip a robot, we do not
// need to construct the robot until we construct any other robot.
// 3. Must be useful to construct. If we have enough robots to mine resources to construct any
// robot each minute, unless it is a geode robot, we do not need to construct more robots.
val candidates = rules
.filter { it.value isSubSetOf minerals }
.filter { it.key !in skippedRobots }
.filter { it.key == Mineral.GEODE || robots[it.key] < maxCost[it.key] }
.keys
// Produce minerals
minerals += robots
var maxGeodes = 0
fun constructRobot(robot: Mineral): Int {
// Construct robot
minerals -= rules[robot]!!
robots += robot
step(robots, minerals, minutesLeft - 1)
.takeIf { it > maxGeodes }
?.let { maxGeodes = it }
// Backtrack to before construction
minerals += rules[robot]!!
robots -= robot
return maxGeodes
}
// A series of heuristics.
// 1. If we can construct a geode robot, do it.
if (Mineral.GEODE in candidates) {
maxGeodes = constructRobot(Mineral.GEODE)
}
// 2. If we have enough robots to construct any robot each minute,
// we don't need to worry about creating more.
else if (maxCost isSubSetOf robots) {
maxGeodes = step(robots, minerals, minutesLeft - 1)
}
// 3. If all heuristics fail, we need to try all candidates.
else {
val newSkippedRobots = candidates + skippedRobots
// 4. If we can construct all robots except geode, we must construct a robot.
if (newSkippedRobots.size < 3) {
maxGeodes = step(robots, minerals, minutesLeft - 1, newSkippedRobots)
}
candidates.forEach { constructRobot(it) }
}
// Backtrack to before production
minerals -= robots
return maxGeodes
}
return step(Bag.of(Mineral.ORE), Bag.of(), totalMinutes)
}
}
fun main() = solution.run()
| 0 | Kotlin | 0 | 0 | 698316da8c38311366ee6990dd5b3e68b486b62d | 4,568 | aoc-kotlin | Apache License 2.0 |
src/Day15Part1.kt | rosyish | 573,297,490 | false | {"Kotlin": 51693} | import kotlin.math.abs
import kotlin.math.max
class Day15Part1 {
companion object {
fun main() {
val regex = Regex("-?\\d+")
val input = readInput("Day15_input")
val y = 2000000
val sensors = input.asSequence()
.mapNotNull { regex.findAll(it).toList() }
.map { match ->
val (sensorPt, beaconPt) =
match
.map { it.groupValues.first().toInt() }
.chunked(2)
.map { Pair(it[0], it[1]) }
Sensor(sensorPt, beaconPt)
}
.toList()
val result =
sensors
.mapNotNull { sensor -> sensor.getNonDistressSegment(y) }
.sortedWith { p1, p2 ->
if (p1.first != p2.first)
p1.first - p2.first
else p1.second - p2.second
}
.fold(ArrayDeque<Pair<Int, Int>>()) { merged, interval ->
val last = merged.lastOrNull()
if (last != null && interval.first in last.first..last.second) {
merged.removeLast()
merged.add(Pair(last.first, max(last.second, interval.second)))
} else {
merged.add(interval)
}
merged
}
.sumOf { it.second - it.first + 1 }
.minus(
sensors
.map { sensor -> sensor.nearestBeacon }
.filter { beacon -> beacon.second == y }
.toSet().size)
println(result)
}
}
private data class Sensor(val position: Pair<Int, Int>, val nearestBeacon: Pair<Int, Int>) {
fun getNonDistressSegment(y: Int): Pair<Int, Int>? {
val distance = abs(position.first - nearestBeacon.first) + abs(position.second - nearestBeacon.second)
val dx = distance - abs(y - position.second)
if (dx < 0) return null
return Pair(position.first - dx, position.first + dx)
}
}
}
fun main() {
Day15Part1.main()
} | 0 | Kotlin | 0 | 2 | 43560f3e6a814bfd52ebadb939594290cd43549f | 2,389 | aoc-2022 | Apache License 2.0 |
src/day13/day.kt | LostMekka | 574,697,945 | false | {"Kotlin": 92218} | package day13
import util.PeekingIterator
import util.nextOrNull
import util.peekingIterator
import util.readInput
import util.shouldBe
fun main() {
val testInput = readInput(Input::class, testInput = true).parseInput()
testInput.part1() shouldBe 13
testInput.part2() shouldBe 140
val input = readInput(Input::class).parseInput()
println("output for part1: ${input.part1()}")
println("output for part2: ${input.part2()}")
}
private sealed class Packet : Comparable<Packet> {
val stringRepresentation: String by lazy {
when (this) {
is Leaf -> value.toString()
is Node -> children.joinToString(",", "[", "]") { it.stringRepresentation }
}
}
override fun compareTo(other: Packet) = comparePackets(this, other)
override fun equals(other: Any?) = other is Packet && stringRepresentation == other.stringRepresentation
override fun hashCode() = stringRepresentation.hashCode()
}
private data class Leaf(val value: Int) : Packet()
private data class Node(val children: List<Packet>) : Packet() {
constructor(vararg children: Packet) : this(children.toList())
}
private class Input(
val packets: List<Packet>,
)
private fun String.toPacket(): Packet = asIterable().peekingIterator().parsePacket()
private fun PeekingIterator<Char>.parsePacket(): Packet {
val firstChar = current()
when {
firstChar.isDigit() -> {
var n = firstChar.digitToInt()
do {
next().digitToIntOrNull()
?.let { n = n * 10 + it }
?: break
} while (true)
return Leaf(n)
}
firstChar == '[' -> {
if (next() == ']') {
nextOrNull()
return Node(emptyList())
}
val packets = mutableListOf<Packet>()
while (true) {
packets += parsePacket()
when (current()) {
']' -> {
nextOrNull()
return Node(packets)
}
',' -> next()
else -> error("unexpected char '${current()}'")
}
}
}
else -> error("unexpected char '$firstChar'")
}
}
private fun List<String>.parseInput(): Input {
val packets = mapNotNull { if (it.isBlank()) null else it.toPacket() }
return Input(packets)
}
private fun comparePackets(a: Packet, b: Packet): Int =
when {
a is Leaf && b is Leaf -> a.value - b.value
a is Leaf && b is Node -> compareChildren(listOf(a), b.children)
a is Node && b is Leaf -> compareChildren(a.children, listOf(b))
a is Node && b is Node -> compareChildren(a.children, b.children)
else -> error("exhaustive boolean expressions, please?")
}
private fun compareChildren(list1: List<Packet>, list2: List<Packet>): Int {
val iterator1 = list1.iterator()
val iterator2 = list2.iterator()
while (true) {
val a = iterator1.nextOrNull()
val b = iterator2.nextOrNull()
return when {
a == null && b == null -> 0
a == null && b != null -> -1
a != null && b == null -> 1
a != null && b != null ->
when (val result = comparePackets(a, b)) {
0 -> continue
else -> result
}
else -> error("exhaustive boolean expressions, please?")
}
}
}
private fun Input.part1(): Int {
return packets.asSequence()
.chunked(2)
.withIndex()
.sumOf { (i, pair) ->
val (a, b) = pair
if (a <= b) i + 1 else 0
}
}
private fun Input.part2(): Int {
val packet1 = Node(Node(Leaf(2)))
val packet2 = Node(Node(Leaf(6)))
val sortedPackets = (packets + listOf(packet1, packet2)).sorted()
val i1 = sortedPackets.indexOf(packet1) + 1
val i2 = sortedPackets.indexOf(packet2) + 1
return i1 * i2
}
| 0 | Kotlin | 0 | 0 | 58d92387825cf6b3d6b7567a9e6578684963b578 | 4,042 | advent-of-code-2022 | Apache License 2.0 |
src/Day09.kt | ShuffleZZZ | 572,630,279 | false | {"Kotlin": 29686} | import kotlin.math.absoluteValue
import kotlin.math.sign
private data class Cell(var x: Int = 0, var y: Int = 0) {
fun move(other: Cell) {
x += other.x
y += other.y
}
fun isAttached(other: Cell) = (x - other.x).absoluteValue < 2 && (y - other.y).absoluteValue < 2
fun follow(other: Cell) {
x += (other.x - x).sign
y += (other.y - y).sign
}
}
private fun moveTheRope(moves: List<String>, rope: List<Cell>): Int {
val res = HashSet<Cell>()
res.add(Cell())
for (move in moves) {
val (direction, value) = move.split(" ")
val step = when (direction) {
"R" -> Cell(1)
"L" -> Cell(-1)
"U" -> Cell(y = 1)
"D" -> Cell(y = -1)
else -> error("incorrect input")
}
for (i in 0 until value.toInt()) {
rope.first().move(step)
for (j in 1 until rope.size) {
if (rope[j].isAttached(rope[j - 1])) continue
rope[j].follow(rope[j - 1])
}
res.add(rope.last().copy())
}
}
return res.size
}
fun main() {
fun part1(input: List<String>) = moveTheRope(input, List(2) { Cell() })
fun part2(input: List<String>) = moveTheRope(input, List(10) { Cell() })
// test if implementation meets criteria from the description, like:
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 | 5a3cff1b7cfb1497a65bdfb41a2fe384ae4cf82e | 1,574 | advent-of-code-kotlin | Apache License 2.0 |
src/Day03.kt | F-bh | 579,719,291 | false | {"Kotlin": 5785} | fun main() {
val tempMap = ('a'..'z').
fold(mutableMapOf<Char, Int>()) { map, ch -> map[ch] = map.size+1; map }
val valueMap = ('A'..'Z').
fold(tempMap) { map, ch -> map[ch] = map.size+1; map }.toMap()
val input = readDayInput(3)
pt1(valueMap, input)
pt2(valueMap, input)
}
fun pt1(valMap: Map<Char, Int>, lines: List<String>){
val res = lines
.map { line -> line.chunked(line.length/2)}
.map { bag ->
bag[0].fold(mutableListOf<Char>()) { list, item ->
bag[1].fold(list) { _, item2 ->
if (item2 == item && !list.contains(item))
list.add(item)
list}
}
}
.flatten()
.sumOf { item ->
valMap[item] ?: 0
}
println(res)
}
fun pt2(valMap: Map<Char, Int>, lines: List<String>) {
val res = lines.chunked(3)
.map { group ->
group[0].fold(mutableSetOf<Char>()){ set, item ->
if (group[1].contains(item) && group[2].contains(item))
set.add(item)
set
}
}.flatten()
.sumOf { item ->
valMap[item] ?: 0
}
println(res)
}
| 0 | Kotlin | 0 | 0 | 19fa2db8842f166daf3aaffd201544658f41d9e0 | 1,238 | Christmas2022 | Apache License 2.0 |
src/y2022/Day11.kt | gaetjen | 572,857,330 | false | {"Kotlin": 325874, "Mermaid": 571} | package y2022
import util.readInput
import util.split
object Day11 {
data class Monkey(
var items: MutableList<Long>,
val operation: (Long) -> Long,
val divisible: Int,
val targetTrue: Int,
val targetFalse: Int,
var numInspections: Long = 0
) {
companion object {
operator fun invoke(input: List<String>): Monkey {
val items = input[1].substringAfterLast(": ").split(", ").map { it.toLong() }.toMutableList()
val op = toOperation(input[2])
val (divisible, targetTrue, targetFalse) = input.drop(3).map { it.substringAfterLast(" ").toInt() }
return Monkey(items, op, divisible, targetTrue, targetFalse)
}
}
fun throwAll(monkeys: List<Monkey>) {
numInspections += items.size
items.forEach {
val newWorry = operation(it) / 3
if (newWorry % divisible == 0L) {
monkeys[targetTrue].items.add(newWorry)
} else {
monkeys[targetFalse].items.add(newWorry)
}
}
items = mutableListOf()
}
fun throwAllBigWorry(monkeys: List<Monkey>) {
val div = monkeys.map { it.divisible }.reduce { acc, d -> acc * d }
numInspections += items.size
items.forEach {
val newWorry = operation(it) % div
if (newWorry % divisible== 0L) {
monkeys[targetTrue].items.add(newWorry)
} else {
monkeys[targetFalse].items.add(newWorry)
}
}
items = mutableListOf()
}
}
private fun toOperation(input: String): (Long) -> Long {
val (operator, operandStr) = input.substringAfterLast("old ").split(" ")
val operand = operandStr.toLongOrNull()
return when (operator) {
"+" -> { it -> (it + (operand ?: it)) }
"*" -> { it -> (it * (operand ?: it)) }
else -> error("unknown operator")
}
}
private fun parse(input: List<String>): List<Monkey> {
return input.split { it.isEmpty() }
.map { Monkey(it) }
}
fun part1(input: List<String>): Long {
val monkeys = parse(input)
repeat(20) {
monkeys.forEach {it.throwAll(monkeys)}
}
val inspections = monkeys.sortedBy { it.numInspections }.takeLast(2)
return inspections[0].numInspections * inspections[1].numInspections
}
fun part2(input: List<String>): Long {
val monkeys = parse(input)
repeat(10000) {
monkeys.forEach {it.throwAllBigWorry(monkeys)}
}
val inspections = monkeys.sortedByDescending { it.numInspections }
println(inspections.map { it.numInspections })
return inspections[0].numInspections * inspections[1].numInspections
}
}
fun main() {
val testInput = """
Monkey 0:
Starting items: 79, 98
Operation: new = old * 19
Test: divisible by 23
If true: throw to monkey 2
If false: throw to monkey 3
Monkey 1:
Starting items: 54, 65, 75, 74
Operation: new = old + 6
Test: divisible by 19
If true: throw to monkey 2
If false: throw to monkey 0
Monkey 2:
Starting items: 79, 60, 97
Operation: new = old * old
Test: divisible by 13
If true: throw to monkey 1
If false: throw to monkey 3
Monkey 3:
Starting items: 74
Operation: new = old + 3
Test: divisible by 17
If true: throw to monkey 0
If false: throw to monkey 1
""".trimIndent().split("\n")
println("------Tests------")
println(Day11.part1(testInput))
println(Day11.part2(testInput))
println("------Real------")
val input = readInput("resources/2022/day11")
println(Day11.part1(input))
println(Day11.part2(input))
}
| 0 | Kotlin | 0 | 0 | d0b9b5e16cf50025bd9c1ea1df02a308ac1cb66a | 3,923 | advent-of-code | Apache License 2.0 |
src/Day17.kt | EdoFanuel | 575,561,680 | false | {"Kotlin": 80963} | import utils.Coord2DLong
import kotlin.math.min
val rocks = listOf(
(0..3L).map { Coord2DLong(it, 0) },
listOf(Coord2DLong(0, 1), Coord2DLong(1, 2), Coord2DLong(1, 1), Coord2DLong(1, 0), Coord2DLong(2, 1)),
listOf(Coord2DLong(0, 0), Coord2DLong(1, 0), Coord2DLong(2, 2), Coord2DLong(2, 1), Coord2DLong(2, 0)),
(0..3L).map { Coord2DLong(0, it) },
listOf(Coord2DLong(0, 0), Coord2DLong(0, 1), Coord2DLong(1, 0), Coord2DLong(1, 1))
)
val directions = mapOf(
'<' to Coord2DLong(-1, 0),
'>' to Coord2DLong(1, 0),
'v' to Coord2DLong(0, -1)
)
fun isValid(pos: Coord2DLong, tower: Set<Coord2DLong>): Boolean =
pos.x in 0 until 7
&& pos.y >= 0
&& pos !in tower
fun dropRock(rock: List<Coord2DLong>, blocks: MutableSet<Coord2DLong>, windIdx: Long, winds: String): Long {
val maxHeight = blocks.maxOfOrNull { it.y } ?: -1
var pos = Coord2DLong(2, maxHeight + 4)
var j = windIdx
while (true) {
val wind = directions[winds[(j % winds.length).toInt()]]!!
pos = if (rock.any { !isValid(it + pos + wind, blocks) }) pos else pos + wind // move sideways
j++
if (rock.any { !isValid(it + pos + directions['v']!!, blocks) }) { // move down
blocks += rock.map { it + pos }
break
} else {
pos += directions['v']!!
}
}
// printRocks(blocks)
return j
}
fun printRocks(blocks: MutableSet<Coord2DLong>) {
for (i in blocks.maxOf { it.y } downTo blocks.minOf { it.y }) {
println((0..6L).joinToString("") { j -> if (Coord2DLong(j, i) in blocks) "#" else "." })
}
println()
}
fun main() {
val test = readInput("Day17_test")
// println(part(test, 10))
println(part(test, 2022) + 1)
println(part(test, 1_000_000_000_000))
val input = readInput("Day17")
println(part(input, 2022) + 1)
println(part(input, 1_000_000_000_000))
}
fun part(input: List<String>, rockCount: Long = 2022): Long {
val winds = input[0]
val simulation = 10_000L
val history = mutableListOf<Long>()
val blockers = mutableSetOf<Coord2DLong>()
var windIndex = 0L
for (i in 0 until min(rockCount, simulation)) {
windIndex = dropRock(rocks[(i % rocks.size).toInt()], blockers, windIndex, winds)
history += blockers.maxOf { it.y }
}
if (rockCount < simulation) return history.last() + 1
val diff = history.zipWithNext().map { (prev, curr) -> curr - prev }
val loopStart = 200 // could be anything that's inside the loop
val markerLength = 10
val marker = diff.subList(loopStart, loopStart + markerLength)
var loopHeight = -1L
var loopLength = -1
val heightBeforeLoop = history[loopStart - 1] + 1
for (i in loopStart + markerLength until diff.size) {
if (marker == diff.subList(i, i + markerLength)) {
// Marker matches the sequence starting at i, so Loop ends at i - 1
loopLength = i - loopStart
loopHeight = history[i - 1] - heightBeforeLoop
break
}
}
// Calculate the height at the target based on the number of loops and the height of the loop
val numFullLoops = (rockCount - loopStart) / loopLength
val offsetIntoLastLoop = ((rockCount - loopStart) % loopLength).toInt()
val extraHeight = history[loopStart + offsetIntoLastLoop] - heightBeforeLoop
return heightBeforeLoop + loopHeight * numFullLoops + extraHeight
}
| 0 | Kotlin | 0 | 0 | 46a776181e5c9ade0b5e88aa3c918f29b1659b4c | 3,466 | Advent-Of-Code-2022 | Apache License 2.0 |
src/Day05.kt | karlwalsh | 573,854,263 | false | {"Kotlin": 32685} | fun main() {
fun part1(input: List<String>): String {
val (stacks, instructions) = input.asStacksAndInstructions()
instructions.forEach {
stacks.handle(it) { from, to, quantity ->
from.moveSingleCrateAtOnce(quantity, to)
}
}
return stacks.message()
}
fun part2(input: List<String>): String {
val (stacks, instructions) = input.asStacksAndInstructions()
instructions.forEach {
stacks.handle(it) { from, to, quantity ->
from.moveAllCratesAtOnce(quantity, to)
}
}
return stacks.message()
}
val input = readInput("Day05")
with(::part1) {
val exampleResult = this(example())
check(exampleResult == "CMZ") { "Part 1 result was $exampleResult" }
println("Part 1: ${this(input)}")
}
with(::part2) {
val exampleResult = this(example())
check(exampleResult == "MCD") { "Part 2 result was $exampleResult" }
println("Part 2: ${this(input)}")
}
}
private fun List<String>.asStacksAndInstructions(): Pair<Stacks, List<Instruction>> {
val split = this.indexOf("") //First empty line splits crate stacks and instructions
//Parse position numbers - get the max, so we can size the array of stacks
val numberOfPositions = this[split - 1].split(" ")
.filter { it.isNotBlank() }
.maxOfOrNull { it.toInt() }
?: throw IllegalStateException("Cannot find number of positions")
//Parse and populate stacks
val stacks = Array(numberOfPositions) { CrateStack() }
subList(0, split - 1).map { line ->
line.forEachIndexed { index, c ->
if (c in 'A'..'Z') {
//Convert to zero-based stack index
val position = if (index == 1) 0 else ((index - 2) / 4) + 1
stacks[position].add(c)
}
}
}
//Parse move Instructions
val instructionsRegex = """move (?<quantity>\d+) from (?<from>\d) to (?<to>\d)""".toRegex()
val instructions = subList(split + 1, size).map {
val groups = instructionsRegex.matchEntire(it)?.groups!!
Instruction(groups["quantity"].toInt(), groups["from"].toInt(), groups["to"].toInt())
}
return Stacks(stacks) to instructions
}
private fun MatchGroup?.toInt() = this!!.value.toInt()
private class Stacks(private val stacks: Array<CrateStack>) {
fun handle(instruction: Instruction, func: (CrateStack, CrateStack, Int) -> Unit) {
val quantity = instruction.quantity
val from = instruction.from - 1
val to = instruction.to - 1
func(stacks[from], stacks[to], quantity)
}
fun message(): String = stacks
.mapNotNull { it.topCrate() }
.joinToString(separator = "")
}
private class CrateStack {
private val crates: MutableList<Char> = mutableListOf()
fun add(crate: Char) {
crates.add(crate)
}
fun moveSingleCrateAtOnce(quantity: Int, other: CrateStack) {
repeat(quantity) { other.crates.add(0, crates.removeAt(0)) }
}
fun moveAllCratesAtOnce(quantity: Int, other: CrateStack) {
repeat(quantity) { index -> other.crates.add(index, crates.removeAt(0)) }
}
fun topCrate(): Char? {
return if (crates.isEmpty()) null else crates[0]
}
}
private data class Instruction(val quantity: Int, val from: Int, val to: Int)
private fun example() = """
[D]
[N] [C]
[Z] [M] [P]
1 2 3
move 1 from 2 to 1
move 3 from 1 to 3
move 2 from 2 to 1
move 1 from 1 to 2
""".trimIndent().lines() | 0 | Kotlin | 0 | 0 | f5ff9432f1908575cd23df192a7cb1afdd507cee | 3,693 | advent-of-code-2022 | Apache License 2.0 |
2015/kotlin/src/main/kotlin/nl/sanderp/aoc/aoc2015/day15/Day15.kt | sanderploegsma | 224,286,922 | false | {"C#": 233770, "Kotlin": 126791, "F#": 110333, "Go": 70654, "Python": 64250, "Scala": 11381, "Swift": 5153, "Elixir": 2770, "Jinja": 1263, "Ruby": 1171} | package nl.sanderp.aoc.aoc2015.day15
import kotlin.math.max
fun Array<Array<Int>>.totals(): Array<Int> {
return Array(this[0].size) { j ->
this.sumOf { it[j] }
}
}
operator fun Array<Array<Int>>.times(factors: Array<Int>): Array<Array<Int>> {
return Array(size) { i ->
Array(this[i].size) { j ->
this[i][j] * factors[i]
}
}
}
val ingredients = arrayOf(
arrayOf(3, 0, 0, -3, 2),
arrayOf(-3, 3, 0, 0, 9),
arrayOf(-1, 0, 4, 0, 1),
arrayOf(0, 0, -2, 2, 8),
)
fun score(recipe: Array<Int>) = recipe.dropLast(1).fold(1) { acc, i -> acc * max(0, i) }
fun main() {
val amounts = sequence {
for (a in 0..100) {
for (b in 0..100 - a) {
for (c in 0..100 - a - b) {
yield(arrayOf(a, b, c, 100 - a - b - c))
}
}
}
}
val recipes = amounts
.map { ingredients * it }
.map { it.totals() }
.toList()
println("Part one: ${recipes.maxOf { score(it) }}")
println("Part two: ${recipes.filter { it.last() == 500 }.maxOf { score(it) }}")
}
| 0 | C# | 0 | 6 | 8e96dff21c23f08dcf665c68e9f3e60db821c1e5 | 1,128 | advent-of-code | MIT License |
src/day02/Day02.kt | wasabi-muffin | 726,936,666 | false | {"Kotlin": 10804} | package day02
import base.Day
import base.filterDigits
import base.filterLetters
fun main() = Day02.run()
object Day02 : Day<Int>("02") {
override val test1Expected: Int = 8
override val test2Expected: Int = 2286
override fun part1(input: List<String>): Int {
return input.map { Game(it) }.sumOf { game ->
if (game.turns.any { !it.isValid(maxRed = 12, maxGreen = 13, maxBlue = 14) }) 0 else game.id
}
}
override fun part2(input: List<String>): Int {
return input.map { Game(it) }.sumOf { game ->
game.turns.fold(Turn(red = 0, green = 0, blue = 0)) { max, turn ->
Turn(
red = maxOf(max.red, turn.red),
green = maxOf(max.green, turn.green),
blue = maxOf(max.blue, turn.blue)
)
}.power()
}
}
private fun Game(input: String): Game {
val parts = input.split(':', ';')
val id = parts.first().filterDigits().toInt()
val turns = parts.drop(1).map { part ->
val map = part.split(',').associate { it.filterLetters() to it.filterDigits().toInt() }
Turn(red = map["red"] ?: 0, green = map["green"] ?: 0, blue = map["blue"] ?: 0)
}
return Game(id = id, turns = turns)
}
data class Game(val id: Int, val turns: List<Turn>)
data class Turn(val red: Int, val green: Int, val blue: Int) {
fun isValid(maxRed: Int, maxGreen: Int, maxBlue: Int) = red <= maxRed && green <= maxGreen && blue <= maxBlue
fun power() = blue * red * green
}
} | 0 | Kotlin | 0 | 0 | 544cdd359e4456a74b1584cbf1e5dddca97f1394 | 1,609 | advent-of-code-2023 | Apache License 2.0 |
src/Day14.kt | Kvest | 573,621,595 | false | {"Kotlin": 87988} | import kotlin.math.max
import kotlin.math.min
fun main() {
val testInput = readInput("Day14_test")
check(part1(testInput) == 24)
check(part2(testInput) == 93)
val input = readInput("Day14")
println(part1(input))
println(part2(input))
}
private val SAND_START_POINT = XY(500, 0)
private fun part1(input: List<String>): Int {
val points = mutableSetOf<XY>()
parseInput(input, points)
val bottom = points.maxOf { it.y }
val rocksCount = points.size
solve(bottom, points, SAND_START_POINT, exitOnBottom = true)
return points.size - rocksCount
}
private fun part2(input: List<String>): Int {
val points = mutableSetOf<XY>()
parseInput(input, points)
val bottom = points.maxOf { it.y } + 2
val rocksCount = points.size
solve(bottom, points, SAND_START_POINT, exitOnBottom = false)
return points.size - rocksCount
}
private fun parseInput(input: List<String>, points: MutableSet<XY>) {
input
.map { it.split(" -> ") }
.forEach { row ->
row.windowed(2, 1) { (from, to) ->
val xFrom = from.substringBefore(",").toInt()
val yFrom = from.substringAfter(",").toInt()
val xTo = to.substringBefore(",").toInt()
val yTo = to.substringAfter(",").toInt()
for (x in min(xFrom, xTo)..max(xFrom, xTo)) {
for (y in min(yFrom, yTo)..max(yFrom, yTo)) {
points.add(XY(x = x, y = y))
}
}
}
}
}
private fun solve(bottom: Int, points: MutableSet<XY>, point: XY, exitOnBottom: Boolean): Boolean {
if (points.contains(point)) {
return false
}
if (point.y == bottom) {
return exitOnBottom
}
if (solve(bottom, points, XY(x = point.x, y = point.y + 1), exitOnBottom)) return true
if (solve(bottom, points, XY(x = point.x - 1, y = point.y + 1), exitOnBottom)) return true
if (solve(bottom, points, XY(x = point.x + 1, y = point.y + 1), exitOnBottom)) return true
points.add(point)
return false
} | 0 | Kotlin | 0 | 0 | 6409e65c452edd9dd20145766d1e0ea6f07b569a | 2,117 | AOC2022 | Apache License 2.0 |
src/main/kotlin/com/github/ferinagy/adventOfCode/aoc2016/2016-22.kt | ferinagy | 432,170,488 | false | {"Kotlin": 787586} | package com.github.ferinagy.adventOfCode.aoc2016
import com.github.ferinagy.adventOfCode.Coord2D
import com.github.ferinagy.adventOfCode.searchGraph
import com.github.ferinagy.adventOfCode.singleStep
import kotlin.math.abs
fun main() {
println("Part1:")
println(part1())
println()
println("Part2:")
println(part2(testInput))
println(part2(input))
}
private fun part1(): Int {
val disks = input.lines().drop(1).map { line ->
val (x, y, size, used) = regex.matchEntire(line)!!.destructured
GridDisk(Coord2D(x.toInt(), y.toInt()), size.toInt(), used.toInt())
}
var result = 0
for (i in disks.indices) {
for (j in disks.indices) {
if (i == j) continue
if (disks[i].canMoveTo(disks[j])) {
result++
}
}
}
return result
}
private fun GridDisk.canMoveTo(other: GridDisk) = used != 0 && used <= other.size - other.used
private fun part2(input: String): Int {
val disks = input.lines().drop(1).map { line ->
val (x, y, size, used) = regex.matchEntire(line)!!.destructured
GridDisk(Coord2D(x.toInt(), y.toInt()), size.toInt(), used.toInt())
}
val x = disks.maxOf { it.position.x }
val y = disks.maxOf { it.position.y }
val free = disks.single { it.used == 0 }
val blocks = disks.filter { it != free && !it.canMoveTo(free) }.map { it.position }.toSet()
val initial = DiskConfiguration(
width = x + 1,
height = y + 1,
goal = Coord2D(x, 0),
free = free.position,
blocks = blocks
)
val finish = Coord2D(0, 0)
return searchGraph(
start = initial,
isDone = { it.goal == finish },
nextSteps = { it.next().singleStep() },
heuristic = { it.assumption() }
)
}
data class DiskConfiguration(val width: Int, val height: Int, val goal: Coord2D, val free: Coord2D, val blocks: Set<Coord2D>) {
override fun toString(): String = buildString {
val exit = Coord2D(0, 0)
for (y in 0 until height) {
for (x in 0 until width) {
when (Coord2D(x, y)) {
in blocks -> append('#')
free -> append('_')
goal -> append('G')
exit -> append('E')
else -> append('.')
}
}
append('\n')
}
}
fun next(): Set<DiskConfiguration> = buildSet {
val adjacent = free.adjacent(includeDiagonals = false)
adjacent.forEach {
if (it.x in 0 until width && it.y in 0 until height && it !in blocks ) {
this += move(free, it)
}
}
}
fun assumption(): Int {
val toFinish = goal.distanceTo(Coord2D(0, 0))
val toEmpty = if (abs(free.x - goal.x) <= 1 && abs(free.y - goal.y) <= 1) 0 else free.distanceTo(goal)
return toFinish + toEmpty
}
fun move(from: Coord2D, to: Coord2D): DiskConfiguration {
val newGoal = if (to == goal) from else goal
val newFree = if (from == free) to else free
return copy(goal = newGoal, free = newFree)
}
}
data class GridDisk(val position: Coord2D, val size: Int, val used: Int)
private val regex = """/dev/grid/node-x(\d+)-y(\d+)\s+(\d+)T\s+(\d+)T\s+\d+T\s+\d+%""".toRegex()
private const val testInput = """Filesystem Size Used Avail Use%
/dev/grid/node-x0-y0 10T 8T 2T 80%
/dev/grid/node-x0-y1 11T 6T 5T 54%
/dev/grid/node-x0-y2 32T 28T 4T 87%
/dev/grid/node-x1-y0 9T 7T 2T 77%
/dev/grid/node-x1-y1 8T 0T 8T 0%
/dev/grid/node-x1-y2 11T 7T 4T 63%
/dev/grid/node-x2-y0 10T 6T 4T 60%
/dev/grid/node-x2-y1 9T 8T 1T 88%
/dev/grid/node-x2-y2 9T 6T 3T 66%"""
private const val input = """Filesystem Size Used Avail Use%
/dev/grid/node-x0-y0 86T 73T 13T 84%
/dev/grid/node-x0-y1 88T 65T 23T 73%
/dev/grid/node-x0-y2 88T 68T 20T 77%
/dev/grid/node-x0-y3 85T 71T 14T 83%
/dev/grid/node-x0-y4 90T 73T 17T 81%
/dev/grid/node-x0-y5 86T 65T 21T 75%
/dev/grid/node-x0-y6 89T 73T 16T 82%
/dev/grid/node-x0-y7 92T 72T 20T 78%
/dev/grid/node-x0-y8 94T 68T 26T 72%
/dev/grid/node-x0-y9 94T 71T 23T 75%
/dev/grid/node-x0-y10 94T 71T 23T 75%
/dev/grid/node-x0-y11 88T 65T 23T 73%
/dev/grid/node-x0-y12 91T 71T 20T 78%
/dev/grid/node-x0-y13 87T 65T 22T 74%
/dev/grid/node-x0-y14 88T 68T 20T 77%
/dev/grid/node-x0-y15 90T 65T 25T 72%
/dev/grid/node-x0-y16 89T 68T 21T 76%
/dev/grid/node-x0-y17 89T 72T 17T 80%
/dev/grid/node-x0-y18 85T 65T 20T 76%
/dev/grid/node-x0-y19 90T 73T 17T 81%
/dev/grid/node-x0-y20 89T 68T 21T 76%
/dev/grid/node-x0-y21 90T 70T 20T 77%
/dev/grid/node-x0-y22 88T 73T 15T 82%
/dev/grid/node-x0-y23 94T 71T 23T 75%
/dev/grid/node-x0-y24 94T 67T 27T 71%
/dev/grid/node-x0-y25 87T 64T 23T 73%
/dev/grid/node-x0-y26 86T 72T 14T 83%
/dev/grid/node-x1-y0 86T 69T 17T 80%
/dev/grid/node-x1-y1 94T 65T 29T 69%
/dev/grid/node-x1-y2 92T 66T 26T 71%
/dev/grid/node-x1-y3 87T 73T 14T 83%
/dev/grid/node-x1-y4 86T 70T 16T 81%
/dev/grid/node-x1-y5 85T 73T 12T 85%
/dev/grid/node-x1-y6 87T 70T 17T 80%
/dev/grid/node-x1-y7 92T 71T 21T 77%
/dev/grid/node-x1-y8 86T 73T 13T 84%
/dev/grid/node-x1-y9 90T 70T 20T 77%
/dev/grid/node-x1-y10 90T 70T 20T 77%
/dev/grid/node-x1-y11 88T 67T 21T 76%
/dev/grid/node-x1-y12 89T 71T 18T 79%
/dev/grid/node-x1-y13 87T 69T 18T 79%
/dev/grid/node-x1-y14 90T 65T 25T 72%
/dev/grid/node-x1-y15 93T 71T 22T 76%
/dev/grid/node-x1-y16 94T 65T 29T 69%
/dev/grid/node-x1-y17 89T 72T 17T 80%
/dev/grid/node-x1-y18 87T 65T 22T 74%
/dev/grid/node-x1-y19 89T 65T 24T 73%
/dev/grid/node-x1-y20 87T 66T 21T 75%
/dev/grid/node-x1-y21 88T 68T 20T 77%
/dev/grid/node-x1-y22 91T 67T 24T 73%
/dev/grid/node-x1-y23 89T 68T 21T 76%
/dev/grid/node-x1-y24 85T 68T 17T 80%
/dev/grid/node-x1-y25 85T 65T 20T 76%
/dev/grid/node-x1-y26 85T 68T 17T 80%
/dev/grid/node-x2-y0 86T 64T 22T 74%
/dev/grid/node-x2-y1 92T 73T 19T 79%
/dev/grid/node-x2-y2 94T 72T 22T 76%
/dev/grid/node-x2-y3 91T 72T 19T 79%
/dev/grid/node-x2-y4 88T 65T 23T 73%
/dev/grid/node-x2-y5 90T 70T 20T 77%
/dev/grid/node-x2-y6 86T 64T 22T 74%
/dev/grid/node-x2-y7 93T 68T 25T 73%
/dev/grid/node-x2-y8 93T 73T 20T 78%
/dev/grid/node-x2-y9 88T 69T 19T 78%
/dev/grid/node-x2-y10 93T 66T 27T 70%
/dev/grid/node-x2-y11 93T 69T 24T 74%
/dev/grid/node-x2-y12 89T 70T 19T 78%
/dev/grid/node-x2-y13 94T 73T 21T 77%
/dev/grid/node-x2-y14 91T 71T 20T 78%
/dev/grid/node-x2-y15 89T 66T 23T 74%
/dev/grid/node-x2-y16 87T 69T 18T 79%
/dev/grid/node-x2-y17 86T 65T 21T 75%
/dev/grid/node-x2-y18 94T 66T 28T 70%
/dev/grid/node-x2-y19 85T 64T 21T 75%
/dev/grid/node-x2-y20 92T 67T 25T 72%
/dev/grid/node-x2-y21 88T 71T 17T 80%
/dev/grid/node-x2-y22 85T 71T 14T 83%
/dev/grid/node-x2-y23 87T 69T 18T 79%
/dev/grid/node-x2-y24 91T 65T 26T 71%
/dev/grid/node-x2-y25 92T 66T 26T 71%
/dev/grid/node-x2-y26 91T 64T 27T 70%
/dev/grid/node-x3-y0 85T 64T 21T 75%
/dev/grid/node-x3-y1 90T 66T 24T 73%
/dev/grid/node-x3-y2 92T 68T 24T 73%
/dev/grid/node-x3-y3 93T 67T 26T 72%
/dev/grid/node-x3-y4 94T 72T 22T 76%
/dev/grid/node-x3-y5 87T 73T 14T 83%
/dev/grid/node-x3-y6 89T 66T 23T 74%
/dev/grid/node-x3-y7 91T 65T 26T 71%
/dev/grid/node-x3-y8 93T 66T 27T 70%
/dev/grid/node-x3-y9 92T 66T 26T 71%
/dev/grid/node-x3-y10 87T 70T 17T 80%
/dev/grid/node-x3-y11 93T 70T 23T 75%
/dev/grid/node-x3-y12 86T 68T 18T 79%
/dev/grid/node-x3-y13 91T 64T 27T 70%
/dev/grid/node-x3-y14 93T 72T 21T 77%
/dev/grid/node-x3-y15 90T 69T 21T 76%
/dev/grid/node-x3-y16 87T 66T 21T 75%
/dev/grid/node-x3-y17 91T 68T 23T 74%
/dev/grid/node-x3-y18 92T 72T 20T 78%
/dev/grid/node-x3-y19 85T 71T 14T 83%
/dev/grid/node-x3-y20 87T 71T 16T 81%
/dev/grid/node-x3-y21 92T 71T 21T 77%
/dev/grid/node-x3-y22 89T 69T 20T 77%
/dev/grid/node-x3-y23 90T 66T 24T 73%
/dev/grid/node-x3-y24 89T 70T 19T 78%
/dev/grid/node-x3-y25 93T 70T 23T 75%
/dev/grid/node-x3-y26 86T 72T 14T 83%
/dev/grid/node-x4-y0 87T 65T 22T 74%
/dev/grid/node-x4-y1 85T 68T 17T 80%
/dev/grid/node-x4-y2 85T 73T 12T 85%
/dev/grid/node-x4-y3 91T 71T 20T 78%
/dev/grid/node-x4-y4 89T 64T 25T 71%
/dev/grid/node-x4-y5 85T 67T 18T 78%
/dev/grid/node-x4-y6 91T 65T 26T 71%
/dev/grid/node-x4-y7 91T 69T 22T 75%
/dev/grid/node-x4-y8 91T 69T 22T 75%
/dev/grid/node-x4-y9 90T 68T 22T 75%
/dev/grid/node-x4-y10 88T 68T 20T 77%
/dev/grid/node-x4-y11 86T 73T 13T 84%
/dev/grid/node-x4-y12 89T 69T 20T 77%
/dev/grid/node-x4-y13 88T 72T 16T 81%
/dev/grid/node-x4-y14 85T 65T 20T 76%
/dev/grid/node-x4-y15 85T 69T 16T 81%
/dev/grid/node-x4-y16 87T 65T 22T 74%
/dev/grid/node-x4-y17 89T 65T 24T 73%
/dev/grid/node-x4-y18 92T 66T 26T 71%
/dev/grid/node-x4-y19 88T 68T 20T 77%
/dev/grid/node-x4-y20 87T 68T 19T 78%
/dev/grid/node-x4-y21 85T 68T 17T 80%
/dev/grid/node-x4-y22 87T 71T 16T 81%
/dev/grid/node-x4-y23 94T 66T 28T 70%
/dev/grid/node-x4-y24 94T 69T 25T 73%
/dev/grid/node-x4-y25 89T 69T 20T 77%
/dev/grid/node-x4-y26 89T 70T 19T 78%
/dev/grid/node-x5-y0 85T 64T 21T 75%
/dev/grid/node-x5-y1 90T 68T 22T 75%
/dev/grid/node-x5-y2 94T 64T 30T 68%
/dev/grid/node-x5-y3 93T 66T 27T 70%
/dev/grid/node-x5-y4 93T 67T 26T 72%
/dev/grid/node-x5-y5 94T 66T 28T 70%
/dev/grid/node-x5-y6 88T 66T 22T 75%
/dev/grid/node-x5-y7 90T 72T 18T 80%
/dev/grid/node-x5-y8 90T 68T 22T 75%
/dev/grid/node-x5-y9 92T 65T 27T 70%
/dev/grid/node-x5-y10 90T 73T 17T 81%
/dev/grid/node-x5-y11 86T 67T 19T 77%
/dev/grid/node-x5-y12 86T 72T 14T 83%
/dev/grid/node-x5-y13 88T 71T 17T 80%
/dev/grid/node-x5-y14 92T 65T 27T 70%
/dev/grid/node-x5-y15 92T 67T 25T 72%
/dev/grid/node-x5-y16 91T 68T 23T 74%
/dev/grid/node-x5-y17 89T 66T 23T 74%
/dev/grid/node-x5-y18 92T 73T 19T 79%
/dev/grid/node-x5-y19 85T 65T 20T 76%
/dev/grid/node-x5-y20 90T 66T 24T 73%
/dev/grid/node-x5-y21 85T 68T 17T 80%
/dev/grid/node-x5-y22 88T 65T 23T 73%
/dev/grid/node-x5-y23 94T 66T 28T 70%
/dev/grid/node-x5-y24 88T 67T 21T 76%
/dev/grid/node-x5-y25 88T 69T 19T 78%
/dev/grid/node-x5-y26 89T 72T 17T 80%
/dev/grid/node-x6-y0 87T 69T 18T 79%
/dev/grid/node-x6-y1 90T 73T 17T 81%
/dev/grid/node-x6-y2 86T 64T 22T 74%
/dev/grid/node-x6-y3 85T 73T 12T 85%
/dev/grid/node-x6-y4 85T 73T 12T 85%
/dev/grid/node-x6-y5 89T 69T 20T 77%
/dev/grid/node-x6-y6 91T 67T 24T 73%
/dev/grid/node-x6-y7 92T 68T 24T 73%
/dev/grid/node-x6-y8 89T 65T 24T 73%
/dev/grid/node-x6-y9 88T 65T 23T 73%
/dev/grid/node-x6-y10 87T 72T 15T 82%
/dev/grid/node-x6-y11 89T 71T 18T 79%
/dev/grid/node-x6-y12 85T 68T 17T 80%
/dev/grid/node-x6-y13 93T 72T 21T 77%
/dev/grid/node-x6-y14 90T 70T 20T 77%
/dev/grid/node-x6-y15 90T 69T 21T 76%
/dev/grid/node-x6-y16 89T 64T 25T 71%
/dev/grid/node-x6-y17 89T 67T 22T 75%
/dev/grid/node-x6-y18 94T 69T 25T 73%
/dev/grid/node-x6-y19 90T 70T 20T 77%
/dev/grid/node-x6-y20 87T 68T 19T 78%
/dev/grid/node-x6-y21 91T 66T 25T 72%
/dev/grid/node-x6-y22 86T 64T 22T 74%
/dev/grid/node-x6-y23 87T 73T 14T 83%
/dev/grid/node-x6-y24 85T 67T 18T 78%
/dev/grid/node-x6-y25 85T 70T 15T 82%
/dev/grid/node-x6-y26 88T 73T 15T 82%
/dev/grid/node-x7-y0 88T 67T 21T 76%
/dev/grid/node-x7-y1 88T 68T 20T 77%
/dev/grid/node-x7-y2 90T 64T 26T 71%
/dev/grid/node-x7-y3 89T 65T 24T 73%
/dev/grid/node-x7-y4 94T 66T 28T 70%
/dev/grid/node-x7-y5 92T 65T 27T 70%
/dev/grid/node-x7-y6 91T 64T 27T 70%
/dev/grid/node-x7-y7 86T 70T 16T 81%
/dev/grid/node-x7-y8 92T 67T 25T 72%
/dev/grid/node-x7-y9 88T 68T 20T 77%
/dev/grid/node-x7-y10 88T 69T 19T 78%
/dev/grid/node-x7-y11 86T 68T 18T 79%
/dev/grid/node-x7-y12 92T 65T 27T 70%
/dev/grid/node-x7-y13 89T 64T 25T 71%
/dev/grid/node-x7-y14 93T 69T 24T 74%
/dev/grid/node-x7-y15 94T 73T 21T 77%
/dev/grid/node-x7-y16 93T 70T 23T 75%
/dev/grid/node-x7-y17 88T 71T 17T 80%
/dev/grid/node-x7-y18 89T 67T 22T 75%
/dev/grid/node-x7-y19 90T 64T 26T 71%
/dev/grid/node-x7-y20 87T 69T 18T 79%
/dev/grid/node-x7-y21 90T 72T 18T 80%
/dev/grid/node-x7-y22 90T 70T 20T 77%
/dev/grid/node-x7-y23 90T 64T 26T 71%
/dev/grid/node-x7-y24 90T 65T 25T 72%
/dev/grid/node-x7-y25 92T 67T 25T 72%
/dev/grid/node-x7-y26 92T 64T 28T 69%
/dev/grid/node-x8-y0 92T 70T 22T 76%
/dev/grid/node-x8-y1 88T 70T 18T 79%
/dev/grid/node-x8-y2 89T 72T 17T 80%
/dev/grid/node-x8-y3 94T 67T 27T 71%
/dev/grid/node-x8-y4 86T 70T 16T 81%
/dev/grid/node-x8-y5 87T 65T 22T 74%
/dev/grid/node-x8-y6 91T 69T 22T 75%
/dev/grid/node-x8-y7 88T 64T 24T 72%
/dev/grid/node-x8-y8 94T 67T 27T 71%
/dev/grid/node-x8-y9 88T 68T 20T 77%
/dev/grid/node-x8-y10 90T 65T 25T 72%
/dev/grid/node-x8-y11 88T 71T 17T 80%
/dev/grid/node-x8-y12 90T 66T 24T 73%
/dev/grid/node-x8-y13 86T 67T 19T 77%
/dev/grid/node-x8-y14 89T 73T 16T 82%
/dev/grid/node-x8-y15 88T 68T 20T 77%
/dev/grid/node-x8-y16 88T 69T 19T 78%
/dev/grid/node-x8-y17 89T 73T 16T 82%
/dev/grid/node-x8-y18 85T 68T 17T 80%
/dev/grid/node-x8-y19 92T 68T 24T 73%
/dev/grid/node-x8-y20 93T 67T 26T 72%
/dev/grid/node-x8-y21 89T 65T 24T 73%
/dev/grid/node-x8-y22 94T 71T 23T 75%
/dev/grid/node-x8-y23 90T 65T 25T 72%
/dev/grid/node-x8-y24 88T 64T 24T 72%
/dev/grid/node-x8-y25 87T 73T 14T 83%
/dev/grid/node-x8-y26 91T 73T 18T 80%
/dev/grid/node-x9-y0 91T 67T 24T 73%
/dev/grid/node-x9-y1 94T 72T 22T 76%
/dev/grid/node-x9-y2 89T 65T 24T 73%
/dev/grid/node-x9-y3 90T 71T 19T 78%
/dev/grid/node-x9-y4 85T 66T 19T 77%
/dev/grid/node-x9-y5 94T 68T 26T 72%
/dev/grid/node-x9-y6 92T 73T 19T 79%
/dev/grid/node-x9-y7 89T 73T 16T 82%
/dev/grid/node-x9-y8 87T 68T 19T 78%
/dev/grid/node-x9-y9 90T 69T 21T 76%
/dev/grid/node-x9-y10 88T 68T 20T 77%
/dev/grid/node-x9-y11 86T 72T 14T 83%
/dev/grid/node-x9-y12 88T 68T 20T 77%
/dev/grid/node-x9-y13 89T 68T 21T 76%
/dev/grid/node-x9-y14 92T 67T 25T 72%
/dev/grid/node-x9-y15 91T 71T 20T 78%
/dev/grid/node-x9-y16 86T 68T 18T 79%
/dev/grid/node-x9-y17 87T 68T 19T 78%
/dev/grid/node-x9-y18 94T 73T 21T 77%
/dev/grid/node-x9-y19 94T 68T 26T 72%
/dev/grid/node-x9-y20 92T 72T 20T 78%
/dev/grid/node-x9-y21 86T 66T 20T 76%
/dev/grid/node-x9-y22 87T 66T 21T 75%
/dev/grid/node-x9-y23 89T 65T 24T 73%
/dev/grid/node-x9-y24 86T 64T 22T 74%
/dev/grid/node-x9-y25 86T 67T 19T 77%
/dev/grid/node-x9-y26 90T 72T 18T 80%
/dev/grid/node-x10-y0 94T 73T 21T 77%
/dev/grid/node-x10-y1 88T 68T 20T 77%
/dev/grid/node-x10-y2 93T 64T 29T 68%
/dev/grid/node-x10-y3 90T 71T 19T 78%
/dev/grid/node-x10-y4 90T 64T 26T 71%
/dev/grid/node-x10-y5 88T 65T 23T 73%
/dev/grid/node-x10-y6 86T 68T 18T 79%
/dev/grid/node-x10-y7 92T 68T 24T 73%
/dev/grid/node-x10-y8 93T 72T 21T 77%
/dev/grid/node-x10-y9 88T 70T 18T 79%
/dev/grid/node-x10-y10 90T 72T 18T 80%
/dev/grid/node-x10-y11 90T 66T 24T 73%
/dev/grid/node-x10-y12 90T 73T 17T 81%
/dev/grid/node-x10-y13 93T 72T 21T 77%
/dev/grid/node-x10-y14 93T 68T 25T 73%
/dev/grid/node-x10-y15 87T 71T 16T 81%
/dev/grid/node-x10-y16 91T 65T 26T 71%
/dev/grid/node-x10-y17 86T 64T 22T 74%
/dev/grid/node-x10-y18 92T 71T 21T 77%
/dev/grid/node-x10-y19 93T 64T 29T 68%
/dev/grid/node-x10-y20 90T 69T 21T 76%
/dev/grid/node-x10-y21 94T 73T 21T 77%
/dev/grid/node-x10-y22 92T 70T 22T 76%
/dev/grid/node-x10-y23 94T 73T 21T 77%
/dev/grid/node-x10-y24 94T 64T 30T 68%
/dev/grid/node-x10-y25 85T 64T 21T 75%
/dev/grid/node-x10-y26 93T 69T 24T 74%
/dev/grid/node-x11-y0 89T 71T 18T 79%
/dev/grid/node-x11-y1 88T 73T 15T 82%
/dev/grid/node-x11-y2 87T 65T 22T 74%
/dev/grid/node-x11-y3 93T 70T 23T 75%
/dev/grid/node-x11-y4 93T 65T 28T 69%
/dev/grid/node-x11-y5 90T 68T 22T 75%
/dev/grid/node-x11-y6 89T 72T 17T 80%
/dev/grid/node-x11-y7 89T 70T 19T 78%
/dev/grid/node-x11-y8 92T 73T 19T 79%
/dev/grid/node-x11-y9 90T 66T 24T 73%
/dev/grid/node-x11-y10 88T 71T 17T 80%
/dev/grid/node-x11-y11 89T 67T 22T 75%
/dev/grid/node-x11-y12 88T 64T 24T 72%
/dev/grid/node-x11-y13 87T 66T 21T 75%
/dev/grid/node-x11-y14 86T 73T 13T 84%
/dev/grid/node-x11-y15 93T 65T 28T 69%
/dev/grid/node-x11-y16 94T 66T 28T 70%
/dev/grid/node-x11-y17 93T 69T 24T 74%
/dev/grid/node-x11-y18 91T 70T 21T 76%
/dev/grid/node-x11-y19 92T 68T 24T 73%
/dev/grid/node-x11-y20 93T 68T 25T 73%
/dev/grid/node-x11-y21 85T 64T 21T 75%
/dev/grid/node-x11-y22 94T 73T 21T 77%
/dev/grid/node-x11-y23 88T 72T 16T 81%
/dev/grid/node-x11-y24 90T 67T 23T 74%
/dev/grid/node-x11-y25 87T 66T 21T 75%
/dev/grid/node-x11-y26 92T 70T 22T 76%
/dev/grid/node-x12-y0 94T 66T 28T 70%
/dev/grid/node-x12-y1 90T 70T 20T 77%
/dev/grid/node-x12-y2 86T 68T 18T 79%
/dev/grid/node-x12-y3 88T 73T 15T 82%
/dev/grid/node-x12-y4 89T 73T 16T 82%
/dev/grid/node-x12-y5 93T 71T 22T 76%
/dev/grid/node-x12-y6 88T 68T 20T 77%
/dev/grid/node-x12-y7 87T 73T 14T 83%
/dev/grid/node-x12-y8 93T 71T 22T 76%
/dev/grid/node-x12-y9 88T 69T 19T 78%
/dev/grid/node-x12-y10 93T 65T 28T 69%
/dev/grid/node-x12-y11 88T 71T 17T 80%
/dev/grid/node-x12-y12 94T 69T 25T 73%
/dev/grid/node-x12-y13 88T 65T 23T 73%
/dev/grid/node-x12-y14 93T 70T 23T 75%
/dev/grid/node-x12-y15 91T 64T 27T 70%
/dev/grid/node-x12-y16 90T 70T 20T 77%
/dev/grid/node-x12-y17 91T 68T 23T 74%
/dev/grid/node-x12-y18 92T 67T 25T 72%
/dev/grid/node-x12-y19 85T 65T 20T 76%
/dev/grid/node-x12-y20 86T 68T 18T 79%
/dev/grid/node-x12-y21 90T 73T 17T 81%
/dev/grid/node-x12-y22 91T 67T 24T 73%
/dev/grid/node-x12-y23 90T 72T 18T 80%
/dev/grid/node-x12-y24 86T 73T 13T 84%
/dev/grid/node-x12-y25 89T 65T 24T 73%
/dev/grid/node-x12-y26 89T 64T 25T 71%
/dev/grid/node-x13-y0 88T 68T 20T 77%
/dev/grid/node-x13-y1 85T 68T 17T 80%
/dev/grid/node-x13-y2 87T 72T 15T 82%
/dev/grid/node-x13-y3 94T 64T 30T 68%
/dev/grid/node-x13-y4 85T 71T 14T 83%
/dev/grid/node-x13-y5 86T 71T 15T 82%
/dev/grid/node-x13-y6 88T 72T 16T 81%
/dev/grid/node-x13-y7 88T 65T 23T 73%
/dev/grid/node-x13-y8 92T 67T 25T 72%
/dev/grid/node-x13-y9 93T 65T 28T 69%
/dev/grid/node-x13-y10 94T 69T 25T 73%
/dev/grid/node-x13-y11 85T 68T 17T 80%
/dev/grid/node-x13-y12 86T 68T 18T 79%
/dev/grid/node-x13-y13 94T 65T 29T 69%
/dev/grid/node-x13-y14 88T 65T 23T 73%
/dev/grid/node-x13-y15 88T 67T 21T 76%
/dev/grid/node-x13-y16 91T 64T 27T 70%
/dev/grid/node-x13-y17 90T 67T 23T 74%
/dev/grid/node-x13-y18 90T 64T 26T 71%
/dev/grid/node-x13-y19 86T 64T 22T 74%
/dev/grid/node-x13-y20 90T 69T 21T 76%
/dev/grid/node-x13-y21 85T 73T 12T 85%
/dev/grid/node-x13-y22 86T 67T 19T 77%
/dev/grid/node-x13-y23 94T 64T 30T 68%
/dev/grid/node-x13-y24 89T 65T 24T 73%
/dev/grid/node-x13-y25 94T 66T 28T 70%
/dev/grid/node-x13-y26 92T 72T 20T 78%
/dev/grid/node-x14-y0 87T 73T 14T 83%
/dev/grid/node-x14-y1 91T 65T 26T 71%
/dev/grid/node-x14-y2 87T 64T 23T 73%
/dev/grid/node-x14-y3 88T 72T 16T 81%
/dev/grid/node-x14-y4 90T 65T 25T 72%
/dev/grid/node-x14-y5 91T 69T 22T 75%
/dev/grid/node-x14-y6 90T 66T 24T 73%
/dev/grid/node-x14-y7 86T 67T 19T 77%
/dev/grid/node-x14-y8 86T 71T 15T 82%
/dev/grid/node-x14-y9 90T 71T 19T 78%
/dev/grid/node-x14-y10 88T 71T 17T 80%
/dev/grid/node-x14-y11 90T 68T 22T 75%
/dev/grid/node-x14-y12 93T 73T 20T 78%
/dev/grid/node-x14-y13 94T 69T 25T 73%
/dev/grid/node-x14-y14 89T 67T 22T 75%
/dev/grid/node-x14-y15 92T 69T 23T 75%
/dev/grid/node-x14-y16 92T 65T 27T 70%
/dev/grid/node-x14-y17 89T 73T 16T 82%
/dev/grid/node-x14-y18 86T 64T 22T 74%
/dev/grid/node-x14-y19 90T 72T 18T 80%
/dev/grid/node-x14-y20 85T 73T 12T 85%
/dev/grid/node-x14-y21 92T 69T 23T 75%
/dev/grid/node-x14-y22 89T 68T 21T 76%
/dev/grid/node-x14-y23 85T 71T 14T 83%
/dev/grid/node-x14-y24 89T 64T 25T 71%
/dev/grid/node-x14-y25 91T 68T 23T 74%
/dev/grid/node-x14-y26 92T 69T 23T 75%
/dev/grid/node-x15-y0 88T 69T 19T 78%
/dev/grid/node-x15-y1 91T 67T 24T 73%
/dev/grid/node-x15-y2 509T 499T 10T 98%
/dev/grid/node-x15-y3 91T 70T 21T 76%
/dev/grid/node-x15-y4 92T 71T 21T 77%
/dev/grid/node-x15-y5 90T 67T 23T 74%
/dev/grid/node-x15-y6 92T 65T 27T 70%
/dev/grid/node-x15-y7 89T 73T 16T 82%
/dev/grid/node-x15-y8 90T 70T 20T 77%
/dev/grid/node-x15-y9 87T 65T 22T 74%
/dev/grid/node-x15-y10 85T 67T 18T 78%
/dev/grid/node-x15-y11 89T 70T 19T 78%
/dev/grid/node-x15-y12 87T 69T 18T 79%
/dev/grid/node-x15-y13 90T 69T 21T 76%
/dev/grid/node-x15-y14 87T 64T 23T 73%
/dev/grid/node-x15-y15 87T 70T 17T 80%
/dev/grid/node-x15-y16 88T 70T 18T 79%
/dev/grid/node-x15-y17 92T 66T 26T 71%
/dev/grid/node-x15-y18 85T 65T 20T 76%
/dev/grid/node-x15-y19 88T 72T 16T 81%
/dev/grid/node-x15-y20 85T 69T 16T 81%
/dev/grid/node-x15-y21 92T 64T 28T 69%
/dev/grid/node-x15-y22 88T 73T 15T 82%
/dev/grid/node-x15-y23 89T 73T 16T 82%
/dev/grid/node-x15-y24 94T 69T 25T 73%
/dev/grid/node-x15-y25 90T 66T 24T 73%
/dev/grid/node-x15-y26 90T 65T 25T 72%
/dev/grid/node-x16-y0 92T 69T 23T 75%
/dev/grid/node-x16-y1 86T 70T 16T 81%
/dev/grid/node-x16-y2 501T 491T 10T 98%
/dev/grid/node-x16-y3 92T 70T 22T 76%
/dev/grid/node-x16-y4 87T 67T 20T 77%
/dev/grid/node-x16-y5 90T 68T 22T 75%
/dev/grid/node-x16-y6 93T 67T 26T 72%
/dev/grid/node-x16-y7 88T 70T 18T 79%
/dev/grid/node-x16-y8 86T 67T 19T 77%
/dev/grid/node-x16-y9 94T 65T 29T 69%
/dev/grid/node-x16-y10 93T 65T 28T 69%
/dev/grid/node-x16-y11 93T 71T 22T 76%
/dev/grid/node-x16-y12 89T 69T 20T 77%
/dev/grid/node-x16-y13 88T 67T 21T 76%
/dev/grid/node-x16-y14 85T 73T 12T 85%
/dev/grid/node-x16-y15 92T 70T 22T 76%
/dev/grid/node-x16-y16 85T 72T 13T 84%
/dev/grid/node-x16-y17 94T 70T 24T 74%
/dev/grid/node-x16-y18 89T 69T 20T 77%
/dev/grid/node-x16-y19 86T 66T 20T 76%
/dev/grid/node-x16-y20 94T 70T 24T 74%
/dev/grid/node-x16-y21 85T 65T 20T 76%
/dev/grid/node-x16-y22 87T 72T 15T 82%
/dev/grid/node-x16-y23 90T 70T 20T 77%
/dev/grid/node-x16-y24 94T 72T 22T 76%
/dev/grid/node-x16-y25 86T 69T 17T 80%
/dev/grid/node-x16-y26 86T 72T 14T 83%
/dev/grid/node-x17-y0 90T 73T 17T 81%
/dev/grid/node-x17-y1 91T 69T 22T 75%
/dev/grid/node-x17-y2 501T 491T 10T 98%
/dev/grid/node-x17-y3 88T 68T 20T 77%
/dev/grid/node-x17-y4 94T 66T 28T 70%
/dev/grid/node-x17-y5 91T 72T 19T 79%
/dev/grid/node-x17-y6 89T 64T 25T 71%
/dev/grid/node-x17-y7 89T 70T 19T 78%
/dev/grid/node-x17-y8 90T 67T 23T 74%
/dev/grid/node-x17-y9 89T 67T 22T 75%
/dev/grid/node-x17-y10 91T 67T 24T 73%
/dev/grid/node-x17-y11 91T 70T 21T 76%
/dev/grid/node-x17-y12 89T 72T 17T 80%
/dev/grid/node-x17-y13 94T 70T 24T 74%
/dev/grid/node-x17-y14 93T 68T 25T 73%
/dev/grid/node-x17-y15 85T 68T 17T 80%
/dev/grid/node-x17-y16 88T 64T 24T 72%
/dev/grid/node-x17-y17 85T 71T 14T 83%
/dev/grid/node-x17-y18 85T 71T 14T 83%
/dev/grid/node-x17-y19 93T 69T 24T 74%
/dev/grid/node-x17-y20 86T 69T 17T 80%
/dev/grid/node-x17-y21 88T 68T 20T 77%
/dev/grid/node-x17-y22 89T 70T 19T 78%
/dev/grid/node-x17-y23 85T 71T 14T 83%
/dev/grid/node-x17-y24 93T 64T 29T 68%
/dev/grid/node-x17-y25 91T 70T 21T 76%
/dev/grid/node-x17-y26 87T 68T 19T 78%
/dev/grid/node-x18-y0 86T 69T 17T 80%
/dev/grid/node-x18-y1 89T 68T 21T 76%
/dev/grid/node-x18-y2 508T 498T 10T 98%
/dev/grid/node-x18-y3 93T 67T 26T 72%
/dev/grid/node-x18-y4 89T 67T 22T 75%
/dev/grid/node-x18-y5 90T 72T 18T 80%
/dev/grid/node-x18-y6 86T 70T 16T 81%
/dev/grid/node-x18-y7 87T 71T 16T 81%
/dev/grid/node-x18-y8 85T 69T 16T 81%
/dev/grid/node-x18-y9 92T 71T 21T 77%
/dev/grid/node-x18-y10 89T 64T 25T 71%
/dev/grid/node-x18-y11 85T 72T 13T 84%
/dev/grid/node-x18-y12 85T 67T 18T 78%
/dev/grid/node-x18-y13 87T 70T 17T 80%
/dev/grid/node-x18-y14 90T 70T 20T 77%
/dev/grid/node-x18-y15 92T 67T 25T 72%
/dev/grid/node-x18-y16 91T 73T 18T 80%
/dev/grid/node-x18-y17 85T 73T 12T 85%
/dev/grid/node-x18-y18 92T 72T 20T 78%
/dev/grid/node-x18-y19 93T 69T 24T 74%
/dev/grid/node-x18-y20 88T 72T 16T 81%
/dev/grid/node-x18-y21 93T 71T 22T 76%
/dev/grid/node-x18-y22 88T 69T 19T 78%
/dev/grid/node-x18-y23 87T 69T 18T 79%
/dev/grid/node-x18-y24 92T 67T 25T 72%
/dev/grid/node-x18-y25 91T 64T 27T 70%
/dev/grid/node-x18-y26 86T 67T 19T 77%
/dev/grid/node-x19-y0 87T 67T 20T 77%
/dev/grid/node-x19-y1 85T 66T 19T 77%
/dev/grid/node-x19-y2 507T 496T 11T 97%
/dev/grid/node-x19-y3 92T 64T 28T 69%
/dev/grid/node-x19-y4 87T 70T 17T 80%
/dev/grid/node-x19-y5 90T 71T 19T 78%
/dev/grid/node-x19-y6 93T 71T 22T 76%
/dev/grid/node-x19-y7 94T 64T 30T 68%
/dev/grid/node-x19-y8 86T 67T 19T 77%
/dev/grid/node-x19-y9 90T 67T 23T 74%
/dev/grid/node-x19-y10 92T 72T 20T 78%
/dev/grid/node-x19-y11 94T 72T 22T 76%
/dev/grid/node-x19-y12 86T 67T 19T 77%
/dev/grid/node-x19-y13 91T 71T 20T 78%
/dev/grid/node-x19-y14 89T 66T 23T 74%
/dev/grid/node-x19-y15 91T 65T 26T 71%
/dev/grid/node-x19-y16 93T 69T 24T 74%
/dev/grid/node-x19-y17 93T 66T 27T 70%
/dev/grid/node-x19-y18 87T 68T 19T 78%
/dev/grid/node-x19-y19 88T 69T 19T 78%
/dev/grid/node-x19-y20 92T 64T 28T 69%
/dev/grid/node-x19-y21 91T 68T 23T 74%
/dev/grid/node-x19-y22 92T 66T 26T 71%
/dev/grid/node-x19-y23 93T 68T 25T 73%
/dev/grid/node-x19-y24 90T 71T 19T 78%
/dev/grid/node-x19-y25 87T 69T 18T 79%
/dev/grid/node-x19-y26 85T 65T 20T 76%
/dev/grid/node-x20-y0 91T 66T 25T 72%
/dev/grid/node-x20-y1 87T 70T 17T 80%
/dev/grid/node-x20-y2 506T 492T 14T 97%
/dev/grid/node-x20-y3 94T 64T 30T 68%
/dev/grid/node-x20-y4 86T 65T 21T 75%
/dev/grid/node-x20-y5 92T 68T 24T 73%
/dev/grid/node-x20-y6 92T 0T 92T 0%
/dev/grid/node-x20-y7 94T 70T 24T 74%
/dev/grid/node-x20-y8 85T 68T 17T 80%
/dev/grid/node-x20-y9 92T 73T 19T 79%
/dev/grid/node-x20-y10 89T 67T 22T 75%
/dev/grid/node-x20-y11 86T 69T 17T 80%
/dev/grid/node-x20-y12 88T 73T 15T 82%
/dev/grid/node-x20-y13 94T 64T 30T 68%
/dev/grid/node-x20-y14 93T 64T 29T 68%
/dev/grid/node-x20-y15 86T 65T 21T 75%
/dev/grid/node-x20-y16 89T 70T 19T 78%
/dev/grid/node-x20-y17 94T 68T 26T 72%
/dev/grid/node-x20-y18 86T 64T 22T 74%
/dev/grid/node-x20-y19 93T 67T 26T 72%
/dev/grid/node-x20-y20 92T 69T 23T 75%
/dev/grid/node-x20-y21 91T 67T 24T 73%
/dev/grid/node-x20-y22 86T 71T 15T 82%
/dev/grid/node-x20-y23 94T 71T 23T 75%
/dev/grid/node-x20-y24 92T 66T 26T 71%
/dev/grid/node-x20-y25 92T 70T 22T 76%
/dev/grid/node-x20-y26 86T 69T 17T 80%
/dev/grid/node-x21-y0 90T 65T 25T 72%
/dev/grid/node-x21-y1 91T 73T 18T 80%
/dev/grid/node-x21-y2 506T 493T 13T 97%
/dev/grid/node-x21-y3 92T 64T 28T 69%
/dev/grid/node-x21-y4 92T 70T 22T 76%
/dev/grid/node-x21-y5 89T 68T 21T 76%
/dev/grid/node-x21-y6 94T 68T 26T 72%
/dev/grid/node-x21-y7 94T 73T 21T 77%
/dev/grid/node-x21-y8 88T 65T 23T 73%
/dev/grid/node-x21-y9 92T 65T 27T 70%
/dev/grid/node-x21-y10 94T 71T 23T 75%
/dev/grid/node-x21-y11 85T 70T 15T 82%
/dev/grid/node-x21-y12 90T 67T 23T 74%
/dev/grid/node-x21-y13 88T 69T 19T 78%
/dev/grid/node-x21-y14 85T 67T 18T 78%
/dev/grid/node-x21-y15 86T 72T 14T 83%
/dev/grid/node-x21-y16 89T 64T 25T 71%
/dev/grid/node-x21-y17 93T 73T 20T 78%
/dev/grid/node-x21-y18 87T 70T 17T 80%
/dev/grid/node-x21-y19 88T 64T 24T 72%
/dev/grid/node-x21-y20 86T 72T 14T 83%
/dev/grid/node-x21-y21 87T 69T 18T 79%
/dev/grid/node-x21-y22 93T 68T 25T 73%
/dev/grid/node-x21-y23 91T 71T 20T 78%
/dev/grid/node-x21-y24 92T 66T 26T 71%
/dev/grid/node-x21-y25 87T 66T 21T 75%
/dev/grid/node-x21-y26 86T 69T 17T 80%
/dev/grid/node-x22-y0 89T 73T 16T 82%
/dev/grid/node-x22-y1 91T 65T 26T 71%
/dev/grid/node-x22-y2 502T 494T 8T 98%
/dev/grid/node-x22-y3 86T 67T 19T 77%
/dev/grid/node-x22-y4 91T 69T 22T 75%
/dev/grid/node-x22-y5 87T 65T 22T 74%
/dev/grid/node-x22-y6 88T 67T 21T 76%
/dev/grid/node-x22-y7 87T 70T 17T 80%
/dev/grid/node-x22-y8 86T 72T 14T 83%
/dev/grid/node-x22-y9 85T 67T 18T 78%
/dev/grid/node-x22-y10 88T 66T 22T 75%
/dev/grid/node-x22-y11 90T 68T 22T 75%
/dev/grid/node-x22-y12 89T 68T 21T 76%
/dev/grid/node-x22-y13 90T 68T 22T 75%
/dev/grid/node-x22-y14 88T 68T 20T 77%
/dev/grid/node-x22-y15 89T 72T 17T 80%
/dev/grid/node-x22-y16 92T 65T 27T 70%
/dev/grid/node-x22-y17 90T 66T 24T 73%
/dev/grid/node-x22-y18 87T 64T 23T 73%
/dev/grid/node-x22-y19 87T 64T 23T 73%
/dev/grid/node-x22-y20 87T 69T 18T 79%
/dev/grid/node-x22-y21 87T 73T 14T 83%
/dev/grid/node-x22-y22 86T 65T 21T 75%
/dev/grid/node-x22-y23 86T 67T 19T 77%
/dev/grid/node-x22-y24 86T 69T 17T 80%
/dev/grid/node-x22-y25 92T 67T 25T 72%
/dev/grid/node-x22-y26 94T 64T 30T 68%
/dev/grid/node-x23-y0 91T 70T 21T 76%
/dev/grid/node-x23-y1 91T 73T 18T 80%
/dev/grid/node-x23-y2 509T 490T 19T 96%
/dev/grid/node-x23-y3 89T 64T 25T 71%
/dev/grid/node-x23-y4 88T 64T 24T 72%
/dev/grid/node-x23-y5 90T 66T 24T 73%
/dev/grid/node-x23-y6 94T 65T 29T 69%
/dev/grid/node-x23-y7 85T 68T 17T 80%
/dev/grid/node-x23-y8 93T 66T 27T 70%
/dev/grid/node-x23-y9 93T 66T 27T 70%
/dev/grid/node-x23-y10 90T 64T 26T 71%
/dev/grid/node-x23-y11 86T 64T 22T 74%
/dev/grid/node-x23-y12 87T 70T 17T 80%
/dev/grid/node-x23-y13 93T 73T 20T 78%
/dev/grid/node-x23-y14 89T 72T 17T 80%
/dev/grid/node-x23-y15 91T 66T 25T 72%
/dev/grid/node-x23-y16 93T 64T 29T 68%
/dev/grid/node-x23-y17 89T 67T 22T 75%
/dev/grid/node-x23-y18 85T 64T 21T 75%
/dev/grid/node-x23-y19 87T 65T 22T 74%
/dev/grid/node-x23-y20 88T 69T 19T 78%
/dev/grid/node-x23-y21 85T 64T 21T 75%
/dev/grid/node-x23-y22 91T 64T 27T 70%
/dev/grid/node-x23-y23 92T 72T 20T 78%
/dev/grid/node-x23-y24 86T 69T 17T 80%
/dev/grid/node-x23-y25 89T 69T 20T 77%
/dev/grid/node-x23-y26 93T 66T 27T 70%
/dev/grid/node-x24-y0 88T 64T 24T 72%
/dev/grid/node-x24-y1 89T 73T 16T 82%
/dev/grid/node-x24-y2 504T 496T 8T 98%
/dev/grid/node-x24-y3 94T 72T 22T 76%
/dev/grid/node-x24-y4 91T 68T 23T 74%
/dev/grid/node-x24-y5 87T 64T 23T 73%
/dev/grid/node-x24-y6 87T 73T 14T 83%
/dev/grid/node-x24-y7 85T 70T 15T 82%
/dev/grid/node-x24-y8 92T 69T 23T 75%
/dev/grid/node-x24-y9 86T 68T 18T 79%
/dev/grid/node-x24-y10 93T 65T 28T 69%
/dev/grid/node-x24-y11 90T 69T 21T 76%
/dev/grid/node-x24-y12 87T 70T 17T 80%
/dev/grid/node-x24-y13 88T 69T 19T 78%
/dev/grid/node-x24-y14 86T 68T 18T 79%
/dev/grid/node-x24-y15 93T 73T 20T 78%
/dev/grid/node-x24-y16 87T 71T 16T 81%
/dev/grid/node-x24-y17 91T 71T 20T 78%
/dev/grid/node-x24-y18 90T 68T 22T 75%
/dev/grid/node-x24-y19 94T 66T 28T 70%
/dev/grid/node-x24-y20 88T 71T 17T 80%
/dev/grid/node-x24-y21 92T 71T 21T 77%
/dev/grid/node-x24-y22 89T 73T 16T 82%
/dev/grid/node-x24-y23 90T 73T 17T 81%
/dev/grid/node-x24-y24 93T 71T 22T 76%
/dev/grid/node-x24-y25 87T 68T 19T 78%
/dev/grid/node-x24-y26 94T 71T 23T 75%
/dev/grid/node-x25-y0 89T 68T 21T 76%
/dev/grid/node-x25-y1 91T 73T 18T 80%
/dev/grid/node-x25-y2 502T 491T 11T 97%
/dev/grid/node-x25-y3 92T 69T 23T 75%
/dev/grid/node-x25-y4 86T 72T 14T 83%
/dev/grid/node-x25-y5 94T 72T 22T 76%
/dev/grid/node-x25-y6 93T 71T 22T 76%
/dev/grid/node-x25-y7 93T 72T 21T 77%
/dev/grid/node-x25-y8 93T 70T 23T 75%
/dev/grid/node-x25-y9 86T 73T 13T 84%
/dev/grid/node-x25-y10 90T 69T 21T 76%
/dev/grid/node-x25-y11 91T 67T 24T 73%
/dev/grid/node-x25-y12 85T 64T 21T 75%
/dev/grid/node-x25-y13 85T 68T 17T 80%
/dev/grid/node-x25-y14 85T 71T 14T 83%
/dev/grid/node-x25-y15 92T 71T 21T 77%
/dev/grid/node-x25-y16 91T 64T 27T 70%
/dev/grid/node-x25-y17 93T 67T 26T 72%
/dev/grid/node-x25-y18 88T 66T 22T 75%
/dev/grid/node-x25-y19 87T 64T 23T 73%
/dev/grid/node-x25-y20 90T 66T 24T 73%
/dev/grid/node-x25-y21 86T 65T 21T 75%
/dev/grid/node-x25-y22 87T 69T 18T 79%
/dev/grid/node-x25-y23 91T 65T 26T 71%
/dev/grid/node-x25-y24 91T 64T 27T 70%
/dev/grid/node-x25-y25 93T 71T 22T 76%
/dev/grid/node-x25-y26 93T 73T 20T 78%
/dev/grid/node-x26-y0 90T 71T 19T 78%
/dev/grid/node-x26-y1 91T 69T 22T 75%
/dev/grid/node-x26-y2 502T 494T 8T 98%
/dev/grid/node-x26-y3 93T 73T 20T 78%
/dev/grid/node-x26-y4 92T 66T 26T 71%
/dev/grid/node-x26-y5 85T 67T 18T 78%
/dev/grid/node-x26-y6 88T 65T 23T 73%
/dev/grid/node-x26-y7 85T 69T 16T 81%
/dev/grid/node-x26-y8 90T 73T 17T 81%
/dev/grid/node-x26-y9 94T 64T 30T 68%
/dev/grid/node-x26-y10 91T 66T 25T 72%
/dev/grid/node-x26-y11 94T 67T 27T 71%
/dev/grid/node-x26-y12 87T 70T 17T 80%
/dev/grid/node-x26-y13 85T 72T 13T 84%
/dev/grid/node-x26-y14 90T 69T 21T 76%
/dev/grid/node-x26-y15 93T 73T 20T 78%
/dev/grid/node-x26-y16 94T 73T 21T 77%
/dev/grid/node-x26-y17 87T 66T 21T 75%
/dev/grid/node-x26-y18 88T 71T 17T 80%
/dev/grid/node-x26-y19 91T 73T 18T 80%
/dev/grid/node-x26-y20 86T 69T 17T 80%
/dev/grid/node-x26-y21 88T 65T 23T 73%
/dev/grid/node-x26-y22 90T 70T 20T 77%
/dev/grid/node-x26-y23 85T 72T 13T 84%
/dev/grid/node-x26-y24 85T 71T 14T 83%
/dev/grid/node-x26-y25 88T 64T 24T 72%
/dev/grid/node-x26-y26 93T 69T 24T 74%
/dev/grid/node-x27-y0 93T 66T 27T 70%
/dev/grid/node-x27-y1 92T 72T 20T 78%
/dev/grid/node-x27-y2 505T 495T 10T 98%
/dev/grid/node-x27-y3 89T 69T 20T 77%
/dev/grid/node-x27-y4 88T 70T 18T 79%
/dev/grid/node-x27-y5 89T 64T 25T 71%
/dev/grid/node-x27-y6 93T 65T 28T 69%
/dev/grid/node-x27-y7 91T 66T 25T 72%
/dev/grid/node-x27-y8 92T 65T 27T 70%
/dev/grid/node-x27-y9 86T 65T 21T 75%
/dev/grid/node-x27-y10 92T 71T 21T 77%
/dev/grid/node-x27-y11 89T 64T 25T 71%
/dev/grid/node-x27-y12 92T 67T 25T 72%
/dev/grid/node-x27-y13 92T 66T 26T 71%
/dev/grid/node-x27-y14 88T 67T 21T 76%
/dev/grid/node-x27-y15 93T 64T 29T 68%
/dev/grid/node-x27-y16 91T 66T 25T 72%
/dev/grid/node-x27-y17 89T 66T 23T 74%
/dev/grid/node-x27-y18 94T 73T 21T 77%
/dev/grid/node-x27-y19 91T 72T 19T 79%
/dev/grid/node-x27-y20 88T 71T 17T 80%
/dev/grid/node-x27-y21 90T 67T 23T 74%
/dev/grid/node-x27-y22 93T 65T 28T 69%
/dev/grid/node-x27-y23 92T 69T 23T 75%
/dev/grid/node-x27-y24 87T 68T 19T 78%
/dev/grid/node-x27-y25 88T 67T 21T 76%
/dev/grid/node-x27-y26 91T 72T 19T 79%
/dev/grid/node-x28-y0 88T 68T 20T 77%
/dev/grid/node-x28-y1 90T 66T 24T 73%
/dev/grid/node-x28-y2 508T 497T 11T 97%
/dev/grid/node-x28-y3 92T 72T 20T 78%
/dev/grid/node-x28-y4 92T 72T 20T 78%
/dev/grid/node-x28-y5 92T 73T 19T 79%
/dev/grid/node-x28-y6 85T 69T 16T 81%
/dev/grid/node-x28-y7 92T 69T 23T 75%
/dev/grid/node-x28-y8 85T 68T 17T 80%
/dev/grid/node-x28-y9 85T 69T 16T 81%
/dev/grid/node-x28-y10 88T 72T 16T 81%
/dev/grid/node-x28-y11 90T 70T 20T 77%
/dev/grid/node-x28-y12 86T 66T 20T 76%
/dev/grid/node-x28-y13 88T 72T 16T 81%
/dev/grid/node-x28-y14 89T 68T 21T 76%
/dev/grid/node-x28-y15 91T 67T 24T 73%
/dev/grid/node-x28-y16 85T 68T 17T 80%
/dev/grid/node-x28-y17 94T 65T 29T 69%
/dev/grid/node-x28-y18 87T 68T 19T 78%
/dev/grid/node-x28-y19 94T 65T 29T 69%
/dev/grid/node-x28-y20 94T 67T 27T 71%
/dev/grid/node-x28-y21 86T 66T 20T 76%
/dev/grid/node-x28-y22 94T 68T 26T 72%
/dev/grid/node-x28-y23 87T 67T 20T 77%
/dev/grid/node-x28-y24 91T 70T 21T 76%
/dev/grid/node-x28-y25 86T 68T 18T 79%
/dev/grid/node-x28-y26 88T 73T 15T 82%
/dev/grid/node-x29-y0 94T 68T 26T 72%
/dev/grid/node-x29-y1 91T 69T 22T 75%
/dev/grid/node-x29-y2 509T 498T 11T 97%
/dev/grid/node-x29-y3 94T 70T 24T 74%
/dev/grid/node-x29-y4 88T 64T 24T 72%
/dev/grid/node-x29-y5 93T 69T 24T 74%
/dev/grid/node-x29-y6 86T 71T 15T 82%
/dev/grid/node-x29-y7 88T 67T 21T 76%
/dev/grid/node-x29-y8 90T 73T 17T 81%
/dev/grid/node-x29-y9 85T 66T 19T 77%
/dev/grid/node-x29-y10 92T 66T 26T 71%
/dev/grid/node-x29-y11 87T 69T 18T 79%
/dev/grid/node-x29-y12 89T 66T 23T 74%
/dev/grid/node-x29-y13 88T 65T 23T 73%
/dev/grid/node-x29-y14 91T 67T 24T 73%
/dev/grid/node-x29-y15 94T 68T 26T 72%
/dev/grid/node-x29-y16 93T 70T 23T 75%
/dev/grid/node-x29-y17 90T 70T 20T 77%
/dev/grid/node-x29-y18 90T 73T 17T 81%
/dev/grid/node-x29-y19 91T 69T 22T 75%
/dev/grid/node-x29-y20 94T 68T 26T 72%
/dev/grid/node-x29-y21 89T 69T 20T 77%
/dev/grid/node-x29-y22 89T 70T 19T 78%
/dev/grid/node-x29-y23 87T 66T 21T 75%
/dev/grid/node-x29-y24 88T 65T 23T 73%
/dev/grid/node-x29-y25 94T 73T 21T 77%
/dev/grid/node-x29-y26 93T 69T 24T 74%
/dev/grid/node-x30-y0 91T 68T 23T 74%
/dev/grid/node-x30-y1 91T 68T 23T 74%
/dev/grid/node-x30-y2 510T 495T 15T 97%
/dev/grid/node-x30-y3 87T 73T 14T 83%
/dev/grid/node-x30-y4 93T 73T 20T 78%
/dev/grid/node-x30-y5 91T 64T 27T 70%
/dev/grid/node-x30-y6 89T 67T 22T 75%
/dev/grid/node-x30-y7 88T 69T 19T 78%
/dev/grid/node-x30-y8 92T 69T 23T 75%
/dev/grid/node-x30-y9 85T 67T 18T 78%
/dev/grid/node-x30-y10 94T 71T 23T 75%
/dev/grid/node-x30-y11 89T 66T 23T 74%
/dev/grid/node-x30-y12 93T 67T 26T 72%
/dev/grid/node-x30-y13 88T 73T 15T 82%
/dev/grid/node-x30-y14 85T 64T 21T 75%
/dev/grid/node-x30-y15 90T 71T 19T 78%
/dev/grid/node-x30-y16 86T 69T 17T 80%
/dev/grid/node-x30-y17 90T 68T 22T 75%
/dev/grid/node-x30-y18 93T 73T 20T 78%
/dev/grid/node-x30-y19 90T 71T 19T 78%
/dev/grid/node-x30-y20 90T 71T 19T 78%
/dev/grid/node-x30-y21 87T 66T 21T 75%
/dev/grid/node-x30-y22 87T 69T 18T 79%
/dev/grid/node-x30-y23 85T 64T 21T 75%
/dev/grid/node-x30-y24 90T 70T 20T 77%
/dev/grid/node-x30-y25 91T 70T 21T 76%
/dev/grid/node-x30-y26 86T 70T 16T 81%
/dev/grid/node-x31-y0 85T 66T 19T 77%
/dev/grid/node-x31-y1 87T 66T 21T 75%
/dev/grid/node-x31-y2 503T 490T 13T 97%
/dev/grid/node-x31-y3 85T 65T 20T 76%
/dev/grid/node-x31-y4 90T 70T 20T 77%
/dev/grid/node-x31-y5 87T 70T 17T 80%
/dev/grid/node-x31-y6 93T 68T 25T 73%
/dev/grid/node-x31-y7 92T 73T 19T 79%
/dev/grid/node-x31-y8 87T 69T 18T 79%
/dev/grid/node-x31-y9 87T 64T 23T 73%
/dev/grid/node-x31-y10 89T 64T 25T 71%
/dev/grid/node-x31-y11 94T 65T 29T 69%
/dev/grid/node-x31-y12 87T 70T 17T 80%
/dev/grid/node-x31-y13 93T 65T 28T 69%
/dev/grid/node-x31-y14 94T 69T 25T 73%
/dev/grid/node-x31-y15 92T 66T 26T 71%
/dev/grid/node-x31-y16 90T 72T 18T 80%
/dev/grid/node-x31-y17 88T 71T 17T 80%
/dev/grid/node-x31-y18 88T 68T 20T 77%
/dev/grid/node-x31-y19 89T 71T 18T 79%
/dev/grid/node-x31-y20 88T 69T 19T 78%
/dev/grid/node-x31-y21 93T 72T 21T 77%
/dev/grid/node-x31-y22 88T 73T 15T 82%
/dev/grid/node-x31-y23 88T 71T 17T 80%
/dev/grid/node-x31-y24 88T 69T 19T 78%
/dev/grid/node-x31-y25 90T 69T 21T 76%
/dev/grid/node-x31-y26 88T 70T 18T 79%
/dev/grid/node-x32-y0 92T 66T 26T 71%
/dev/grid/node-x32-y1 90T 70T 20T 77%
/dev/grid/node-x32-y2 503T 497T 6T 98%
/dev/grid/node-x32-y3 87T 67T 20T 77%
/dev/grid/node-x32-y4 86T 70T 16T 81%
/dev/grid/node-x32-y5 91T 68T 23T 74%
/dev/grid/node-x32-y6 90T 71T 19T 78%
/dev/grid/node-x32-y7 87T 69T 18T 79%
/dev/grid/node-x32-y8 87T 64T 23T 73%
/dev/grid/node-x32-y9 94T 69T 25T 73%
/dev/grid/node-x32-y10 87T 72T 15T 82%
/dev/grid/node-x32-y11 89T 72T 17T 80%
/dev/grid/node-x32-y12 94T 69T 25T 73%
/dev/grid/node-x32-y13 89T 70T 19T 78%
/dev/grid/node-x32-y14 90T 71T 19T 78%
/dev/grid/node-x32-y15 93T 64T 29T 68%
/dev/grid/node-x32-y16 88T 65T 23T 73%
/dev/grid/node-x32-y17 86T 73T 13T 84%
/dev/grid/node-x32-y18 90T 73T 17T 81%
/dev/grid/node-x32-y19 89T 66T 23T 74%
/dev/grid/node-x32-y20 92T 71T 21T 77%
/dev/grid/node-x32-y21 93T 73T 20T 78%
/dev/grid/node-x32-y22 87T 71T 16T 81%
/dev/grid/node-x32-y23 90T 73T 17T 81%
/dev/grid/node-x32-y24 93T 68T 25T 73%
/dev/grid/node-x32-y25 90T 67T 23T 74%
/dev/grid/node-x32-y26 93T 71T 22T 76%
/dev/grid/node-x33-y0 90T 66T 24T 73%
/dev/grid/node-x33-y1 87T 67T 20T 77%
/dev/grid/node-x33-y2 503T 498T 5T 99%
/dev/grid/node-x33-y3 93T 69T 24T 74%
/dev/grid/node-x33-y4 91T 64T 27T 70%
/dev/grid/node-x33-y5 89T 70T 19T 78%
/dev/grid/node-x33-y6 86T 68T 18T 79%
/dev/grid/node-x33-y7 91T 65T 26T 71%
/dev/grid/node-x33-y8 93T 64T 29T 68%
/dev/grid/node-x33-y9 87T 68T 19T 78%
/dev/grid/node-x33-y10 90T 73T 17T 81%
/dev/grid/node-x33-y11 92T 64T 28T 69%
/dev/grid/node-x33-y12 88T 65T 23T 73%
/dev/grid/node-x33-y13 86T 71T 15T 82%
/dev/grid/node-x33-y14 93T 71T 22T 76%
/dev/grid/node-x33-y15 88T 69T 19T 78%
/dev/grid/node-x33-y16 91T 69T 22T 75%
/dev/grid/node-x33-y17 87T 70T 17T 80%
/dev/grid/node-x33-y18 93T 67T 26T 72%
/dev/grid/node-x33-y19 90T 73T 17T 81%
/dev/grid/node-x33-y20 88T 68T 20T 77%
/dev/grid/node-x33-y21 86T 68T 18T 79%
/dev/grid/node-x33-y22 94T 70T 24T 74%
/dev/grid/node-x33-y23 85T 65T 20T 76%
/dev/grid/node-x33-y24 86T 67T 19T 77%
/dev/grid/node-x33-y25 86T 67T 19T 77%
/dev/grid/node-x33-y26 88T 73T 15T 82%
/dev/grid/node-x34-y0 85T 67T 18T 78%
/dev/grid/node-x34-y1 90T 71T 19T 78%
/dev/grid/node-x34-y2 503T 491T 12T 97%
/dev/grid/node-x34-y3 92T 68T 24T 73%
/dev/grid/node-x34-y4 92T 64T 28T 69%
/dev/grid/node-x34-y5 86T 67T 19T 77%
/dev/grid/node-x34-y6 88T 67T 21T 76%
/dev/grid/node-x34-y7 87T 66T 21T 75%
/dev/grid/node-x34-y8 87T 70T 17T 80%
/dev/grid/node-x34-y9 90T 72T 18T 80%
/dev/grid/node-x34-y10 87T 66T 21T 75%
/dev/grid/node-x34-y11 87T 69T 18T 79%
/dev/grid/node-x34-y12 90T 66T 24T 73%
/dev/grid/node-x34-y13 85T 66T 19T 77%
/dev/grid/node-x34-y14 85T 64T 21T 75%
/dev/grid/node-x34-y15 93T 72T 21T 77%
/dev/grid/node-x34-y16 89T 73T 16T 82%
/dev/grid/node-x34-y17 85T 64T 21T 75%
/dev/grid/node-x34-y18 94T 69T 25T 73%
/dev/grid/node-x34-y19 86T 71T 15T 82%
/dev/grid/node-x34-y20 86T 69T 17T 80%
/dev/grid/node-x34-y21 86T 70T 16T 81%
/dev/grid/node-x34-y22 86T 72T 14T 83%
/dev/grid/node-x34-y23 93T 68T 25T 73%
/dev/grid/node-x34-y24 90T 68T 22T 75%
/dev/grid/node-x34-y25 90T 67T 23T 74%
/dev/grid/node-x34-y26 92T 70T 22T 76%
/dev/grid/node-x35-y0 91T 70T 21T 76%
/dev/grid/node-x35-y1 88T 64T 24T 72%
/dev/grid/node-x35-y2 505T 492T 13T 97%
/dev/grid/node-x35-y3 93T 69T 24T 74%
/dev/grid/node-x35-y4 86T 68T 18T 79%
/dev/grid/node-x35-y5 90T 73T 17T 81%
/dev/grid/node-x35-y6 90T 67T 23T 74%
/dev/grid/node-x35-y7 94T 64T 30T 68%
/dev/grid/node-x35-y8 87T 70T 17T 80%
/dev/grid/node-x35-y9 91T 68T 23T 74%
/dev/grid/node-x35-y10 91T 64T 27T 70%
/dev/grid/node-x35-y11 89T 73T 16T 82%
/dev/grid/node-x35-y12 89T 68T 21T 76%
/dev/grid/node-x35-y13 94T 69T 25T 73%
/dev/grid/node-x35-y14 90T 70T 20T 77%
/dev/grid/node-x35-y15 91T 69T 22T 75%
/dev/grid/node-x35-y16 89T 72T 17T 80%
/dev/grid/node-x35-y17 94T 67T 27T 71%
/dev/grid/node-x35-y18 89T 64T 25T 71%
/dev/grid/node-x35-y19 91T 64T 27T 70%
/dev/grid/node-x35-y20 88T 64T 24T 72%
/dev/grid/node-x35-y21 86T 72T 14T 83%
/dev/grid/node-x35-y22 87T 65T 22T 74%
/dev/grid/node-x35-y23 93T 73T 20T 78%
/dev/grid/node-x35-y24 87T 64T 23T 73%
/dev/grid/node-x35-y25 93T 66T 27T 70%
/dev/grid/node-x35-y26 88T 70T 18T 79%
/dev/grid/node-x36-y0 93T 70T 23T 75%
/dev/grid/node-x36-y1 94T 70T 24T 74%
/dev/grid/node-x36-y2 502T 498T 4T 99%
/dev/grid/node-x36-y3 86T 65T 21T 75%
/dev/grid/node-x36-y4 90T 64T 26T 71%
/dev/grid/node-x36-y5 90T 71T 19T 78%
/dev/grid/node-x36-y6 91T 67T 24T 73%
/dev/grid/node-x36-y7 88T 66T 22T 75%
/dev/grid/node-x36-y8 87T 72T 15T 82%
/dev/grid/node-x36-y9 89T 68T 21T 76%
/dev/grid/node-x36-y10 88T 68T 20T 77%
/dev/grid/node-x36-y11 85T 66T 19T 77%
/dev/grid/node-x36-y12 91T 65T 26T 71%
/dev/grid/node-x36-y13 87T 69T 18T 79%
/dev/grid/node-x36-y14 94T 70T 24T 74%
/dev/grid/node-x36-y15 87T 67T 20T 77%
/dev/grid/node-x36-y16 88T 72T 16T 81%
/dev/grid/node-x36-y17 90T 69T 21T 76%
/dev/grid/node-x36-y18 87T 65T 22T 74%
/dev/grid/node-x36-y19 91T 67T 24T 73%
/dev/grid/node-x36-y20 89T 73T 16T 82%
/dev/grid/node-x36-y21 86T 67T 19T 77%
/dev/grid/node-x36-y22 93T 68T 25T 73%
/dev/grid/node-x36-y23 87T 64T 23T 73%
/dev/grid/node-x36-y24 85T 69T 16T 81%
/dev/grid/node-x36-y25 94T 73T 21T 77%
/dev/grid/node-x36-y26 85T 70T 15T 82%"""
| 0 | Kotlin | 0 | 1 | f4890c25841c78784b308db0c814d88cf2de384b | 51,884 | advent-of-code | MIT License |
src/main/kotlin/de/niemeyer/aoc2022/Day12.kt | stefanniemeyer | 572,897,543 | false | {"Kotlin": 175820, "Shell": 133} | /**
* Advent of Code 2022, Day 12: Hill Climbing Algorithm
* Problem Description: https://adventofcode.com/2022/day/12
*/
package de.niemeyer.aoc2022
import de.niemeyer.aoc.points.Point2D
import de.niemeyer.aoc.utils.Resources.resourceAsList
import de.niemeyer.aoc.utils.getClassName
fun main() {
fun part1(input: Hightmap): Int =
input.countMap[input.startPoint] ?: 0
fun part2(input: Hightmap): Int =
input.map.filterValues('a'::equals)
.filterKeys { input.countMap.containsKey(it)}
.keys.minOf { input.countMap.getValue(it) }
val name = getClassName()
val testInput = resourceAsList(fileName = "${name}_test.txt")
val puzzleInput = resourceAsList(fileName = "${name}.txt")
val testMap = Hightmap(testInput)
check(part1(testMap) == 31)
val puzzleMap = Hightmap(puzzleInput)
println(part1(puzzleMap))
check(part1(puzzleMap) == 504)
check(part2(testMap) == 29)
println(part2(puzzleMap))
check(part2(puzzleMap) == 500)
}
class Hightmap(val input: List<String>) {
var startPoint = Point2D.ORIGIN
var endPoint = Point2D.ORIGIN
val map: Map<Point2D, Char> = input.flatMapIndexed { row, line ->
line.mapIndexed { col, elevation ->
val point = Point2D(col, row)
point to when (elevation) {
'S' -> 'a'.also { startPoint = point }
'E' -> 'z'.also { endPoint = point }
else -> elevation
}
}
}.toMap()
val countMap = buildMap {
var count = 0
var candidates = setOf(endPoint)
while (candidates.isNotEmpty()) {
candidates = buildSet {
candidates.forEach { candidate ->
if (putIfAbsent(candidate, count) != null) {
return@forEach
}
addAll(validNeighbors((candidate)))
}
}
count++
}
}
fun validNeighbors(candidate: Point2D): List<Point2D> {
val candidateElevation = map.getOrDefault(candidate, Char.MAX_VALUE)
return candidate.neighbors.filter { neighbor ->
val neighborElevation = map.getOrDefault(neighbor, Char.MAX_VALUE)
neighbor.x >= 0 && neighbor.y >= 0
&& candidate.sharesAxisWith(neighbor)
&& neighbor in map.keys
&& candidateElevation - neighborElevation <= 1
}
}
}
| 0 | Kotlin | 0 | 0 | ed762a391d63d345df5d142aa623bff34b794511 | 2,492 | AoC-2022 | Apache License 2.0 |
src/main/kotlin/com/github/solairerove/algs4/leprosorium/arrays/DistinctEvenPairSum.kt | solairerove | 282,922,172 | false | {"Kotlin": 251919} | package com.github.solairerove.algs4.leprosorium.arrays
/**
* Given a circular array of N integers (i.e. A[0] and A[N — 1] are adjacent to each other),
* what's the maximum number of adjacent pairs that you can form whose sum are even?
* Note that each element can belong to at most one pair.
*
* Examples:
* 1. Given A = [4, 2, 5, 8, 7, 3, 71], the function should return 2.
* We can create two pairs with even sums: (A[0], A[1]) and (A[4], A[5]).
* Another way to choose two pairs is: (A[0], A[1]) and (A[5], A[6]).
*
* 2. Given A = [14, 21, 16, 35, 22], the function should return 1.
* There is only one qualifying pair: (A[0], A[4]).
*
* 3. Given A = [5, 5, 5, 5, 5, 5], the function should return 3.
* We can create three pairs: (A[0], A(5]), (A[1], A(2) and (A(3], A[4)).
*
* Write an efficient algorithm for the following assumptions:
* N is an integer within the range [1.100,000];
*
* each element of array A is an integer within the range
* [0..1,000,000,000].
*/
// O(n) time | O(1) space
fun getDistinctPair(arr: IntArray): Int {
if (arr.size == 1) return 0
if (arr.size == 2) return if ((arr[0] + arr[1]) % 2 == 0) 1 else 0
var cnt = 0
var slow = 0
var fast = arr.size - 1
if ((arr[slow] + arr[fast]) % 2 == 0) {
cnt++
slow = 1
fast = 2
} else {
fast = 1
}
val endIdx = if (cnt == 1) arr.size - 2 else arr.size - 1
while (fast <= endIdx) {
if ((arr[slow] + arr[fast]) % 2 == 0) {
slow += 2
fast += 2
cnt++
} else {
slow++
fast++
}
}
return cnt
}
// O(n) time | O(n) space
fun getDistinctPairUsingSet(arr: IntArray): Int {
val indices = hashSetOf<Int>()
for (i in arr.indices) {
val idx = if (i == arr.size - 1) Pair(i, 0) else Pair(i, i + 1)
if (!indices.containsAll(listOf(idx.first, idx.second)) && (arr[idx.first] + arr[idx.second]) % 2 == 0) {
indices.addAll(listOf(idx.first, idx.second))
}
}
return indices.size / 2
}
// O(2n) time | O(n) space
fun getDistinctPairUsingBoolArray(arr: IntArray): Int {
val indices = Array(arr.size) { false }
for (i in arr.indices) {
val idx = if (i == arr.size - 1) Pair(i, 0) else Pair(i, i + 1)
if (!indices[idx.first] && !indices[idx.second]) {
if ((arr[idx.first] + arr[idx.second]) % 2 == 0) {
indices[idx.first] = true.also { indices[idx.second] = true }
}
}
}
return indices.filter { it }.size / 2
}
| 1 | Kotlin | 0 | 3 | 64c1acb0c0d54b031e4b2e539b3bc70710137578 | 2,589 | algs4-leprosorium | MIT License |
src/Day15.kt | a-glapinski | 572,880,091 | false | {"Kotlin": 26602} | import Day15.rangesFor
import utils.Coordinate2D
import utils.readInputAsLines
import utils.union
import kotlin.math.abs
fun main() {
val input = readInputAsLines("day15_input")
val regex = """x=(-?[0-9]+), y=(-?[0-9]+).*x=(-?[0-9]+), y=(-?[0-9]+)""".toRegex()
val sensorReports = input
.mapNotNull { regex.find(it)?.destructured }
.map { (x1, y1, x2, y2) -> Coordinate2D(x1.toInt(), y1.toInt()) to Coordinate2D(x2.toInt(), y2.toInt()) }
val beacons = sensorReports.map { it.second }.toSet()
fun part1(rowNumber: Int) = sensorReports.rangesFor(rowNumber).let { ranges ->
IntRange(ranges.minOf { it.first }, ranges.maxOf { it.last }).count() - beacons.count { it.y == rowNumber }
}
println(part1(rowNumber = 2_000_000))
fun part2(): Long {
for (rowNumber in 0..4_000_000) {
sensorReports.rangesFor(rowNumber).reduce { acc, range ->
(acc union range).takeUnless { it.isEmpty() } ?: return (acc.last + 1) * 4_000_000L + rowNumber
}
}
error("Distress beacon not found.")
}
println(part2())
}
object Day15 {
fun List<Pair<Coordinate2D, Coordinate2D>>.rangesFor(rowNumber: Int): List<IntRange> =
mapNotNull { (sensor, beacon) ->
val distance = sensor distanceTo beacon
val first = sensor.x - distance + abs(rowNumber - sensor.y)
val last = sensor.x + distance - abs(rowNumber - sensor.y)
IntRange(first, last).takeUnless { it.isEmpty() }
}.sortedBy { it.first }
} | 0 | Kotlin | 0 | 0 | c830d23ffc2ab8e9a422d015ecd413b5b01fb1a8 | 1,558 | advent-of-code-2022 | Apache License 2.0 |
src/Day14.kt | Fenfax | 573,898,130 | false | {"Kotlin": 30582} | import java.awt.Point
fun main() {
val startPoint = Point(500, 0)
fun buildWalls(input: List<String>): Set<Point> {
return input.flatMap { row ->
row.split("->")
.map { cord ->
cord.split(",")
.map { it.trim().toInt() }
.let { Point(it[0], it[1]) }
}
.zipWithNext { current, next ->
(minOf(current.x, next.x)..maxOf(current.x, next.x))
.flatMap { x ->
(minOf(current.y, next.y)..maxOf(current.y, next.y))
.map { y ->
Point(x, y)
}
}
}.flatten()
.toSet()
}.toSet()
}
fun nextPoint(currentPoint: Point, occupiedPoints: Set<Point>, maxY: Int): Point {
val nextPoint: Point = currentPoint.location
if (nextPoint.y + 1 == maxY) {
return nextPoint
}
nextPoint.translate(0, 1)
if (!occupiedPoints.contains(nextPoint))
return nextPoint(nextPoint, occupiedPoints, maxY)
nextPoint.translate(-1, 0)
if (!occupiedPoints.contains(nextPoint))
return nextPoint(nextPoint, occupiedPoints, maxY)
nextPoint.translate(2, 0)
if (!occupiedPoints.contains(nextPoint))
return nextPoint(nextPoint, occupiedPoints, maxY)
return currentPoint
}
fun part1(input: List<String>): Int {
val occupiedPoints = buildWalls(input).toMutableSet()
val maxY = occupiedPoints.maxOf { it.y } + 1
var stepCount = 0
do {
stepCount += 1
val nextPoint = nextPoint(startPoint, occupiedPoints, maxY)
occupiedPoints.add(nextPoint)
} while (nextPoint.y <= maxY - 2)
return stepCount - 1
}
fun part2(input: List<String>): Int{
val occupiedPoints = buildWalls(input).toMutableSet()
val maxY = occupiedPoints.maxOf { it.y } + 2
var stepCount = 0
do {
stepCount += 1
val nextPoint = nextPoint(startPoint, occupiedPoints, maxY)
occupiedPoints.add(nextPoint)
} while (nextPoint != startPoint)
return stepCount
}
val input = readInput("Day14")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 28af8fc212c802c35264021ff25005c704c45699 | 2,464 | AdventOfCode2022 | Apache License 2.0 |
src/main/kotlin/aoc2023/Day11.kt | davidsheldon | 565,946,579 | false | {"Kotlin": 161960} | package aoc2023
import utils.ArrayAsSurface
import utils.Coordinates
import utils.InputUtils
import utils.boundingBox
fun Coordinates.distanceTo(other: Coordinates) = (other - this).length()
fun <T> allPairs(items: List<T>): Sequence<Pair<T,T>> = items.asSequence().flatMapIndexed { a, first ->
(a..<items.size).mapNotNull { b -> items[b].let { first to it } }
}
fun main() {
val testInput = """...#......
.......#..
#.........
..........
......#...
.#........
.........#
..........
.......#..
#...#.....""".trimIndent().split("\n")
fun expand(galaxies: List<Coordinates>, scale: Int = 2): List<Coordinates> {
val bounds = galaxies.boundingBox()
val emptyColumns = (bounds.first.x..bounds.second.x)
.filter { x -> galaxies.none { it.x == x } }
val emptyRows = (bounds.first.y..bounds.second.y)
.filter { y -> galaxies.none { it.y == y } }
val expanded = galaxies.map { coord ->
val newX = coord.x + (emptyColumns.count { it < coord.x } * (scale - 1))
val newY = coord.y + (emptyRows.count { it < coord.y } * (scale - 1))
Coordinates(newX, newY)
}
return expanded
}
fun part1(input: List<String>): Int {
val universe = ArrayAsSurface(input)
val galaxies = universe.indexed()
.filter { (_, char) -> char != '.' }
.map { it.first }.toList()
val expanded = expand(galaxies)
println((galaxies.size * (galaxies.size - 1)) / 2)
println(expanded)
println(expanded[4].distanceTo(expanded[8]))
println(expanded[0].distanceTo(expanded[6]))
println(expanded[2].distanceTo(expanded[5]))
return allPairs(expanded).sumOf { it.first.distanceTo(it.second) }
}
fun part2(input: List<String>): Long {
val universe = ArrayAsSurface(input)
val galaxies = universe.indexed()
.filter { (_, char) -> char != '.' }
.map { it.first }.toList()
val expanded = expand(galaxies, 1_000_000)
return allPairs(expanded).sumOf { it.first.distanceTo(it.second).toLong() }
}
// test if implementation meets criteria from the description, like:
val testValue = part1(testInput)
println(testValue)
check(testValue == 374)
println(part2(testInput))
val puzzleInput = InputUtils.downloadAndGetLines(2023, 11)
val input = puzzleInput.toList()
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 5abc9e479bed21ae58c093c8efbe4d343eee7714 | 2,487 | aoc-2022-kotlin | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.