path
stringlengths
5
169
owner
stringlengths
2
34
repo_id
int64
1.49M
755M
is_fork
bool
2 classes
languages_distribution
stringlengths
16
1.68k
content
stringlengths
446
72k
issues
float64
0
1.84k
main_language
stringclasses
37 values
forks
int64
0
5.77k
stars
int64
0
46.8k
commit_sha
stringlengths
40
40
size
int64
446
72.6k
name
stringlengths
2
64
license
stringclasses
15 values
src/Day15.kt
IvanChadin
576,061,081
false
{"Kotlin": 26282}
import kotlin.math.abs import kotlin.math.max import kotlin.math.min fun main() { val inputName = "Day15_test" data class Pt(val x: Int, val y: Int) fun distance(a: Pt, b: Pt) = abs(b.x - a.x) + abs(b.y - a.y) fun part1(): Int { val ansY = 2000000 var l = Int.MAX_VALUE var r = Int.MIN_VALUE val dist = HashMap<Pt, Int>() val occupied = HashSet<Pt>() readInput(inputName).map { s -> s.split(" ", "=", ":", ",") .filter { it.isNotBlank() && (it[0].isDigit() || it[0] == '-') } .map { it.toInt() } .toIntArray() }.forEach { val s = Pt(it[0], it[1]) val b = Pt(it[2], it[3]) val d = distance(s, b) dist[s] = d occupied.add(s) occupied.add(b) l = min(l, s.x - d) r = max(r, s.x + d) } var ans = 0 for (x in l..r) { val cur = Pt(x, ansY) if (occupied.contains(cur)) { continue } for (station in dist.keys) { if (distance(cur, station) <= dist[station]!!) { ans++ break } } } return ans } fun part2(): Long { val dist = HashMap<Pt, Int>() val occupied = HashSet<Pt>() readInput(inputName).map { s -> s.split(" ", "=", ":", ",") .filter { it.isNotBlank() && (it[0].isDigit() || it[0] == '-') } .map { it.toInt() } .toIntArray() }.forEach { val s = Pt(it[0], it[1]) val b = Pt(it[2], it[3]) val d = distance(s, b) dist[s] = d occupied.add(s) occupied.add(b) } val maxXY = 4_000_000 for (a in dist.keys) { val d = dist[a]!! + 1 for (k in 0..d) { for (xsign in arrayOf(-1, 1)) { for (ysign in arrayOf(-1, 1)) { val cur = Pt(a.x + xsign * k, a.y + ysign * (d - k)) if (cur.x !in 0..maxXY || cur.y !in 0..maxXY) { continue } var isAns = true for (b in dist.keys) { if (a == b) { continue } if (distance(cur, b) <= dist[b]!!) { isAns = false break } } if (isAns) { return cur.x.toLong() * 4_000_000L + cur.y.toLong() } } } } } return 0 } val result = part2() println(result) }
0
Kotlin
0
0
2241437e6c3a20de70306a0cb37b6fe2ed8f9e3a
2,974
aoc-2022
Apache License 2.0
src/main/kotlin/dev/bogwalk/util/combinatorics/reusable.kt
bog-walk
381,459,475
false
null
package dev.bogwalk.util.combinatorics import dev.bogwalk.util.maths.factorial import java.math.BigInteger /** * Returns the number of ways to choose [k] items from [n] items without repetition and without * order, namely C(n, k). * * @throws IllegalArgumentException if either Int is negative. */ fun binomialCoefficient(n: Int, k: Int): BigInteger { require(n >= 0 && k >= 0) { "Both numbers must be non-negative" } if (k > n) return BigInteger.ZERO return n.factorial() / (k.factorial() * (n - k).factorial()) } /** * Original implementation of an algorithm that returns [r]-length subLists of [elements]. * * SPEED (EQUAL) 23.8ms for N = 9, r = 6 * SPEED (WORSE) 485.19ms for N = 19, r = 15 */ private fun <T: Any> getCombinations(elements: Iterable<T>, r: Int): List<List<T>> { if (r == 1) return elements.map { listOf(it) } val input = elements.toList() if (r > input.size || r == 0) return emptyList() val combinations = mutableListOf<List<T>>() for (i in input.indices) { val element = mutableListOf(input[i]) for (c in getCombinations(input.slice((i+1)..input.lastIndex), r-1)) { combinations.add(element + c) } } return combinations } /** * Mimics the Python itertools module function and returns [r]-length subLists of [elements]. * * If [elements] is sorted, combinations will be yielded in lexicographic order. * * If [elements] contains only unique values, there will be no repeat values in each combination. * * e.g. elements = "ABCD", r = 2 -> AB AC AD BC BD CD * * The number of yielded combinations, if n = the amount of elements, is: * * n!/r!/(n - r)! * * This solution will be preferentially used in future solutions. * * SPEED (EQUAL) 24.1ms for N = 9, r = 6 * SPEED (BETTER) 69.72ms for N = 19, r = 15 */ fun <T: Any> combinations(elements: Iterable<T>, r: Int) = sequence { val input = elements.toList() val n = input.size if (r == 0 || r > n) return@sequence val indices = (0 until r).toMutableList() while (true) { yield(List(r) { input[indices[it]] }) var i = r - 1 while (i >= 0) { if (indices[i] != i + n - r) break if (i-- == 0) return@sequence } indices[i]++ for (j in i + 1 until r) { indices[j] = indices[j-1] + 1 } } } /** * Mimics the Python itertools module function and returns [r]-length subLists of [elements] * allowing individual elements to be repeated more than once. * * If [elements] is sorted, combinations will be yielded in lexicographic order. * * If [elements] contains only unique values, combinations will also be unique. * * e.g. elements = "ABCD", r = 2 -> AA AB AC AD BB BC BD CC CD DD * * The number of yielded combinations, if n = the amount of elements, is: * * (n + r - 1)!/r!/(n - 1)! */ fun <T: Any> combinationsWithReplacement(elements: Iterable<T>, r: Int) = sequence { val input = elements.toList() val n = input.size if (r == 0 || n == 0) return@sequence var indices = List(r) { 0 } while (true) { yield(List(r) { input[indices[it]] }) var i = r - 1 while (i >= 0) { if (indices[i] != n - 1) break if (i-- == 0) return@sequence } indices = indices.slice(0 until i) + List(r - i) { indices[i] + 1 } } } /** * Heap's Algorithm to generate all [size]! permutations of a list of [size] characters with * minimal movement, so returned list is not necessarily sorted. This is unlike the solution * below that returns an already sorted order of permutations & is flexible enough to accept a * size smaller than the size of elements available, as well as elements other than CharSequence. * * Initially k = [size], then recursively k decrements and each step generates k! permutations that * end with the same [size] - k elements. Each step modifies the initial k - 1 elements with a * swap based on k's parity. * * SPEED (WORSE) 2.46s for N = 10, r = 10 * * @throws OutOfMemoryError if [size] > 10, consider using an iterative approach instead. */ private fun getPermutations( chars: MutableList<Char>, size: Int, perms: MutableList<String> = mutableListOf() ): List<String> { if (size == 1) { perms.add(chars.joinToString("")) } else { repeat(size) { i -> getPermutations(chars, size - 1, perms) // avoids unnecessary swaps of the kth & 0th element if (i < size - 1) { val swap = if (size % 2 == 0) i else 0 chars[size - 1] = chars[swap].also { chars[swap] = chars[size - 1] } } } } return perms } /** * Mimics the Python itertools module function and returns successive [r]-length permutations of * [elements]. * * If [elements] is sorted, permutations will be yielded in lexicographic order. * * If [elements] contains only unique values, there will be no repeat values in each permutation. * * e.g. elements = "ABCD", r = 2 -> AB AC AD BA BC BD CA CB CD DA DB DC * * The number of yielded permutations, if n = the amount of elements, is: * * n!/(n - r)! * * This solution will be preferentially used in future solutions. * * SPEED (BETTER) 20500ns for N = 10, r = 10 */ fun <T: Any> permutations(elements: Iterable<T>, r: Int = -1) = sequence { val input = elements.toList() val n = input.size val k = if (r == -1) n else r if (k == 0 || k > n) return@sequence var indices = (0 until n).toMutableList() val cycles = (n downTo n - k + 1).toMutableList() yield(List(k) { input[indices[it]] }) while (true) { var i = k - 1 while (i >= 0) { if (--cycles[i] == 0) { indices = (indices.take(i) + indices.slice(i + 1..indices.lastIndex) + indices[i]).toMutableList() cycles[i] = n - i if (i-- == 0) return@sequence } else { val j = cycles[i] indices[n-j] = indices[i].also { indices[i] = indices[n-j] } yield(List(k) { input[indices[it]] }) break } } } } /** * Generates a hash key based on the amount of repeated digits, represented as an ordered LTR * array. * * Hash key must be stored as an array rather than a number to allow for the possibility that [n] * may have a digit that is repeated more than 9 times. * * e.g. 1487 -> [0, 1, 0, 0, 1, 0, 0, 1, 1] * 2214 -> [0, 1, 2, 0, 4] * 1_000_000_000_000 -> [12, 1] * * N.B. An alternative hash key would be the sorted string cast of the number, using * num.toString().toList().sorted().joinToString(""). * e.g. 1487 -> "1478", 2023 -> "0223". * * N.N.B. Permutation ID results should be compared using contents of the IntArray, as comparing * joined String representations, may lead to errors; e.g. 1_000_000_000_000 has the same String * ID ("121") as 1012. * * This solution would only be used if arguments were expected to consistently be greater than * 15-digits long or performance was not a concern. * * SPEED (WORSE) 30.59ms for N = Long.MAX_VALUE * * @param [n] Number may have digits that are duplicated any number of times. */ internal fun permutationIDOG(n: Long): IntArray { var perm = n val permID = IntArray(n.toString().maxOf { it }.digitToInt() + 1) while (perm > 0) { val digit = (perm % 10).toInt() permID[digit]++ perm /= 10 } return permID } /** * Generates a hash key based on the amount of repeated digits, represented as a String. * * Instead of storing digits counts in an array, a bitwise left shift accumulates a Long value * that is unique, based on the fact that a left arithmetic shift by x is equivalent to * multiplying by 2^x, such that: * * 1 << x * d == (2^x)^d, * with x equal 4, since 2^4 is the first to exceed a single-digit value. * * If 2 is used, 2222222222222222 will have the same hash as 3333 (i.e. 256) because * (16 * (2^2)^2) == (4 * 4^3). * If 3 is used, 22222222 will have the same hash as 3 (i.e. 512) because * (8 * (2^3)^2) == (1 * 8^3). * * This means that the following solution cannot allow a digit to occur 16 times, * e.g. 2222222222222222 will have the same hash as 3 (i.e. 4096) because * (16 * (2^4)^2) == (1 * 16^3). * * This solution will be preferentially used in future solutions when speed is necessary and * arguments are not expected to be greater than 15-digits long. * * SPEED (BETTER) 1.8e+04ns for N = Long.MAX_VALUE * * @param [n] Number should not be greater than 15-digits long to ensure duplicates of 16 digits * are not present. */ fun permutationID(n: Long): String { var perm = n var permID = 0L while (perm > 0) { val digit = (perm % 10).toInt() permID += 1L shl 4 * digit perm /= 10 } return permID.toString() } /** * Returns Cartesian product of [elements]. * * To return the product of an iterable with itself, specify the number of repetitions using * [repeat]. * * If [elements] is sorted, product lists will be yielded in lexicographic order. * * e.g. elements = "ABCD", "xy" -> Ax Ay Bx By Cx Cy Dx Dy * e.g. elements = "AB", repeat = 2 -> AA AB BA BB */ fun <T: Any> product( vararg elements: Iterable<T>, repeat: Int = 1 ) = sequence { if (elements.isEmpty()) return@sequence val inputs = mutableListOf<List<T>>() for (i in 0 until repeat) { inputs += elements.map { it.toList() } } val results = inputs.fold(listOf(listOf<T>())) { acc, list -> acc.flatMap { accList -> list.map { e -> accList + e } } } for (result in results) { yield(result) } }
0
Kotlin
0
0
62b33367e3d1e15f7ea872d151c3512f8c606ce7
9,800
project-euler-kotlin
MIT License
src/Day11.kt
gojoel
573,543,233
false
{"Kotlin": 28426}
fun main() { val input = readInput("11") // val input = readInput("11_test") data class Monkey(val id: Int, val items: ArrayList<Long>, var inspections: Long = 0, val op: (old: Long) -> Long, val mod: Long, val test: (worry: Long) -> Boolean, val recipients: Pair<Int, Int>) fun operation(input: String) : (old: Long) -> Long { val subString = input.substringAfter("=").split(" ").takeLast(2) val operator = subString[0] val operand = subString[1] return { i: Long -> val value = if (operand == "old") { i } else { operand.toLong() } when (operator) { "+" -> i + value "*" -> i * value else -> i } } } fun parseMonkey(input: List<String>) : Monkey { val monkeyId = input[0].filter { char -> char.isDigit() }.toInt() val items = ArrayList(input[1].substringAfter(":").split(",").map { item -> item.trim().toLong() }) val op = operation(input[2]) val mod = input[3].split(" ").last().trim().toLong() val test = { i : Long -> i % mod == 0L } val trueRecipient = input[4].split(" ").last().trim().toInt() val falseRecipient = input[5].split(" ").last().trim().toInt() return Monkey(monkeyId, items, 0, op, mod, test, Pair(trueRecipient, falseRecipient)) } fun getMonkeys(input: List<String>) : HashMap<Int, Monkey> { val monkeyMap: HashMap<Int, Monkey> = hashMapOf() for (i in 0..input.size step 7) { val monkey = parseMonkey(input.subList(i, i+6)) monkeyMap[monkey.id] = monkey } return monkeyMap } fun part1(input: List<String>) : Long { val map = getMonkeys(input) for (i in 0 until 20) { map.keys.forEach { map[it]?.let { monkey -> val itr = monkey.items.iterator() while (itr.hasNext()) { val item = itr.next() var worryLevel = monkey.op(item) worryLevel = (worryLevel / 3) monkey.inspections++ if (monkey.test(worryLevel)) { map[monkey.recipients.first]?.items?.add(worryLevel) } else { map[monkey.recipients.second]?.items?.add(worryLevel) } itr.remove() } } } } return map.values.sortedBy { m -> m.inspections }.map { m -> m.inspections }.takeLast(2).fold(1L) { mul, item -> mul * item.toLong() } } fun part2(input: List<String>) : Long { val map = getMonkeys(input) var worryMod: Long = 1 map.keys.forEach { key -> map[key]?.let { worryMod *= it.mod } } for (i in 0 until 10000) { map.keys.forEach { map[it]?.let { monkey -> val itr = monkey.items.iterator() while (itr.hasNext()) { val item = itr.next() var worryLevel = monkey.op(item) worryLevel %= worryMod monkey.inspections++ if (monkey.test(worryLevel)) { map[monkey.recipients.first]?.items?.add(worryLevel) } else { map[monkey.recipients.second]?.items?.add(worryLevel) } itr.remove() } } } } return map.values.sortedBy { m -> m.inspections }.map { m -> m.inspections }.takeLast(2).fold(1L) { mul, item -> mul * item.toLong() } } println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
0690030de456dad6dcfdcd9d6d2bd9300cc23d4a
3,942
aoc-kotlin-22
Apache License 2.0
src/day08/Code.kt
ldickmanns
572,675,185
false
{"Kotlin": 48227}
package day08 import readInput fun main() { val input = readInput("day08/input") // val input = readInput("day08/input_test") val grid = extractGrid(input) println(part1(grid)) println(part2(grid)) } private fun extractGrid( input: List<String> ): Array<IntArray> = input.map { row: String -> IntArray(row.length) { row[it].digitToInt() } }.toTypedArray() private val <T> Array<T>.nRows get() = size private val Array<IntArray>.nColumns get() = first().size fun part1(grid: Array<IntArray>): Int { val isVisible = Array(grid.nRows) { BooleanArray(grid.nColumns) } checkRows(grid, isVisible) checkColumns(grid, isVisible) return isVisible.sumOf { row -> row.count { it } } } private fun checkRows( grid: Array<IntArray>, isVisible: Array<BooleanArray>, ): Array<BooleanArray> { grid.forEachIndexed { rowIndex, row -> var highestTreeFromLeft = -1 var highestTreeFromRight = -1 repeat(row.size) { columnIndexFromLeft -> val treeFromLeft = row[columnIndexFromLeft] if (treeFromLeft > highestTreeFromLeft) { highestTreeFromLeft = treeFromLeft isVisible[rowIndex][columnIndexFromLeft] = true } val columnIndexFromRight = row.lastIndex - columnIndexFromLeft val treeFromRight = row[columnIndexFromRight] if (treeFromRight > highestTreeFromRight) { highestTreeFromRight = treeFromRight isVisible[rowIndex][columnIndexFromRight] = true } } } return isVisible } private fun checkColumns( grid: Array<IntArray>, isVisible: Array<BooleanArray>, ) { repeat(grid.nColumns) { columnIndex -> var highestTreeFromTop = -1 var highestTreeFromBottom = -1 repeat(grid.nRows) { rowIndexFromTop -> val treeFromTop = grid[rowIndexFromTop][columnIndex] if (treeFromTop > highestTreeFromTop) { highestTreeFromTop = treeFromTop isVisible[rowIndexFromTop][columnIndex] = true } val rowIndexFromBottom = grid.lastIndex - rowIndexFromTop val treeFromBottom = grid[rowIndexFromBottom][columnIndex] if (treeFromBottom > highestTreeFromBottom) { highestTreeFromBottom = treeFromBottom isVisible[rowIndexFromBottom][columnIndex] = true } } } } fun part2( grid: Array<IntArray>, ): Int { val scenicScore = Array(grid.nRows) { IntArray(grid.nColumns) { 1 } } checkRows(grid, scenicScore) checkColumns(grid, scenicScore) return scenicScore.maxOf { it.max() } } private const val N_DIGITS = 10 private fun checkRows( grid: Array<IntArray>, scenicScore: Array<IntArray>, ) { repeat(grid.nRows) { rowIndex -> val canSeeTreesToLeft = IntArray(N_DIGITS) // going from left to right val canSeeTreesToRight = IntArray(N_DIGITS) // going from right to left repeat(grid.nColumns) { columnIndexFromLeft -> val treeFromLeft = grid[rowIndex][columnIndexFromLeft] scenicScore[rowIndex][columnIndexFromLeft] *= canSeeTreesToLeft[treeFromLeft] for (i in 0..treeFromLeft) canSeeTreesToLeft[i] = 1 for (i in treeFromLeft + 1 until N_DIGITS) canSeeTreesToLeft[i] += 1 val columnIndexFromRight = grid[rowIndex].lastIndex - columnIndexFromLeft val treeFromRight = grid[rowIndex][columnIndexFromRight] scenicScore[rowIndex][columnIndexFromRight] *= canSeeTreesToRight[treeFromRight] for (i in 0..treeFromRight) canSeeTreesToRight[i] = 1 for (i in treeFromRight + 1 until N_DIGITS) canSeeTreesToRight[i] += 1 } } } private fun checkColumns( grid: Array<IntArray>, scenicScore: Array<IntArray>, ) { repeat(grid.nColumns) { columnIndex -> val canSeeTreesToTop = IntArray(N_DIGITS) // going from top to bottom val canSeeTreesToBottom = IntArray(N_DIGITS) // going from bottom to top repeat(grid.nRows) { rowIndexFromTop -> val treeFromTop = grid[rowIndexFromTop][columnIndex] scenicScore[rowIndexFromTop][columnIndex] *= canSeeTreesToTop[treeFromTop] for (i in 0..treeFromTop) canSeeTreesToTop[i] = 1 for (i in treeFromTop + 1 until N_DIGITS) canSeeTreesToTop[i] += 1 val rowIndexFromBottom = grid.lastIndex - rowIndexFromTop val treeFromBottom = grid[rowIndexFromBottom][columnIndex] scenicScore[rowIndexFromBottom][columnIndex] *= canSeeTreesToBottom[treeFromBottom] for (i in 0..treeFromBottom) canSeeTreesToBottom[i] = 1 for (i in treeFromBottom + 1 until N_DIGITS) canSeeTreesToBottom[i] += 1 } } }
0
Kotlin
0
0
2654ca36ee6e5442a4235868db8174a2b0ac2523
4,868
aoc-kotlin-2022
Apache License 2.0
2020/src/year2021/day05/code.kt
eburke56
436,742,568
false
{"Kotlin": 61133}
package year2021.day05 import util.readAllLines import kotlin.math.max import kotlin.math.min private class Node(initialValue: Int) { var value: Int = initialValue private set fun increment() { value += 1 } } private class Board(values: List<String>, val allowDiagonal: Boolean = false) { private val data = mutableMapOf<Pair<Int, Int>, Node>() init { values.forEach { line -> val points = line.split(Regex(" -> ")).map { it.split(",") } val (x1, y1) = points[0].map { it.toInt() } val (x2, y2) = points[1].map { it.toInt() } val xmin = min(x1, x2) val xmax = max(x1, x2) val ymin = min(y1, y2) val ymax = max(y1, y2) if (allowDiagonal && (ymax - ymin == xmax - xmin)) { val xstep = (if (x2 > x1) 1 else -1) val ystep = (if (y2 > y1) 1 else -1) var key = <KEY>) repeat((xmin..xmax).count()) { incrementNode(key) key = Pair(key.first + xstep, key.second + ystep) } } else if (xmin == xmax) { (ymin..ymax).forEach { incrementNode(Pair(x1, it)) } } else if (ymin == ymax) { (xmin..xmax).forEach { incrementNode(Pair(it, ymin)) } } } } private fun incrementNode(key: Pair<Int, Int>) { if (!data.containsKey(key)) { data[key] = Node(1) } else { data[key]?.increment() } } fun countNodesGreaterThan(value: Int): Int { return data.values.count { it.value > value } } } fun main() { part1() part2() } private fun part1() { val input = readAllLines("input.txt") val board = Board(input) println(board.countNodesGreaterThan(1)) } private fun part2() { val input = readAllLines("input.txt") val board = Board(input, true) println(board.countNodesGreaterThan(1)) }
0
Kotlin
0
0
24ae0848d3ede32c9c4d8a4bf643bf67325a718e
2,074
adventofcode
MIT License
src/day03/Day03.kt
Klaus-Anderson
572,740,347
false
{"Kotlin": 13405}
package day03 import readInput fun main() { fun part1(input: List<String>): Int { return input.sumOf { bagString -> val comp1 = bagString.substring(0, bagString.length / 2) val comp2 = bagString.substring(bagString.length / 2, bagString.length) val commonLetters = comp1.filter { comp2.contains(it) }.toSet().toList() commonLetters.sumOf { it.convertToScore() } } } fun part2(input: List<String>): Int { return List(input.size) { index -> if (index.mod(3) == 0) { val bag1 = input[index] val bag2 = input[index + 1] val bag3 = input[index + 2] bag1.first { bag2.contains(it) && bag3.contains(it) }.convertToScore() } else { 0 } }.sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("day03", "Day03_test") check(part1(testInput) == 157) // check(part2(testInput) == 12) val input = readInput("day03", "Day03") println(part1(input)) println(part2(input)) } private fun Char.convertToScore(): Int { return this.lowercase()[0] - 'a' + 1 + if (this.isUpperCase()) { 26 } else { 0 } }
0
Kotlin
0
0
faddc2738011782841ec20475171909e9d4cee84
1,397
harry-advent-of-code-kotlin-template
Apache License 2.0
src/Day04.kt
max-zhilin
573,066,300
false
{"Kotlin": 114003}
fun main() { fun contains(a: String, b: String): Boolean { val (ax, ay) = a.split("-").map { it.toInt() } val (bx, by) = b.split("-").map { it.toInt() } if (ax <= bx && ay >= by) return true if (bx <= ax && by >= ay) return true return false } fun overlaps(a: String, b: String): Boolean { val (ax, ay) = a.split("-").map { it.toInt() } val (bx, by) = b.split("-").map { it.toInt() } if (ax in bx..by) return true if (ay in bx..by) return true if (bx in ax..ay) return true if (by in ax..ay) return true return false } fun part1(input: List<String>): Int { var sum = 0 input.forEach { val (left, right) = it.split(",") if (contains(left, right)) sum++ } return sum } fun part2(input: List<String>): Int { var sum = 0 input.forEach { val (left, right) = it.split(",") if (overlaps(left, right)) sum++ } return sum } // test if implementation meets criteria from the description, like: val testInput = readInput("Day04_test") // println(part1(testInput)) check(part1(testInput) == 2) // println(part2(testInput)) check(part2(testInput) == 4) val input = readInput("Day04") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
d9dd7a33b404dc0d43576dfddbc9d066036f7326
1,400
AoC-2022
Apache License 2.0
src/day10/Day10.kt
GrzegorzBaczek93
572,128,118
false
{"Kotlin": 44027}
package day10 import readInput import utils.withStopwatch fun main() { val testInput = readInput("input10_test") // withStopwatch { part1(testInput) } // withStopwatch { part2(testInput) } val input = readInput("input10") // withStopwatch { part1(input) } withStopwatch { part2(input) } } private fun part1(input: List<String>): Int { val cyclesHistory = mutableMapOf( 20 to 0, 60 to 0, 100 to 0, 140 to 0, 180 to 0, 220 to 0, ) var cycle = 0 var x = 1 input.forEach { line -> Command.from(line).execute( onEachCycle = { cycle++ if (cyclesHistory.containsKey(cycle)) { cyclesHistory[cycle] = cycle * x } }, onCyclesEnd = { cmd -> if (cmd is Command.Addx) x += cmd.x } ) } return cyclesHistory.values.sum() } private fun part2(input: List<String>) { var cycle = 0 var x = 1 input.forEach { line -> Command.from(line).execute( onEachCycle = { cycle += 1 print(x = x, cycle = cycle) }, onCyclesEnd = { cmd -> if (cmd is Command.Addx) x += cmd.x } ) } } private fun print(x: Int, cycle: Int) { val char = if ((cycle - 1).mod(40) + 1 in (x..x + 2)) '#' else '.' if (cycle.mod(40) == 0) println(char) else print(char) } private sealed class Command { abstract val cycles: Int data class Addx(val x: Int = 0) : Command() { override val cycles: Int = 2 } object Noop : Command() { override val cycles: Int = 1 } companion object { fun from(line: String): Command { return when { line.startsWith("addx") -> Addx(line.split(" ").last().toInt()) line.startsWith("noop") -> Noop else -> error("Unsupported operation") } } } } private fun Command.execute(onEachCycle: () -> Unit, onCyclesEnd: (Command) -> Unit) { repeat(cycles) { onEachCycle() } onCyclesEnd(this) }
0
Kotlin
0
0
543e7cf0a2d706d23c3213d3737756b61ccbf94b
2,201
advent-of-code-kotlin-2022
Apache License 2.0
src/main/kotlin/aoc/day7/NoSpaceLeftOnDevice.kt
hofiisek
573,543,194
false
{"Kotlin": 17421}
package aoc.day7 import aoc.dropFirst import aoc.loadInput import java.io.File /** * https://adventofcode.com/2022/day/8 * * @author <NAME> */ val RGX_FILE = "(\\d+) ([\\w.]+)".toRegex() val RGX_DIR = "dir (\\w+)".toRegex() val RGX_CD_DIR = "\\$ cd (\\w+)".toRegex() val RGX_CD_BACK = "\\$ cd ..".toRegex() val RGX_LS = "\\$ ls".toRegex() sealed interface Command object Ls : Command object CdBack : Command object Dir : Command data class CdDir(val into: String): Command data class AocFile(val name: String, val size: Int): Command data class Directory( val name: String, val parent: Directory? = null, val directories: MutableList<Directory> = mutableListOf(), val files: MutableList<AocFile> = mutableListOf() ) fun Directory.size(): Int = files.sumOf(AocFile::size) + directories.sumOf(Directory::size) fun String.asCommand(): Command = when { matches(RGX_FILE) -> RGX_FILE.matchEntire(this)!! .groupValues .let { val size = it[1] val name = it[2] AocFile(name, size.toInt()) } matches(RGX_CD_DIR) -> RGX_CD_DIR.matchEntire(this)!! .groupValues .last() .let(::CdDir) matches(RGX_CD_BACK) -> CdBack matches(RGX_DIR) -> Dir matches(RGX_LS) -> Ls else -> throw IllegalArgumentException("Invalid command: $this") } fun List<Command>.readDirectories(): List<Directory> { fun readDirectories( currentDir: Directory, dirs: List<Directory> = emptyList(), commands: List<Command> = this ): List<Directory> = when (val command = commands.firstOrNull()) { null -> dirs // no more commands is AocFile -> readDirectories(currentDir.also { it.files.add(command) }, dirs, commands.dropFirst()) CdBack -> readDirectories( currentDir.parent ?: throw IllegalArgumentException("Dir $currentDir has no parent"), dirs, commands.dropFirst() ) is CdDir -> { val newDir = Directory(command.into, currentDir) readDirectories(newDir.also { currentDir.directories.add(it) }, dirs + newDir, commands.dropFirst()) } Ls, Dir -> readDirectories(currentDir, dirs, commands.dropFirst()) } val rootDir = Directory("/") return readDirectories(rootDir, listOf(rootDir)) } fun File.part1() = readLines() .dropFirst() .map(String::asCommand) .let(List<Command>::readDirectories) .map(Directory::size) .filter { it < 100000 } .sum() .also(::println) fun File.part2() = readLines() .dropFirst() .map(String::asCommand) .let(List<Command>::readDirectories) .let { directories -> val freeSpace = 70000000 - directories.first().size() directories.map { it.size() } .filter { size -> freeSpace + size >= 30000000 } .minBy { it } } .also(::println) fun main() { with(loadInput(day = 7)) { part1() part2() } }
0
Kotlin
0
2
5908a665db4ac9fc562c44d6907f81cd3cd8d647
2,995
Advent-of-code-2022
MIT License
src/Day03.kt
graesj
572,651,121
false
{"Kotlin": 10264}
fun Char.getScore(): Int { return if (this.isLowerCase()) this - 'a' + 1 else this - 'A' + 27 } fun main() { operator fun List<Set<Char>>.component1() = this.first() operator fun List<Set<Char>>.component2() = this[1] operator fun List<Set<Char>>.component3() = this[2] fun part1(input: List<String>): Int { return input.sumOf { racksack -> val compartments: List<Set<Char>> = racksack.chunked(racksack.length / 2).map { it.toCharArray().toSet() } val (compartmentOne, compartmentTwo) = compartments val intersection = compartmentOne intersect compartmentTwo intersection.first().getScore() } } fun part2(input: List<String>): Int { return input.map { it.toCharArray().toSet() }.chunked(3).sumOf { group -> val (rsOne, rsTwo, rsThree) = group val intersection = (rsOne intersect rsTwo) intersect rsThree intersection.first().getScore() } } // test if implementation meets criteria from the description, like: val testInput = readLines("Day03_test") check(part2(testInput) == 70) val input = readLines("Day03") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
df7f855a14c532f3af7a8dc86bd159e349cf59a6
1,233
aoc-2022
Apache License 2.0
src/Day03.kt
khongi
572,983,386
false
{"Kotlin": 24901}
fun main() { fun Char.getPriority(): Int { return if (isLowerCase()) { this - 'a' + 1 } else { this - 'A' + 27 } } fun Set<Char>.findCommon(other: String): Set<Char> { return toCharArray().intersect(other.asIterable().toSet()) } fun part1(input: List<String>): Int { var sum = 0 input.forEach { rucksack -> val firstHalf = rucksack.substring(0..rucksack.lastIndex/2) val secondHalf = rucksack.substring(rucksack.length/2..rucksack.lastIndex) sum += firstHalf.asIterable().toSet().findCommon(secondHalf).sumOf { it.getPriority() } } return sum } fun part2(input: List<String>): Int { val groups = input.chunked(3) var sum = 0 groups.forEach { group -> val (first, second, third) = group sum += first .asIterable() .toSet() .findCommon(second) .findCommon(third) .sumOf { it.getPriority() } } 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
9cc11bac157959f7934b031a941566d0daccdfbf
1,313
adventofcode2022
Apache License 2.0
src/Day03.kt
rickbijkerk
572,911,701
false
{"Kotlin": 31571}
fun main() { fun part1(input: List<String>): Int { val alphabet = "<KEY>" val duplicateLetters = input.map { line -> val part1 = line.substring(0, line.length / 2) val part2 = line.substring(line.length / 2, line.length) part1.toCharArray().toList().intersect(part2.toCharArray().toList()).first() }.map { letter -> var number = alphabet.indexOf(letter, ignoreCase = true) +1 if (letter.isUpperCase()) { number += 26 } number } return duplicateLetters.sum() } fun part2(input: List<String>): Int { val alphabet = "abcdefgh<KEY>" val setsOfThree = input.map { it.toCharArray().toList() }.chunked(3) val result = setsOfThree.map {setOfThree -> setOfThree[0].intersect(setOfThree[1]).intersect(setOfThree[2]).first() }.map { letter -> var number = alphabet.indexOf(letter, ignoreCase = true) +1 if (letter.isUpperCase()) { number += 26 } number } return result.sum() } val testInput = readInput("day03_test") // test part1 val resultPart1 = part1(testInput) val expectedPart1 = 157 //TODO Change me println("Part1\nresult: $resultPart1") println("expected:$expectedPart1 \n") check(resultPart1 == expectedPart1) //Check results part1 val input = readInput("day03") println("Part1 ${part1(input)}\n\n") // test part2 val resultPart2 = part2(testInput) val expectedPart2 = 70 //TODO Change me println("Part2\nresult: $resultPart2") println("expected:$expectedPart2 \n") check(resultPart2 == expectedPart2) //Check results part2 println("Part2 ${part2(input)}") }
0
Kotlin
0
0
817a6348486c8865dbe2f1acf5e87e9403ef42fe
1,860
aoc-2022
Apache License 2.0
src/day16/Day16.kt
dkoval
572,138,985
false
{"Kotlin": 86889}
package day16 import readInput import kotlin.system.measureTimeMillis private const val DAY_ID = "16" private data class Valve( val id: String, val rate: Int, val adj: List<String> ) fun main() { fun parseInput(input: List<String>): Map<String, Valve> { val valve = """Valve ([A-Z]{2}) has flow rate=(\d+)""".toRegex() val tunnels = """tunnels? leads? to valves? (.*)""".toRegex() return input.asSequence() .map { line -> val (s1, s2) = line.split("; ") val (id, rate) = valve.let { it.find(s1)!!.destructured } val adj = tunnels.let { it.find(s2)!!.groupValues[1] }.split(", ") Valve(id, rate.toInt(), adj) } .associateBy { it.id } } fun solve(lookup: Map<String, Valve>, start: String, maxTime: Int, withElephant: Boolean): Int { data class Key( val valve: String, val time: Int, val opened: Set<String>, val withElephant: Boolean ) // DP top-down val dp = mutableMapOf<Key, Int>() fun traverse(valve: String, time: Int, opened: Set<String>, withElephant: Boolean): Int { // base case if (time == 0) { // Work alone first, then get an elephant to help you and make him aware about // the valves your opened to let the elephant make his own decisions. // This will simulate the process of two of you working together. if (withElephant) { return traverse(start, maxTime, opened, false) } return 0 } // already solved? val key = Key(valve, time, opened, withElephant) if (key in dp) { return dp[key]!! } val curr = lookup[valve]!! var best = 0 // option #1: skip the current valve for (neighbor in curr.adj) { best = maxOf(best, traverse(neighbor, time - 1, opened, withElephant)) } // option #2: open the current valve to release more pressure in the remaining (time - 1) minutes if (curr.id !in opened && curr.rate > 0) { best = maxOf(best, traverse(curr.id, time - 1, opened + curr.id, withElephant) + (time - 1) * curr.rate) } // cache and return the answer dp[key] = best return best } return traverse(start, maxTime, setOf(), withElephant) } fun part1(input: List<String>): Int { val lookup = parseInput(input) return solve(lookup, "AA", 30, false) } fun part2(input: List<String>): Int { val lookup = parseInput(input) return solve(lookup, "AA", 26, true) } // test if implementation meets criteria from the description, like: val testInput = readInput("day${DAY_ID}/Day${DAY_ID}_test") check(part1(testInput) == 1651) check(part2(testInput) == 1707) val input = readInput("day${DAY_ID}/Day${DAY_ID}") // takes ~ 2 seconds on MacBook Pro 2015 measureTimeMillis { println(part1(input)) // answer = 1845 }.also { println("Part 1 took $it ms") } // takes ~ 9 minutes on MacBook Pro 2015 // // Food for thoughts: // - use integers to label valves, i.e. AA -> 0, BB -> 1, CC -> 2, ... // - bitmask to compress the set of opened valves into an integer, i.e. ["AA", "CC", "DD] -> ...1101 // - use a pure integer for a DP key // - DP can be represented as an array instead of a map, which is more performant measureTimeMillis { println(part2(input)) // answer = 2286 }.also { println("Part 2 took $it ms") } }
0
Kotlin
1
0
791dd54a4e23f937d5fc16d46d85577d91b1507a
3,795
aoc-2022-in-kotlin
Apache License 2.0
src/main/kotlin/com/chriswk/aoc/advent2020/Day11.kt
chriswk
317,863,220
false
{"Kotlin": 481061}
package com.chriswk.aoc.advent2020 import com.chriswk.aoc.AdventDay import com.chriswk.aoc.util.Pos import com.chriswk.aoc.util.report import java.lang.IllegalStateException class Day11 : AdventDay(2020, 11) { companion object { @JvmStatic fun main(args: Array<String>) { val day = Day11() report { day.part1() } report { day.part2() } } val neighbours = sequenceOf( Pair(-1, -1), Pair(0, -1), Pair(1, -1), Pair(-1, 0), Pair(1, 0), Pair(-1, 1), Pair(0, 1), Pair(1, 1) ) } fun findEquilibrium(seats: Seats, tolerance: Int, comparisonFunction: (Seats, Seat) -> Int): Seats { return generateSequence(seats) { it.next(tolerance, comparisonFunction) }.zipWithNext().first { (current, next) -> current.contentDeepEquals(next) }.first } fun closestSeatAxis(seats: Seats, seat: Seat, axis: Seat): Char? { return generateSequence(seat + axis) { it + axis }.map { if (it in seats) { seats[it.first][it.second] } else { null } }.first { it == null || it != '.' } } fun occupiedNeighboursAxis(seats: Seats, seat: Seat): Int { return neighbours.mapNotNull { closestSeatAxis(seats, seat, it) }.count { it == '#' } } fun part1(): Int { val seats: Seats = inputAsLines.map { it.toCharArray() }.toTypedArray() return findEquilibrium(seats, 4, this::occupiedNeighbours).occupied() } fun occupiedNeighbours(seats: Seats, seat: Seat): Int { return neighbours.map { it + seat }.filter { it in seats }.count { seats[it.first][it.second] == '#' } } fun part2(): Int { val seats: Seats = inputAsLines.map { it.toCharArray() }.toTypedArray() return findEquilibrium(seats, 5, this::occupiedNeighboursAxis).occupied() } } typealias Seats = Array<CharArray> operator fun Seats.contains(seat: Seat) = seat.first in this.indices && seat.second in this.first().indices fun Seats.occupied() = this.sumOf { row -> row.count { it == '#' } } fun Seats.next(tolerance: Int, countFunction: (Seats, Seat) -> Int): Seats { return this.mapIndexed { x, row -> row.mapIndexed { y, spot -> val occupied = countFunction(this, Seat(x, y)) when { spot == 'L' && occupied == 0 -> '#' spot == '#' && occupied >= tolerance -> 'L' else -> spot } }.toCharArray() }.toTypedArray() } typealias Seat = Pair<Int, Int> private operator fun Seat.plus(other: Seat): Seat = Seat(this.first + other.first, this.second + other.second)
116
Kotlin
0
0
69fa3dfed62d5cb7d961fe16924066cb7f9f5985
2,756
adventofcode
MIT License
src/day02/Day02.kt
elenavuceljic
575,436,628
false
{"Kotlin": 5472}
package day02 import java.io.File enum class MyHand(val hand: Char, val scoreWorth: Int) { X('R', 1), Y('P', 2), Z('S', 3); } enum class OpponentHand(val hand: Char) { A('R'), B('P'), C('S'); } fun scoreGame(theirs: OpponentHand, mine: MyHand): Int = when { mine.hand == theirs.hand -> 3 (mine == MyHand.X && theirs == OpponentHand.C) || (mine == MyHand.Y && theirs == OpponentHand.A) || (mine == MyHand.Z && theirs == OpponentHand.B) -> 6 else -> 0 } + mine.scoreWorth fun calculateHand(round: String): Int = when (round) { "A X", "B Z", "C Y" -> 3 "B Y", "C X", "A Z" -> 2 "A Y", "B X", "C Z" -> 1 else -> 0 } + (round[2] - 'X') * 3 fun main() { fun part1(input: String): Int { val games = input.split("\n").map { it.split(" ") } println(games) val score = games.fold(0) { acc, hands -> acc + scoreGame(OpponentHand.valueOf(hands[0]), MyHand.valueOf(hands[1])) } return score } fun part2(input: String): Int { val games = input.split("\n") println(games) val score = games.fold(0) { acc, game -> acc + calculateHand(game) } return score } val testInput = File("src/day02/Day02_test.txt").readText().trim() val part1Solution = part1(testInput) val part2Solution = part2(testInput) println(part1Solution) check(part1Solution == 15) check(part2Solution == 12) val input = File("src/day02/Day02.txt").readText().trim() println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
c5093b111fd02e28823d31f2edddb7e66c295add
1,565
advent-of-code-2022
Apache License 2.0
src/Day04.kt
arhor
572,349,244
false
{"Kotlin": 36845}
fun main() { val input = readInput {}.map { line -> line.split(",") .map { pair -> pair.split("-").map(String::toInt) } .map { (min, max) -> Range(min, max) } } println("Part 1: " + solvePuzzle(input)) println("Part 2: " + solvePuzzle(input, completelyOverlapping = false)) } private fun solvePuzzle(input: List<List<Range>>, completelyOverlapping: Boolean = true): Int { return input.count { (one, two) -> one.overlaps(two, completely = completelyOverlapping) } } private data class Range(val min: Int, val max: Int) { fun overlaps(that: Range, completely: Boolean = false): Boolean = if (completely) { that.min >= this.min && that.max <= this.max || that.min <= this.min && that.max >= this.max } else { that.min >= this.min && that.min <= this.max || that.min <= this.min && that.max >= this.min } }
0
Kotlin
0
0
047d4bdac687fd6719796eb69eab2dd8ebb5ba2f
886
aoc-2022-in-kotlin
Apache License 2.0
src/day18/first/Solution.kt
verwoerd
224,986,977
false
null
package day18.first import tools.Coordinate import tools.adjacentCoordinates import tools.origin import tools.priorityQueueOf import tools.timeSolution /** * @author verwoerd * @since 18-12-2019 */ typealias Maze = MutableMap<Coordinate, MazeTile> typealias PointsOfInterest = Map<Coordinate, Char> // key, path, keys on you typealias SearchTriple = Triple<Char, MutableSet<Char>, Int> fun main() = timeSolution { val keyLocations = mutableMapOf<Char, Coordinate>() val doorLocations = mutableMapOf<Char, Coordinate>() val poi = mutableMapOf<Coordinate, Char>() var startLocation: Coordinate = origin val maze = System.`in`.bufferedReader().readLines().mapIndexed { y: Int, value: String -> value.toCharArray().mapIndexed { x, char -> val coordinate = Coordinate(x, y) coordinate to when (char) { '#' -> MazeTile.WALL '.' -> MazeTile.EMPTY '@' -> { startLocation = coordinate poi[coordinate] = char MazeTile.START } in 'a'..'z' -> { keyLocations[char] = coordinate poi[coordinate] = char MazeTile.KEY } in 'A'..'Z' -> { doorLocations[char] = coordinate poi[coordinate] = char MazeTile.DOOR } else -> error("invalid Tile $char") } } }.flatten().toMap().toMutableMap() val optionsMap = maze.optionsMap(keyLocations, poi, startLocation) println(traverseTheOptions(optionsMap, keyLocations)) } fun Maze.findKeysRequiredFor( coordinate: Coordinate, targetCoordinate: Coordinate, poi: PointsOfInterest ): Triple<Coordinate, PointsOfInterest, Int>? { var queue = listOf<Triple<Coordinate, PointsOfInterest, Int>>(Triple(coordinate, mutableMapOf(), 0)) val seen = mutableSetOf<Coordinate>() var startFound = false while (queue.isNotEmpty() && !startFound) { queue = queue.flatMap { (current, pointsOfInterest, distance) -> adjacentCoordinates(current).filter { seen.add(it) } .filter { getValue(it) != MazeTile.WALL } .map { val newPoi = pointsOfInterest.toMutableMap() when (it) { targetCoordinate -> startFound = true else -> when (getValue(it)) { MazeTile.DOOR, MazeTile.KEY -> newPoi[it] = poi.getValue(it) else -> Unit } } Triple(it, newPoi, distance + 1) }.toList() } } return queue.firstOrNull { it.first == targetCoordinate } } fun Maze.optionsMap(keyLocations: Map<Char, Coordinate>, poi: PointsOfInterest, startLocation: Coordinate) = keyLocations.mapValues { (_, targetCoordinate) -> keyLocations.filter { it.value != targetCoordinate }.mapValues { this.findKeysRequiredFor(targetCoordinate, it.value, poi) } } + ('@' to keyLocations.mapValues { findKeysRequiredFor(it.value, startLocation, poi) }) fun traverseTheOptions( optionsMap: Map<Char, Map<Char, Triple<Coordinate, PointsOfInterest, Int>?>>, keyLocations: Map<Char, Coordinate> ): SearchTriple? { val filterDoorMap = mutableMapOf<PointsOfInterest, Set<Char>>() val filterKeyMap = mutableMapOf<PointsOfInterest, Set<Char>>() val seen = mutableSetOf<SearchTriple>() // Greedy search for the longest path to create a cutoff point val queue = priorityQueueOf<SearchTriple>( Comparator { o1, o2 -> -1 * o1.second.size.compareTo(o2.second.size) }, Triple('@', mutableSetOf(), 0) ) var bestPath: SearchTriple? = null while (queue.isNotEmpty()) { val (current, path, distance) = queue.poll() if (distance > bestPath?.third ?: Int.MAX_VALUE) continue val options = optionsMap.getValue(current) .filter { it.key !in path } .filter { candidate -> path.containsAll(filterDoorMap.computeIfAbsent(candidate.value!!.second) { key -> key.values.filter { it in 'A'..'Z' }.map { it.toLowerCase() }.toSet() }) } .map { candidate -> Triple( candidate.key, path.toMutableSet().also { entry -> entry.addAll( filterKeyMap.computeIfAbsent( candidate.value!!.second ) { key -> key.values.filter { it in 'a'..'z' }.toSet() }) }.also { it.add(candidate.key) }, distance + candidate.value!!.third ) }.filter { it.third < bestPath?.third ?: Int.MAX_VALUE }.filter { seen.add(it) } options.filter { it.second.containsAll(keyLocations.keys) }.forEach { println("Found possible path $it") bestPath = when (bestPath) { null -> it else -> when { it.third < bestPath!!.third -> it else -> bestPath } } } options .toCollection(queue) } return bestPath } enum class MazeTile { WALL, EMPTY, START, KEY, DOOR }
0
Kotlin
0
0
554377cc4cf56cdb770ba0b49ddcf2c991d5d0b7
4,988
AoC2019
MIT License
src/Day09.kt
VadimB95
574,449,732
false
{"Kotlin": 19743}
import kotlin.math.absoluteValue import kotlin.math.sign fun main() { // 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)) } private fun part1(input: List<String>): Int { return getVisitedCount(input, 2) } private fun part2(input: List<String>): Int { return getVisitedCount(input, 10) } private fun getVisitedCount(input: List<String>, knotsCount: Int): Int { val startCoordinates = Coordinates(0, 0) val knotsCoordinates = List(knotsCount) { startCoordinates }.toMutableList() val visited = HashSet<Coordinates>() visited.add(startCoordinates) for (line in input) { val command = parseCommand(line) repeat(command.moves) { var headX = knotsCoordinates[0].x var headY = knotsCoordinates[0].y when (command.direction) { Direction.R -> headX++ Direction.L -> headX-- Direction.U -> headY++ Direction.D -> headY-- } knotsCoordinates[0] = Coordinates(headX, headY) for (i in 1..knotsCoordinates.lastIndex) { knotsCoordinates[i] = getNewKnotCoordinates(knotsCoordinates[i], knotsCoordinates[i - 1]) } visited.add(knotsCoordinates.last()) } } return visited.size } private fun getNewKnotCoordinates(oldKnotCoordinates: Coordinates, leadingKnotCoordinates: Coordinates): Coordinates { val isUnchanged = (leadingKnotCoordinates.x - oldKnotCoordinates.x).absoluteValue <= 1 && (leadingKnotCoordinates.y - oldKnotCoordinates.y).absoluteValue <= 1 if (isUnchanged) return oldKnotCoordinates var x = oldKnotCoordinates.x var y = oldKnotCoordinates.y x += (leadingKnotCoordinates.x - oldKnotCoordinates.x).sign y += (leadingKnotCoordinates.y - oldKnotCoordinates.y).sign return Coordinates(x, y) } private fun parseCommand(line: String): Command { val split = line.split(" ") return Command(Direction.valueOf(split[0]), split[1].toInt()) } data class Command( val direction: Direction, val moves: Int ) enum class Direction { R, L, U, D } data class Coordinates(val x: Int, val y: Int)
0
Kotlin
0
0
3634d1d95acd62b8688b20a74d0b19d516336629
2,397
aoc-2022
Apache License 2.0
src/Day01.kt
timmiller17
577,546,596
false
{"Kotlin": 44667}
fun main() { fun part1(input: List<String>): Int { var elfFoodItems = input var mostCalories = 0 while (elfFoodItems.isNotEmpty()) { val endOfItemsIndex = elfFoodItems.indexOfFirst { it.isBlank() } if (endOfItemsIndex != -1) { val calories = elfFoodItems.takeWhile { it.isNotEmpty() } .sumOf { it.toInt() } if (calories > mostCalories) { mostCalories = calories } elfFoodItems = elfFoodItems.subList(endOfItemsIndex + 1, elfFoodItems.size) } else { val calories = elfFoodItems.sumOf { it.toInt() } if (calories > mostCalories) { mostCalories = calories } elfFoodItems = listOf() } } return mostCalories } fun part2(input: List<String>): Int { var elfFoodItems = input val elfCalorieList = mutableListOf<Int>() while (elfFoodItems.isNotEmpty()) { val endOfItemsIndex = elfFoodItems.indexOfFirst { it.isBlank() } if (endOfItemsIndex != -1) { elfCalorieList.add( elfFoodItems.takeWhile { it.isNotEmpty() } .sumOf { it.toInt() } ) elfFoodItems = elfFoodItems.subList(endOfItemsIndex + 1, elfFoodItems.size) } else { elfCalorieList.add(elfFoodItems.sumOf { it.toInt() }) elfFoodItems = listOf() } } return elfCalorieList.sortedDescending().take(3).sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") check(part1(testInput) == 24000) val input = readInput("Day01") part1(input).println() part2(input).println() }
0
Kotlin
0
0
b6d6b647c7bb0e6d9e5697c28d20e15bfa14406c
1,907
advent-of-code-2022
Apache License 2.0
src/Day02.kt
vjgarciag96
572,719,091
false
{"Kotlin": 44399}
import RockPaperScissorsPlayResult.* import RockPaperScissorsShape.* private enum class RockPaperScissorsShape { ROCK, PAPER, SCISSORS, } private enum class RockPaperScissorsPlayResult { WIN, LOSE, DRAW } private fun play( shapeA: RockPaperScissorsShape, shapeB: RockPaperScissorsShape, ): RockPaperScissorsPlayResult { return when (shapeA) { ROCK -> when (shapeB) { PAPER -> LOSE ROCK -> DRAW SCISSORS -> WIN } PAPER -> when (shapeB) { SCISSORS -> LOSE PAPER -> DRAW ROCK -> WIN } SCISSORS -> when (shapeB) { ROCK -> LOSE SCISSORS -> DRAW PAPER -> WIN } } } private fun deserializeOpponentShape(rawShape: String): RockPaperScissorsShape { return when (rawShape) { "A" -> ROCK "B" -> PAPER "C" -> SCISSORS else -> error("Invalid shape $rawShape") } } private fun deserializeYourShape(rawShape: String): RockPaperScissorsShape { return when (rawShape) { "X" -> ROCK "Y" -> PAPER "Z" -> SCISSORS else -> error("Invalid shape $rawShape") } } private fun deserializeResult(result: String): RockPaperScissorsPlayResult { return when (result) { "X" -> LOSE "Y" -> DRAW "Z" -> WIN else -> error("Invalid result $result") } } private fun calculateExpectedShape( opponentShape: RockPaperScissorsShape, expectedResult: RockPaperScissorsPlayResult, ): RockPaperScissorsShape { return RockPaperScissorsShape.values().first { yourShape -> play(shapeA = yourShape, shapeB = opponentShape) == expectedResult } } private fun calculateScore( result: RockPaperScissorsPlayResult, shape: RockPaperScissorsShape, ): Int { val resultScore = when (result) { WIN -> 6 LOSE -> 0 DRAW -> 3 } val shapeScore = when (shape) { ROCK -> 1 PAPER -> 2 SCISSORS -> 3 } return resultScore + shapeScore } fun main() { fun part1(input: List<String>): Int { return input .map { it.split(" ") } .sumOf { (opponent, you) -> val yourShape = deserializeYourShape(you) val opponentShape = deserializeOpponentShape(opponent) val result = play(shapeA = yourShape, shapeB = opponentShape) calculateScore(result, yourShape) } } fun part2(input: List<String>): Int { return input .map { it.split(" ") } .sumOf { (opponent, expectedResult) -> val opponentShape = deserializeOpponentShape(opponent) val result = deserializeResult(expectedResult) val yourShape = calculateExpectedShape(opponentShape, result) calculateScore(result, yourShape) } } val testInput = readInput("Day02_test") check(part1(testInput) == 15) check(part2(testInput) == 12) val input = readInput("Day02") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
ee53877877b21166b8f7dc63c15cc929c8c20430
3,161
advent-of-code-2022
Apache License 2.0
jeorg-kotlin-algorithms/jeorg-kotlin-alg-3-weigh-term-frequency/src/main/kotlin/org/jesperancinha/algorithms/weigh/term/frequency/WeighTermFrequency.kt
jesperancinha
354,756,418
false
{"Kotlin": 35444, "Java": 14401, "JavaScript": 10140, "Python": 4018, "Makefile": 1258, "Shell": 89}
package org.jesperancinha.algorithms.weigh.term.frequency import org.jesperancinha.console.consolerizer.console.ConsolerizerComposer import org.jesperancinha.console.consolerizer.console.ConsolerizerComposer.title import kotlin.math.sqrt fun main(args: Array<String>) { val sentence1 = "I travelled in Germany using the Deutsche Autobahn. I loved the views when going from Berlin to Köln. It is a convenient and fast way to travel. Some find it less dangerous than riding a bike" val sentence2 = "In Germany we could drive fast and for a long time in some of the Autobahn. We could experience views going very fast. It was convenient for some and dangerous for others. Many loved driving there" ConsolerizerComposer.outSpace() .blue(title("Similarity using the Weigh Term Frequency Algorithm")) .magenta("Sentence 1: %s", sentence1) .magenta("Sentence 2: %s", sentence2) .reset() val similarity = findSimilarity(sentence1, sentence2) ConsolerizerComposer.outSpace() .cyan("The similarity is %s", similarity) ConsolerizerComposer.outSpace() .cyan("Our sentences as %.2f%s similar to each other", similarity * 100, "%%") } fun findSimilarity(sentence1: String, sentence2: String): Double { val words1 = sentence1.replace(".", "").split(" ") val words2 = sentence2.replace(".", "").split(" ") val allWords = words1.plus(words2).distinct().sorted() println(words1) println(words2) ConsolerizerComposer.outSpace() .orange(allWords) val tf = allWords.map { mutableListOf(it, words1.filter { word -> word == it }.count(), words2.filter { word -> word == it }.count()) } val document1: List<Int> = tf.map { it[1] as Int } val document2: List<Int> = tf.map { it[2] as Int } tf.forEach { ConsolerizerComposer.outSpace() .yellow("%s\t%s\t%s", (it[0] as String).padStart(10), it[1], it[2]) } val product = multiply(document1, document2) println(product) val length1 = pLength(document1) val length2 = pLength(document2) ConsolerizerComposer.outSpace() .green(length1) ConsolerizerComposer.outSpace() .green(length2) return product.toDouble() / (length1 * length2).toDouble() } fun pLength(document1: List<Int>): Long { var total: Long = 0 for (i in document1.indices) { total += document1[i] * document1[i] } return sqrt(total.toDouble()).toLong() } fun multiply(document1: List<Int>, document2: List<Int>): Long { var total: Long = 0 for (i in document1.indices) { total += document1[i] * document2[i] } return total }
1
Kotlin
0
1
7a382ed529ebdc53cc025671a453c7bd5699539e
2,687
jeorg-algorithms-test-drives
Apache License 2.0
src/Day11.kt
wooodenleg
572,658,318
false
{"Kotlin": 30668}
private const val Lcd = 9699690L class Monkey( val name: String, // for debugging var items: List<Long>, private val inspectionTransformation: (item: Long) -> Long, private val getTargetIndex: (item: Long) -> Int ) { var inspectionCounter = 0L private set fun inspect(divideByThree: Boolean) { inspectionCounter += items.size.toLong() items = items.map { item -> val finalNumber = inspectionTransformation(item) if (divideByThree) finalNumber / 3L else finalNumber % Lcd } } fun throwItems(monkeys: List<Monkey>) { items.forEach { item -> monkeys[getTargetIndex(item)].receiveItem(item) } items = emptyList() } private fun receiveItem(item: Long) { items += item } override fun toString(): String = "$name with items: $items" } fun parseMonkey( name: String, lines: List<String> ): Monkey { val (itemsLine, operationLine, testLine, condition1Line, condition2Line) = lines.drop(1) val items = itemsLine.replace(",", "").split(" ").mapNotNull(String::toLongOrNull) val (firstNum, operator, secondNum) = operationLine.split(" ").takeLast(3) val divisibleBy = testLine.split(" ").last().toLong() val trueTarget = condition1Line.split(" ").last().toInt() val falseTarget = condition2Line.split(" ").last().toInt() return Monkey( name = name, items = items, inspectionTransformation = { item -> val first = if (firstNum == "old") item else firstNum.toLong() val second = if (secondNum == "old") item else secondNum.toLong() if (operator == "*") first * second else first + second }, getTargetIndex = { item -> if ((item % divisibleBy) == 0L) trueTarget else falseTarget } ) } fun parseInput(input: List<String>) = input .filter(String::isNotBlank) .chunked(6) .mapIndexed { index, lines -> parseMonkey("Monkey $index", lines) } fun main() { fun part1(input: List<String>): Int { val monkeys = parseInput(input) repeat(20) { // println("=== Round $it ===") // monkeys.forEach(::println) // println() for (monkey in monkeys) { monkey.inspect(true) monkey.throwItems(monkeys) } } val (first, second) = monkeys.sortedByDescending(Monkey::inspectionCounter).take(2) return (first.inspectionCounter * second.inspectionCounter).toInt() } fun part2(input: List<String>): Long { val monkeys = parseInput(input) repeat(10_000) { // println("=== Round $it ===") // monkeys.forEach(::println) // println() for (monkey in monkeys) { monkey.inspect(false) monkey.throwItems(monkeys) } } val (first, second) = monkeys.sortedByDescending(Monkey::inspectionCounter).take(2) return first.inspectionCounter * second.inspectionCounter } val testInput = readInputLines("Day11_test") check(part1(testInput) == 10605) // check(part2(testInput) == 2713310158L) val input = readInputLines("Day11") println(part1(input)) println(part2(input)) }
0
Kotlin
0
1
ff1f3198f42d1880e067e97f884c66c515c8eb87
3,297
advent-of-code-2022
Apache License 2.0
src/Day03.kt
ds411
573,543,582
false
{"Kotlin": 16415}
fun main() { fun part1(input: List<String>): Int { return input.map { val midpoint = it.length / 2 val sack1 = it.substring(0, midpoint) val sack2 = it.substring(midpoint) sack1.toCharArray().first { sack2.contains(it) } }.map(::itemValue).sum() } fun part2(input: List<String>): Int { return (0 until input.size step 3).map { val sack1 = input[it].toHashSet() val sack2 = input[it+1].toHashSet() val sack3 = input[it+2].toHashSet() sack1.first { sack2.contains(it) && sack3.contains(it) } }.map(::itemValue).sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day03_test") check(part1(testInput) == 157) val input = readInput("Day03") println(part1(input)) println(part2(input)) } private fun itemValue(item: Char): Int { if (item.isLowerCase()) return item.minus('a') + 1 else return item.minus('A') + 27 }
0
Kotlin
0
0
6f60b8e23ee80b46e7e1262723960af14670d482
1,098
advent-of-code-2022
Apache License 2.0
src/main/kotlin/pl/jpodeszwik/aoc2023/Day11.kt
jpodeszwik
729,812,099
false
{"Kotlin": 55101}
package pl.jpodeszwik.aoc2023 import kotlin.math.abs import kotlin.math.max import kotlin.math.min const val GALAXY = '#' data class Universe(val lines: List<String>, val expandedRows: Set<Int>, val expandedCols: Set<Int>, val galaxies: List<Coord>) private fun parseUniverse(lines: List<String>): Universe { val expandedRows = lines.indices.toMutableSet() val expandedCols = lines[0].indices.toMutableSet() val galaxies = ArrayList<Coord>() lines.forEachIndexed { row, s -> s.forEachIndexed { col, c -> if (c == GALAXY) { expandedRows.remove(row) expandedCols.remove(col) galaxies.add(Coord(col, row)) } } } return Universe(lines, expandedRows, expandedCols, galaxies) } private fun calculateDistance(universe: Universe, age: Int): Long { var sum = 0L universe.galaxies.forEachIndexed { idx1, coord1 -> universe.galaxies.forEachIndexed { idx2, coord2 -> if (idx1 < idx2) { var distance = (abs(coord1.x - coord2.x) + abs(coord1.y - coord2.y)) distance += universe.expandedCols.count { it > min(coord1.x, coord2.x) && it < max(coord1.x, coord2.x) } * age distance += universe.expandedRows.count { it > min(coord1.y, coord2.y) && it < max(coord1.y, coord2.y) } * age sum += distance } } } return sum } private fun part1(lines: List<String>) { val universe = parseUniverse(lines) val sum = calculateDistance(universe, 1) println(sum) } private fun part2(lines: List<String>) { val universe = parseUniverse(lines) val sum = calculateDistance(universe, 999999) println(sum) } fun main() { val lines = loadFile("/aoc2023/input11") part1(lines) part2(lines) }
0
Kotlin
0
0
2b90aa48cafa884fc3e85a1baf7eb2bd5b131a63
1,831
advent-of-code
MIT License
src/main/kotlin/coursera/algorithms1/week3/classroom/MergeSort.kt
rupeshsasne
359,696,544
false
null
package coursera.algorithms1.week3.classroom inline fun <reified T> mergeWithSmallerAux(arr: Array<T>, lo: Int, mid: Int, hi: Int, comparator: Comparator<T>) { val aux = Array(((hi - lo) / 2)) { arr[lo + it] } var i = lo var j = mid + 1 var k = lo while (i <= mid && j <= hi) { if (comparator.compare(aux[i], arr[j]) > 0) arr[k++] = arr[j++] else arr[k++] = aux[i++] } while (i <= mid) arr[k++] = aux[i++] while (j <= hi) arr[k++] = arr[j++] } fun <T> merge(arr: Array<T>, aux: Array<T>, lo: Int, mid: Int, hi: Int, comparator: Comparator<T>) { for (i in lo..hi) { aux[i] = arr[i] } var i = lo var j = mid + 1 for (k in lo..hi) { when { i > mid -> arr[k] = aux[j++] j > hi -> arr[k] = aux[i++] // keeps the sort stable. comparator.compare(aux[j], aux[i]) < 0 -> arr[k] = aux[j++] else -> arr[k] = aux[i++] } } } fun <T> mergeSort(arr: Array<T>, aux: Array<T>, lo: Int, hi: Int, comparator: Comparator<T>) { if (hi <= lo) return val mid = lo + (hi - lo) / 2 mergeSort(arr, aux, lo, mid, comparator) mergeSort(arr, aux, mid + 1, hi, comparator) merge(arr, aux, lo, mid, hi, comparator) } inline fun <reified T> mergeSort(arr: Array<T>, comparator: Comparator<T>) { val aux = Array(arr.size) { arr[it] } mergeSort(arr, aux, 0, arr.lastIndex, comparator) } inline fun <reified T> mergeSortIterative(arr: Array<T>, comparator: Comparator<T>) { val aux = Array(arr.size) { arr[it] } var sz = 1 while (sz < arr.size) { var lo = 0 while (lo < arr.size - sz) { merge(arr, aux, lo, lo + sz - 1, (lo + sz + sz - 1).coerceAtMost(arr.lastIndex), comparator) lo += sz + sz } sz += sz } } fun main() { val arr = arrayOf(4, 5, 1, 2, 8, 9, 0, 10) mergeSortIterative(arr) { a, b -> a - b } println(arr.joinToString()) }
0
Kotlin
0
0
e5a9b1f2d1c497ad7925fb38d9e4fc471688298b
2,030
algorithms-sedgewick-wayne
MIT License
src/Day20.kt
l8nite
573,298,097
false
{"Kotlin": 105683}
private fun move(index: Int, amounts: MutableList<Pair<Int, Long>>) { val indexFrom = amounts.indexOfFirst { (initialIndex) -> initialIndex == index } val value = amounts[indexFrom] val (_, amount) = value if (amount == 0L) return amounts.removeAt(indexFrom) val indexTo = findIndex(indexFrom, amount, amounts.size) amounts.add(indexTo, value) } private fun decrypt(inputs: List<Long>, mixes: Int, decryptionKey: Int): Long { val amounts = inputs .mapIndexed { index, amount -> index to amount * decryptionKey } .toMutableList() repeat(mixes) { (0 until amounts.size).forEach { index -> move(index, amounts) } } val startIndex = amounts.indexOfFirst { (_, value) -> value == 0L } return listOf(1000L, 2000L, 3000L) .map { endIndex -> amounts[findIndex(startIndex, endIndex, amounts.size)] } .sumOf { (_, amount) -> amount } } private fun findIndex(startIndex: Int, endIndex: Long, size: Int): Int = (startIndex + endIndex).mod(size) fun main() { fun part1(input: List<String>): Long { val inputs = input.map(String::toLong) return decrypt(inputs, 1, 1) } fun part2(input: List<String>): Long { val inputs = input.map(String::toLong) return decrypt(inputs, 10, 811589153) } // test if implementation meets criteria from the description, like: val testInput = readInput("Day20_test") check(part1(testInput) == 3L) println("Part 1 checked out!") check(part2(testInput) == 1623178306L) println("Part 2 checked out!") val input = readInput("Day20") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
f74331778fdd5a563ee43cf7fff042e69de72272
1,697
advent-of-code-2022
Apache License 2.0
src/Day09.kt
mkulak
573,910,880
false
{"Kotlin": 14860}
import java.lang.IllegalArgumentException import kotlin.math.absoluteValue import kotlin.math.sign fun main() { fun part1(input: List<String>): Int { val visited = HashSet<Long>() val rope = List(2) { XY(0, 0) } input.forEach { line -> val dir = line[0] val steps = line.drop(2).toInt() repeat(steps) { moveRope(rope, dir) visited += rope.last().encode() } } return visited.size } fun part2(input: List<String>): Int { val visited = HashSet<Long>() val rope = List(10) { XY(0, 0) } input.forEach { line -> val dir = line[0] val steps = line.drop(2).toInt() repeat(steps) { moveRope(rope, dir) visited += rope.last().encode() } } return visited.size } val input = readInput("Day09") println(part1(input)) println(part2(input)) } fun moveRope(rope: List<XY>, dir: Char) { val head = rope.first() when (dir) { 'U' -> head.y -= 1 'D' -> head.y += 1 'L' -> head.x -= 1 'R' -> head.x += 1 else -> throw IllegalArgumentException("Unknown dir: $dir") } for (i in 1..rope.lastIndex) { val prev = rope[i - 1] val current = rope[i] val diffX = prev.x - current.x val diffY = prev.y - current.y if (diffX.absoluteValue >= 2 || diffY.absoluteValue >= 2) { current.x += diffX.sign current.y += diffY.sign } } } fun printRope(rope: List<XY>) { val map = HashMap<XY, Int>() rope.forEachIndexed { i, xy -> map[xy] = i } for (y in 0..4) { for (x in 0..5) { val s = map[XY(x, y)]?.toString() ?: "." print(s) } println() } println() } data class XY(var x: Int, var y: Int) { fun encode(): Long = (x.toLong() shl 32) + y }
0
Kotlin
0
0
3b4e9b32df24d8b379c60ddc3c007d4be3f17d28
1,981
AdventOfKo2022
Apache License 2.0
src/Day04.kt
richardmartinsen
572,910,850
false
{"Kotlin": 14993}
fun main() { fun findPairs(input: List<String>) = input.map { line -> line.split(",") .map { pair -> pair.split("-") }.map { values -> val a = values[0].toInt() val b = values[1].toInt() a to b } } fun part1(input: List<String>) = findPairs(input).filter { it[0].overlapComplete(it[1]) }.count() fun part2(input: List<String>) = findPairs(input).filter { it[0].overlapSome(it[1]) }.count() val input = readInput("Day04") println(part1(input)) println(part2(input)) check(part1(input) == 605) check(part2(input) == 914) } private fun Pair<Int, Int>.overlapComplete(other: Pair<Int, Int>): Boolean { if ((this.first >= other.first) && (this.second <= other.second)) return true if ((other.first >= this.first) && (other.second <= this.second)) return true return false } private fun Pair<Int, Int>.overlapSome(other: Pair<Int, Int>): Boolean { if ((this.second < other.first) || (this.first > other.second)) return false return true } //private fun <A, B> Pair<A, B>.overlap() { // TODO("Not yet implemented") //}
0
Kotlin
0
0
bd71e11a2fe668d67d7ee2af5e75982c78cbe193
1,284
adventKotlin
Apache License 2.0
src/main/kotlin/days/y2023/day10/Day10.kt
jewell-lgtm
569,792,185
false
{"Kotlin": 161272, "Jupyter Notebook": 103410, "TypeScript": 78635, "JavaScript": 123}
package days.y2023.day10 import util.InputReader typealias PuzzleLine = String typealias PuzzleInput = List<PuzzleLine> class Day10(val input: PuzzleInput) { val grid = parseGrid(input) fun partOne(): Int { val len = findLen() return len / 2 } fun partTwo(): Int { val pipe = findPipe() val pointsToCheck = grid.positions() - pipe.positions() val insidePoints = pointsToCheck.filter { grid.pipeContains(pipe, it) } return -1 } fun findLen(): Int { val visited = findPipe() return visited.size } private fun findPipe(): Set<PipeSection> { val start = grid.filterPosition { it == 'S' }.only() val startNeighbors = grid.whereNeighbors(start) { section -> section.connectsTo(start) } .also { if (it.size != 2) TODO("Loop impossible") } val visited = mutableSetOf(start, startNeighbors.first()) while (true) { val curr = visited.last() val next = curr.onlyUnvisited(visited) ?: break visited.add(next) } return visited } } private fun PuzzleGrid.pipeContains(pipe: Set<PipeSection>, position: Position): Boolean { val bounds = pipe.positions() var isInsideAPipe = false var currPosition = position while (currPosition.y > 0) { if (isInsideAPipe == false) { currPosition = currPosition.copy(y = currPosition.y - 1) } } return false // TODO: here } private fun Collection<PipeSection>.positions(): Set<Position> { return this.map { it.position }.toSet() } typealias PuzzleGrid = List<List<Char>> data class Position(val y: Int, val x: Int) { } fun parseGrid(input: PuzzleInput): PuzzleGrid { return input.map { it.toList() } } fun <E> Collection<E>.only(): E { if (this.size != 1) throw Exception("Collection has ${this.size} elements") return this.first() } fun <E> Collection<E>.onlyOrNone(): E? { if (this.size > 1) throw Exception("Collection has ${this.size} elements") return this.firstOrNull() } fun PuzzleGrid.filterPosition(predecate: (Char) -> Boolean): List<PipeSection> { return this.mapIndexed { y, row -> row.mapIndexed { x, cell -> if (predecate(cell)) PipeSection(this, Position(y = y, x)) else null }.filterNotNull() }.flatten() } fun PuzzleGrid.whereNeighbors(start: PipeSection, predicate: (PipeSection) -> Boolean) = this.neighbors(start.position).filter { predicate(it) } fun PuzzleGrid.neighbors(position: Position): Set<PipeSection> { return listOf(-1 to 0, 1 to 0, 0 to -1, 0 to 1).map { (dy, dx) -> Position(y = position.y + dy, position.x + dx) } .filter { it.y >= 0 && it.x >= 0 && it.y < this.size && it.x < this[0].size } .map { PipeSection(this, it) } .toSet() } fun PuzzleGrid.positions(): Set<Position> { return this.mapIndexed { y, row -> row.mapIndexed { x, cell -> Position(y = y, x = x) } }.flatten().toSet() } data class PipeSection(val grid: PuzzleGrid, val position: Position) { val char = grid[position.y][position.x] val y = position.y val x = position.x override fun toString(): String { return "PipeSection($position, $char)" } fun connectsTo(other: PipeSection): Boolean { return connections().contains(other) } fun connections(): Set<PipeSection> = when (char) { '|' -> listOf(north(), south()) '-' -> listOf(east(), west()) 'L' -> listOf(north(), east()) 'J' -> listOf(north(), west()) '7' -> listOf(south(), west()) 'F' -> listOf(south(), east()) '.' -> emptyList() 'S' -> emptyList() else -> TODO("$char") }.filterValid().toSet() fun north(): PipeSection { return PipeSection(grid, Position(y - 1, x)) } fun south(): PipeSection { return PipeSection(grid, Position(y + 1, x)) } fun east(): PipeSection { return PipeSection(grid, Position(y, x + 1)) } fun west(): PipeSection { return PipeSection(grid, Position(y, x - 1)) } fun List<PipeSection>.filterValid(): List<PipeSection> { return this.filter { it.y >= 0 && it.x >= 0 && it.y < grid.size && it.x < grid[0].size } } } private fun PipeSection.onlyUnvisited( visited: Collection<PipeSection> ) = connections().filter { !visited.contains(it) }.onlyOrNone() private fun expandPipe(pipe: Set<PipeSection>): Set<PipeSection> = // transforms the positions, so they are 3x bigger pipe.map { it.copy(position = it.position * 3) }.toSet() private operator fun Position.times(i: Int): Position { return copy(y = y * i, x = x * i) } fun main() { val year = 2023 val day = 10 val exampleInput: PuzzleInput = InputReader.getExampleLines(year, day) val puzzleInput: PuzzleInput = InputReader.getPuzzleLines(year, day) fun partOne(input: PuzzleInput) = Day10(input).partOne() fun partTwo(input: PuzzleInput) = Day10(input).partTwo() println("Example 1: ${partOne(exampleInput)}") println("Puzzle 1: ${partOne(puzzleInput)}") println("Example 2: ${partTwo(exampleInput)}") println("Puzzle 2: ${partTwo(puzzleInput)}") }
0
Kotlin
0
0
b274e43441b4ddb163c509ed14944902c2b011ab
5,289
AdventOfCode
Creative Commons Zero v1.0 Universal
src/Day01.kt
seana-zr
725,858,211
false
{"Kotlin": 28265}
fun main() { fun getCalibrationValue(s: String): Int { // we know there MUST be a first and last digit in the input val first = s.first { it.isDigit() }.digitToInt() val last = s.last { it.isDigit() }.digitToInt() return first.times(10).plus(last) } fun part1(input: List<String>): Int { return input.sumOf { getCalibrationValue(it) } } val wordsDigits = 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 ) fun getRealCalibrationValue(s: String): Int { // first we consider the digits like last time val initialFirst = s.find { it.isDigit() } val initialLast = s.findLast { it.isDigit() } var first = initialFirst?.digitToInt() ?: 0 var firstIndex = s.indexOfFirst { it == initialFirst } var last = initialLast?.digitToInt() ?: 0 var lastIndex = s.indexOfLast { it == initialLast } // now we look for each word, and compare indices if they're found for ((word, digit) in wordsDigits) { val i = s.indexOf(word) val j = s.lastIndexOf(word) if (i != -1 && (i < firstIndex || firstIndex == -1)) { first = digit firstIndex = i } if (j != -1 && (j > lastIndex || lastIndex == -1)) { last = digit lastIndex = j } } return first.times(10).plus(last) } fun part2(input: List<String>): Int { return input.sumOf { getRealCalibrationValue(it) } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") check(part2(testInput) == 281) val input = readInput("Day01") part1(input).println() part2(input).println() }
0
Kotlin
0
0
da17a5de6e782e06accd3a3cbeeeeb4f1844e427
1,944
advent-of-code-kotlin-template
Apache License 2.0
src/Day02.kt
joy32812
573,132,774
false
{"Kotlin": 62766}
const val SCORE_WIN = 6 const val SCORE_DRAW = 3 val selectScore = listOf(1, 2, 3) fun Char.toIntNum() = when (this) { in "AX" -> 0 in "BY" -> 1 else -> 2 } fun getScore(a: Int, b: Int): Int { val matchScore = when { a == b -> SCORE_DRAW a + 1 == b || (a == 2 && b == 0) -> SCORE_WIN else -> 0 } return matchScore + selectScore[b] } fun part1(input: List<String>): Int { return input.sumOf { getScore(it[0].toIntNum(), it[2].toIntNum()) } } fun part2(input: List<String>): Int { return input.sumOf { val a = it[0].toIntNum() val b = when (it[2]) { 'X' -> (3 + a - 1) % 3 'Y' -> a else -> (a + 1) % 3 } getScore(a, b) } } fun main() { println(part1(readInput("Day02_test"))) println(part1(readInput("Day02_part1"))) println(part2(readInput("Day02_test"))) println(part2(readInput("Day02_part1"))) }
0
Kotlin
0
0
5e87958ebb415083801b4d03ceb6465f7ae56002
879
aoc-2022-in-kotlin
Apache License 2.0
ceria/13/src/main/kotlin/Solution.kt
VisionistInc
317,503,410
false
null
import java.io.File import java.math.BigInteger fun main(args : Array<String>) { val input = File(args.first()).readLines() println("Solution 1: ${solution1(input)}") println("Solution 2: ${solution2(input)}") } private fun solution1(input :List<String>) :Int { var time = input.first().toInt() val busses = input.last().split(",").filter{ it != "x" }.map{ it.toInt() } var yourBus = 0 while (yourBus == 0) { for (bus in busses) { if (time.rem(bus) == 0) { yourBus = bus break } } if (yourBus == 0) { time++ } } return (time - input.first().toInt()) * yourBus } private fun solution2(input :List<String>) :Long { val busses = input.last().split(",") val vals = mutableListOf<Long>() val modVals = mutableListOf<Long>() for (i in busses.indices) { if (! busses[i].equals("x")) { modVals.add(busses[i].toLong()) vals.add(i.toLong()) } } return modVals.product() - chineseRemainder(vals, modVals) } private fun chineseRemainder(vals : List<Long>, modVals : List<Long>) : Long{ val modProduct = modVals.product() var res = 0L for(i in vals.indices){ val gcd = extendedEuclid(modVals[i], modProduct/modVals[i]) val a = BigInteger(vals[i].toString()) val b = BigInteger(gcd[2].toString()) val c = BigInteger((modProduct/modVals[i]).toString()) val mod = BigInteger(modProduct.toString()) res += a.multiply(b).multiply(c).remainder(mod).toLong() res = (res.rem(modProduct) + modProduct).rem(modProduct) } return res } /** * Find the product of all the numbers in the list */ private fun <E : Number> List<E>.product(): Long { if (this.isEmpty()) { return 0L } var product = 1L for (numb in this) { when (numb) { is Long -> product *= numb } } return product } private fun extendedEuclid(a: Long, b: Long): LongArray { return if (b == 0L) { longArrayOf(a, 1L, 0L) } else { val res = extendedEuclid(b, a.rem(b)) longArrayOf(res[0], res[2], res[1] - (a / b) * res[2]) } }
0
Rust
0
0
002734670384aa02ca122086035f45dfb2ea9949
2,098
advent-of-code-2020
MIT License
src/main/kotlin/io/github/clechasseur/adventofcode2021/Day19.kt
clechasseur
435,726,930
false
{"Kotlin": 315943}
package io.github.clechasseur.adventofcode2021 import io.github.clechasseur.adventofcode2021.data.Day19Data import io.github.clechasseur.adventofcode2021.util.Pt3D import io.github.clechasseur.adventofcode2021.util.manhattan object Day19 { private val data = Day19Data.data fun part1(): Int = data.toScanners().merge().beacons.size fun part2(): Int { val map = data.toScanners().merge() return map.pos.maxOf { s1 -> map.pos.filter { it != s1 }.maxOf { s2 -> manhattan(s1, s2) } } } private val facings: List<(Pt3D) -> Pt3D> = listOf( { it }, { Pt3D(-it.y, it.x, it.z) }, { Pt3D(-it.x, -it.y, it.z) }, { Pt3D(it.y, -it.x, it.z) }, ) private val rotations: List<(Pt3D) -> Pt3D> = listOf( { it }, { Pt3D(it.x, -it.z, it.y) }, { Pt3D(it.x, -it.y, -it.z) }, { Pt3D(it.x, it.z, -it.y) }, { Pt3D(it.z, it.y, -it.x) }, { Pt3D(-it.z, it.y, it.x) }, ) private val orientations: List<(Pt3D) -> Pt3D> = facings.flatMap { facing -> rotations.map { rotation -> { rotation(facing(it)) } } } private class DistanceInfo(val dist: Pt3D, val from: Pt3D, val to: Pt3D) : Comparable<DistanceInfo> { override fun equals(other: Any?): Boolean = other != null && other is DistanceInfo && other.dist == dist override fun hashCode(): Int = dist.hashCode() override fun compareTo(other: DistanceInfo): Int = dist.compareTo(other.dist) } private class Scanner(val beacons: Set<Pt3D>, val pos: Set<Pt3D>) { fun allOrientations(): Sequence<Scanner> = orientations.asSequence().map { orientation -> Scanner(beacons.map { orientation(it) }.toSet(), pos) } fun distanceMap(): Set<DistanceInfo> = beacons.flatMap { b1 -> beacons.filter { it != b1 }.map { b2 -> DistanceInfo(b1 - b2, b1, b2) } }.toSet() fun connect(other: Scanner): Scanner? { val leftDm = distanceMap() val (rightDm, right) = other.allOrientations().map { it.distanceMap() to it }.find { (rdm, _) -> leftDm.intersect(rdm).size >= 66 } ?: return null leftDm.forEach { leftInfo -> rightDm.forEach { rightInfo -> if (leftInfo.dist == rightInfo.dist) { val rightPos = leftInfo.from - rightInfo.from return Scanner(beacons + right.beacons.map { it + rightPos }.toSet(), pos + rightPos) } } } return null } } private fun List<Scanner>.merge(): Scanner { val scanners = toMutableList() loop@while (scanners.size > 1) { for (i in scanners.indices.drop(1)) { val connected = scanners.first().connect(scanners[i]) if (connected != null) { scanners.removeAt(i) scanners[0] = connected continue@loop } } error("Should not reach this point") } return scanners.first() } private val beaconRegex = """^(-?\d+),(-?\d+),(-?\d+)$""".toRegex() private fun String.toScanners(): List<Scanner> { val it = lines().iterator() val scanners = mutableListOf<Scanner>() var pos = setOf(Pt3D.ZERO) while (it.hasNext()) { it.next() val beacons = mutableListOf<Pt3D>() while (it.hasNext()) { val beaconLine = it.next() if (beaconLine.isNotBlank()) { val beaconMatch = beaconRegex.matchEntire(beaconLine) ?: error("Wrong beacon line: $beaconLine") val (x, y, z) = beaconMatch.destructured beacons.add(Pt3D(x.toInt(), y.toInt(), z.toInt())) } else { break } } scanners.add(Scanner(beacons.toSet(), pos)) pos = emptySet() } return scanners } }
0
Kotlin
0
0
4b893c001efec7d11a326888a9a98ec03241d331
4,101
adventofcode2021
MIT License
src/Day09.kt
diesieben07
572,879,498
false
{"Kotlin": 44432}
import kotlin.math.abs import kotlin.math.sign private val file = "Day09" //private val file = "Day09Example" private enum class Direction(val x: Int, val y: Int) { UP(0, -1), DOWN(0, 1), LEFT(-1, 0), RIGHT(1, 0) } private data class Step(val direction: Direction, val amount: Int) { companion object { fun parse(line: String): Step { val direction = Direction.values().single { it.name.startsWith(line[0]) } val amount = line.substring(2).toInt() return Step(direction, amount) } } } private fun part1() { val visited = mutableSetOf<Pair<Int, Int>>() streamInput(file) { input -> var xH = 0 var yH = 0 var xT = 0 var yT = 0 visited.add(Pair(xT, yT)) input.map { Step.parse(it) } .forEach { step -> repeat(step.amount) { xH += step.direction.x yH += step.direction.y val distX = xH - xT val distY = yH - yT val tailNeedsToMove = maxOf(abs(distX), abs(distY)) > 1 if (tailNeedsToMove) { xT += distX.sign yT += distY.sign } visited.add(Pair(xT, yT)) } } } println(visited.size) } private class RopePart(var x: Int, var y: Int) private fun part2() { val tailVisited = mutableSetOf<Pair<Int, Int>>() val partCount = 10 streamInput(file) { input -> val parts = List(partCount) { RopePart(0, 0) } val tail = parts.last() val head = parts.first() tailVisited.add(Pair(tail.x, tail.y)) input.map { Step.parse(it) } .forEach { step -> repeat(step.amount) { head.x += step.direction.x head.y += step.direction.y for (i in 1..parts.lastIndex) { val myHead = parts[i - 1] val me = parts[i] val distX = myHead.x - me.x val distY = myHead.y - me.y val needToMove = maxOf(abs(distX), abs(distY)) > 1 if (needToMove) { me.x += distX.sign me.y += distY.sign } } tailVisited.add(Pair(tail.x, tail.y)) } } println(tailVisited.size) } } fun main() { part1() part2() }
0
Kotlin
0
0
0b9993ef2f96166b3d3e8a6653b1cbf9ef8e82e6
2,605
aoc-2022
Apache License 2.0
src/main/kotlin/Day02.kt
brigham
573,127,412
false
{"Kotlin": 59675}
enum class Outcome { Loss, Draw, Win; val score: Int get() = this.ordinal * 3 fun against(opp: Piece): Piece { return when (this) { Loss -> opp.beats Draw -> opp Win -> opp.beatenBy } } } enum class Piece { Rock { override val beats: Piece get() = Scissors override val beatenBy: Piece get() = Paper }, Paper { override val beats: Piece get() = Rock override val beatenBy: Piece get() = Scissors }, Scissors { override val beats: Piece get() = Paper override val beatenBy: Piece get() = Rock }; abstract val beats: Piece abstract val beatenBy: Piece val score: Int = ordinal + 1 fun play(other: Piece): Outcome { return when (other) { this -> Outcome.Draw this.beats -> Outcome.Loss this.beatenBy -> Outcome.Win else -> error("Someone added a new piece.") } } } val pieces = mapOf( "A" to Piece.Rock, "X" to Piece.Rock, "B" to Piece.Paper, "Y" to Piece.Paper, "C" to Piece.Scissors, "Z" to Piece.Scissors ) val outcomes = mapOf("X" to Outcome.Loss, "Y" to Outcome.Draw, "Z" to Outcome.Win) fun main() { fun part1(input: List<String>): Int { var score = 0 for (line in input) { val (oppC, meC) = line.split(' ') val opp = pieces[oppC]!! val me = pieces[meC]!! score += opp.play(me).score + me.score } return score } fun part2(input: List<String>): Int { var score = 0 for (line in input) { val (oppC, outcomeC) = line.split(' ') val opp = pieces[oppC]!! val outcome = outcomes[outcomeC]!! score += outcome.score + outcome.against(opp).score } return score } // test if implementation meets criteria from the description, like: val testInput = readInput("Day02_test") check(part1(testInput) == 15) val input = readInput("Day02") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
b87ffc772e5bd9fd721d552913cf79c575062f19
2,201
advent-of-code-2022
Apache License 2.0
src/Day11.kt
Riari
574,587,661
false
{"Kotlin": 83546, "Python": 1054}
fun main() { data class Monkey( val operation: Char, val operand: Long?, val divisor: Long, val trueRecipient: Int, val falseRecipient: Int, var items: ArrayDeque<Long> = ArrayDeque(), var inspectionCount: Long = 0) // Worry level reduction idea taken from https://github.com/ClouddJR/advent-of-code-2022/blob/main/src/main/kotlin/com/clouddjr/advent2022/Day11.kt fun solve(input: List<String>, rounds: Int, processWorry: (Long, Long) -> Long): Long { val inputChunked = input.chunked(7) val monkeys = mutableListOf<Monkey>() val regex = Regex("\\d+") // Monkey setup for (notes in inputChunked) { val monkey = Monkey( if (notes[2].contains('+')) '+' else '*', regex.find(notes[2])?.value?.toLong(), regex.find(notes[3])!!.value.toLong(), regex.find(notes[4])!!.value.toInt(), regex.find(notes[5])!!.value.toInt(), ) val items = regex.findAll(notes[1]).toList().map { it.value.toLong() } items.forEach { monkey.items.addFirst(it) } monkeys.add(monkey) } val modulus = monkeys.map { it.divisor }.reduce(Long::times) // Monkey business repeat (rounds) { for (monkey in monkeys) { val itemIterator = monkey.items.iterator() while (itemIterator.hasNext()) { // Item value represents 'worry level' var item = itemIterator.next() // If operand is null, assume 'old', i.e. the level should be applied to itself when (monkey.operation) { '+' -> item += monkey.operand ?: item '*' -> item *= monkey.operand ?: item } item = processWorry(item, modulus) if (item % monkey.divisor == 0L) { monkeys[monkey.trueRecipient].items.add(item) } else { monkeys[monkey.falseRecipient].items.add(item) } itemIterator.remove() monkey.inspectionCount++ } } } return monkeys.map { it.inspectionCount }.sortedDescending().take(2).reduce(Long::times) } fun part1(input: List<String>): Long { return solve(input, 20) { level, _ -> level / 3 } } fun part2(input: List<String>): Long { return solve(input, 10000) { level, modulus -> level % modulus } } val testInput = readInput("Day11_test") check(part1(testInput) == 10605.toLong()) check(part2(testInput) == 2713310158) val input = readInput("Day11") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
8eecfb5c0c160e26f3ef0e277e48cb7fe86c903d
2,879
aoc-2022
Apache License 2.0
src/Day16.kt
cypressious
572,898,685
false
{"Kotlin": 77610}
import java.util.* import java.util.stream.IntStream import kotlin.math.pow fun main() { val regex = """Valve (\w+) has flow rate=(\d+); \w+ \w+ to \w+ (.+)""".toRegex() class Valve( val name: String, val rate: Int, val tunnels: MutableList<Valve> = mutableListOf() ) { val distances = mutableMapOf<Valve, Int>() override fun toString(): String { return "Valve(name='$name', rate=$rate, tunnels=${tunnels.joinToString { it.name }})" } } fun calculateDistances(valve: Valve) { val distances = mutableMapOf(valve to 0).withDefault { Int.MAX_VALUE } val unvisited = PriorityQueue(compareBy(distances::getValue)).apply { add(valve) } val visited = mutableSetOf<Valve>() while (unvisited.isNotEmpty()) { val v = unvisited.poll() for (neighbor in v.tunnels) { if (neighbor !in visited && distances.getValue(neighbor) > distances.getValue(v) + 1) { unvisited -= neighbor distances[neighbor] = distances.getValue(v) + 1 unvisited += neighbor } } visited += v } valve.distances.putAll(distances) } fun parse(input: List<String>): Map<String, Valve> { val valves = mutableMapOf<String, Valve>() val allTunnels = mutableMapOf<String, List<String>>() for (line in input) { val (name, rate, tunnels) = regex.matchEntire(line)!!.destructured valves[name] = Valve(name, rate.toInt()) allTunnels[name] = tunnels.split(", ") } for ((name, tunnels) in allTunnels) { for (tunnel in tunnels) { valves.getValue(name).tunnels.add(valves.getValue(tunnel)) } } for (valve in valves.values) { calculateDistances(valve) } return valves } fun calculateMaxRelease(start: Valve, maxTime: Int, nonZeroValves: List<Valve>): Int { val visited = mutableSetOf<String>() val cache = mutableMapOf<Triple<String, Int, String>, Int>() fun getMaxRelease(current: Valve, minute: Int): Int { if (visited.size == nonZeroValves.size) return 0 if (minute >= maxTime) return 0 val key = Triple(current.name, minute, visited.sorted().joinToString(",")) cache[key]?.let { return it } var max = 0 for (valve in nonZeroValves) { if (valve.name in visited) continue val distance = current.distances.getValue(valve) if (minute + distance >= maxTime) continue visited += valve.name val release = valve.rate * (maxTime - minute - distance) val candidate = release + getMaxRelease(valve, minute + distance + 1) max = maxOf(max, candidate) visited -= valve.name } if (max > 0) cache[key] = max return max } return getMaxRelease(start, 1) } fun part1(input: List<String>): Int { val valves = parse(input) val start = valves.getValue("AA") return calculateMaxRelease(start, 30, valves.values.filter { it.rate > 0 }) } fun part2(input: List<String>): Int { val valves = parse(input) val start = valves.getValue("AA") val nonZeroValves = valves.values.filter { it.rate > 0 } // https://stackoverflow.com/a/6999554/615306 return IntStream.range(1, 2.0.pow(nonZeroValves.size - 1).toInt()) .parallel() .map { mask -> val yours = mutableListOf<Valve>() val elephant = mutableListOf<Valve>() for ((index, valve) in nonZeroValves.withIndex()) { if (mask and (1 shl index) != 0) { yours.add(valve) } else { elephant.add(valve) } } calculateMaxRelease(start, 26, yours) + calculateMaxRelease(start, 26, elephant) } .max() .asInt } // test if implementation meets criteria from the description, like: val testInput = readInput("Day16_test") check(part1(testInput) == 1651) check(part2(testInput) == 1707) val input = readInput("Day16") println(part1(input)) println(part2(input)) }
0
Kotlin
0
1
7b4c3ee33efdb5850cca24f1baa7e7df887b019a
4,529
AdventOfCode2022
Apache License 2.0
src/Day09.kt
WilsonSunBritten
572,338,927
false
{"Kotlin": 40606}
import kotlin.math.absoluteValue fun main() { fun part1(input: List<String>): Int { val moves = input.map { val split = it.split(" ") Move(positions = split[1].toInt(), direction = directionMap[split[0].first()]!!) } val tailPositions = mutableSetOf(Position(0, 0)) var headPosition = Position(0, 0) var tailPosition = Position(0, 0) moves.forEach { move -> repeat(move.positions) { val currentHeadPosition = headPosition headPosition = move.direction.move(currentHeadPosition) if (move.direction.moveCondition(currentHeadPosition, tailPosition)) { tailPosition = move.direction.followPosition(headPosition) } tailPositions.add(tailPosition) } } return tailPositions.count() } fun part2(input: List<String>): Int { val moves = input.map { val split = it.split(" ") Move(positions = split[1].toInt(), direction = directionMap[split[0].first()]!!) } val tailPositions = mutableSetOf(Position(0, 0)) var chain = (0 until 9).map { Position(0, 0) } var headPosition = Position(0, 0) moves.forEach { move -> repeat(move.positions) { val newHead = move.direction.move(headPosition) headPosition = newHead val movedChain = chain.runningFold(newHead) { relativeHead, relativeTail -> val differenceX = relativeHead.x - relativeTail.x val differenceY = relativeHead.y - relativeTail.y // we went right a nominal amount if (differenceX > 1 && differenceY == 0) { relativeTail.copy(x = relativeTail.x + 1) } else if (differenceX < -1 && differenceY == 0) { relativeTail.copy(x = relativeTail.x - 1) } else if (differenceY > 1 && differenceX == 0) { relativeTail.copy(y = relativeTail.y + 1) } else if (differenceY < -1 && differenceX == 0) { relativeTail.copy(y = relativeTail.y - 1) } // pesky diagnal moves do nothing but diagnal BEYOND does thing else if (differenceX.absoluteValue > 1 || differenceY.absoluteValue > 1) { val newX = if (differenceX > 1) { relativeTail.x + 1 } else if (differenceX < -1) { relativeTail.x - 1 } else { relativeTail.x } val newY = if (differenceY > 1) { relativeTail.y + 1 } else if (differenceY < -1) { relativeTail.y -1 } else { relativeTail.y } Position(x = newX, y = newY) } else { relativeTail } } // println(movedChain) // head is being tracked seperatedly still chain = movedChain.drop(1) // println(chain) tailPositions.add(chain.last()) } } println(tailPositions) return tailPositions.count() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day09_test") val input = readInput("Day09") // val p1TestResult = part1(testInput) // println(p1TestResult) // check(p1TestResult == 13) // println(part1(input)) println("Part 2") val p2TestResult = part2(testInput) println(p2TestResult) check(p2TestResult == 36) println(part2(input)) } data class Move(val positions: Int, val direction: Direction) val directionMap = mapOf( 'U' to Direction.UP, 'D' to Direction.DOWN, 'L' to Direction.LEFT, 'R' to Direction.RIGHT ) data class Position(var x: Int, var y: Int) // 1. tell us where H moves // 2. tell us if T follows // 3. tell us T's new position, if it moved enum class Direction(val move: (Position) -> Position, val moveCondition: (Position, Position) -> Boolean, val followPosition: (Position) -> Position) { UP( { position -> position.copy(y = position.y + 1) }, { head, tail -> tail.y == head.y - 1 }, { head -> head.copy(y = head.y - 1) } ), DOWN( { position -> position.copy(y = position.y - 1) }, { head, tail -> tail.y == head.y + 1 }, { head -> head.copy(y = head.y + 1) } ), LEFT( { position -> position.copy(x = position.x - 1) }, { head, tail -> tail.x == head.x + 1 }, { head -> head.copy(x = head.x + 1) } ), RIGHT( { position -> position.copy(x = position.x + 1) }, { head, tail -> tail.x == head.x - 1 }, { head -> head.copy(x = head.x - 1) } ); }
0
Kotlin
0
0
363252ffd64c6dbdbef7fd847518b642ec47afb8
5,148
advent-of-code-2022-kotlin
Apache License 2.0
src/Day05.kt
pimts
573,091,164
false
{"Kotlin": 8145}
import java.util.Stack data class MoveInstruction(val amount: Int, val from: Int, val to: Int) fun main() { fun parseStacks(input: String): MutableMap<Int, Stack<Char>> { val stacks = mutableMapOf<Int, Stack<Char>>() val cratesInput = input.substringBefore("\n\n").lines().dropLast(1) cratesInput.map { it.windowed(size = 3, step = 4) } .forEach { it.forEachIndexed { stack, crate -> if (stacks[stack] == null) { stacks[stack] = Stack() } if (crate.isNotBlank()) { stacks[stack]!!.push(crate[1]) } } } stacks.values.forEach { it.reverse() } return stacks } fun parseMoves(input: String) = input.substringAfter("\n\n").lines() .map { val (_, amount, _, from, _, to) = it.split(" ") MoveInstruction(amount.toInt(), from.toInt() - 1, to.toInt() - 1) } fun MutableMap<Int,Stack<Char>>.topCrates() = values.fold("") { s, e -> s + e.pop() } fun part1(input: String): String { val stacks = parseStacks(input) val moves = parseMoves(input) moves.forEach { (amount, from, to) -> repeat(amount) { val crate = stacks[from]?.pop() stacks[to]?.push(crate) } } return stacks.topCrates() } fun part2(input: String): String { val stacks = parseStacks(input) val moves = parseMoves(input) moves.forEach { (amount, from, to) -> var substack = "" repeat(amount) { substack = stacks[from]?.pop()!! + substack } substack.forEach { stacks[to]?.push(it) } } return stacks.topCrates() } // test if implementation meets criteria from the description, like: val testInput = readInputText("Day05_test") check(part1(testInput) == "CMZ") check(part2(testInput) == "MCD") val input = readInputText("Day05") println(part1(input)) println(part2(input)) } private operator fun <E> List<E>.component6(): E { return this[5] }
0
Kotlin
0
0
dc7abb10538bf6ad9950a079bbea315b4fbd011b
2,254
aoc-2022-in-kotlin
Apache License 2.0
src/y2016/Day08.kt
gaetjen
572,857,330
false
{"Kotlin": 325874, "Mermaid": 571}
package y2016 import util.getCol import util.printMatrix import util.readInput import util.set sealed class LightsInstruction { companion object { fun parse(string: String): LightsInstruction { return when { string.startsWith("rect") -> Rect.fromString(string) string.startsWith("rotate column") -> RotateColumn.fromString(string) string.startsWith("rotate row") -> RotateRow.fromString(string) else -> error("invalid instruction") } } } abstract fun execute(display: MutableList<MutableList<Boolean>>) } data class Rect(val columns: Int, val rows: Int) : LightsInstruction() { companion object { fun fromString(str: String): Rect { val (columns, rows) = str.split(' ').last().split('x').map { it.toInt() } return Rect(columns, rows) } } override fun execute(display: MutableList<MutableList<Boolean>>) { (0 until rows).forEach { row -> (0 until columns).forEach { col -> display[row to col] = true } } } } data class RotateRow(val row: Int, val distance: Int) : LightsInstruction() { companion object { fun fromString(str: String): RotateRow { val splits = str.split(' ') return RotateRow( splits[2].substringAfter('=').toInt(), splits.last().toInt() ) } } override fun execute(display: MutableList<MutableList<Boolean>>) { display[row] = (display[row].takeLast(distance) + display[row].dropLast(distance)).toMutableList() } } data class RotateColumn(val column: Int, val distance: Int) : LightsInstruction() { companion object { fun fromString(str: String): RotateColumn { val splits = str.split(' ') return RotateColumn( splits[2].substringAfter('=').toInt(), splits.last().toInt() ) } } override fun execute(display: MutableList<MutableList<Boolean>>) { val col = getCol(display, column) val rotatedColumn = col.takeLast(distance) + col.dropLast(distance) (0 until display.size).forEach { display[it to column] = rotatedColumn[it] } } } object Day08 { private fun parse(input: List<String>): List<LightsInstruction> { return input.map { LightsInstruction.parse(it) } } fun part1(input: List<String>): Int { val parsed = parse(input) val display = MutableList(6) { MutableList(50) { false } } parsed.forEach { it.execute(display) } printMatrix(display) { if (it) "██" else " " } val totalRect = parsed.sumOf { if (it is Rect) { it.columns * it.rows } else { 0 } } println("total rect: $totalRect") return display.flatten().count { it } } } fun main() { val testInput = """ rect 3x2 rotate column x=1 by 1 rotate row y=0 by 4 rotate column x=1 by 1 """.trimIndent().split("\n") println("------Tests------") println(Day08.part1(testInput)) println("------Real------") val input = readInput("resources/2016/day08") println(Day08.part1(input)) }
0
Kotlin
0
0
d0b9b5e16cf50025bd9c1ea1df02a308ac1cb66a
3,439
advent-of-code
Apache License 2.0
src/main/kotlin/com/jacobhyphenated/advent2022/day8/Day8.kt
jacobhyphenated
573,603,184
false
{"Kotlin": 144303}
package com.jacobhyphenated.advent2022.day8 import com.jacobhyphenated.advent2022.Day /** * Day 8: Treetop Tree House * * A 2d array is a grid of tree sizes (where 9 is the tallest possible tree) */ class Day8: Day<List<List<Int>>> { override fun getInput(): List<List<Int>> { return readInputFile("day8").lines() .map { line -> line.toCharArray().map { it.digitToInt() } } } /** * Find how many trees are visible from the edge of the grid. * All edge trees are visible * A tree is visible it is taller than the trees in front of it. * * Look down each row and column (left to right, right to left, top to bottom, and bottom to top) * Proceed in a line from the starting point counting all visible trees * This approach is more efficient than checking if each individual tree is visible at an edge */ override fun part1(input: List<List<Int>>): Any { // use a set to store trees we can see to avoid duplicate counts val visible = mutableSetOf<Pair<Int,Int>>() // Combine ranges for each side. This results in multiple List<List<Pair<Int,Int>>> // where the Pair is a tuple of the row and column indexes val indices = input.indices val topToBottom = indices.map { r -> indices.map { c -> Pair(r,c) } } val bottomToTop = indices.map { r -> indices.reversed().map { c -> Pair(r,c) } } val leftToRight = indices.map { c -> indices.map { r -> Pair(r,c) } } val rightToLeft = indices.map { c -> indices.reversed().map { r -> Pair(r,c) } } val allSides = topToBottom + bottomToTop + leftToRight + rightToLeft // Each list of (Row,Col) that looks down one row or column is a "lineOfSight" // iterate down the line of sight and mark the trees that are visible val valueAtLocation = { pair: Pair<Int,Int> -> input[pair.first][pair.second] } for (lineOfSight in allSides) { var tallestSoFar = -1 for (tree in lineOfSight) { if (valueAtLocation(tree) > tallestSoFar) { visible.add(tree) tallestSoFar = valueAtLocation(tree) } if (tallestSoFar == 9) { break } } } return visible.size } /** * Find which tree has the best view. * The view is defined by how many other trees you can see from each edge of the tree. * Your view is blocked once you reach a tree of equal or greater height than the starting tree. * Multiply the view counts from each edge to get the view score. * * return the best view score possible in the grid of trees. */ override fun part2(input: List<List<Int>>): Any { var largestScore = 0 // Look from the perspective of each tree in the grid for (row in input.indices) { for (col in input[row].indices) { val treeHeight = input[row][col] // Sizes of trees in each direction, in order val up = (row - 1 downTo 0).map { input[it][col] } val down = (row + 1 until input.size).map { input[it][col] } val left = (col - 1 downTo 0).map { input[row][it] } val right = (col + 1 until input.size).map { input[row][it] } // calculate the number of trees that can be seen in each direction val viewScore = { lineOfSight: List<Int> -> var score = 0 for (tree in lineOfSight) { score++ if (tree >= treeHeight) { break } } score } val totalScore = viewScore(up) * viewScore(down) * viewScore(left) * viewScore(right) if (totalScore > largestScore){ largestScore = totalScore } } } return largestScore } }
0
Kotlin
0
0
9f4527ee2655fedf159d91c3d7ff1fac7e9830f7
4,085
advent2022
The Unlicense
src/Day05.kt
mandoway
573,027,658
false
{"Kotlin": 22353}
fun parseStacks(stackLines: List<String>): List<ArrayDeque<Char>> { val stacks = mutableListOf<ArrayDeque<Char>>() stackLines.forEach { line -> line.chunked(4) .map { it.trim() } .forEachIndexed { index, crate -> if (stacks.lastIndex < index) { stacks.add(ArrayDeque(stackLines.size)) } if (crate.isNotBlank()) { val (_, crateChar, _) = crate.toCharArray() stacks[index].addFirst(crateChar) } } } return stacks } data class Move(val amount: Int, val fromStack: Int, val toStack: Int) { val fromStackIndex get() = fromStack - 1 val toStackIndex get() = toStack - 1 } fun String.toMove(): Move { val parts = split(" ") return Move( amount = parts[1].toInt(), fromStack = parts[3].toInt(), toStack = parts[5].toInt() ) } fun List<ArrayDeque<Char>>.perform(move: Move) { repeat(move.amount) { get(move.toStackIndex).addLast( get(move.fromStackIndex).removeLast() ) } } fun List<ArrayDeque<Char>>.performKeepingOrder(move: Move) { val topCrates = mutableListOf<Char>() repeat(move.amount) { topCrates.add(get(move.fromStackIndex).removeLast()) } get(move.toStackIndex).addAll(topCrates.reversed()) } fun main() { fun parseInput(input: List<String>): Pair<List<ArrayDeque<Char>>, List<Move>> { val stackLines = input.takeWhile { it.isNotBlank() }.dropLast(1) val stacks = parseStacks(stackLines) val moveLines = input.dropWhile { it.isNotBlank() }.drop(1) val moves = moveLines.map { it.toMove() } return Pair(stacks, moves) } fun part1(input: List<String>): String { val (stacks, moves) = parseInput(input) moves.forEach { stacks.perform(it) } val topCrates = stacks.joinToString("") { it.last().toString() } return topCrates } fun part2(input: List<String>): String { val (stacks, moves) = parseInput(input) moves.forEach { stacks.performKeepingOrder(it) } return stacks.joinToString("") { it.last().toString() } } // 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
0393a4a25ae4bbdb3a2e968e2b1a13795a31bfe2
2,540
advent-of-code-22
Apache License 2.0
src/Day8/Day8.kt
tomashavlicek
571,148,715
false
{"Kotlin": 23780}
package Day8 import readInput fun main() { fun parseInput(input: List<String>): List<List<Int>> { return input.map { row -> row.windowed(1).map { it.toInt() } } } fun part1(input: List<String>): Int { val map = parseInput(input) var count = 0 for ((rowIndex, row) in map.withIndex()) { for ((index, r) in row.withIndex()) { // all trees from sides are visible if (index == 0 || index == row.lastIndex || rowIndex == 0 || rowIndex == map.lastIndex) { count += 1 } else { val left = row.subList(0, index).maxOrNull() ?: -1 val right = row.subList(index + 1, row.size).maxOrNull() ?: -1 val column = map.map { it[index] } val top = column.subList(0, rowIndex).maxOrNull() ?: -1 val down = column.subList(rowIndex + 1, column.size).maxOrNull() ?: -1 if (left < r || right < r || top < r || down < r) { count += 1 } } } } return count } fun List<Int>.countUntil(predicate: (Int) -> Boolean): Int { var count = 0 for (item in this) { count++ if (predicate(item)) return count } return count } fun part2(input: List<String>): Int { val map = parseInput(input) var highScore = 0 for ((rowIndex, row) in map.withIndex()) { for ((index, r) in row.withIndex()) { if (index == 0 || index == row.lastIndex || rowIndex == 0 || rowIndex == map.lastIndex) { continue } else { val left = row.subList(0, index).reversed().countUntil { r <= it } val right = row.subList(index + 1, row.size).countUntil { r <= it } val column = map.map { it[index] } val top = column.subList(0, rowIndex).reversed().countUntil { r <= it } val down = column.subList(rowIndex + 1, column.size).countUntil { r <= it } val score = left * right * top * down if (score > highScore) { highScore = score } } } } return highScore } // test if implementation meets criteria from the description, like: val testInput = readInput("Day8/Day8_test") val testResult = part1(testInput) println(testResult) check(testResult == 21) val testResult2 = part2(testInput) println(testResult2) check(testResult2 == 8) val input = readInput("Day8/Day8") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
899d30e241070903fe6ef8c4bf03dbe678310267
2,860
aoc-2022-in-kotlin
Apache License 2.0
src/main/kotlin/adventofcode/year2021/Day14ExtendedPolymerization.kt
pfolta
573,956,675
false
{"Kotlin": 199554, "Dockerfile": 227}
package adventofcode.year2021 import adventofcode.Puzzle import adventofcode.PuzzleInput class Day14ExtendedPolymerization(customInput: PuzzleInput? = null) : Puzzle(customInput) { private val polymerTemplate by lazy { input.lines().first() } private val pairInsertionRules by lazy { input.lines().drop(2).map { it.split(" -> ") }.associate { it.first() to it.last() } } override fun partOne(): Int { val elementCounts = generateSequence(polymerTemplate) { polymer -> polymer .windowed(2) .mapIndexed { index, pair -> when (index) { 0 -> "${pair.first()}${pairInsertionRules[pair]}${pair.last()}" else -> "${pairInsertionRules[pair]}${pair.last()}" } } .joinToString("") } .drop(1) .take(10) .last() .groupingBy { it } .eachCount() .values .sorted() return elementCounts.last() - elementCounts.first() } override fun partTwo(): Long { val elementCounts = generateSequence(polymerTemplate.windowed(2).groupingBy { it }.eachCount() as Map<String, Long>) { previous -> previous .flatMap { (pair, count) -> listOf( "${pair.first()}${pairInsertionRules[pair]}" to count, "${pairInsertionRules[pair]}${pair.last()}" to count ) } .fold(mapOf()) { acc, (pair, count) -> if (acc.contains(pair)) { val existingCount = acc[pair]!! acc.minus(pair) + mapOf(pair to existingCount + count) } else { acc + mapOf(pair to count) } } } .drop(1) .take(40) .last() .toList() .fold(mapOf<Char, Long>()) { acc, (pair, count) -> val last = pair.last() if (acc.contains(last)) { val existingCount = acc[last]!! acc.minus(last) + mapOf(last to existingCount + count) } else { acc + mapOf(last to count) } } .map { (element, count) -> if (element == polymerTemplate.first()) element to count + 1 else element to count } .map { (_, count) -> count } .sorted() return elementCounts.last() - elementCounts.first() } }
0
Kotlin
0
0
72492c6a7d0c939b2388e13ffdcbf12b5a1cb838
2,644
AdventOfCode
MIT License
src/main/kotlin/com/staricka/adventofcode2022/Day12.kt
mathstar
569,952,400
false
{"Kotlin": 77567}
package com.staricka.adventofcode2022 class Day12 : Day { override val id = 12 data class Tile(val height: Char) { fun canStepFrom(other: Tile): Boolean = other.height - height >= -1 fun canStepReverse(other: Tile): Boolean = other.canStepFrom(this) } private fun shortestPath( start: Pair<Int, Int>, grid: List<List<Tile>>, stepCondition: Tile.(Tile) -> Boolean, endCondition: (Pair<Int, Int>, Tile) -> Boolean ): Int { val explored = Array(grid.size) { BooleanArray(grid[0].size) } explored[start.first][start.second] = true var next = listOf(start) var steps = 0 while (true) { val nextStep = ArrayList<Pair<Int, Int>>() for (n in next) { val (i, j) = n if (endCondition(n, grid[i][j])) return steps if (i > 0 && grid[i - 1][j].stepCondition(grid[i][j]) && !explored[i-1][j]) { explored[i-1][j] = true nextStep.add(Pair(i - 1, j)) } if (j > 0 && grid[i][j - 1].stepCondition(grid[i][j]) && !explored[i][j-1]) { explored[i][j-1] = true nextStep.add(Pair(i, j - 1)) } if (i < grid.size - 1 && grid[i + 1][j].stepCondition(grid[i][j]) && !explored[i+1][j]) { explored[i+1][j] = true nextStep.add(Pair(i + 1, j)) } if (j < grid[0].size - 1 && grid[i][j + 1].stepCondition(grid[i][j]) && !explored[i][j+1]) { explored[i][j+1] = true nextStep.add(Pair(i, j + 1)) } } steps++ next = nextStep } } override fun part1(input: String): Any { var start = Pair(0,0) var end = Pair(0,0) val grid = input.lines().withIndex().map { (i, line) -> line.withIndex().map {(j, t) -> when (t) { 'S' -> { start = Pair(i,j) Tile('a') } 'E' -> { end = Pair(i,j) Tile('z') } else -> Tile(t) } } } return shortestPath(start, grid, Tile::canStepFrom) {coord, _ -> coord == end} } override fun part2(input: String): Any { var end = Pair(0,0) val grid = input.lines().withIndex().map { (i, line) -> line.withIndex().map {(j, t) -> when (t) { 'S' -> { Tile('a') } 'E' -> { end = Pair(i,j) Tile('z') } else -> Tile(t) } } } return shortestPath(end, grid, Tile::canStepReverse) {_, tile -> tile.height == 'a'} } }
0
Kotlin
0
0
2fd07f21348a708109d06ea97ae8104eb8ee6a02
2,521
adventOfCode2022
MIT License
src/Day12.kt
Fenfax
573,898,130
false
{"Kotlin": 30582}
import java.awt.Point import java.util.* import kotlin.collections.ArrayDeque fun main() { val alphabet = ('a'..'z').joinToString ("") fun genPoints(input: List<String>): MapGraph{ val points = mutableMapOf<Point, MapPoint>() for (x in input.indices){ for (y in input[x].indices){ var height = input[x][y] if(height == 'S') height = 'a' if(height == 'E') height = 'z' points[Point(x,y)] = MapPoint(pos = Point(x,y), height = alphabet.indexOfFirst { it == height} + 1) } } val mapGraph = MapGraph(points = points) for (x in input.indices){ for (y in input[x].indices){ val workingPoint: MapPoint = points.getOrElse(Point(x,y)){throw IllegalStateException()} mapGraph.edges[workingPoint] = mutableListOf() for (add in listOf(-1,1)){ points[Point(add + x, y)]?.takeIf { it.height - workingPoint.height <= 1 }?.let { mapGraph.edges[workingPoint]?.add(it) } points[Point(x, add + y)]?.takeIf { it.height - workingPoint.height <= 1 }?.let { mapGraph.edges[workingPoint]?.add(it) } } } } return mapGraph } fun getFirstWithChar(input: List<String>, char: Char): Point{ for (x in input.indices) { for (y in input[x].indices) { if (input[x][y] == char) return Point(x,y) } } return Point(-1,-1) } fun searchPath(mapGraph: MapGraph, start: MapPoint, end: MapPoint): Map<MapPoint, Optional<MapPoint>>{ val queue = ArrayDeque(listOf(start)) val cameFrom = mutableMapOf<MapPoint, Optional<MapPoint>>(start to Optional.empty()) while (queue.isNotEmpty()){ val pos = queue.removeFirst() if (pos == end) return cameFrom for (neighbor in mapGraph.getNeighbors(pos)) if (!cameFrom.keys.contains(neighbor)){ queue.add(neighbor) cameFrom[neighbor] = Optional.of(pos) } } return cameFrom } fun getPath(paths: Map<MapPoint, Optional<MapPoint>>, end: MapPoint): List<MapPoint>{ val path = mutableListOf(end) var currentPos = end while (paths[currentPos]?.isPresent == true){ path.add(paths[currentPos]?.get()!!) currentPos = paths[currentPos]?.get()!! } return path } fun part1(input: List<String>): Int { val graph = genPoints(input) val start = graph.points[getFirstWithChar(input, 'S')]!! val end = graph.points[getFirstWithChar(input, 'E')]!! val paths = searchPath(graph, start, end) val startToEnd = getPath(paths, end) return startToEnd.size - 1 } fun part2(input: List<String>): Int { val graph = genPoints(input) val end = graph.points[getFirstWithChar(input, 'E')]!! return graph.points.values.asSequence() .filter{it.height == 1} .map { getPath(searchPath(graph, it, end), end) } .filter { it.size > 1 } .minOf { it.size - 1 } } val input = readInput("Day12") println(part1(input)) println(part2(input)) } data class MapPoint(val pos: Point, val height: Int) data class MapGraph(val points: Map<Point, MapPoint>, val edges: MutableMap<MapPoint, MutableList<MapPoint>> = mutableMapOf()){ fun getNeighbors(id: MapPoint): List<MapPoint>{ return edges[id]?.toList() ?: listOf() } }
0
Kotlin
0
0
28af8fc212c802c35264021ff25005c704c45699
3,713
AdventOfCode2022
Apache License 2.0
kotlin/src/Day11.kt
ekureina
433,709,362
false
{"Kotlin": 65477, "C": 12591, "Rust": 7560, "Makefile": 386}
import java.lang.Integer.parseInt fun main() { val part1Iterations = 100 fun surroundingCells(line: Int, row: Int, constraints: Pair<Int, Int>): Collection<Pair<Int, Int>> { return ((line-1).coerceAtLeast(0)..(line+1).coerceAtMost(constraints.first)).flatMap { lineNum -> ((row-1).coerceAtLeast(0)..(row+1).coerceAtMost(constraints.second)).map { rowNum -> lineNum to rowNum } } } fun flash( octopi: List<MutableList<Int>>, lineIdex: Int, rowIdex: Int, flashed: MutableSet<Pair<Int, Int>> ) { val toVisit = surroundingCells(lineIdex, rowIdex, (octopi.size - 1) to (octopi[0].size - 1)) .toMutableList() while (toVisit.isNotEmpty()) { val visit = toVisit.removeFirst() octopi[visit.first][visit.second]++ if (octopi[visit.first][visit.second] > 9 && !flashed.contains(visit)) { flashed.add(visit) toVisit.addAll(surroundingCells(visit.first, visit.second, (octopi.size - 1) to (octopi[0].size - 1))) } } } fun part1(input: List<String>): Int { val octopi = input.map { line -> line.map(Char::toString).map(::parseInt).toMutableList() } return (0 until part1Iterations).sumOf { val flashed = mutableSetOf<Pair<Int, Int>>() octopi.indices.forEach { lineNumber -> octopi[lineNumber].indices.forEach { octopusNumber -> octopi[lineNumber][octopusNumber]++ val octopusEnergy = octopi[lineNumber][octopusNumber] if (octopusEnergy > 9) { if (!flashed.contains(lineNumber to octopusNumber)) { flashed.add(lineNumber to octopusNumber) flash(octopi, lineNumber, octopusNumber, flashed) } } } } octopi.indices.sumOf { lineNumber -> octopi[lineNumber].indices.sumOf { octopusNumber -> if (octopi[lineNumber][octopusNumber] > 9) { octopi[lineNumber][octopusNumber] = 0 1.toInt() } else { 0 } } } } } fun part2(input: List<String>): Int { val octopi = input.map { line -> line.map(Char::toString).map(::parseInt).toMutableList() } return generateSequence(1) { it + 1 }.first { val flashed = mutableSetOf<Pair<Int, Int>>() octopi.indices.forEach { lineNumber -> octopi[lineNumber].indices.forEach { octopusNumber -> octopi[lineNumber][octopusNumber]++ val octopusEnergy = octopi[lineNumber][octopusNumber] if (octopusEnergy > 9) { if (!flashed.contains(lineNumber to octopusNumber)) { flashed.add(lineNumber to octopusNumber) flash(octopi, lineNumber, octopusNumber, flashed) } } } } val flashes = octopi.indices.sumOf { lineNumber -> octopi[lineNumber].indices.sumOf { octopusNumber -> if (octopi[lineNumber][octopusNumber] > 9) { octopi[lineNumber][octopusNumber] = 0 1 } else { 0.toInt() } } } flashes == octopi.size * octopi[0].size } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day11_test") check(part1(testInput) == 1656) { "${part1(testInput)}" } check(part2(testInput) == 195) { "${part2(testInput)}" } val input = readInput("Day11") println(part1(input)) println(part2(input)) }
0
Kotlin
0
1
391d0017ba9c2494092d27d22d5fd9f73d0c8ded
4,089
aoc-2021
MIT License
2021/02/28/jjeda/PrefixSums.kt
Road-of-CODEr
323,110,862
false
null
// https://app.codility.com/programmers/lessons/5-prefix_sums/count_div fun countDiv(A: Int, B: Int, K: Int): Int { val startNumber = (A..B).firstOrNull { it % K ==0 } ?: return 0 return (B - startNumber) / K + 1 } // https://app.codility.com/programmers/lessons/5-prefix_sums/genomic_range_query /* // O(N * M) fun solution(S: String, P: IntArray, Q: IntArray): IntArray { fun String.findMinValue(): Int { if (this.contains('A')) return 1 if (this.contains('C')) return 2 if (this.contains('G')) return 3 return 4 } return P.indices.map { S.substring(P[it], Q[it] + 1).findMinValue() }.toIntArray() } */ // O(N + M) fun genomicRangeQuery(S: String, P: IntArray, Q: IntArray): IntArray { fun generateDeltaList(char: Char): IntArray { val deltaArray = IntArray(S.length + 1) (0..S.length).fold(0) { acc, index -> deltaArray[index] = acc if (index == S.length) { return@fold 0 } acc + if (S[index] == char) 1 else 0 } return deltaArray } val deltaA = generateDeltaList('A') val deltaC = generateDeltaList('C') val deltaG = generateDeltaList('G') fun String.findMinValue(start: Int, end: Int): Int { if (start == end) { return when (S[start]) { 'A' -> 1 'C' -> 2 'G' -> 3 else -> 4 } } if (deltaA[start] != deltaA[end]) return 1 if (deltaC[start] != deltaC[end]) return 2 if (deltaG[start] != deltaG[end]) return 3 return 4 } return P.indices.map { S.substring(P[it], Q[it] + 1).findMinValue(P[it], Q[it] + 1) }.toIntArray() } // TODO: https://app.codility.com/programmers/lessons/5-prefix_sums/min_avg_two_slice // https://app.codility.com/programmers/lessons/5-prefix_sums/passing_cars fun passingCars(A: IntArray): Int { val accumulateCount = IntArray(A.size) A.foldIndexed(0) { index, acc, number -> accumulateCount[index] = acc + number acc + number } val totalCount = accumulateCount[A.size - 1] var count = 0 accumulateCount.forEachIndexed { index, number -> if (A[index] == 1) return@forEachIndexed if (count + totalCount - number > 1000000000) return -1 count += totalCount - number } return count }
1
Java
25
22
cae1df83ac110519a5f5d6b940fa3e90cebb48c1
2,232
stupid-week-2021
MIT License
src/Day21.kt
kenyee
573,186,108
false
{"Kotlin": 57550}
import java.lang.IllegalArgumentException sealed class MonkeyNode(val name: String) { class ShoutMonkey(name: String, private val value: Long) : MonkeyNode(name) { override fun compute(monkeys: Map<String, MonkeyNode>): Long { return value } } class CalcMonkey( name: String, private val left: String, private val right: String, val calc: (x: Long, y: Long) -> Long ) : MonkeyNode(name) { override fun compute( monkeys: Map<String, MonkeyNode> ): Long { return calc(monkeys[left]!!.compute(monkeys), monkeys[right]!!.compute(monkeys)) } } abstract fun compute(monkeys: Map<String, MonkeyNode>): Long } fun main() { // ktlint-disable filename fun part1(input: List<String>): Long { val monkeys = mutableMapOf<String, MonkeyNode>() for (line in input) { val tokens = line.split(" ") val name = tokens[0].trimEnd(':') if (tokens.size == 2) { monkeys[name] = MonkeyNode.ShoutMonkey(name, tokens[1].toLong()) } else { monkeys[name] = when (tokens[2]) { "+" -> MonkeyNode.CalcMonkey(name, tokens[1], tokens[3]) { x, y -> x + y } "-" -> MonkeyNode.CalcMonkey(name, tokens[1], tokens[3]) { x, y -> x - y } "*" -> MonkeyNode.CalcMonkey(name, tokens[1], tokens[3]) { x, y -> x * y } "/" -> MonkeyNode.CalcMonkey(name, tokens[1], tokens[3]) { x, y -> x / y } else -> throw IllegalArgumentException("Unknown token $line") } } } return monkeys["root"]!!.compute(monkeys) } fun part2(input: List<String>): Long { return 0 } // test if implementation meets criteria from the description, like: val testInput = readInput("Day21_test") println("Test root monkey yells: ${part1(testInput)}") check(part1(testInput) == 152L) // println("Test #Exterior sides: ${part2(testInput)}") // check(part2(testInput) == 301) val input = readInput("Day21_input") println("root monkey yells: ${part1(input)}") // println("#Exterior sides: ${part2(input)}") }
0
Kotlin
0
0
814f08b314ae0cbf8e5ae842a8ba82ca2171809d
2,265
KotlinAdventOfCode2022
Apache License 2.0
src/day05/Day05.kt
dkoval
572,138,985
false
{"Kotlin": 86889}
package day05 import readInput import java.util.* private const val DAY_ID = "05" private data class Instruction(val quantity: Int, val from: Int, val to: Int) fun main() { fun solve(input: List<String>, strategy: (stacks: Array<Deque<Char>>, instruction: Instruction) -> Unit): String { val data = input.takeWhile { line -> line.isNotEmpty() } // fill in the stacks val n = """(\d+)$""".toRegex().find(data.last())!!.value.toInt() val stacks = Array<Deque<Char>>(n) { ArrayDeque() } data.dropLast(1).forEach { line -> val crates = line.withIndex().filter { (_, c) -> c.isLetter() } crates.forEach { (index, c) -> // compute the index of the stack to put the current crate into: // pattern "[X]_" takes 4 characters stacks[index / 4].offerFirst(c) } } // process instructions val instruction = """move (\d+) from (\d+) to (\d+)""".toRegex() input.drop(data.size + 1).forEach { line -> val (quantity, from, to) = instruction.find(line)!!.destructured strategy(stacks, Instruction(quantity.toInt(), from.toInt(), to.toInt())) } return buildString { stacks.forEach { stack -> append(stack.peekLast()) } } } fun part1(input: List<String>): String = solve(input) { stacks, (quantity, from, to) -> repeat(quantity) { val top = stacks[from - 1].pollLast() stacks[to - 1].offerLast(top) } } fun part2(input: List<String>): String = solve(input) { stacks, (quantity, from, to) -> val buffer = ArrayDeque<Char>() repeat(quantity) { val top = stacks[from - 1].pollLast() buffer.push(top) } while (!buffer.isEmpty()) { val top = buffer.pop() stacks[to - 1].offerLast(top) } } // test if implementation meets criteria from the description, like: val testInput = readInput("day${DAY_ID}/Day${DAY_ID}_test") check(part1(testInput) == "CMZ") check(part2(testInput) == "MCD") val input = readInput("day${DAY_ID}/Day$DAY_ID") println(part1(input)) // answer = JCMHLVGMG println(part2(input)) // answer = LVMRWSSPZ }
0
Kotlin
1
0
791dd54a4e23f937d5fc16d46d85577d91b1507a
2,382
aoc-2022-in-kotlin
Apache License 2.0
src/Day11.kt
adrianforsius
573,044,406
false
{"Kotlin": 68131}
import org.assertj.core.api.Assertions.assertThat data class Monkey( val items: MutableList<Long> = mutableListOf(), val worry: (Long) -> Long, var inspections: Long = 0, ) data class MonkeyPart1( val monkey: Monkey, val next: (Long) -> Int, ) data class MonkeyPart2( val monkey: Monkey, val dividedBy: Long = 1, val destTrue: Int = 0, val destFalse: Int = 0, ) fun main() { fun part1(input: String): Long { val monkeys = input.split("\n\n").map { var worry: (i: Long) -> Long = fun(i: Long): Long { return i } var items = mutableListOf<Long>() var div = 1 var destTrue = 0 var destFalse = 0 it.split("\n").map { when { it.contains("Starting items: ") -> items = it.split(": ")[1].split(", ").map { it.toLong() }.toMutableList() it.contains("Operation: ") -> it.split(" new = ")[1].let { val (_, op, val2) = it.split(" ") val f: (Long, Long) -> Long = when (op) { "+" -> Long::plus "*" -> Long::times else -> error("invalid operator") } worry = fun(i: Long): Long = if (val2 == "old") f(i,i) else f(i, val2.toLong()) } it.contains("Test: ") -> div = it.split(" divisible by ")[1].toInt() it.contains("If true: ") -> destTrue = it.split(" throw to monkey ")[1].toInt() it.contains("If false: ") -> destFalse = it.split(" throw to monkey ")[1].toInt() } } MonkeyPart1( Monkey( items, worry, ), fun(i: Long): Int = when (i.toInt() % div == 0) { true -> destTrue false -> destFalse }, ) } for (round in 1..20) { for (monkey in monkeys) { repeat(monkey.monkey.items.size) { val item = monkey.monkey.items.removeFirst() val level = Math.floor(monkey.monkey.worry(item) / 3.0).toLong() monkey.monkey.inspections++ monkeys[monkey.next(level)].monkey.items.add(level) } } } return monkeys.sortedByDescending { it.monkey.inspections }.take(2).flatMap { monkey: MonkeyPart1 -> listOf(monkey.monkey.inspections) } .reduce { acc, el -> acc * el } } fun part2(input: String): Long { val monkeys = input.split("\n\n").map { var worry: (Long) -> Long = fun(i: Long):Long { return i} var items = mutableListOf<Long>() var div = 1L var destTrue = 0 var destFalse = 0 it.split("\n").map { when { it.contains("Starting items: ") -> items = it.split(": ")[1].split(", ").map { it.toLong() }.toMutableList() it.contains("Operation: ") -> it.split(" new = ")[1].let { val (_, op, val2) = it.split(" ") val f: (Long, Long) -> Long = when (op) { "+" -> Long::plus "*" -> Long::times else -> error("invalid operator") } worry = fun(i: Long): Long = if (val2 == "old") f(i,i) else f(i, val2.toLong()) } it.contains("Test: ") -> div = it.split(" divisible by ")[1].toLong() it.contains("If true: ") -> destTrue = it.split(" throw to monkey ")[1].toInt() it.contains("If false: ") -> destFalse = it.split(" throw to monkey ")[1].toInt() } } MonkeyPart2(Monkey(items, worry), div, destTrue, destFalse) } val modulo = monkeys .map { it.dividedBy } .reduce { acc, i -> acc * i } for (round in 1..10_000) { for (monkey in monkeys) { repeat(monkey.monkey.items.size) { val item = monkey.monkey.items.removeLast() monkey.monkey.inspections++ val level = monkey.monkey.worry(item).mod(modulo) val next = when (level.mod(monkey.dividedBy) == 0L) { true -> monkey.destTrue false -> monkey.destFalse } monkeys[next].monkey.items.add(level) } } } return monkeys .sortedByDescending { it.monkey.inspections } .take(2) .flatMap { monkey: MonkeyPart2 -> listOf(monkey.monkey.inspections) } .reduce{ acc, em -> acc*em } } // test if implementation meets criteria from the description, like: // Test val testInput = readText("Day11_test") val output1 = part1(testInput) assertThat(output1).isEqualTo(10605) // Answek val input = readText("Day11") val outputAnswer1 = part1(input) assertThat(outputAnswer1).isEqualTo(90294) // Test val output2 = part2(testInput) assertThat(output2).isEqualTo(2713310158) // Answer val outputAnswer2 = part2(input) assertThat(outputAnswer2).isEqualTo(18170818354L) }
0
Kotlin
0
0
f65a0e4371cf77c2558d37bf2ac42e44eeb4bdbb
5,555
kotlin-2022
Apache License 2.0
2021/src/Day05.kt
Bajena
433,856,664
false
{"Kotlin": 65121, "Ruby": 14942, "Rust": 1698, "Makefile": 454}
import java.lang.Math.abs // https://adventofcode.com/2021/day/5 fun main() { fun part1() { val lines = mutableListOf<Pair<Pair<Int, Int>, Pair<Int, Int>>>() for (line in readInput("Day05")) { val points = line.split(" -> ").map { points -> val values = points.split(",").map { it.toInt() } Pair(values.first(), values.last()) } val a = points.first() val b = points.last() if (a.first == b.first || a.second == b.second) lines.add(Pair(a, b)) } val selectedPoints = mutableMapOf<Pair<Int, Int>, Int>().withDefault { 0 } lines.forEach { line -> val a = line.first val b = line.second if (a.first == b.first) { val range = if (b.second >= a.second) a.second..b.second else b.second..a.second for (i in range) { val p = Pair(a.first, i) selectedPoints[p] = selectedPoints.getValue(p) + 1 } } if (a.second == b.second) { val range = if (b.first >= a.first) a.first..b.first else b.first..a.first for (i in range) { val p = Pair(i, a.second) selectedPoints[p] = selectedPoints.getValue(p) + 1 } } } println(selectedPoints.values.filter { it > 1 }.size) } fun part2() { val lines = mutableListOf<Pair<Pair<Int, Int>, Pair<Int, Int>>>() for (line in readInput("Day05")) { val points = line.split(" -> ").map { points -> val values = points.split(",").map { it.toInt() } Pair(values.first(), values.last()) } val a = points.first() val b = points.last() if (a.first == b.first || a.second == b.second || kotlin.math.abs(a.first - b.first) == kotlin.math.abs(a.second - b.second)) lines.add(Pair(a, b)) } val selectedPoints = mutableMapOf<Pair<Int, Int>, Int>().withDefault { 0 } lines.forEach { line -> val a = line.first val b = line.second if (a.first == b.first) { val range = if (b.second >= a.second) a.second..b.second else b.second..a.second for (i in range) { val p = Pair(a.first, i) selectedPoints[p] = selectedPoints.getValue(p) + 1 } } else if (a.second == b.second) { val range = if (b.first >= a.first) a.first..b.first else b.first..a.first for (i in range) { val p = Pair(i, a.second) selectedPoints[p] = selectedPoints.getValue(p) + 1 } } else if (kotlin.math.abs(a.first - b.first) == kotlin.math.abs(a.second - b.second)) { val smallerXPoint = if (a.first < b.first) a else b val biggerXPoint = if (a.first >= b.first) a else b val length = kotlin.math.abs(a.first - b.first) val direction = if (biggerXPoint.second - smallerXPoint.second > 0) 1 else -1 for (i in 0..length) { val p = Pair(smallerXPoint.first + i, smallerXPoint.second + i * direction) selectedPoints[p] = selectedPoints.getValue(p) + 1 } } } println(selectedPoints.values.filter { it > 1 }.size) } part1() part2() }
0
Kotlin
0
0
a5ca56b7ac8d9d48f82dc079c8ea0cf06d17109a
3,091
advent-of-code
Apache License 2.0
src/Day05.kt
mjossdev
574,439,750
false
{"Kotlin": 81859}
fun main() { data class Move(val n: Int, val source: Int, val target: Int) fun String.toMove(): Move { val (n, source, target) = Regex("""move (\d+) from (\d+) to (\d+)""") .matchEntire(this)!! .groupValues .drop(1) .map { it.toInt() } return Move(n, source - 1, target - 1); } fun readStacks(input: List<String>): Array<ArrayDeque<Char>> { val size = input.last().split(Regex("""\s+""")).last().toInt() val stackData = input.dropLast(1) val stacks = Array(size) { ArrayDeque<Char>() } for (line in stackData) { for (i in 0..line.length / 4) { if (line[i * 4] == '[') { stacks[i].addFirst(line[i * 4 + 1]) } } } return stacks } fun part1(input: List<String>): String { val divider = input.indexOf("") val stacks = readStacks(input.take(divider)) val moves = input.drop(divider + 1).map { it.toMove() } for ((n, source, target) in moves) { repeat(n) { stacks[target].addLast(stacks[source].removeLast()) } } return stacks.joinToString("") { it.last().toString() } } fun part2(input: List<String>): String { val divider = input.indexOf("") val stacks = readStacks(input.take(divider)) val moves = input.drop(divider + 1).map { it.toMove() } for ((n, source, target) in moves) { val elements = ArrayDeque<Char>() repeat(n) { elements.addFirst(stacks[source].removeLast()) } stacks[target].addAll(elements) } return stacks.joinToString("") { it.last().toString() } } // 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
afbcec6a05b8df34ebd8543ac04394baa10216f0
2,073
advent-of-code-22
Apache License 2.0
src/Day03.kt
BionicCa
574,904,899
false
{"Kotlin": 20039}
fun main() { fun part1(input: List<String>): Int { var totalScore = 0 for (rucksack in input) { val chunks = rucksack.chunked(rucksack.length / 2) val commonElements = findCommonCharacter(chunks[0].toCharArray(), chunks[1].toCharArray()) val score = commonElements.sumOf { when { it.isLowerCase() -> it.code - 96 // a - z -> 1 - 26 else -> it.code - 38// A - Z -> 27 - 52 } } totalScore += score } return totalScore } fun part2(input: List<String>): Int { val chunks = input.windowed(3, step = 3) var totalScore = 0 for (rucksackGroup in chunks) { val commonElements = findCommonCharacter( findCommonCharacter(rucksackGroup[0].toCharArray(), rucksackGroup[1].toCharArray()).toCharArray(), rucksackGroup[2].toCharArray() ) val score = commonElements.sumOf { when { it.isLowerCase() -> it.code - 96 // a - z -> 1 - 26 else -> it.code - 38// A - Z -> 27 - 52 } } totalScore += score } return totalScore } val testInput = readInput("Day03_test") println(part1(testInput)) println(part2(testInput)) val input = readInput("Day03") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
ed8bda8067386b6cd86ad9704bda5eac81bf0163
1,488
AdventOfCode2022
Apache License 2.0
src/Day05.kt
ds411
573,543,582
false
{"Kotlin": 16415}
fun main() { fun part1(input: List<String>): String { return runCrane(input, reversed = true) } fun part2(input: List<String>): String { return runCrane(input, reversed = false) } // test if implementation meets criteria from the description, like: val testInput = readInput("Day05_test") check(part1(testInput) == "CMZ") check(part2(testInput) == "MCD") val input = readInput("Day05") println(part1(input)) println(part2(input)) } private fun runCrane(input: List<String>, reversed: Boolean): String { val breakpoint = input.indexOf("") val boxes = input.subList(0, breakpoint) val rules = input.subList(breakpoint+1, input.size) val columnRow = boxes.last() val columns = columnRow.toCharArray().filter(Char::isDigit) val indexByColumn = columns.fold(mutableMapOf<Char, Int>()) { map, col -> map[col] = columnRow.indexOf(col) map } val boxRows = boxes.subList(0, boxes.lastIndex).reversed() val stackByCol = mutableMapOf<Char, String>() columns.forEach { stackByCol[it] = "" } boxRows.forEach { row -> columns.forEach { col -> val index = indexByColumn[col]!! if (index < row.length) { val char = row[index] if (char != ' ') { stackByCol[col] = char + stackByCol[col]!! } } } } val regex = Regex("move ([\\d]+) from ([\\d]+) to ([\\d]+)") rules.forEach { rule -> val (len, src, tgt) = regex.find(rule)!!.destructured val _str = stackByCol[src[0]]!!.substring(0, len.toInt()) val str = if (reversed) _str.reversed() else _str stackByCol[src[0]] = stackByCol[src[0]]!!.substring(len.toInt()) stackByCol[tgt[0]] = str + stackByCol[tgt[0]]!! } return columns.map { stackByCol[it]!!.first() }.filter { it.isLetter() }.joinToString("") }
0
Kotlin
0
0
6f60b8e23ee80b46e7e1262723960af14670d482
1,940
advent-of-code-2022
Apache License 2.0
src/day14/Day14.kt
bartoszm
572,719,007
false
{"Kotlin": 39186}
package day14 import readInput import toPair fun main() { println(solve1(parse(readInput("day14/test")), 500 to 0)) println(solve1(parse(readInput("day14/input")), 500 to 0)) println(solve2(parse(readInput("day14/test")), 500 to 0)) println(solve2(parse(readInput("day14/input")), 500 to 0)) } typealias Point = Pair<Int, Int> typealias Line = List<Point> typealias Board = Array<IntArray> fun solve1(rocks: List<Line>, start: Point): Int { val simulation = Simulation(fillBoard(rocks)) var sandUnits = 0 while (true) { val landed = simulation.drop(start) if (landed.second == simulation.bottom) { return sandUnits } sandUnits += 1 } } fun solve2(rocks: List<Line>, start: Point): Int { val simulation = Simulation(fillBoard(rocks)) var sandUnits = 0 while (true) { val landed = simulation.drop(start) if (landed == start) { print(simulation) return sandUnits + 1 } sandUnits += 1 } } class Simulation(val board: Board) { private fun next(p: Point): Point? { return sequenceOf( p.first to p.second + 1, p.first - 1 to p.second + 1, p.first + 1 to p.second + 1 ) .filter { it.second <= bottom } //rows .filter { it.first in board[0].indices } //columns .firstOrNull { board[it.second][it.first] == 0 } } val bottom: Int by lazy { val x = board.withIndex() .filter { (_, v) -> v.any { c -> c > 0 } } .map { it.index } .max() x + 1 } fun simulate(from: Point): Point { tailrec fun traverse(p: Point): Point { val n = next(p) return if (n == null) p else traverse(n) } return traverse(from) } fun mark(p: Point) { board[p.second][p.first] = 1 } fun drop(from: Point): Point { val landed = simulate(from) mark(landed) return landed } } fun print(s: Simulation) { s.board.forEach { row -> val r = row.map { when (it) { 0 -> '.' 1 -> 'o' 2 -> '#' else -> throw java.lang.IllegalStateException() } }.joinToString("") println(r) } } fun fillBoard(input: List<Line>): Board { val board = (0 until 200).map { IntArray(1000) { 0 } }.toTypedArray() fun prog(a: Int, b: Int) = if (a > b) (a downTo b) else (a..b) fun fillRow(a: Point, b: Point) { if (a.first == b.first) { prog(a.second, b.second).forEach { board[it][a.first] = 2 } } } fun fillColumn(a: Point, b: Point) { if (a.second == b.second) { prog(a.first, b.first).forEach { board[a.second][it] = 2 } } } fun fill(l: Line) { l.windowed(2).map { it.toPair() }.forEach { (a, b) -> fillColumn(a, b) fillRow(a, b) } } input.forEach { fill(it) } return board } fun parse(input: List<String>) = input.map { parse(it) } fun parse(i: String): Line { fun point(s: String): Point = s.split(",").map { it.trim().toInt() }.toPair() return i.split("->").map { point(it) } }
0
Kotlin
0
0
f1ac6838de23beb71a5636976d6c157a5be344ac
3,321
aoc-2022
Apache License 2.0
aoc/src/main/kotlin/com/bloidonia/aoc2023/day05/Main.kt
timyates
725,647,758
false
{"Kotlin": 45518, "Groovy": 202}
package com.bloidonia.aoc2023.day05 import com.bloidonia.aoc2023.lines private const val example = """seeds: 79 14 55 13 seed-to-soil map: 50 98 2 52 50 48 soil-to-fertilizer map: 0 15 37 37 52 2 39 0 15 fertilizer-to-water map: 49 53 8 0 11 42 42 0 7 57 7 4 water-to-light map: 88 18 7 18 25 70 light-to-temperature map: 45 77 23 81 45 19 68 64 13 temperature-to-humidity map: 0 69 1 1 0 69 humidity-to-location map: 60 56 37 56 93 4""" private data class Mapping(val source: LongRange, val dx: Long) { constructor(line: String) : this( line.split(" ").map { it.toLong() }.let { it[1]..<(it[1] + it[2]) }, line.split(" ").map { it.toLong() }.let { it[0] - it[1] } ) } private data class Mapper(val mappings: List<Mapping>) { fun map(input: Long) = (mappings.firstOrNull { input in it.source }?.dx ?: 0).let { input + it } } private fun seeds(input: List<String>) = input .find { it.startsWith("seeds: ") }!! .split(" ") .drop(1).map { it.toLong() } private fun seeds2(input: List<String>) = input .find { it.startsWith("seeds: ") }!! .split(" ") .drop(1) .map { it.toLong() } .windowed(2, 2) .map { it[0]..<(it[0] + it[1]) } private fun mappings(input: List<String>): List<Mapper> { val result = mutableListOf<Mapper>() var current = mutableListOf<Mapping>() var started = false var index = 0 while (index < input.size) { val line = input[index] when { line.endsWith("map:") -> { started = true } started && line.isEmpty() -> { started = false if (current.isNotEmpty()) { result.add(Mapper(current)) current = mutableListOf() } } started -> { current.add(Mapping(line)) } } index++ } if (current.isNotEmpty()) { result.add(Mapper(current)) } return result } private fun part1(input: List<String>) = seeds(input).let { seeds -> val mappings = mappings(input) seeds.minOfOrNull { seed -> mappings.fold(seed) { a, b -> b.map(a) } }.apply(::println) } private fun part2(input: List<String>) = seeds2(input).let { seeds -> val mappings = mappings(input) var min = Long.MAX_VALUE for (range in seeds) { for (seed in range) { val mapped = mappings.fold(seed) { a, b -> b.map(a) } if (mapped < min) { min = mapped } } } println(min) } fun main() { part1(example.lines()) part1(lines("/day05.input")) part2(example.lines()) part2(lines("/day05.input")) }
0
Kotlin
0
0
158162b1034e3998445a4f5e3f476f3ebf1dc952
2,707
aoc-2023
MIT License
src/Day05.kt
D000L
575,350,411
false
{"Kotlin": 23716}
fun main() { fun process(input: List<String>, withReverse: Boolean): String { val stacks = input.takeWhile { it.isNotEmpty() }.dropLast(1) .map { it.replace(" ", " ") .replace("[", "") .replace("]", "") } val moves = input.dropWhile { it.isNotEmpty() }.drop(1) val stackMap = sortedMapOf<Int, List<String>>() stacks.forEach { it.split(" ").forEachIndexed { index, s -> if (s.isEmpty()) return@forEachIndexed stackMap[index + 1] = (stackMap[index + 1] ?: listOf()) + s } } moves.forEach { val (amount, a, b) = it.split(" ").mapNotNull { it.toIntOrNull() } stackMap[b] = if (withReverse) stackMap[a]!!.take(amount).reversed() + stackMap[b]!! else stackMap[a]!!.take(amount) + stackMap[b]!! stackMap[a] = stackMap[a]!!.drop(amount) } return stackMap.map { it.value.first() }.joinToString("") } fun part1(input: List<String>): String { return process(input, true) } fun part2(input: List<String>): String { return process(input, false) } val input = readInput("Day05") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
b733a4f16ebc7b71af5b08b947ae46afb62df05e
1,341
adventOfCode
Apache License 2.0
src/Day03.kt
mr3y-the-programmer
572,001,640
false
{"Kotlin": 8306}
fun main() { fun part1(input: List<String>): Int { return input.sumOf { rucksack -> rucksack .chunked(rucksack.length / 2) .let { it[0].intersect(it[1]) } .calculatePriority() } } fun part2(input: List<String>): Int { return input.chunked(3) { groupOfThree -> groupOfThree .let { it[0].intersect(it[1], it[2]) } .calculatePriority() }.sum() } check(part1(readInput("Day03_sample")) == 157) println(part1(readInput("Day03_input"))) check(part2(readInput("Day03_sample")) == 70) println(part2(readInput("Day03_input"))) } private fun String.intersect(vararg others: String): Char { var chain = toSet() others.forEach { chain = chain.intersect(it.toSet()) } return chain.single() } private fun Char.calculatePriority(): Int { return when { isLowerCase() -> { this - 'a' + 1 } isUpperCase() -> { this - 'A' + 27 } else -> -1 } }
0
Kotlin
0
0
96d1567f38e324aca0cb692be3dae720728a383d
1,054
advent-of-code-2022
Apache License 2.0
src/2022/Day07.kt
nagyjani
572,361,168
false
{"Kotlin": 369497}
package `2022` import java.io.File import java.util.* fun main() { Day07().solve() } class Day07 { data class Node ( val name: String, val isDir: Boolean, val parent: Node? = null, val size: Long = 0, val content: MutableMap<String, Node> = mutableMapOf() ) { fun size(): Long { return size + content.values.sumOf { it.size() } } fun add(name: String, isDir: Boolean, size: Long) { if (content[name] == null) { content[name] = Node(name, isDir, this, size) } } fun get(name: String): Node { if (name == "..") { return parent!! } add(name, true, 0) return content[name]!! } fun sizeAndMax(max: Int): Pair<Long, Long> { val children = content.values val sumFiles = children.filter { !it.isDir }.sumOf { it.size } val sumDirs = children.filter { it.isDir }.fold(Pair(0L, 0L)){ acc, node -> val p = node.sizeAndMax(max) Pair(acc.first + p.first, acc.second + p.second) } val sumSize = sumFiles + sumDirs.first if (sumSize > max) { return Pair(sumSize, sumDirs.second) } return Pair(sumSize, sumDirs.second + sumSize) } fun minLarger(limit: Long, current: Long): Long { val children = content.values val subdirs = children.filter { it.isDir } var c = current if (!subdirs.isEmpty()) { c = subdirs.minOf { it.minLarger(limit, current) } } val s = size() if (s < c && s >= limit) { return s } return c } } val root = Node("", true) val input1 = """ ${'$'} cd / ${'$'} ls dir a 14848514 b.txt 8504156 c.dat dir d ${'$'} cd a ${'$'} ls dir e 29116 f 2557 g 62596 h.lst ${'$'} cd e ${'$'} ls 584 i ${'$'} cd .. ${'$'} cd .. ${'$'} cd d ${'$'} ls 4060174 j 8033020 d.log 5626152 d.ext 7214296 k """.trimIndent() fun solve() { val f = File("src/2022/inputs/day07.in") val s = Scanner(f) // val s = Scanner(input1) var current = root while (s.hasNextLine()) { val line = s.nextLine().trim() val tokens = line.split(" ") if (tokens[0] == "$") { if (tokens[1] == "cd") { if (tokens[2] == "/") { current = root } else { current = current.get(tokens[2]) } } } else if (tokens[0] == "dir") { current.add(tokens[1], true, 0) } else { current.add(tokens[1], false, tokens[0].toLong()) } } val minDelete = 30000000 - (70000000 - root.size()) val minLarger = root.minLarger(minDelete, root.size()) println("$minLarger $minDelete ${root.sizeAndMax(100000)}") } }
0
Kotlin
0
0
f0c61c787e4f0b83b69ed0cde3117aed3ae918a5
3,160
advent-of-code
Apache License 2.0
src/main/kotlin/com/tonnoz/adventofcode23/day4/Four.kt
tonnoz
725,970,505
false
{"Kotlin": 78395}
package com.tonnoz.adventofcode23.day4 import com.tonnoz.adventofcode23.day2.COLON import com.tonnoz.adventofcode23.day2.SPACE import com.tonnoz.adventofcode23.utils.readInput import kotlin.math.pow const val PIPE = "|" object Four{ @JvmStatic fun main(args: Array<String>) { val input = "inputFour.txt".readInput() problemOne(input) problemTwo(input) } //PROBLEM 1 private fun Set<Int>.countPoints(): Int = 2.toDouble().pow(this.size-1).toInt() private fun String.spacedStringsToCardValues(): HashSet<Int> = this.split(SPACE) .filter{ it.isNotEmpty() } .map{ it.trim().toInt() } .toHashSet() private fun problemOne(input:List<String>){ input.sumOf { val line = it.split(COLON, limit = 2).last() val (winningCardsString, myCardString) = line.split(PIPE, limit = 2) val winningCards = winningCardsString.spacedStringsToCardValues() val myCards = myCardString.spacedStringsToCardValues() winningCards.intersect(myCards).countPoints() }.let { println("solution to problem one is $it") } } //PROBLEM 2 data class Game(val winningCards: HashSet<Int>, val myCards: HashSet<Int>) private fun problemTwo(input:List<String>) { input .parseGame() .toTotalScratchCards() .let { println("solution to problem two is $it") } } private fun List<String>.parseGame(): List<Game> = this.map{ val line = it.split(COLON, limit = 2).last() val (winningCardsString, myCardString) = line.split(PIPE, limit = 2) val winningCards = winningCardsString.spacedStringsToCardValues() val myCards = myCardString.spacedStringsToCardValues() Game(winningCards, myCards) } private fun List<Game>.toTotalScratchCards(): Int { val copies = List(this.size){ 1 }.toMutableList() this.forEachIndexed { i, game -> val (winningCards, myCards) = game val matchingNumbers = myCards.intersect(winningCards).count() (1..matchingNumbers).forEach{ copies[i + it] += copies[i] } //here we are adding the number of copies of the game to the next games } return copies.sum() } }
0
Kotlin
0
0
d573dfd010e2ffefcdcecc07d94c8225ad3bb38f
2,115
adventofcode23
MIT License
src/aoc2023/Day02.kt
dayanruben
433,250,590
false
{"Kotlin": 79134}
package aoc2023 import readInput import checkValue fun main() { val (year, day) = "2023" to "Day02" fun gameSets(game: String) = game.split(";").map { it.trim().split(",").map { val (cubesStr, color) = it.trim().split(" ") val cubes = cubesStr.toInt() color to cubes } } fun gamePossibility(game: String): Int { val (gameId, gameInfo) = game.split(":") val (_, id) = gameId.split(" ") val sets = gameSets(gameInfo) val possible = sets.all { set -> set.all { (color, cubes) -> when (color) { "red" -> cubes <= 12 "green" -> cubes <= 13 "blue" -> cubes <= 14 else -> false } } } return if (possible) id.toInt() else 0 } fun gamePower(game: String): Int { val (_, gameInfo) = game.split(":") val sets = gameSets(gameInfo) val maxCubes = mutableMapOf("red" to 0, "green" to 0, "blue" to 0) sets.forEach { set -> set.forEach { (color, cubes) -> maxCubes[color] = maxOf(maxCubes[color] ?: 0, cubes) } } return maxCubes.values.reduce { acc, i -> acc * i } } fun part1(input: List<String>) = input.sumOf { gamePossibility(it) } fun part2(input: List<String>) = input.sumOf { gamePower(it) } val testInput = readInput(name = "${day}_test", year = year) val input = readInput(name = day, year = year) checkValue(part1(testInput), 8) println(part1(input)) checkValue(part2(testInput), 2286) println(part2(input)) }
1
Kotlin
2
30
df1f04b90e81fbb9078a30f528d52295689f7de7
1,762
aoc-kotlin
Apache License 2.0
src/Day04.kt
dragere
440,914,403
false
{"Kotlin": 62581}
import java.util.regex.Pattern class Bingo(fie: String, num: String, var marked: Array<IntArray> = Array(5) { IntArray(5) { 0 } }) { val field: List<List<Int>> val numbers: List<Int> var counter = 0 init { numbers = num.split(",").map { it.toInt() } field = fie.split("\r\n").map { it.trim().split(Pattern.compile(" +")).map { s -> s.toInt() } } } fun next(): Bingo { print("") for (i in 0 until 5) { for (j in 0 until 5) { if (field[i][j] == numbers[counter]) { marked[i][j] = 1 } } } counter++ return this } fun check(): Boolean { marked.forEachIndexed { i, r -> if (r.sum() == 5) { return true } if (this.marked.map { it[i] }.sum() == 5) { return true } } return false } fun get_winning_sum() = field.mapIndexed { i, r -> r.filterIndexed { j, _ -> marked[i][j] == 0 } } .map { it.sum() }.sum() * numbers[counter - 1] override fun toString(): String { var o = "" field.forEachIndexed { i, r -> r.forEachIndexed { j, n -> o += if (marked[i][j] == 1) { (" ") } else if (n < 9) { (" $n") } else { (" $n") } } o += ('\n') } return o } } fun main() { fun part1(input: List<Bingo>): Int { while (true) { for (it in input) { if (it.next().check()) { return it.get_winning_sum() } } } } fun part2(input: List<Bingo>): Int { val mutIn = input.toMutableList() while (mutIn.size > 0) { val toRemove = mutableListOf<Bingo>() for (i in mutIn.indices) { if (mutIn[i].next().check()) { toRemove.add(mutIn[i]) } } mutIn.removeAll(toRemove) if (mutIn.size == 0) { return toRemove[0].get_winning_sum() } } return 0 // println("Winner:\n${winner}") // return winner!!.get_winning_sum() } fun preprocessing(input: String): List<Bingo> { val (numbers, fields) = input.split(Pattern.compile("\r\n"), 2) return fields.trim().split("\r\n\r\n").map { Bingo(it, numbers.trim()) } } val realInp = read_testInput("real4") val testInp = read_testInput("test4") // println("Test 1: ${part1(preprocessing(testInp))}") // println("Real 1: ${part1(preprocessing(realInp))}") // println("-----------") println("Test 2: ${part2(preprocessing(testInp))}") println("Real 2: ${part2(preprocessing(realInp))}") }
0
Kotlin
0
0
3e33ab078f8f5413fa659ec6c169cd2f99d0b374
2,934
advent_of_code21_kotlin
Apache License 2.0
src/Day04.kt
kaeaton
572,831,118
false
{"Kotlin": 7766}
import kotlin.math.min import kotlin.math.max fun main() { fun part1(input: List<String>): Int { var nestedRegions = 0 input.forEach { //split into two val elves = it.split(",") // break down into the range for each elf var elfRegion1 = (elves[0].split("-")[0]).toInt()..(elves[0].split("-")[1]).toInt() var elfRegion2 = (elves[1].split("-")[0]).toInt()..(elves[1].split("-")[1]).toInt() // if the max of elfRange1 is greater than max elfRange2 if(elfRegion1.endInclusive.compareTo(elfRegion2.endInclusive) >= 0 && // AND min of elfRange1 is less than min of elfRange2 elfRegion1.start.compareTo(elfRegion2.start) <= 0 || // OR max of elfRange2 is greater than max of elfRange1 elfRegion2.endInclusive.compareTo(elfRegion1.endInclusive) >= 0 && // AND min of elfRange2 is less than min of elfRange1 elfRegion2.start.compareTo(elfRegion1.start) <= 0) { nestedRegions += 1 } } return nestedRegions } fun part2(input: List<String>): Int { var overlappingRegions = 0 input.forEach { //split into two val elves = it.split(",") // break down into the range for each elf var elfRegion1 = (elves[0].split("-")[0]).toInt()..(elves[0].split("-")[1]).toInt() var elfRegion2 = (elves[1].split("-")[0]).toInt()..(elves[1].split("-")[1]).toInt() // if elfRange1 contains the max elfRange2 if((elfRegion1.contains(elfRegion2.endInclusive)) or // OR elfRange1 contains the min of elfRange2 (elfRegion1.contains(elfRegion2.start)) or // OR elfRange2 contains the max of elfRange1 (elfRegion2.contains(elfRegion1.endInclusive)) or // OR elfRange2 contains the min of elfRange1 (elfRegion2.contains(elfRegion1.start))) { overlappingRegions += 1 } } return overlappingRegions } // testing compareTo println((4..4).endInclusive.compareTo((3..5).endInclusive)) println((3..5).endInclusive.compareTo((4..4).endInclusive)) println((4..4).start.compareTo((3..5).start)) println((3..5).start.compareTo((4..4).start)) val input = readInput("input_4") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
c2a92c68bd5822c72c1075f055fc2163762d6deb
2,526
AoC-2022
Apache License 2.0
ratio/src/main/kotlin/com/seanshubin/factor/analysis/ratio/Ratio.kt
SeanShubin
202,797,257
false
null
package com.seanshubin.factor.analysis.ratio data class Ratio(val numerator: Int, val denominator: Int) : Comparable<Ratio> { init { require(denominator != 0){ "Denominator must not be zero in $numerator/$denominator" } } operator fun plus(that: Ratio): Ratio { val lcm = leastCommonMultiple(denominator, that.denominator) return Ratio(numerator * lcm / denominator + that.numerator * lcm / that.denominator, lcm).simplify() } operator fun minus(that: Ratio): Ratio = (this + -that).simplify() operator fun times(that: Ratio): Ratio = Ratio(numerator * that.numerator, denominator * that.denominator).simplify() operator fun times(that: Int): Ratio = this * Ratio(that,1) operator fun div(that: Ratio): Ratio = (this * that.recriprocal()).simplify() operator fun unaryMinus(): Ratio = Ratio(-numerator, denominator).simplify() fun recriprocal(): Ratio = Ratio(denominator, numerator).simplify() fun withDenominator(newDenominator: Int): Ratio = Ratio(numerator * newDenominator / denominator, newDenominator) override fun compareTo(that: Ratio): Int { val lcm = leastCommonMultiple(denominator, that.denominator) return (numerator * lcm / denominator).compareTo(that.numerator * lcm / that.denominator) } override fun toString(): String = if(denominator == 1) "$numerator" else "$numerator/$denominator" fun simplify(): Ratio = simplifyFactor().simplifySign() private fun simplifySign(): Ratio = if (denominator < 0) Ratio(-numerator, -denominator) else this private fun simplifyFactor(): Ratio { val gcf = greatestCommonFactor(numerator, denominator) return Ratio(numerator / gcf, denominator / gcf) } companion object { val ZERO = Ratio(0,1) val ONE = Ratio(1,1) fun greatestCommonFactor(a: Int, b: Int): Int = if (b == 0) a else greatestCommonFactor(b, a % b) fun leastCommonMultiple(a: Int, b: Int): Int = if (a == 0 && b == 0) 0 else a * b / greatestCommonFactor(a, b) val regex = Regex("""(-?\d+)/(-?\d+)""") fun parse(s: String): Ratio { val matchResult = regex.matchEntire(s) if (matchResult == null) throw RuntimeException("Value '$s' could did not match expression $regex") val numerator = matchResult.groupValues[1].toInt() val denominator = matchResult.groupValues[2].toInt() return Ratio(numerator, denominator).simplify() } fun Int.toRatio():Ratio = Ratio(this, 1) fun List<Ratio>.toRatioArray():Array<Ratio> = toTypedArray() operator fun Int.div(x:Ratio):Ratio = ONE / x fun List<Ratio>.sum():Ratio { var sum: Ratio = ZERO for (element in this) { sum += element } return sum } } val toDouble: Double get() = numerator.toDouble() / denominator.toDouble() }
0
Kotlin
0
0
a0ae7f3f1a58b8263105a58c5cacfe31849d968f
3,045
factor-analysis
The Unlicense
src/Day07.kt
Miguel1235
726,260,839
false
{"Kotlin": 21105}
private enum class CardNames { HIGH_CARD, ONE_PAIR, TWO_PAIR, THREE_OF_A_KIND, FULL_HOUSE, FOUR_OF_A_KIND, FIVE_OF_A_KIND } private enum class Letters { T, J, Q, K, A, } private fun determineHandName(card: Map<Char, Int>): CardNames { if (card.containsValue(5)) return CardNames.FIVE_OF_A_KIND if (card.containsValue(4)) return CardNames.FOUR_OF_A_KIND if (card.containsValue(3) && card.containsValue(2)) return CardNames.FULL_HOUSE if (card.containsValue(3)) return CardNames.THREE_OF_A_KIND if (card.filter { it.value == 2 }.size == 2) return CardNames.TWO_PAIR if (card.containsValue(2)) return CardNames.ONE_PAIR return CardNames.HIGH_CARD } private data class Hand(val name: CardNames, val cards: String, val bet: Int) private val makeHand = {handString: String, bet: Int -> val cardMap = handString.groupBy { it }.mapValues { it.value.size } Hand(determineHandName(cardMap), handString, bet) } private val makeHands = { input: List<String> -> input.map { line -> val (strHand, bet) = line.split(" ") makeHand(strHand, bet.toInt()) } } private fun compareHands(h1: Hand, h2: Hand): Int { if (h1.name.ordinal > h2.name.ordinal) return 1 if (h1.name.ordinal < h2.name.ordinal) return -1 // card types are equal, so we are going to compare card by card val hand1 = h1.cards.toList() val hand2 = h2.cards.toList() for (i in hand1.indices) { val card1 = hand1[i] val card2 = hand2[i] if (!card1.isDigit() && card2.isDigit()) return 1 if (!card2.isDigit() && card1.isDigit()) return -1 if (!card1.isDigit() && !card2.isDigit()) { val l1 = Letters.valueOf(card1.toString()) val l2 = Letters.valueOf(card2.toString()) if (l1.ordinal > l2.ordinal) return 1 if (l2.ordinal > l1.ordinal) return -1 continue } // the two cards are digits, so compare them by its value if (card1.code > card2.code) return 1 if (card2.code > card1.code) return -1 } return 0 } private val calculateTotalWinnings = { hands: List<Hand> -> hands.mapIndexed { i, hand -> hand.bet * (i + 1) }.sum() } private val allParts = { hands: List<Hand> -> calculateTotalWinnings(hands.sortedWith { h1, h2 -> compareHands(h1, h2) }) } private val improveHands = {hands: List<Hand> -> hands.map {hand -> val jokers = hand.cards.count { it == 'J' } val improvedCard = when (hand.name) { CardNames.HIGH_CARD -> CardNames.ONE_PAIR CardNames.ONE_PAIR -> CardNames.THREE_OF_A_KIND CardNames.TWO_PAIR -> if (jokers == 1) CardNames.FULL_HOUSE else CardNames.FOUR_OF_A_KIND CardNames.THREE_OF_A_KIND -> CardNames.FOUR_OF_A_KIND else -> CardNames.FIVE_OF_A_KIND } if (jokers == 0) hand else Hand(improvedCard, hand.cards.replace('J', '1'), hand.bet) } } fun main() { val testInput = readInput("Day07_test") val testHands = makeHands(testInput) val testImprovedHands = improveHands(testHands) check(allParts(testHands) == 6440) check(allParts(testImprovedHands) == 5905) val input = readInput("Day07") val hands = makeHands(input) val improvedHands = improveHands(hands) check(allParts(hands) == 253603890) check(allParts(improvedHands) == 253630098) }
0
Kotlin
0
0
69a80acdc8d7ba072e4789044ec2d84f84500e00
3,433
advent-of-code-2023
MIT License
src/aoc2023/Day11.kt
dayanruben
433,250,590
false
{"Kotlin": 79134}
package aoc2023 import checkValue import readInput import kotlin.math.abs fun main() { val (year, day) = "2023" to "Day11" fun sumPaths(input: List<String>, expansion: Int): Long { val galaxies = mutableListOf<Galaxy>() val galaxyRows = mutableSetOf<Int>() val galaxyCols = mutableSetOf<Int>() val rows = input.size val cols = input.first().length for ((row, line) in input.withIndex()) { for ((col, cell) in line.withIndex()) { if (cell == '#') { galaxies += Galaxy(row, col) galaxyRows += row galaxyCols += col } } } val emptyRows = (0 until rows).filter { row -> row !in galaxyRows } val emptyCols = (0 until cols).filter { col -> col !in galaxyCols } for (galaxy in galaxies) { val expandedRows = (galaxy.row downTo 0).count { it in emptyRows } * (expansion - 1) galaxy.row += expandedRows val expandedCols = (galaxy.col downTo 0).count { it in emptyCols } * (expansion - 1) galaxy.col += expandedCols } return galaxies.allPairs().sumOf { (gal1, gal2) -> (abs(gal1.row - gal2.row) + abs(gal1.col - gal2.col)).toLong() } } fun part1(input: List<String>) = sumPaths(input, 2) fun part2(input: List<String>, expansion: Int = 1_000_000) = sumPaths(input, expansion) val testInput = readInput(name = "${day}_test", year = year) val input = readInput(name = day, year = year) checkValue(part1(testInput), 374) println(part1(input)) checkValue(part2(testInput, 10), 1030) checkValue(part2(testInput, 100), 8410) println(part2(input)) } data class Galaxy(var row: Int, var col: Int) fun <T> List<T>.allPairs(): List<Pair<T, T>> { val pairs = mutableListOf<Pair<T, T>>() for (i in 0..<this.size - 1) { for (j in i + 1..<this.size) { pairs.add(Pair(this[i], this[j])) } } return pairs }
1
Kotlin
2
30
df1f04b90e81fbb9078a30f528d52295689f7de7
2,064
aoc-kotlin
Apache License 2.0
src/Day02.kt
filipradon
573,512,032
false
{"Kotlin": 6146}
import Result.Companion.toRightResult import Shape.Companion.toLeftShape import Shape.Companion.toRightShape sealed interface Shape { companion object { fun Char.toLeftShape(): Shape { return when (this) { 'A' -> Rock 'B' -> Paper 'C' -> Scissors else -> throw IllegalArgumentException() } } fun Char.toRightShape(): Shape { return when (this) { 'X' -> Rock 'Y' -> Paper 'Z' -> Scissors else -> throw IllegalArgumentException() } } } } object Rock : Shape object Paper : Shape object Scissors : Shape sealed interface Result { companion object { fun Char.toRightResult(): Result { return when (this) { 'X' -> Lose 'Y' -> Draw 'Z' -> Win else -> throw IllegalArgumentException() } } } } object Lose : Result object Draw : Result object Win : Result fun result(left: Shape, right: Shape): Int { return when (right) { is Rock -> when (left) { is Paper -> 1 + 0 is Rock -> 1 + 3 is Scissors -> 1 + 6 } is Paper -> when (left) { is Paper -> 2 + 3 is Rock -> 2 + 6 is Scissors -> 2 + 0 } is Scissors -> when (left) { is Paper -> 3 + 6 is Rock -> 3 + 0 is Scissors -> 3 + 3 } } } fun result(left: Shape, right: Result): Int { return when (right) { Lose -> when (left) { Paper -> 1 + 0 Rock -> 3 + 0 Scissors -> 2 + 0 } Draw -> when (left) { Paper -> 2 + 3 Rock -> 1 + 3 Scissors -> 3 + 3 } Win -> when (left) { Paper -> 3 + 6 Rock -> 2 + 6 Scissors -> 1 + 6 } } } fun calculateRockPaperScissorsResult(input: List<String>): Int { return input .map { it.trim() } .sumOf { result(it[0].toLeftShape(), it[2].toRightShape()) } } fun calculateRockPaperScissorsResult2(input: List<String>): Int { return input .map { it.trim() } .sumOf { result(it[0].toLeftShape(), it[2].toRightResult()) } } fun main() { fun part1(input: List<String>): Int { return calculateRockPaperScissorsResult(input) } fun part2(input: List<String>): Int { return calculateRockPaperScissorsResult2(input) } val input = readInputAsList("input-day2") println(part1(input)) println(part2(input)) // test if implementation meets criteria from the description, like: // val testInput = readInputAsString("input-day1") // check(part1(testInput) == 1) }
0
Kotlin
0
0
dbac44fe421e29ab2ce0703e5827e4645b38548e
2,877
advent-of-code-kotlin-2022
Apache License 2.0
src/main/kotlin/io/github/clechasseur/adventofcode2021/Day8.kt
clechasseur
435,726,930
false
{"Kotlin": 315943}
package io.github.clechasseur.adventofcode2021 import io.github.clechasseur.adventofcode2021.data.Day8Data import io.github.clechasseur.adventofcode2021.util.permutations object Day8 { private val data = Day8Data.data private val lineInfos = data.lines().map { it.toLineInfo() } fun part1(): Int = lineInfos.flatMap { it.outputValues }.count { it.length in listOf(2, 3, 4, 7) } fun part2(): Int = lineInfos.map { lineInfo -> crossedWiresPermutations.asSequence().mapNotNull { wiresCrossing -> lineInfo.toDigitsLine(wiresCrossing) }.single() }.sumOf { it.display } private data class LineInfo(val signalPatterns: List<String>, val outputValues: List<String>) private fun String.toLineInfo(): LineInfo { val (patternsPart, outputPart) = split('|') return LineInfo( patternsPart.trim().split("\\s+".toRegex()), outputPart.trim().split("\\s+".toRegex()) ) } private val digits = mapOf( "abcefg" to 0, "cf" to 1, "acdeg" to 2, "acdfg" to 3, "bcdf" to 4, "abdfg" to 5, "abdefg" to 6, "acf" to 7, "abcdefg" to 8, "abcdfg" to 9, ) private val wiresPermutations = permutations("abcdefg".toList()) private val crossedWiresPermutations = wiresPermutations.map { crossed -> crossed.zip("abcdefg".toList()).toMap() } private data class DigitsLine(val signalPatterns: List<Int>, val outputValues: List<Int>) { val display: Int get() = outputValues.joinToString("") { it.toString() }.toInt() } private fun LineInfo.toDigitsLine(wiresCrossing: Map<Char, Char>): DigitsLine? { val digitsSignalPatterns = signalPatterns.map { pattern -> digits[pattern.toList().map { wiresCrossing[it]!! }.sorted().joinToString("")] ?: return null } val digitsOutputValues = outputValues.map { value -> digits[value.toList().map { wiresCrossing[it]!! }.sorted().joinToString("")] ?: return null } return DigitsLine(digitsSignalPatterns, digitsOutputValues) } }
0
Kotlin
0
0
4b893c001efec7d11a326888a9a98ec03241d331
2,154
adventofcode2021
MIT License
2022/src/main/kotlin/de/skyrising/aoc2022/day16/solution.kt
skyrising
317,830,992
false
{"Kotlin": 411565}
package de.skyrising.aoc2022.day16 import de.skyrising.aoc.* import it.unimi.dsi.fastutil.objects.Object2IntMap import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap private fun parseInput(input: PuzzleInput): Triple<Object2IntMap<String>, Object2IntMap<Pair<String, String>>, Set<String>> { val graph = Graph<String, Nothing>() val flows = Object2IntOpenHashMap<String>() for (line in input.lines) { val (_, name, rate, next) = Regex("Valve (..) has flow rate=(\\d+); tunnels? leads? to valves? (.*)").matchEntire(line)!!.groupValues flows[name] = rate.toInt() for (nextName in next.split(", ")) { graph.edge(name, nextName, 1) } } val paths = Object2IntOpenHashMap<Pair<String, String>>() for ((a, b) in graph.getVertexes().toList().pairs()) { paths[a to b] = (graph.dijkstra(a, b)?:continue).size } val closed = graph.getVertexes().filter { flows.getInt(it) != 0 }.toSet() return Triple(flows, paths, closed) } private fun findBestValve(paths: Object2IntMap<Pair<String, String>>, flows: Object2IntMap<String>, currentPos: String, currentTime: Int, closed: Set<String>, totalTime: Int): Int { return closed.maxOfOrNull { val timeThere = currentTime + paths.getInt(currentPos to it) + 1 if (timeThere >= totalTime) { 0 } else { val flow = (totalTime - timeThere) * flows.getInt(it) flow + findBestValve(paths, flows, it, timeThere, closed - it, totalTime) } } ?: 0 } val test = TestInput(""" Valve AA has flow rate=0; tunnels lead to valves DD, II, BB Valve BB has flow rate=13; tunnels lead to valves CC, AA Valve CC has flow rate=2; tunnels lead to valves DD, BB Valve DD has flow rate=20; tunnels lead to valves CC, AA, EE Valve EE has flow rate=3; tunnels lead to valves FF, DD Valve FF has flow rate=0; tunnels lead to valves EE, GG Valve GG has flow rate=0; tunnels lead to valves FF, HH Valve HH has flow rate=22; tunnel leads to valve GG Valve II has flow rate=0; tunnels lead to valves AA, JJ Valve JJ has flow rate=21; tunnel leads to valve II """) @PuzzleName("Probosciedea Volcanium") fun PuzzleInput.part1(): Any { val (flows, paths, closed) = parseInput(this) return findBestValve(paths, flows, "AA", 0, closed, 30) } fun PuzzleInput.part2(): Any { val (flows, paths, closed) = parseInput(this) return closed.subsets().maxOf { subset -> val myResult = findBestValve(paths, flows, "AA", 0, subset, 26) val elephantResult = findBestValve(paths, flows, "AA", 0, closed - subset, 26) myResult + elephantResult } }
0
Kotlin
0
0
19599c1204f6994226d31bce27d8f01440322f39
2,685
aoc
MIT License
src/Day10.kt
Xacalet
576,909,107
false
{"Kotlin": 18486}
/** * ADVENT OF CODE 2022 (https://adventofcode.com/2022/) * * Solution to day 10 (https://adventofcode.com/2022/day/10) * */ fun main() { fun part1(instructions: Sequence<Int>): Int { return instructions .runningFold(1) { acc, x -> acc + x } .withIndex() .filter { (index, _) -> index in listOf(19, 59, 99, 139, 179, 219) } .sumOf { (index, x) -> (index + 1) * x } } fun part2(instructions: Sequence<Int>): String { return instructions .runningFold(1) { acc, x -> acc + x } .withIndex() .map { (index, x) -> if (index.mod(40) in ((x - 1)..(x + 1))) "#" else "." } .chunked(40) .map { row -> row.joinToString("") }.joinToString("\n") } val instructions = buildList { readInputLines("day10_dataset").map { line -> add(0) "addx (-?\\d+)".toRegex().find(line)?.destructured?.let { (x) -> add(x.toInt()) } } }.dropLast(1).asSequence() part1(instructions).println() part2(instructions).println() }
0
Kotlin
0
0
5c9cb4650335e1852402c9cd1bf6f2ba96e197b2
1,100
advent-of-code-2022
Apache License 2.0
src/main/kotlin/Day21.kt
Avataw
572,709,044
false
{"Kotlin": 99761}
package aoc fun solve21A(input: List<String>): Long { val monkeys = input.parse() val root = monkeys.first { it.name == "root" } monkeys.solveRiddle(root) return root.value!! } fun solve21B(input: List<String>): Long { val monkeys = input.parse() val root = monkeys.first { it.name == "root" } monkeys.solveRiddle(root) val firstValue = monkeys.getValue(root.operation!!.firstMonkeyName)!! val secondValue = monkeys.getValue(root.operation!!.secondMonkeyName)!! val firstOperation = monkeys.getFullOperation(root.operation!!.firstMonkeyName) val secondOperation = monkeys.getFullOperation(root.operation!!.secondMonkeyName) return if (firstOperation.length > secondOperation.length) solveEquation(firstOperation, secondValue) else solveEquation(secondOperation, firstValue) } fun List<Monkey>.solveRiddle(root: Monkey) { while (root.value == null) { val unsolvedMonkeys = this.filter { it.value == null && it.operation != null } for (monkey in unsolvedMonkeys) { val firstValue = this.first { it.name == monkey.operation!!.firstMonkeyName }.value val secondValue = this.first { it.name == monkey.operation!!.secondMonkeyName }.value if (firstValue == null || secondValue == null) continue monkey.value = calc(firstValue, secondValue, monkey.operation!!.operator) } } } fun solveEquation(operation: String, target: Long): Long { if (operation == "X") return target val removedSurrounding = operation.drop(1).dropLast(1) if (!removedSurrounding.contains('(') && !removedSurrounding.contains(')')) { return if (removedSurrounding[0] == 'X') tryCalc(removedSurrounding, target, reversed = true) else tryCalc(removedSurrounding, target) } val preOperation = removedSurrounding.takeWhile { it != '(' } val postOperation = removedSurrounding.takeLastWhile { it != ')' } return if (preOperation.isNotEmpty()) { val newTarget = tryCalc(preOperation, target) solveEquation(removedSurrounding.drop(preOperation.length), newTarget) } else { val newTarget = tryCalc(postOperation, target, reversed = true) solveEquation(removedSurrounding.dropLast(postOperation.length), newTarget) } } fun String.extractValue(operation: String, reversed: Boolean): Long { val split = this.split(operation) return (if (reversed) split.last() else split.first()).toLong() } fun tryCalc(input: String, target: Long, reversed: Boolean = false) = when { input.contains("+") -> calc(target, input.extractValue(" + ", reversed), '-') input.contains("/") -> calc(target, input.extractValue(" / ", reversed), '*') input.contains("*") -> calc(target, input.extractValue(" * ", reversed), '/') input.contains("-") -> { val value = input.extractValue(" - ", reversed) if (reversed) calc(target, value, '+') else calc(value, target, '-') } else -> throw Exception("Input $input could not be parsed") } fun List<Monkey>.getValue(name: String) = this.first { it.name == name }.value fun List<Monkey>.getFullOperation(name: String): String { val monkey = this.first { it.name == name } val operation = monkey.operation if (monkey.name == "humn") return "X" if (operation == null) return monkey.value.toString() val left = this.getFullOperation(operation.firstMonkeyName) val right = this.getFullOperation(operation.secondMonkeyName) return if (!left.contains("X") && !right.contains("X")) monkey.value.toString() else "(" + left + " " + operation.operator + " " + right + ")" } fun calc(a: Long, b: Long, operator: Char) = when (operator) { '+' -> a + b '-' -> a - b '*' -> a * b '/' -> a / b else -> throw Exception("Operator $operator does not compute.") } fun List<String>.parse(): List<Monkey> = this.map { val split = it.split(": ") val name = split.first() val value = split.last().toLongOrNull() if (value == null) { val firstName = split.last().take(4) val secondName = split.last().takeLast(4) val operation = split.last()[5] Monkey(name, operation = Operation(firstName, secondName, operation)) } else { Monkey(name, value) } } data class Monkey(val name: String, var value: Long? = null, var operation: Operation? = null) data class Operation(val firstMonkeyName: String, val secondMonkeyName: String, var operator: Char)
0
Kotlin
2
0
769c4bf06ee5b9ad3220e92067d617f07519d2b7
4,504
advent-of-code-2022
Apache License 2.0
src/main/kotlin/kr/co/programmers/P77485.kt
antop-dev
229,558,170
false
{"Kotlin": 695315, "Java": 213000}
package kr.co.programmers // https://github.com/antop-dev/algorithm/issues/253 class P77485 { fun solution(rows: Int, columns: Int, queries: Array<IntArray>): IntArray { // 숫자 채우기 var n = 1 val box = Array(rows + 1) { Array(columns + 1) { 0 } } for (i in 1 until box.size) { for (j in 1 until box[i].size) { box[i][j] = n++ } } // 회전 return IntArray(queries.size) { i -> rotate(box, queries[i]) } } private fun rotate(box: Array<Array<Int>>, q: IntArray): Int { var min = Int.MAX_VALUE val tmp = box[q[0] + 1][q[1]] for (i in q[0] + 1..q[2]) { box[i][q[1]] = if (i < q[2]) box[i + 1][q[1]] else box[i][q[1] + 1] min = minOf(min, box[i][q[1]]) } for (j in q[1] + 1..q[3]) { box[q[2]][j] = if (j < q[3]) box[q[2]][j + 1] else box[q[2] - 1][j] min = minOf(min, box[q[2]][j]) } for (i in q[2] - 1 downTo q[0]) { box[i][q[3]] = if (i > q[0]) box[i - 1][q[3]] else box[i][q[3] - 1] min = minOf(min, box[i][q[3]]) } for (j in q[3] - 1 downTo q[1]) { box[q[0]][j] = if (j > q[1]) box[q[0]][j - 1] else tmp min = minOf(min, box[q[0]][j]) } return min } }
1
Kotlin
0
0
9a3e762af93b078a2abd0d97543123a06e327164
1,360
algorithm
MIT License
aoc2022/day18.kt
davidfpc
726,214,677
false
{"Kotlin": 127212}
package aoc2022 import utils.InputRetrieval fun main() { Day18.execute() } object Day18 { fun execute() { val input = readInput() println("Part 1: ${part1(input)}") // println("Part 2: ${part2(input)}") } private fun part1(input: List<Cube>): Int = input.sumOf { it.countSidesNotInContactWithOtherCubes(input) } private fun part2(input: List<Cube>): Int { val context = Context(input) return input.sumOf { context.validating.clear() it.countSidesInContactWithWater(context) } } fun readInput(): List<Cube> = InputRetrieval.getFile(2022, 18).readLines().map { pos -> val (x, y, z) = pos.split(",").map { it.toInt() } Cube(x, y, z) } class Context(val input: List<Cube>) { val minX = input.minOf { it.x } val maxX = input.maxOf { it.x } val minY = input.minOf { it.y } val maxY = input.maxOf { it.y } val minZ = input.minOf { it.z } val maxZ = input.maxOf { it.z } val validating: MutableSet<Cube> = mutableSetOf() } data class Cube(val x: Int, val y: Int, val z: Int) { private fun getNeighbours(): Set<Cube> = setOf( Cube(x - 1, y, z), // LEFT Cube(x + 1, y, z), // RIGHT Cube(x, y, z + 1), // UP Cube(x, y, z - 1), // DOWN Cube(x, y - 1, z), // BACK Cube(x, y + 1, z), // FRONT ) fun countSidesNotInContactWithOtherCubes(input: List<Cube>): Int = getNeighbours().count { !input.contains(it) } fun countSidesInContactWithWater(context: Context): Int { return getNeighbours().count { !context.input.contains(it) && !it.isInPocket(context) } } private fun isInPocket(context: Context): Boolean { context.validating.add(this) if (context.input.contains(this)) { return true } if (x < context.minX || x > context.maxX || y < context.minY || y > context.maxY || z < context.minZ || z > context.maxZ) { // outside of borders return false } // Let's check the neighbours to check if we are inside a pocket return getNeighbours().filter { !context.validating.contains(it) }.all { it.isInPocket(context) } } } }
0
Kotlin
0
0
8dacf809ab3f6d06ed73117fde96c81b6d81464b
2,380
Advent-Of-Code
MIT License
src/Day08.kt
oleksandrbalan
572,863,834
false
{"Kotlin": 27338}
fun main() { val input = readInput("Day08") .filterNot { it.isEmpty() } val rows = input.size val columns = input.first().length val matrix = IntMatrix(rows, columns) { row, column -> input[row][column].digitToInt() } // Matrix with 0 and 1, where 1 represents that the tree is visible val visibilityMatrix = IntMatrix(rows, columns) // Fill the new matrix with 4 double cycles, one for each side // The complexity then should be 4*n*m ~ O(n*m), // where n is count of rows and m is a count of columns computeVisibility(matrix, visibilityMatrix, Traverse.LeftToRight(rows, columns)) computeVisibility(matrix, visibilityMatrix, Traverse.RightToLeft(rows, columns)) computeVisibility(matrix, visibilityMatrix, Traverse.TopToBottom(rows, columns)) computeVisibility(matrix, visibilityMatrix, Traverse.BottomToTop(rows, columns)) val part1 = visibilityMatrix.asSequence().count { it > 0 } println("Part1: $part1") // Matrix with scenic score of the tree val scenicScoreMatrix = IntMatrix(rows, columns) { _, _ -> 1 } // Fill the new matrix with 4 double cycles, one for each side // The complexity then should be 4*n*m*h ~ O(n*m), // where n is count of rows and m is a count of columns, and h (constant = 9) is a max height // of the tree computeHeights(matrix, scenicScoreMatrix, Traverse.LeftToRight(rows, columns)) computeHeights(matrix, scenicScoreMatrix, Traverse.RightToLeft(rows, columns)) computeHeights(matrix, scenicScoreMatrix, Traverse.TopToBottom(rows, columns)) computeHeights(matrix, scenicScoreMatrix, Traverse.BottomToTop(rows, columns)) val part2 = scenicScoreMatrix.asSequence().max() println("Part2: $part2") } private fun computeVisibility( from: IntMatrix, to: IntMatrix, traverse: Traverse, ) { repeat(traverse.outer) { i -> var max = -1 repeat(traverse.inner) { j -> val (pi, pj) = traverse.projection(i, j) val value = from.get(pi, pj) if (value > max) { max = value to.set(pi, pj, 1) } } } } private fun computeHeights( from: IntMatrix, to: IntMatrix, traverse: Traverse, ) { repeat(traverse.outer) { i -> val heightMap = Array(10) { -1 } repeat(traverse.inner) { j -> val (pi, pj) = traverse.projection(i, j) val value = from.get(pi, pj) val distance = heightMap[value].let { if (it >= 0) j - it else j } heightMap.fill(value, j) to.set(pi, pj, to.get(pi, pj) * distance) } } } private fun Array<Int>.fill(to: Int, value: Int) { repeat(to + 1) { set(it, value) } } private sealed class Traverse( val outer: Int, val inner: Int, val projection: (Int, Int) -> Pair<Int, Int>, ) { class LeftToRight(rows: Int, columns: Int) : Traverse( outer = rows, inner = columns, projection = { i, j -> i to j } ) class RightToLeft(rows: Int, columns: Int) : Traverse( outer = rows, inner = columns, projection = { i, j -> i to columns - j - 1 } ) class TopToBottom(rows: Int, columns: Int) : Traverse( outer = columns, inner = rows, projection = { i, j -> j to i } ) class BottomToTop(rows: Int, columns: Int) : Traverse( outer = columns, inner = rows, projection = { i, j -> columns - j - 1 to i } ) }
0
Kotlin
0
2
1493b9752ea4e3db8164edc2dc899f73146eeb50
3,538
advent-of-code-2022
Apache License 2.0
games-impl/src/commonMain/kotlin/net/zomis/games/common/cards/probabilities/CardAnalyze2.kt
Zomis
125,767,793
false
{"Kotlin": 1346310, "Vue": 212095, "JavaScript": 43020, "CSS": 4513, "HTML": 1459, "Shell": 801, "Dockerfile": 348}
package net.zomis.games.cards.probabilities import net.zomis.games.cards.CardZone import kotlin.math.floor import kotlin.math.min typealias CardPredicate<T> = (T) -> Boolean class ZoneRuleDef<T>(val name: Int, val zone: CardZone<T>, val size: Int, val predicate: CardPredicate<T>) { override fun toString(): String { return "Rule#$name($zone:$size)" } } data class CardGroup2<T>(val cards: Set<T>, val placementsLeft: Int) data class ZoneRule2<T>(val zone: CardZone<T>, val size: Int, val groups: Set<CardGroup2<T>>) { fun order(): Int { return size * groups.size // Very simple ordering, actual order should be using int partitioning perhaps } fun isEmpty(): Boolean { return this.groups.isEmpty() && this.size == 0 } } data class ZoneGroupAssignment<T>(val zone: CardZone<T>, val group: CardGroup2<T>, val count: Int) { override fun toString(): String { return "$zone $count of $group" } } class CardAnalyzeSolution<T>(val assignments: List<ZoneGroupAssignment<T>>) { fun getCombinationsOf(zone: CardZone<T>, predicate: (T) -> Boolean): DoubleArray { // Compare with how the old approach is working val zoneAssigns = assignments.filter { it.zone == zone && it.count > 0 } if (zoneAssigns.isEmpty()) throw IllegalStateException("Nothing assigned to zone $zone") val groups: List<CardGroup2<T>> = zoneAssigns.map { it.group }.distinct() var count = 0 val groupsCount = groups.size val values = IntArray(groupsCount) val loopMaxs = IntArray(groupsCount) val predicateCounts = IntArray(groupsCount) for (i in groups.indices) { val group = groups[i] val value = zoneAssigns.single { it.group == group }.count val cardsMatchingPredicate = group.cards.count(predicate) values[i] = value loopMaxs[i] = min(value, cardsMatchingPredicate) predicateCounts[i] = cardsMatchingPredicate count += cardsMatchingPredicate } val result = DoubleArray(min(count, zone.size) + 1) // println("Creating array with length " + result.size) // Zone{Player1 Hand} --> Assign:Zone{Player1 Hand}={CG:[4 CLUBS + 9 others]=0, CG:[9 CLUBS + 30 others]=13} // Zone{Player1 Hand} --> Assign:Zone{Player1 Hand}={CG:[2 CLUBS + 7 others]=2, CG:[2 CLUBS + 7 others]=4, CG:[9 CLUBS + 30 others]=7} // Zone{Player0 __Y__} --> Assign:Zone{Player0 __Y__}={CG:[Card:a, Card:a]=0, CG:[Card:d, Card:d]=1, CG:[Card:b, Card:c]=0, CG:[Card:b, Card:c]=1} // List<Map<CardGroup<C>, Integer>> mapList = new ArrayList<>(); val loop = IntArray(groups.size) val lastIndex = loop.size - 1 while (loop[0] <= loopMaxs[0]) { // print(loop.contentToString() + " = ") var loopSum = 0 var combinations = 1.0 for (i in 0 until groupsCount) { loopSum += loop[i] val group = groups[i] combinations *= Combinatorics.NNKKwithDiv(group.cards.size, predicateCounts[i], values[i], loop[i]) } result[loopSum] += combinations // Increase the count loop[lastIndex]++ var overflow = lastIndex while (overflow >= 1 && loop[overflow] > loopMaxs[overflow]) { loop[overflow] = 0 loop[overflow - 1]++ overflow-- } } // a + a + a + b + b = 2, a + a + c + c = 1 for (i in result.indices) { result[i] = result[i] * combinations } // println("Result = " + result.contentToString()) // println("Sum = " + result.sum()) // ProgressAnalyze(zones, groups, rules, assignments) return result } fun getSpecificCombination(solution: Double): Map<CardZone<T>, List<T>> { // 8 zone assignments, each with a+a+a+a+a+a+a+a = 1 var remainingCombinations = solution val result = mutableMapOf<CardZone<T>, List<T>>() val groups = this.assignments.map { it.group }.distinct() if (groups.size != 1) { throw UnsupportedOperationException("getting specific combination only supports one unique group at the moment") } val remainingCards = groups.single().cards.toMutableList() for (assignment in assignments) { val thisAssignmentTotalCombinations = Combinatorics.nCr(assignment.group.cards.size, assignment.count) val thisAssignmentCombination = remainingCombinations % thisAssignmentTotalCombinations remainingCombinations = floor(remainingCombinations / thisAssignmentTotalCombinations) val originalCards = assignment.group.cards.toList() val cards = Combinatorics.specificCombination(assignment.group.cards.size, assignment.count, thisAssignmentCombination + 1).map { originalCards[it] } // groups.getValue(assignment.group).removeAll(cards) result[assignment.zone] = cards } return result // a+a+a+a=2, b+b+b=2 ---> 6 * 3 --> divide by 6 for the first, then mod by 6 } val combinations = assignments.groupBy { it.group.cards }.entries.fold(1.0) { acc, nextGroup -> val groupSize = nextGroup.key.size var positioned = 0 var groupCombinations = 1.0 for (assignment in nextGroup.value) { if (assignment.count == 0) { continue } val n = groupSize - positioned val r = assignment.count groupCombinations *= Combinatorics.nCr(n, r) positioned += r } acc * groupCombinations } } class CardAnalyzeSolutions<T>(val solutions: List<CardAnalyzeSolution<T>>) { val totalCombinations = solutions.sumByDouble { it.combinations } fun getProbabilityDistributionOf(zone: CardZone<T>, predicate: (T) -> Boolean): DoubleArray { val dbl = DoubleArray(zone.size + 1) for (sol in solutions) { val result = sol.getCombinationsOf(zone, predicate) result.indices.forEach { dbl[it] += result[it] } } for (i in dbl.indices) { dbl[i] = dbl[i] / totalCombinations } return dbl } fun getSpecificCombination(solution: Double): Map<CardZone<T>, List<T>> { require(solution >= 0 && solution < totalCombinations) { "solution must be an integer between 0 and total ($totalCombinations)" } check(solutions.isNotEmpty()) { "There are no solutions." } val iterator = solutions.iterator() var theSolution = iterator.next() var solutionsRemaining = solution while (solutionsRemaining > theSolution.combinations) { solutionsRemaining -= theSolution.combinations theSolution = iterator.next() } return theSolution.getSpecificCombination(solutionsRemaining) } } class CardAssignments<T>(val groups: Collection<CardGroup2<T>>, val assignments: List<ZoneGroupAssignment<T>>) { fun assign(vararg newAssignments: ZoneGroupAssignment<T>): CardAssignments<T> { val newAssignmentsPerGroup = newAssignments.groupBy {it.group} .mapValues { it.value.sumBy { assignment -> assignment.count } } val newGroups = groups.map { CardGroup2(it.cards, it.placementsLeft - (newAssignmentsPerGroup[it] ?: 0)) } return CardAssignments(newGroups, assignments + newAssignments.toList()) } constructor(groups: Collection<CardGroup2<T>>): this(groups, emptyList()) // remainingZones is taken care of by the regular ZoneRules } class CardsAnalyze2<T> { val zones = mutableListOf<CardZone<T>>() private val cards = mutableListOf<T>() private val rules = mutableListOf<ZoneRuleDef<T>>() fun addZone(zone: CardZone<T>) { zones.add(zone) } fun addCards(list: List<T>) { cards.addAll(list) } fun addRule(zone: CardZone<T>, size: Int, predicate: CardPredicate<T>) { rules.add(ZoneRuleDef(rules.size, zone, size, predicate)) } fun addRule(zone: CardZone<T>, countStyle: CountStyle, size: Int, predicate: CardPredicate<T>) { TODO("countStyle not supported yet") } fun createCardGroups(): Map<Set<ZoneRuleDef<T>>, CardGroup2<T>> { return cards.groupBy { card -> rules.filter { it.predicate(card) }.toSet() }.mapValues { CardGroup2(it.value.toSet(), it.value.size) } } fun createRules(cardGroups: Map<Set<ZoneRuleDef<T>>, CardGroup2<T>>, groups: Set<CardGroup2<T>>): List<ZoneRule2<T>> { // Create rules for the known rules with card groups val ruleRules = rules.map { rule -> val cardGroupsInRule = cardGroups.entries.filter { entry -> entry.key.contains(rule) }.map { it.value }.toSet() ZoneRule2(rule.zone, rule.size, cardGroupsInRule) } // Create rules for zones to have their appropriate size val zoneRules = zones.map { ZoneRule2(it, it.size, groups) } return ruleRules.plus(zoneRules).sortedBy { it.order() } } fun rules(): List<ZoneRule2<T>> { val cardGroups = createCardGroups() val groups = cardGroups.values.toSet() return createRules(cardGroups, groups) } fun solve(): Sequence<CardAnalyzeSolution<T>> { /* * A B C D E * A B * A C */ val cardGroups = createCardGroups() val groups = cardGroups.values.toSet() val rules = createRules(cardGroups, groups) val assignments = CardAssignments(groups) // Order rules by combinations possible, ascending return sequence { yieldAll(ProgressAnalyze(zones.toSet(), groups, rules, assignments).solve()) } } } class ProgressAnalyze<T>( private val zones: Set<CardZone<T>>, private val groups: Set<CardGroup2<T>>, private val rules: List<ZoneRule2<T>>, private val assignments: CardAssignments<T> ) { fun findAutoAssignments(groups: Set<CardGroup2<T>>, rules: List<ZoneRule2<T>>): CardAssignments<T>? { var newAssignments = CardAssignments(groups) rules.forEach { rule -> // See also https://github.com/Zomis/Minesweeper-Analyze/blob/master/src/main/java/net/zomis/minesweeper/analyze/BoundedFieldRule.java#L64 if (rule.size > rule.groups.sumBy { it.cards.size }) { return null } if (rule.size < 0) { return null } if (rule.groups.isEmpty() && rule.size != 0) { return null } if (rule.size == 0) { newAssignments = newAssignments.assign(*rule.groups.map { group -> ZoneGroupAssignment(rule.zone, group, 0) }.toTypedArray()) } if (rule.groups.size == 1) { newAssignments = newAssignments.assign(ZoneGroupAssignment(rule.zone, rule.groups.single(), rule.size)) } } return newAssignments } fun simplify(rules: List<ZoneRule2<T>>, assignments: CardAssignments<T>): List<ZoneRule2<T>> { if (assignments.assignments.isEmpty()) { return rules } val uniqueAssignments = assignments.assignments.distinct() val groupAssignments = uniqueAssignments.groupBy { it.group } .mapValues { entry -> entry.value.sumBy { it.count } } return rules.mapNotNull { rule -> val zoneAssignments = uniqueAssignments.filter { it.zone == rule.zone } val zoneAssignmentSum = zoneAssignments.filter { rule.groups.contains(it.group) }.sumBy { it.count } val zoneGroupsAssigned = zoneAssignments.map { it.group } val simplifiedRule = ZoneRule2(rule.zone, rule.size - zoneAssignmentSum, rule.groups.minus(zoneGroupsAssigned).map { val placementsDone = groupAssignments[it] ?: 0 CardGroup2(it.cards, it.placementsLeft - placementsDone) }.toSet()) if (simplifiedRule.isEmpty()) null else simplifiedRule } } fun solve(): Sequence<CardAnalyzeSolution<T>> { var fullAssignments: List<ZoneGroupAssignment<T>> = assignments.assignments.toList() var autoAssignments: CardAssignments<T> = assignments var simplifiedRules: List<ZoneRule2<T>> = rules var simplificationDone: Boolean do { autoAssignments = this.findAutoAssignments(autoAssignments.groups.toSet(), simplifiedRules) ?: return emptySequence() simplifiedRules = this.simplify(simplifiedRules, autoAssignments) fullAssignments = fullAssignments + autoAssignments.assignments simplificationDone = autoAssignments.assignments.isNotEmpty() } while (simplificationDone) /* println("# Zones") zones.forEach { println(it) } println("# Groups") groups.forEach { println(it) } println("# Rules") rules.forEach { println(it) } println("# Auto Assign") fullAssignments.forEach { println(it) } autoAssignments.groups.forEach { println(it) } println("# Simplified Rules") simplifiedRules.forEach { println(it) } */ if (simplifiedRules.isEmpty()) { return sequenceOf(CardAnalyzeSolution(fullAssignments.distinct())) } if (simplifiedRules.size == 1) { val singleRule = simplifiedRules.single() val totalPlacementsLeft = singleRule.groups.sumBy { it.placementsLeft } if (singleRule.size != totalPlacementsLeft) { throw IllegalStateException("Sanity check failed: Rule wants ${singleRule.size} but $totalPlacementsLeft needs to be placed") } val remainingAssignments = singleRule.groups.map { ZoneGroupAssignment(singleRule.zone, it, it.placementsLeft) } // val combinedGroup = CardGroup2(singleRule.groups.flatMap { it.cards }.toSet(), singleRule.groups.sumBy { it.placementsLeft }) // val remainingAssignment = ZoneGroupAssignment(singleRule.zone, combinedGroup, singleRule.size) // val solution = CardAnalyzeSolution(fullAssignments + remainingAssignment) val finalAssignments = fullAssignments + remainingAssignments val solution = CardAnalyzeSolution(finalAssignments.distinct()) return sequenceOf(solution) } val rule = simplifiedRules.first() if (rule.size < 0) { // No solution return emptySequence() } val smallestGroup = rule.groups.minByOrNull { it.placementsLeft }!! val maxAssignment = min(rule.size, smallestGroup.placementsLeft) return sequence { for (assignmentValue in 0..maxAssignment) { val assignments2 = findAutoAssignments(autoAssignments.groups.toSet(), simplifiedRules + ZoneRule2(rule.zone, assignmentValue, setOf(smallestGroup))) if (assignments2 == null) { continue } val rules2 = simplify(simplifiedRules, assignments2) val assignmentList = fullAssignments + assignments2.assignments val next = ProgressAnalyze(zones, autoAssignments.groups.toSet(), rules2, CardAssignments(autoAssignments.groups, assignmentList)) val solve = next.solve() yieldAll(solve) } } // Find smallest possibilities in zone // or find smallest number of zones that a card group can be in // val groupsCanBeIn = Map<Group, Set<Zone>> // val zonesCanHave = Map<Zone, Set<Group>> // Find rule with lowest size, and then by lowest number of possible groups } }
89
Kotlin
5
17
dd9f0e6c87f6e1b59b31c1bc609323dbca7b5df0
16,021
Games
MIT License
src/main/kotlin/com/jacobhyphenated/advent2023/day6/Day6.kt
jacobhyphenated
725,928,124
false
{"Kotlin": 121644}
package com.jacobhyphenated.advent2023.day6 import com.jacobhyphenated.advent2023.Day import com.jacobhyphenated.advent2023.product /** * Day 6: Wait For It * * You are participating in a boat race. The boats are charged by pressing a button for a length of time. * The longer the button is pressed, the faster the boat travels, but the boat doesn't move while pressed. */ class Day6: Day<List<Pair<Long,Long>>> { override fun getInput(): List<Pair<Long, Long>> { return parseInput(readInputFile("6")) } /** * Part 1: The puzzle has a set of numbers that represent the total time of the race, and the record distance. * There are several races represented. * Find how many solutions exist for beating the record time, and multiply those numbers for each race. */ override fun part1(input: List<Pair<Long, Long>>): Long { return input.map { race -> val (time, distanceRecord) = race findWinningTimes(time, distanceRecord) }.product() } /** * Part 2: The puzzle is not several races, only one race. Remove the spaces between numbers of the puzzle input */ override fun part2(input: List<Pair<Long, Long>>): Long { val (time, distanceRecord) = input.reduce { p1, p2 -> Pair("${p1.first}${p2.first}".toLong(), "${p1.second}${p2.second}".toLong()) } return findWinningTimes(time, distanceRecord) } /** * Distance is a normal distribution with the longest distance achieved by pressing the button for 1/2 the total time * If we find the number of solutions that exceed the distance record on one side of the distribution, * we can double that value for the total number of solutions. * * Note: A binary search is faster. But since this solution solves part 2 in 10ms, I didn't bother. */ private fun findWinningTimes(time: Long, distanceRecord: Long): Long { val half = time / 2 var current = half while (distanceFromTime(time, current) > distanceRecord) { current -- } val winningTimes = (half - current) * 2 // Even numbers have an exact middle point - remove the duplicate count return if (time % 2 == 0L) { winningTimes - 1 } else { winningTimes } } private fun distanceFromTime(totalTime: Long, timeHoldingButton: Long): Long { return timeHoldingButton * (totalTime - timeHoldingButton) } fun parseInput(input: String): List<Pair<Long, Long>> { val intLines = input.lines().map { line -> line.split(":")[1] .trim() .split("\\s+".toRegex()) .map { it.toLong() } } return (intLines[0].indices).map { Pair(intLines[0][it], intLines[1][it]) } } override fun warmup(input: List<Pair<Long, Long>>) { part2(input) } } fun main(@Suppress("UNUSED_PARAMETER") args: Array<String>) { Day6().run() }
0
Kotlin
0
0
90d8a95bf35cae5a88e8daf2cfc062a104fe08c1
2,798
advent2023
The Unlicense
src/Day05/Day05.kt
Nathan-Molby
572,771,729
false
{"Kotlin": 95872, "Python": 13537, "Java": 3671}
package Day05 import readInput import java.util.* fun applyMovesToTowers(towers: List<Stack<Char>>, moves: List<String>, smartCrane: Boolean) { for (move in moves) { val moveItems = move.split("move ", " from ", " to ").filter {!it.isEmpty()}.map { it.toInt() } val itemCountToMove = moveItems[0] val fromTower = moveItems[1] - 1 val toTower = moveItems[2] - 1 if (smartCrane) { var itemsToMove = mutableListOf<Char>() for (i in 1..itemCountToMove) { itemsToMove.add(towers[fromTower].pop()) } itemsToMove.reverse() for(item in itemsToMove) { towers[toTower].add(item) } } else { for (i in 1..itemCountToMove) { val itemToMove = towers[fromTower].pop() towers[toTower].add(itemToMove) } } } } fun getTowers(input: List<String>): List<Stack<Char>> { val numOfCols = input.last().split(" ").filter { !it.isBlank() }.count() val actualRows = input.dropLast(1) var resultList = (0..numOfCols - 1).map { Stack<Char>() } for (row in actualRows.reversed()) { for (col in 0..numOfCols - 1) { val stringIndex = colIndexToStringIndex(col) if (row.length >= stringIndex && row[stringIndex].isLetter()) { resultList[col].add(row[stringIndex]) } } } return resultList } fun getTopElementsFromTowers(towers: List<Stack<Char>>): String { return towers.map { it.peek() }.joinToString(separator = "") } fun colIndexToStringIndex(colIndex: Int): Int { return colIndex * 4 + 1 } fun main() { fun part1(input: List<String>): String { val splitIndex = input.indexOf("") val drawing = input.subList(0, splitIndex) val moves = input.subList(splitIndex + 1, input.size) val towers = getTowers(drawing) applyMovesToTowers(towers, moves, false) return getTopElementsFromTowers(towers) } fun part2(input: List<String>): String { val splitIndex = input.indexOf("") val drawing = input.subList(0, splitIndex) val moves = input.subList(splitIndex + 1, input.size) val towers = getTowers(drawing) applyMovesToTowers(towers, moves, true) return getTopElementsFromTowers(towers) } // test if implementation meets criteria from the description, like: val testInput = readInput("Day05","Day05_test") println(part1(testInput)) check(part1(testInput) == "CMZ") println(part2(testInput)) check(part2(testInput) == "MCD") val input = readInput("Day05","Day05") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
750bde9b51b425cda232d99d11ce3d6a9dd8f801
2,757
advent-of-code-2022
Apache License 2.0
src/main/kotlin/aoc23/day07.kt
asmundh
573,096,020
false
{"Kotlin": 56155}
package aoc23 import runTask import splitToPair import utils.InputReader import java.lang.IllegalArgumentException import java.lang.IllegalStateException fun day7part1(input: List<String>): Int { val cards = input.getCards().sorted() return cards.mapIndexed { idx, card -> card.bid * (idx + 1) }.sum() } fun day7part2(input: List<String>): Int { val cards = input.getCards(jokerBad = true).sorted() return cards.mapIndexed { idx, card -> card.bid * (idx + 1) }.sum() } fun List<String>.getCards(jokerBad: Boolean = false) = this.map { val (card, bid) = it.splitToPair(' ') Hand(card, bid.toInt(), jokerBad) } data class Hand( val cards: String, val bid: Int, val jokerBad: Boolean ) : Comparable<Hand> { override fun compareTo(other: Hand): Int { val otherCardType = other.cards.groupingBy { it }.eachCount().mapToHandType(jokerBad) val thisCardType = cards.groupingBy { it }.eachCount().mapToHandType(jokerBad) if (thisCardType != otherCardType) return thisCardType - otherCardType for (i in 0 until 5) { val thisCardScore = this.cards[i].mapToCardNumber(jokerBad) val otherCardScore = other.cards[i].mapToCardNumber(jokerBad) if (thisCardScore == otherCardScore && i == 4) return 0 if (thisCardScore != otherCardScore) return thisCardScore - otherCardScore } throw IllegalStateException("compareTo has not been implemented correctly.") } } fun Map<Char, Int>.mapToHandType(jokerBad: Boolean = false): Int { val amountOfJ = this['J'] ?: 0 if (amountOfJ == 0 || !jokerBad) return this.mapToScore() val enhancedHands: MutableList<Map<Char, Int>> = mutableListOf() val handWithoutJ = this.keys.filter { it != 'J' }.associateWith { this[it]!! } val scores = mutableListOf<Int>() for (i in 0 until handWithoutJ.size) { val newHand = handWithoutJ.toMutableMap() val cardToInc = newHand.keys.toList()[i] newHand[cardToInc] = newHand[cardToInc]?.plus(amountOfJ)!! enhancedHands.add(newHand) scores.add(newHand.mapToScore()) } return scores.maxOrNull() ?: 7 } fun Map<Char, Int>.mapToScore(): Int = when (this.map { it.value }.sortedDescending().joinToString("")) { "5" -> 7 "41" -> 6 "32" -> 5 "311" -> 4 "221" -> 3 "2111" -> 2 "11111" -> 1 else -> throw IllegalArgumentException("INPUT: $this. Should not happen.") } fun Char.mapToCardNumber(jokerBad: Boolean = false): Int = when (this) { 'A' -> 14 'K' -> 13 'Q' -> 12 'J' -> if (jokerBad) 1 else 11 'T' -> 10 else -> this.digitToInt() } fun main() { val input = InputReader.getInputAsList<String>(7) runTask("D7P1") { day7part1(input) } runTask("D7P2") { day7part2(input) } }
0
Kotlin
0
0
7d0803d9b1d6b92212ee4cecb7b824514f597d09
2,931
advent-of-code
Apache License 2.0
src/aoc2023/Day4.kt
RobertMaged
573,140,924
false
{"Kotlin": 225650}
package aoc2023 import utils.checkEquals import utils.readInput fun main(): Unit = with(Day4) { part1(testInput).checkEquals(13) part1(input) .checkEquals(21485) // .sendAnswer(part = 1, day = "4", year = 2023) part2(testInput).checkEquals(30) part2(input) .checkEquals(11024379) // .sendAnswer(part = 2, day = "4", year = 2023) } object Day4 { private val spaceRegex = "\\s+".toRegex() fun part1(input: List<String>): Int = input.sumOf { line -> val (winningNums, myNums) = line.substringAfter(":").split(" | ") .map { it.trim().split(spaceRegex) } return@sumOf myNums.filter { it in winningNums } .fold(0) { acc, _ -> if (acc == 0) 1 else acc * 2 }.toInt() } fun part2(input: List<String>): Int { val cardsCurrentInstances = IntArray(input.size) { 1 } val cardsInstancesLog = IntArray(input.size) { 1 } val cardWinningCachedProcess = Array<(() -> Unit)?>(input.size) { null } var cardPos = 0 while (cardPos <= input.lastIndex) { cardsCurrentInstances[cardPos] = cardsCurrentInstances[cardPos] - 1 if (cardWinningCachedProcess[cardPos] == null) { val (winningNums, myNums) = input[cardPos].substringAfter(":").split(" | ") .map { it.trim().split(spaceRegex) } val winCount = myNums.count { it in winningNums } cardWinningCachedProcess[cardPos] = { for (winingCopyCard in (cardPos + 1)..cardPos + winCount) { cardsCurrentInstances[winingCopyCard] = cardsCurrentInstances[winingCopyCard] + 1 cardsInstancesLog[winingCopyCard] = cardsInstancesLog[winingCopyCard] + 1 } } } cardWinningCachedProcess[cardPos]!!.invoke() if (cardsCurrentInstances[cardPos] < 1) cardPos++ } return cardsInstancesLog.sum() } val input get() = readInput("Day4", "aoc2023") val testInput get() = readInput("Day4_test", "aoc2023") }
0
Kotlin
0
0
e2e012d6760a37cb90d2435e8059789941e038a5
2,320
Kotlin-AOC-2023
Apache License 2.0
src/Day02.kt
simonbirt
574,137,905
false
{"Kotlin": 45762}
fun main() { val scores = mapOf("A" to 1, "B" to 2, "C" to 3, "X" to 1, "Y" to 2, "Z" to 3) fun choose(them:Int, req:Int):Int { return when (them) { 1 -> when (req) { 1 -> 3 2 -> 1 else -> 2} 2 -> when (req) { 1 -> 1 2 -> 2 else -> 3} 3 -> when (req) { 1 -> 2 2 -> 3 else -> 1} else -> 0 } } fun game(them:Int, me:Int):Int { return when (them) { 1 -> when (me) { 2 -> 6 3 -> 0 else -> 3} 2 -> when (me) { 3 -> 6 1 -> 0 else -> 3} 3 -> when (me) { 1 -> 6 2 -> 0 else -> 3} else -> 0 } } fun part1(input: List<String>): Int { var total = 0 input.forEach { val (elf, me) = it.split(" ").map { c -> scores[c] } total += game (elf!!, me!!) + me } return total } fun part2(input: List<String>): Int { var total = 0 input.forEach { val (elf, req) = it.split(" ").map { c -> scores[c] } val me = choose(elf!!, req!!) total += game (elf, me) + me } return total } val input = readInput("day2") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
962eccac0ab5fc11c86396fc5427e9a30c7cd5fd
1,237
advent-of-code-2022
Apache License 2.0
src/Day07.kt
mikrise2
573,939,318
false
{"Kotlin": 62406}
data class File(val name: String, val size: Int) class Directory(private val parent: Directory? = null) { private val files = mutableListOf<File>() var amountSize = 0 private set fun addFile(file: File) { files.add(file) increaseSize(file.size) } private fun increaseSize(size: Int) { amountSize += size parent?.increaseSize(size) } } fun backDirectory(path: String): String { val index = path.indexOfLast { it == '/' } return path.substring(0, index) } fun main() { fun getDirectories(input: List<String>): Map<String, Directory> { val directories = mutableMapOf<String, Directory>() directories["/"] = Directory() var currentDirectory = "/" input.forEach { val command = it.split(" ") if (it[0] == '$') { if (command[1] == "cd") { when (command[2]) { "/" -> currentDirectory = "/" ".." -> currentDirectory = backDirectory(currentDirectory) else -> { val newPath = "$currentDirectory/${command[2]}" if (!directories.contains(newPath)) directories["$currentDirectory/${command[2]}"] = Directory(directories[currentDirectory]) currentDirectory += "/${command[2]}" } } } } else { if (command[0] != "dir") { directories[currentDirectory]?.addFile(File(command[1], command[0].toInt())) } } } return directories } fun part1(input: List<String>): Int { return getDirectories(input).values.filter { it.amountSize <= 100000 }.sumOf { it.amountSize } } fun part2(input: List<String>): Int { val directories = getDirectories(input) val freeSpace = 70000000 - (directories["/"]?.amountSize ?: 0) val needToFree = 30000000 - freeSpace return directories.values.sortedBy { it.amountSize }.first { it.amountSize>=needToFree }.amountSize } val input = readInput("Day07") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
d5d180eaf367a93bc038abbc4dc3920c8cbbd3b8
2,327
Advent-of-code
Apache License 2.0
src/main/kotlin/tr/emreone/kotlin_utils/extensions/Combinatorics.kt
EmRe-One
442,916,831
false
{"Kotlin": 173543}
package tr.emreone.kotlin_utils.extensions /** * Generates all combinations of the elements of the given [Iterable] for the requested size. * Note: combinations do not include all their permutations! * @receiver the [Iterable] to take elements from * @param size the size of the combinations to create * @return a sequence of all combinations */ fun <T> Iterable<T>.combinations(size: Int): Sequence<List<T>> = toList().combinations(size) /** * Generates all combinations of the elements of the given list for the requested size. * Note: combinations do not include all their permutations! * @receiver the list to take elements from * @param size the size of the combinations to create * @return a sequence of all combinations */ fun <T> List<T>.combinations(size: Int): Sequence<List<T>> = when (size) { 0 -> emptySequence() 1 -> asSequence().map { listOf(it) } else -> sequence { this@combinations.forEachIndexed { index, element -> val head = listOf(element) val tail = this@combinations.subList(index + 1, this@combinations.size) tail.combinations(size - 1).forEach { tailCombinations -> yield(head + tailCombinations) } } } } /** * Generates all combinations of the elements of the given [IntRange] for the requested size. * Note: combinations do not include all their permutations! * @receiver the [IntRange] to take elements from * @param size the size of the combinations to create * @return a sequence of all combinations */ fun IntRange.combinations(size: Int): Sequence<List<Int>> = when (size) { 0 -> emptySequence() 1 -> asSequence().map { listOf(it) } else -> sequence { for (element in this@combinations) { val head = listOf(element) val tail = element + 1..this@combinations.last tail.combinations(size - 1).forEach { yield(head + it) } } } } /** * Generates a sequence of all permutations of the given list of elements. * @receiver the list of elements for permutation of order * @return a sequence of all permutations of the given list */ fun <T> Collection<T>.permutations(): Sequence<List<T>> = when (size) { 0 -> emptySequence() 1 -> sequenceOf(toList()) else -> { val head = first() val tail = drop(1) tail.permutations() .flatMap { perm -> (0..perm.size).asSequence().map { perm.copyAndInsert(it, head) } } .asSequence() } } /** * Generates a sequence of all permutations of the given numbers in the [IntRange] * @receiver the [IntRange] for permutation of order * @return a sequence of all permutations of the numbers in the range */ fun IntRange.permutations(): Sequence<List<Int>> = when { first > last -> emptySequence() first == last -> sequenceOf(listOf(first)) else -> { val head = first val tail = first + 1..last tail.permutations().flatMap { perm -> (0..perm.size).asSequence().map { perm.copyAndInsert(it, head) } } } } fun String.permutations(): Sequence<String> = toList().permutations().map { it.joinToString("") }.asSequence() fun String.combinations(size: Int): Sequence<String> = toList().combinations(size).map { it.joinToString("") } private fun <T> List<T>.copyAndInsert(insertAt: Int, element: T): List<T> = List(size + 1) { idx -> when { idx < insertAt -> this[idx] idx == insertAt -> element else -> this[idx - 1] } }
0
Kotlin
0
0
aee38364ca1827666949557acb15ae3ea21881a1
3,814
kotlin-utils
Apache License 2.0
src/Day07.kt
Cryosleeper
572,977,188
false
{"Kotlin": 43613}
import kotlin.math.min private const val DISK_SIZE = 70000000 private const val UPDATE_SPACE_REQUIREMENT = 30000000 fun main() { fun part1(input: List<String>): Int { val root = input.parse() return root.sumOfFoldersUnder100000() } fun part2(input: List<String>): Int { val root = input.parse() val spaceToFree = UPDATE_SPACE_REQUIREMENT - (DISK_SIZE - root.size) if (spaceToFree <= 0) return 0 return root.smallestFolderBiggerThan(spaceToFree) } // 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)) } private fun Folder.smallestFolderBiggerThan(spaceToFree: Int): Int { var result = Int.MAX_VALUE this.children.forEach { if (it is Folder) { if (it.size >= spaceToFree) { result = min(result, it.size) result = min(result, it.smallestFolderBiggerThan(spaceToFree)) } } } return result } private fun Folder.sumOfFoldersUnder100000(): Int { var sum = 0 this.children.forEach { if (it is Folder) { if (it.size < 100000) { sum += it.size } sum += it.sumOfFoldersUnder100000() } } return sum } private fun List<String>.parse(): Folder { val root = Folder("/", null, mutableListOf()) var currentFolder = root this.forEach { line -> if (line.startsWith("$ cd")) { currentFolder = when (line.replace("$ cd ", "")) { "/" -> root ".." -> currentFolder.parent!! else -> { currentFolder.children.find { it.name == line.replace("$ cd ", "") } as Folder } } } else if (line.startsWith("$ ls")) { //not useful for anything } else { val (prefix, name) = line.split(" ") val entity = if (prefix == "dir") { Folder(name, currentFolder, mutableListOf()) } else { File(name, currentFolder, prefix.toInt()) } currentFolder.children.add(entity) } } return root } private abstract class Entry { abstract val name: String abstract val parent: Folder? abstract val size: Int override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is Entry) return false if (name != other.name) return false if (parent != other.parent) return false return true } override fun hashCode(): Int { var result = name.hashCode() result = 31 * result + (parent?.hashCode() ?: 0) return result } } private class Folder(override val name: String, override val parent: Folder?, val children: MutableList<Entry>): Entry() { override val size: Int get() = children.sumOf { it.size } } private class File(override val name: String, override val parent: Folder?, override val size: Int): Entry()
0
Kotlin
0
0
a638356cda864b9e1799d72fa07d3482a5f2128e
3,220
aoc-2022
Apache License 2.0
src/main/kotlin/Day11.kt
alex859
573,174,372
false
{"Kotlin": 80552}
fun main() { val testInput = readInput("Day11_test.txt") check(testInput.day11Part1() == 10605) // check(testInput.day10Part2() == ) val input = readInput("Day11.txt") println(input.day11Part1()) // println(input.day10Part2()) } private fun String.day11Part1(): Int { val endGame = split("\n\n").map { it.toMonkey() }.playRounds() return endGame.sortedByDescending { it.itemsInspected }.take(2).map { it.itemsInspected }.reduce { a, b -> a * b } } internal fun List<Monkey>.playRounds(): List<Monkey> { var monkeys = this for (i in 1..20) { monkeys = monkeys.playRound() } return monkeys } internal fun List<Monkey>.playRound(): List<Monkey> { var monkeys = this for (i in indices) { monkeys = monkeys.playTurn(i) } return monkeys } internal fun List<Monkey>.playTurn(index: Int): List<Monkey> { val monkeys = this.toMutableList() var monkey = monkeys[index] while (monkey.items.isNotEmpty()) { val result = monkeys[index].playTurn() monkeys[index] = result.monkey monkey = result.monkey if (result.pass != null) { val otherMonkey = monkeys[result.pass.second] monkeys[result.pass.second] = otherMonkey.copy(items = otherMonkey.items + result.pass.first) } } return monkeys } private fun Monkey.playTurn(): TurnResult { val item = items.first() val worry = when (val op = operation) { is Times -> item * when (val n = op.n) { is N -> n.value is Old -> item } is Plus -> item + when (val n = op.n) { is N -> n.value is Old -> item } } / 3 val pass = worry to if (worry % divisibleBy == 0) { nextMonkeyIfTrue } else { nextMonkeyIfFalse } return TurnResult(copy(items = items - item, itemsInspected = itemsInspected + 1), pass) } data class TurnResult( val monkey: Monkey, val pass: Pair<Int, Int>? ) internal fun String.toMonkey(): Monkey { val lines = lines() return Monkey( code = lines[0].toCode(), items = lines[1].toItems(), operation = lines[2].toOperation(), divisibleBy = lines[3].toDivisibleBy(), nextMonkeyIfTrue = lines[4].toNextMonkey("true"), nextMonkeyIfFalse = lines[5].toNextMonkey("false"), ) } private fun String.toNextMonkey(s: String): Int { return trim().replace("If $s: throw to monkey ", "").toInt() } private fun String.toDivisibleBy() = trim().replace("Test: divisible by ", "").toInt() private fun String.toCode() = split(" ")[1].replace(":", "").toInt() private fun String.toItems() = replace("Starting items: ", "") .split(", ") .map { it.trim() } .map { it.toInt() } private fun String.toOperation(): Operation { val (op, n) = trim().replace("Operation: new = old ", "").split(" ") return when (op) { "*" -> Times(n.toOperand()) "+" -> Plus(n.toOperand()) else -> TODO() } } private fun String.toOperand(): Operand { return when (this) { "old" -> Old else -> N(toInt()) } } data class Monkey( val code: Int, val items: List<Int>, val operation: Operation, val divisibleBy: Int, val nextMonkeyIfTrue: Int, val nextMonkeyIfFalse: Int, val itemsInspected: Int = 0 ) sealed interface Operation { val n: Operand } sealed interface Operand data class N(val value: Int) : Operand object Old : Operand data class Times(override val n: Operand) : Operation data class Plus(override val n: Operand) : Operation
0
Kotlin
0
0
fbbd1543b5c5d57885e620ede296b9103477f61d
3,635
advent-of-code-kotlin-2022
Apache License 2.0
advent-of-code-2022/src/main/kotlin/eu/janvdb/aoc2022/day15/SensorBeacon.kt
janvdbergh
318,992,922
false
{"Java": 1000798, "Kotlin": 284065, "Shell": 452, "C": 335}
package eu.janvdb.aoc2022.day15 import eu.janvdb.aocutil.kotlin.point2d.Point2D import kotlin.math.abs import kotlin.math.max import kotlin.math.min val PATTERN = Regex("Sensor at x=(-?\\d+), y=(-?\\d+): closest beacon is at x=(-?\\d+), y=(-?\\d+)") data class SensorBeacon(val sensor: Point2D, val beacon: Point2D) { private val distance = sensor.manhattanDistanceTo(beacon) val minX = sensor.x - distance val maxX = sensor.x + distance fun getRangeForLine(line: Int): Range { val offset = distance - abs(line - sensor.y) return Range(sensor.x - offset, sensor.x + offset) } } fun String.toSensorBeacon(): SensorBeacon { val matchResult = PATTERN.matchEntire(this) ?: throw IllegalArgumentException(this) return SensorBeacon( Point2D(matchResult.groupValues[1].toInt(), matchResult.groupValues[2].toInt()), Point2D(matchResult.groupValues[3].toInt(), matchResult.groupValues[4].toInt()) ) } data class SensorBeacons(val sensorBeacons: List<SensorBeacon>) { private val minX = sensorBeacons.minOfOrNull { it.minX }!! private val maxX = sensorBeacons.maxOfOrNull { it.maxX }!! private val beacons = sensorBeacons.map { it.beacon }.toSet() fun countPointsWhereNoBeaconCanBe(line: Int): Int { val positionWhereBeaconsCanBe = getIntervalWhereBeaconCanBe(line, Range(minX, maxX)).size() val beaconsOnLine = beacons.count { it.y == line } return maxX - minX + 1 - positionWhereBeaconsCanBe - beaconsOnLine } fun findPointsWhereBeaconCanBe(line: Int, searchRegion: IntRange): Set<Point2D> { return getIntervalWhereBeaconCanBe(line, Range.from(searchRegion)).getValues() .map { Point2D(it, line) } .toSet() } private fun getIntervalWhereBeaconCanBe(line: Int, range: Range): Intervals { var intervals = Intervals(listOf(range)) sensorBeacons.asSequence() .map { it.getRangeForLine(line) } .filter { !it.isEmpty() } .forEach { intervals = intervals.subtract(it) } return intervals } } fun List<String>.toSensorBeacons(): SensorBeacons = SensorBeacons(map(String::toSensorBeacon)) data class Range(val from: Int, val to: Int) { fun isEmpty() = to < from fun getValues() = IntRange(from, to).asSequence() fun size():Int = if (isEmpty()) 0 else to - from + 1 companion object { fun from(intRange: IntRange): Range = Range(intRange.first, intRange.last) } } data class Intervals(val ranges: List<Range>) { fun subtract(range: Range): Intervals { val newRanges = ranges.asSequence() .flatMap { sequenceOf( Range(it.from, min(it.to, range.from - 1)), Range(max(it.from, range.to + 1), it.to) ) } .filter { !it.isEmpty() } .toList() return Intervals(newRanges) } fun getValues() = ranges.asSequence().flatMap(Range::getValues) fun size(): Int = ranges.sumOf { it.size() } }
0
Java
0
0
78ce266dbc41d1821342edca484768167f261752
2,771
advent-of-code
Apache License 2.0
src/Day01.kt
fedochet
573,033,793
false
{"Kotlin": 77129}
fun main() { fun splitByEmptyLines(input: List<String>): List<List<String>> { val emptyLinesPositions = input.mapIndexedNotNull { index, line -> if (line.isBlank()) index else null } return buildList { var currentStart = 0 for (idx in emptyLinesPositions) { add(input.subList(currentStart, idx)) currentStart = idx + 1 } add(input.subList(currentStart, input.size)) } } /** * Sum of calories for elf with the biggest amount of calories. */ fun part1(input: List<String>): Int { val subLists = splitByEmptyLines(input) return subLists .maxOfOrNull { subList -> subList.sumOf { it.toInt() } } ?: error("At least one elf should be present") } /** * Sum of calories for 3 elves with the biggest amount of calories. */ fun part2(input: List<String>): Int { val subLists = splitByEmptyLines(input) return subLists .map { subList -> subList.sumOf { it.toInt() } } .sorted() .takeLast(3) .sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") check(part1(testInput) == 24000) check(part2(testInput) == 45000) val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
1
975362ac7b1f1522818fc87cf2505aedc087738d
1,483
aoc2022
Apache License 2.0
src/test/kotlin/com/igorwojda/list/maxsublistsum/MaxSubListSumSolution.kt
tmdroid
347,052,411
true
{"Kotlin": 199701}
package com.igorwojda.list.maxsublistsum // Time Complexity: O(n) // Space Complexity: O(1) // Use "sliding window" - store sum in single variable and with each iteration add (current item) // and remove (first item before current sub-list) private object Solution1 { private fun maxSubListSum(list: List<Int>, n: Int): Int? { if (list.size < n) { return null } var maxSum = list.take(n).sum() var tempSum = maxSum (n..list.lastIndex).forEach { index -> tempSum = tempSum - list[index - n] + list[index] maxSum = Math.max(maxSum, tempSum) } return maxSum } } private object Solution2 { private fun maxSubListSum(list: List<Int>, n: Int): Int? { if (list.size < n) { return null } return list.foldIndexed(0 to 0) { i, (sum, max), next -> (sum + next - (list.getOrNull(i - n) ?: 0)).let { it to if (it > max) it else max } }.second } } // Time Complexity: O(n*m) // Loop through the list and at each index loop again to calculate sum of sublist (from index to index + n) private object Solution3 { private fun maxSubListSum(list: List<Int>, n: Int): Int? { if (list.size < n) { return null } var maxSum: Int? = null for (i in 0..list.size - n) { var tempSum: Int? = null for (j in i until (i + n)) { if (tempSum == null) { tempSum = list[j] } else { tempSum += list[j] } } maxSum = max(maxSum, tempSum) } return maxSum } private fun max(i1: Int?, i2: Int?): Int? { return when { i1 != null && i2 != null -> Math.max(i1, i2) i1 != null && i2 == null -> i1 i1 == null && i2 != null -> i2 else -> null } } } private object Solution4 { private fun maxSubListSum(list: List<Int>, n: Int): Int? { if (list.isEmpty()) return null return (0..list.size - n) .map { i -> list.subList(i, i + n).sum() } .max() } }
0
Kotlin
2
0
f82825274ceeaf3bef81334f298e1c7abeeefc99
2,232
kotlin-puzzles
MIT License
src/Day08.kt
DiamondMiner88
573,073,199
false
{"Kotlin": 26457, "Rust": 4093, "Shell": 188}
fun main() { val input = readInput("input/day08.txt") .split("\n") .filter { it.isNotBlank() } val map: List<List<Int>> = input.map { row -> row.toList().map { it.digitToInt() } } val size = map.size val visibleMap = map.mapIndexed { rowI, row -> row.mapIndexed { colI, height -> if (colI == 0 || colI == size - 1 || rowI == 0 || rowI == size - 1) true else { val leftTrees = row.slice(0 until colI) val rightTrees = row.slice(colI + 1 until size) val topTrees = (0 until rowI).map { map[it][colI] } val btmTrees = (rowI + 1 until size).map { map[it][colI] } if (leftTrees.max() < height) true else if (rightTrees.max() < height) true else if (topTrees.max() < height) true else btmTrees.max() < height } } } println(visibleMap.map { it.count { it } }.sum()) val scenicScores = map.mapIndexed { rowI, row -> row.mapIndexed { colI, height -> val leftTrees = row.slice(0 until colI).reversed() val rightTrees = row.slice(colI + 1 until size) val topTrees = (0 until rowI).map { map[it][colI] }.reversed() val btmTrees = (rowI + 1 until size).map { map[it][colI] } val leftScore = run { var cnt = 0 leftTrees.forEach { tree -> cnt++ if (tree >= height) return@run cnt } cnt } val rightScore = run { var cnt = 0 rightTrees.forEach { tree -> cnt++ if (tree >= height) return@run cnt } cnt } val topScore = run { var cnt = 0 topTrees.forEach { tree -> cnt++ if (tree >= height) return@run cnt } cnt } val btmScore = run { var cnt = 0 btmTrees.forEach { tree -> cnt++ if (tree >= height) return@run cnt } cnt } leftScore * rightScore * topScore * btmScore } } println(scenicScores.map { it.max() }.max()) }
0
Kotlin
0
0
55bb96af323cab3860ab6988f7d57d04f034c12c
2,556
advent-of-code-2022
Apache License 2.0
src/main/kotlin/Problem5.kt
jimmymorales
496,703,114
false
{"Kotlin": 67323}
import kotlin.math.floor import kotlin.math.log10 import kotlin.math.pow import kotlin.math.sqrt /** * Smallest multiple * * 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. * * What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20? * * https://projecteuler.net/problem=5 */ fun main() { println(smallestNumberDivisibleBy(20)) } // Initial answer /*fun smallestNumberDivisibleBy(k : Int): Long { for (n in (k..Long.MAX_VALUE)) { if ((2..k).all { n % it == 0L }) { return n } } return 0 }*/ private fun smallestNumberDivisibleBy(k: Int): Long { val p = primes(k) val a = Array(p.size) { 0 } val limit = sqrt(k.toDouble()) var n = 1L var check = true for (i in 1 until p.size) { a[i] = 1 if (check) { if (p[i] <= limit) { a[i] = floor(log10(k.toDouble())/ log10(p[i].toDouble())).toInt() } else { check = false } } n *= p[i].toDouble().pow(a[i]).toLong() } return n } // Generating a List of Primes: The Sieve of Eratosthenes fun primes(n: Int): List<Int> { val flags = Array(n) { true } var prime = 2 while (prime <= sqrt(n.toDouble())) { flags.crossOff(prime) prime = flags.indexOfFirst(from = prime + 1) { it } } return flags.mapIndexedNotNull { index, isPrime -> if (isPrime) index else null } } private fun Array<Boolean>.crossOff(prime: Int) { for (i in (prime * prime) until size step prime) { this[i] = false } } inline fun <T> Array<out T>.indexOfFirst(from: Int, predicate: (T) -> Boolean): Int { for (index in from until size) { if (predicate(this[index])) { return index } } return -1 }
0
Kotlin
0
0
e881cadf85377374e544af0a75cb073c6b496998
1,883
project-euler
MIT License
src/main/kotlin/org/sjoblomj/adventofcode/day8/Visualiser.kt
sjoblomj
161,537,410
false
null
package org.sjoblomj.adventofcode.day8 internal fun visualise(licenseFile: String, tree: Tree): String { val lengthOfOnePosition = 3 val header = licenseFile.split(" ").joinToString("") { it.padStart(lengthOfOnePosition) } val lines = visualise(tree, 0, lengthOfOnePosition).sortedBy { it.level } val numberOfLevels = lines.map { it.level }.max() ?: 0 val stringsWithLines = (0 .. numberOfLevels).map { level -> val relevantLines = lines .filter { it.level == level } .sortedBy { it.startPosition } relevantLines.mapIndexed { index, visualisation -> val prevEndPos = if (index > 0) relevantLines[index - 1].startPosition + (relevantLines[index - 1].line.length / lengthOfOnePosition) else 0 val indendation = " ".repeat((visualisation.startPosition - prevEndPos) * lengthOfOnePosition) indendation + visualisation.line }.joinToString("") } return header + "\n" + stringsWithLines.joinToString("\n") } private fun visualise(tree: Tree, level: Int, lengthOfOnePosition: Int): List<Visualisation> { fun drawLine(length: Int) = " #-" + "-".repeat(lengthOfOnePosition * length) val currNodeLine = Visualisation(drawLine(tree.endedAt - tree.beganAt), tree.beganAt, level) return tree.children.flatMap { visualise(it, level + 1, lengthOfOnePosition) }.plus(currNodeLine) } private data class Visualisation(val line: String, val startPosition: Int, val level: Int)
0
Kotlin
0
0
80db7e7029dace244a05f7e6327accb212d369cc
1,428
adventofcode2018
MIT License
src/Day25.kt
rod41732
572,917,438
false
{"Kotlin": 85344}
fun main() { fun part1(input: List<String>): String { return toSNAFU( input.map(::parseSNAFU).sum() ) } val testInput = readInput("Day25_test") println(part1(testInput)) check(part1(testInput) == "2=-1=0") check(parseSNAFU("1121-1110-1=0") == 314159265L) check(parseSNAFU("1-0---0") == 12345L) check(parseSNAFU("1=11-2") == 2022L) println(toSNAFU(314159265L)) check(toSNAFU(314159265L) == "1121-1110-1=0") check(toSNAFU(12345L) == "1-0---0") check(toSNAFU(2022L) == "1=11-2") val input = readInput("Day25") println("Part 1") println(part1(input)) // 33010101016442 // there's no Part 2 for Day25 } private fun Char.digitValue(): Int = when (this) { '0', '1', '2' -> this - '0' '-' -> -1 '=' -> -2 else -> throw Error("Invalid digit") } private fun parseSNAFU(digits: String): Long = digits.map { it.digitValue() }.fold(0L) { acc, v -> acc * 5 + v } private fun Int.toDigit(): Pair<Char, Int> = when (this) { 0, 1, 2 -> '0' + this to 0 // n = 5(0) + n 3 -> '=' to 1 // 3 = 5(1) - 2 4 -> '-' to 1 // 4 = 5(1) - 1 else -> throw Error("Invalid position number") } private fun toSNAFU(x: Long): String = buildList { var p = x while (p != 0L) { val rem = p.mod(5) p /= 5 rem.toDigit().also { (char, carry) -> add(char) p += carry } } }.joinToString("").reversed()
0
Kotlin
0
0
1d2d3d00e90b222085e0989d2b19e6164dfdb1ce
1,459
advent-of-code-kotlin-2022
Apache License 2.0
src/Day05.kt
hufman
573,586,479
false
{"Kotlin": 29792}
data class Instruction(val count: Int, val src: Int, val dest: Int) { companion object { val matcher = Regex("""move (\d+) from (\d+) to (\d+)""") fun fromString(input: String): Instruction { val result = matcher.matchEntire(input)!! return Instruction(result.groupValues[1].toInt(), result.groupValues[2].toInt(), result.groupValues[3].toInt()) } } } data class Puzzle(val stacks: List<MutableList<Char>>, val instructions: List<Instruction>) fun main() { fun parse(rows: List<String>): Puzzle { val columns = ArrayList<MutableList<Char>>().apply { (0..9).forEach { _ -> add(ArrayList()) } } val instructions = ArrayList<Instruction>() rows.forEach { row -> if (row.contains('[')) { for (i in 1 until row.length step 4) { val columnNumber = i / 4 + 1 if (row[i].isLetter()) { columns[columnNumber].add(0, row[i]) } } } else if (row.contains("move")) { instructions.add(Instruction.fromString(row)) } } return Puzzle(columns, instructions) } fun part1(input: List<String>): String { val puzzle = parse(input) puzzle.instructions.forEach { (0 until it.count).forEach { _ -> puzzle.stacks[it.dest].add(puzzle.stacks[it.src].removeLast()) } } return puzzle.stacks.mapNotNull { it.lastOrNull() }.joinToString("") } fun part2(input: List<String>): String { val puzzle = parse(input) puzzle.instructions.forEach { val cut = puzzle.stacks[it.src].size - it.count (0 until it.count).forEach { _ -> puzzle.stacks[it.dest].add(puzzle.stacks[it.src].removeAt(cut)) } } return puzzle.stacks.mapNotNull { it.lastOrNull() }.joinToString("") } // test if implementation meets criteria from the description, like: val testInput = readInput("Day05_test") check(part1(testInput) == "CMZ") check(part2(testInput) == "MCD") val input = readInput("Day05") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
1bc08085295bdc410a4a1611ff486773fda7fcce
1,910
aoc2022-kt
Apache License 2.0
advent-of-code-2022/src/main/kotlin/year_2022/Day09.kt
rudii1410
575,662,325
false
{"Kotlin": 37749}
package year_2022 import util.Runner fun main() { fun Pair<Int, Int>.move(move: Pair<Int, Int>): Pair<Int, Int> { return copy(first = first + move.first, second = second + move.second) } fun getDirection(a: Int, b: Int) = if (a > b) 1 else if (a < b) -1 else 0 val zero = Pair(0, 0) val moveMap = mapOf( "L" to Pair(-1, 0), "R" to Pair(1, 0), "U" to Pair(0, -1), "D" to Pair(0, 1) ) fun calculate(input: List<String>, len: Int): Int { val visited = mutableMapOf<Pair<Int, Int>, Boolean>() val rope = MutableList(len) { zero } return input.sumOf { str -> val row = str.split(" ") List(row[1].toInt()) { _ -> rope[0] = rope[0].move(moveMap.getOrDefault(row[0], zero)) for (i in 1 until rope.size) { if (rope[i - 1].first in (rope[i].first - 1)..(rope[i].first + 1) && rope[i - 1].second in (rope[i].second - 1)..(rope[i].second + 1)) break rope[i] = rope[i].let { it.move( Pair( getDirection(rope[i - 1].first, it.first), getDirection(rope[i - 1].second, it.second) ) ) } } if (!visited.getOrDefault(rope[len - 1], false)) { visited[rope[len - 1]] = true 1 } else 0 }.sum() } } /* Part 1 */ fun part1(input: List<String>): Int { return calculate(input, 2) } Runner.run(::part1, 88, 13) /* Part 2 */ fun part2(input: List<String>): Int { return calculate(input, 10) } Runner.run(::part2, 36) }
1
Kotlin
0
0
ab63e6cd53746e68713ddfffd65dd25408d5d488
1,862
advent-of-code
Apache License 2.0
src/y2016/Day07.kt
gaetjen
572,857,330
false
{"Kotlin": 325874, "Mermaid": 571}
package y2016 import util.readInput object Day07 { fun part1(input: List<String>): Int { return input.count { supportTls(it) } } private fun supportTls(ip: String): Boolean { val (supernet, hypernet) = ip.split(Regex("[\\[\\]]")) .mapIndexed { index, s -> index to s } .partition { it.first % 2 == 0 } return supernet.any { hasAbba(it.second) } && hypernet.none { hasAbba(it.second) } } private fun hasAbba(string: String): Boolean { val re = Regex("(.)(.)\\2\\1") return re.findAll(string).any { it.value.toSet().size == 2 } } fun part2(input: List<String>): Int { return input.count { supportSsl(it) } } private fun supportSsl(ip: String): Boolean { val (supernet, hypernet) = ip.split(Regex("[\\[\\]]")) .mapIndexed { index, s -> index to s } .partition { it.first % 2 == 0 } return hasAba(supernet.map { it.second }, hypernet.map { it.second }) } private fun hasAba(superNet: List<String>, hyperNet: List<String>): Boolean { val re = Regex("(.)(?=.\\1)") val superAbas = getAbas(superNet, re) val hyperBabs = getAbas(hyperNet, re) return superAbas.toSet().intersect(hyperBabs.map { it.reversed() }.toSet()).isNotEmpty() } private fun getAbas(superNet: List<String>, re: Regex) = superNet.flatMap { nets -> re.findAll(nets).map { nets.substring(it.range.first, it.range.first + 2) } }.filter { it.toSet().size == 2 } } fun main() { val testInput = """ abba[mnop]qrst abcd[bddb]xyyx aaaa[qwer]tyui ioxxoj[asdfgh]zxcvbn aba[bab]xyz xyx[xyx]xyx aaa[kek]eke zazbzb[bzb]cdb """.trimIndent().split("\n") println("------Tests------") println(Day07.part1(testInput)) println(Day07.part2(testInput)) println("------Real------") val input = readInput("resources/2016/day07") println(Day07.part1(input)) println(Day07.part2(input)) }
0
Kotlin
0
0
d0b9b5e16cf50025bd9c1ea1df02a308ac1cb66a
2,118
advent-of-code
Apache License 2.0
src/day07/Day07.kt
zypus
573,178,215
false
{"Kotlin": 33417, "Shell": 3190}
package day07 import AoCTask // https://adventofcode.com/2022/day/7 sealed interface Command sealed interface TreeNode { val name: String val size: Int } sealed class CmdLine { data class CdCommand(val path: String): CmdLine(), Command object LsCommand: CmdLine(), Command data class File(override val name: String, override val size: Int): CmdLine(), TreeNode data class Directory(override val name: String, override var size: Int = 0): CmdLine(), TreeNode } data class Tree(val data: TreeNode, val parent: Tree? = null, val children: MutableList<Tree> = mutableListOf()) fun parseLine(line: String): CmdLine { return if (line.startsWith("$")) { val cmdAndArgs = line.drop(2).split(" ") if (cmdAndArgs.first() == "cd") { CmdLine.CdCommand(path = cmdAndArgs.last()) } else { CmdLine.LsCommand } } else { val fileOrDir = line.split(" ") if (fileOrDir.first() == "dir") { CmdLine.Directory(fileOrDir.last()) } else { CmdLine.File(fileOrDir.last(), fileOrDir.first().toInt()) } } } fun renderTree(tree: Tree, depth: Int = 0): String { return when (tree.data) { is CmdLine.Directory -> { val string = "${" ".repeat(depth)}- ${tree.data.name} (dir)" string + tree.children.joinToString("\n") { renderTree(it, depth + 1) } } is CmdLine.File -> { "${" ".repeat(depth)}- ${tree.data.name} (file, size=${tree.data.size})" } } } fun computeSizes(tree: Tree): Int { return if (tree.children.isEmpty()) { if (tree.data is CmdLine.File) { tree.data.size } else { 0 } } else { if (tree.data is CmdLine.Directory) { val totalSize = tree.children.sumOf { computeSizes(it) } tree.data.size = totalSize totalSize } else { 0 } } } fun collectDirectories(tree: Tree): List<CmdLine.Directory> { return if (tree.data is CmdLine.Directory) { listOf(tree.data) + tree.children.flatMap { collectDirectories(it) } } else { emptyList() } } private fun constructFileSystem(input: List<String>): Tree { val lines = input.map { parseLine(it) } var currentDir = Tree(CmdLine.Directory("/")) lines.forEach { line -> when (line) { is CmdLine.CdCommand -> { currentDir = when (line.path) { "/" -> Tree(CmdLine.Directory("/")) ".." -> currentDir.parent!! else -> currentDir.children.first { it.data is CmdLine.Directory && it.data.name == line.path } } } is CmdLine.Directory -> { currentDir.children.add(Tree(line, currentDir)) } is CmdLine.File -> { currentDir.children.add(Tree(line, currentDir)) } CmdLine.LsCommand -> { } } } while (currentDir.parent != null) { currentDir = currentDir.parent!! } computeSizes(currentDir) return currentDir } fun part1(input: List<String>): Int { val root = constructFileSystem(input) val dirs = collectDirectories(root) val total = dirs.filter { it.size <= 100000 }.sumOf { it.size } return total } fun part2(input: List<String>): Int { val diskSize = 70000000 val minSizeRequired = 30000000 val root = constructFileSystem(input) val currentFreeSpace = diskSize - root.data.size val minSpaceToFreeUp = minSizeRequired - currentFreeSpace val dirs = collectDirectories(root) val dirToDelete = dirs.filter { it.size >= minSpaceToFreeUp }.minBy { it.size } return dirToDelete.size } fun main() = AoCTask("day07").run { // test if implementation meets criteria from the description, like: check(part1(testInput).also(::println) == 95437) check(part2(testInput).also(::println) == 24933642) println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
f37ed8e9ff028e736e4c205aef5ddace4dc73bfc
4,223
aoc-2022
Apache License 2.0
src/Day01.kt
bin-wang
573,219,628
false
{"Kotlin": 4145}
fun main() { fun findProductWithSum(nums: List<Int>, target: Int): Int? { var head = 0 var tail = nums.size - 1 while (head < tail) { val sum = nums[head] + nums[tail] when { sum < target -> head++ sum > target -> tail-- else -> { return nums[head] * nums[tail] } } } return null } fun part1(input: List<String>): Int { val expenses = input.map(Integer::parseInt).sorted() return findProductWithSum(expenses, 2020) ?: error("No solution found") } fun part2(input: List<String>): Int { val expenses = input.map(Integer::parseInt).sorted() for ((i, v) in expenses.withIndex()) { val product = findProductWithSum(expenses.slice(i + 1 until expenses.size), 2020 - v) if (product != null) { return product * v } } error("No solution found") } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") check(part1(testInput) == 514579) check(part2(testInput) == 241861950) val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
929f812efb37d5aea34e741510481ca3fab0c3da
1,311
aoc20-kt
Apache License 2.0
src/Day09.kt
tomoki1207
572,815,543
false
{"Kotlin": 28654}
import Motion.* import kotlin.math.abs import kotlin.math.sign enum class Motion { Up, Down, Left, Right; companion object { fun from(from: String) = when (from) { "U" -> Up "D" -> Down "L" -> Left "R" -> Right else -> throw Error("Unknown motion $from") } } } data class Knot(val row: Int, val col: Int) data class Rope(val knotCount: Int) { private var head = Knot(0, 0) private var knots = List(knotCount) { Knot(0, 0) } fun step(motion: Motion, callbackWithTail: (Knot) -> Unit) { var forward = nextHead(motion) head = forward knots = knots.map { k -> val diffRow = forward.row - k.row val diffCol = forward.col - k.col if (abs(diffRow) <= 1 && abs(diffCol) <= 1) { forward = k return@map k } val moved = Knot(k.row + diffRow.sign, k.col + diffCol.sign) forward = moved moved } callbackWithTail(knots.last()) } private fun nextHead(motion: Motion) = when (motion) { Up -> Knot(head.row + 1, head.col) Down -> Knot(head.row - 1, head.col) Left -> Knot(head.row, head.col - 1) Right -> Knot(head.row, head.col + 1) } } fun main() { fun countTailVisited(input: List<String>, knotCount: Int): Int { val steps = input.map { step -> step.split(" ").let { Pair(Motion.from(it[0]), it[1].toInt()) } } val rope = Rope(knotCount) val tailHistory = mutableSetOf<Knot>() steps.forEach { step -> repeat(step.second) { rope.step(step.first) { tailHistory.add(it) } } } return tailHistory.size } fun part1(input: List<String>) = countTailVisited(input, 1) fun part2(input: List<String>) = countTailVisited(input, 9) check(part1(readInput("Day09_test")) == 13) check(part2(readInput("Day09_test")) == 1) check(part2(readInput("Day09_test2")) == 36) val input = readInput("Day09") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
2ecd45f48d9d2504874f7ff40d7c21975bc074ec
2,194
advent-of-code-kotlin-2022
Apache License 2.0
src/com/ncorti/aoc2023/Day12.kt
cortinico
723,409,155
false
{"Kotlin": 76642}
package com.ncorti.aoc2023 fun main() { val memo = mutableMapOf<Triple<Int, Int, Int>, Long>() fun score(pattern: CharArray, numberList: List<Int>, idxPattern: Int, idxNumber: Int, bangCount: Int): Long { val input = Triple(idxPattern, idxNumber, bangCount) if (input in memo) { return memo[input]!! } if (idxPattern == pattern.size) { return when { idxNumber == numberList.size && bangCount == 0 -> 1 idxNumber == numberList.size - 1 && numberList[idxNumber] == bangCount -> 1 else -> 0 } } var result = 0L for (char in listOf('.', '#')) { if (pattern[idxPattern] == char || pattern[idxPattern] == '?') { if (char == '.' && bangCount == 0) { result += score(pattern, numberList, idxPattern + 1, idxNumber, bangCount) } else if (char == '.' && bangCount > 0 && idxNumber < numberList.size && numberList[idxNumber] == bangCount) { result += score(pattern, numberList, idxPattern + 1, idxNumber + 1, 0) } else if (char == '#') { result += score(pattern, numberList, idxPattern + 1, idxNumber, bangCount + 1) } } } memo[input] = result return result } fun parseInput() = getInputAsText("12") { split("\n").filter(String::isNotBlank).map { it.split(" ") }.map { val (pattern, numbers) = it pattern to numbers.split(",").map(String::toInt) } } fun part1(): Long = parseInput().sumOf { sample -> memo.clear() score(sample.first.toCharArray(), sample.second, 0, 0, 0) } fun part2(): Long = parseInput().sumOf { sample -> memo.clear() val pattern = "${sample.first}?${sample.first}?${sample.first}?${sample.first}?${sample.first}".toCharArray() val numberList = sample.second + sample.second + sample.second + sample.second + sample.second score(pattern, numberList, 0, 0, 0) } println(part1()) println(part2()) }
1
Kotlin
0
1
84e06f0cb0350a1eed17317a762359e9c9543ae5
2,221
adventofcode-2023
MIT License
src/day7/Day07.kt
HGilman
572,891,570
false
{"Kotlin": 109639, "C++": 5375, "Python": 400}
package day7 import day7.Day.File.Companion.isFile import day7.Day.File.Companion.toFile import day7.Day.Folder.Companion.isFolder import day7.Day.Folder.Companion.toFolder import day7.Day.buildTree import readInput import java.util.Stack fun main() { val testInput = readInput("day7/Day07_test") val testRoot = buildTree(testInput) // testRoot.print() check(Day.part1(testRoot) == 95437) check(Day.part2(testRoot) == 24933642) val input = readInput("day7/Day07") val root = buildTree(input) // root.print() println(Day.part1(root)) println(Day.part2(root)) } object Day { fun buildTree(input: List<String>): Folder { val root = "/".toFolder() val folderStack = Stack<Folder>() folderStack.push(root) fun String.isLS() = equals("$ ls") fun String.isCD() = startsWith("$ cd") fun String.getCdName() = substringAfter("$ cd ") fun String.isBack() = getCdName() == ".." input.drop(1).forEach { line -> val currentFolder = folderStack.peek() when { line.isLS() -> return@forEach line.isFolder() -> currentFolder.nodes.add(line.toFolder()) line.isFile() -> currentFolder.nodes.add(line.toFile()) line.isCD() -> { if (line.isBack()) { folderStack.pop() } else { val innerFolder = currentFolder.nodes.first { it.name == line.getCdName() } as Folder folderStack.push(innerFolder) } } } } return root } fun part1(root: Folder): Int { val acc = mutableListOf<Pair<Node, Int>>() root.findFoldersInSizeOf(100000, acc) return acc.sumOf { it.second } } fun part2(root: Folder): Int { val acc = mutableListOf<Pair<Node, Int>>() val currentFreeMemory = 70_000_000 - root.getTotalSize() val requiredFreeMemory = 30_000_000 root.findFoldersBiggerThen(requiredFreeMemory - currentFreeMemory, acc) acc.sortBy { it.second } return acc.first().second } sealed class Node(val name: String) { fun print() { println(getString()) } private fun getString(indentCount: Int = 0): String { val indention = (0 until indentCount).joinToString("") { " " } return indention + (when (this) { is Folder -> { val childPrint = nodes.joinToString("") { it.getString(indentCount + 2) } "- $name (dir)\n$childPrint" } is File -> { "- $name (file, size = $size) \n" } }) } abstract fun getTotalSize(): Int fun findFoldersInSizeOf(maxTotal: Int, acc: MutableList<Pair<Node, Int>>) { when (this) { is File -> return is Folder -> { val total = getTotalSize() if (total <= maxTotal) { acc.add(this to total) } nodes.forEach { it.findFoldersInSizeOf(maxTotal, acc) } } } } fun findFoldersBiggerThen(amount: Int, acc: MutableList<Pair<Node, Int>>) { when (this) { is File -> return is Folder -> { val total = getTotalSize() if (total >= amount) { acc.add(this to total) nodes.forEach { it.findFoldersBiggerThen(amount, acc) } } } } } } class File(name: String, val size: Int) : Node(name) { override fun getTotalSize() = size companion object { private val fileRegexp = """(\d+)\s([a-z]+\.*[a-z]*)""".toRegex() fun String.isFile(): Boolean { return matches(fileRegexp) } fun String.toFile(): File { val (_, fileSize, fileName) = fileRegexp.find(this)!!.groupValues return File(fileName, fileSize.toInt()) } } } class Folder(name: String, val nodes: MutableList<Node>) : Node(name) { override fun getTotalSize() = nodes.sumOf { it.getTotalSize() } companion object { fun String.isFolder() = startsWith("dir") || equals("/") private fun String.folderName(): String? { return if (!isFolder()) { null } else { if (equals("/")) { this } else { split(" ")[1] } } } fun String.toFolder() = Folder(folderName()!!, mutableListOf()) } } }
0
Kotlin
0
1
d05a53f84cb74bbb6136f9baf3711af16004ed12
5,079
advent-of-code-2022
Apache License 2.0