path
stringlengths
5
169
owner
stringlengths
2
34
repo_id
int64
1.49M
755M
is_fork
bool
2 classes
languages_distribution
stringlengths
16
1.68k
content
stringlengths
446
72k
issues
float64
0
1.84k
main_language
stringclasses
37 values
forks
int64
0
5.77k
stars
int64
0
46.8k
commit_sha
stringlengths
40
40
size
int64
446
72.6k
name
stringlengths
2
64
license
stringclasses
15 values
src/main/kotlin/y2022/day08/Day08.kt
TimWestmark
571,510,211
false
{"Kotlin": 97942, "Shell": 1067}
package y2022.day08 import Matrix import MatrixUtils fun main() { AoCGenerics.printAndMeasureResults( part1 = { part1() }, part2 = { part2() } ) } data class Tree( val height: Int, var counted: Boolean, var scenicScore: Int = 0, ) fun input(): Matrix<Tree> { return MatrixUtils.createMatrix(AoCGenerics.getInputLines("/y2022/day08/input.txt")) { _index, row -> row.map { char -> Tree(char.digitToInt(), false) } } } fun List<Tree>.countVisibleTrees() { var curHighestTree = this.first().height this.forEach { tree -> if (tree.height > curHighestTree) { tree.counted = true curHighestTree = tree.height } } } fun calculateScenicScore(tree: Tree, spalte: Int, zeile: Int, forest: List<List<Tree>>) { var leftScore = 0 var upScore = 0 var rightScore = 0 var downScore = 0 // look left for (i in spalte - 1 downTo 0) { leftScore++ if (forest[zeile][i].height >= tree.height) { break } } // look right for (i in spalte + 1 until forest[spalte].size) { rightScore++ if (forest[zeile][i].height >= tree.height) { break } } // look up for (i in zeile - 1 downTo 0) { upScore++ if (forest[i][spalte].height >= tree.height) { break } } // look down for (i in zeile + 1 until forest.size) { downScore++ if (forest[i][spalte].height >= tree.height) { break } } tree.scenicScore = leftScore * rightScore * downScore * upScore } fun part1(): Int { val input = input() input.subList(1, input.size - 1) .forEach { treeLine -> treeLine.countVisibleTrees() treeLine.reversed().countVisibleTrees() } val transposed = MatrixUtils.transposeMatrix(input) transposed.subList(1, input.size - 1) .forEach { treeLine -> treeLine.countVisibleTrees() treeLine.reversed().countVisibleTrees() } input.first().forEach { tree -> tree.counted = true } input.last().forEach { tree -> tree.counted = true } input.forEach { row -> row.first().counted = true row.last().counted = true } return input.map { row -> row.count { tree -> tree.counted } }.sum() } fun part2(): Int { val forest = input() forest.forEachIndexed { zeile, trees -> trees.forEachIndexed { spalte, tree -> calculateScenicScore(tree, spalte, zeile, forest) } } return forest.flatten().maxOf { it.scenicScore } }
0
Kotlin
0
0
23b3edf887e31bef5eed3f00c1826261b9a4bd30
2,694
AdventOfCode
MIT License
code-sample-kotlin/algorithms/src/main/kotlin/com/codesample/leetcode/easy/1534_CountGoodTriplets.kt
aquatir
76,377,920
false
{"Java": 674809, "Python": 143889, "Kotlin": 112192, "Haskell": 57852, "Elixir": 33284, "TeX": 20611, "Scala": 17065, "Dockerfile": 6314, "HTML": 4714, "Shell": 387, "Batchfile": 316, "Erlang": 269, "CSS": 97}
package com.codesample.leetcode.easy /** * 1534. Count Good Triplets. https://leetcode.com/problems/count-good-triplets/ * * Given an array of integers arr, and three integers a, b and c. You need to find the number of good triplets. * * A triplet (arr[i], arr[j], arr[k]) is good if the following conditions are true: * * 0 <= i < j < k < arr.length * |arr[i] - arr[j]| <= a * |arr[j] - arr[k]| <= b * |arr[i] - arr[k]| <= c * * Where |x| denotes the absolute value of x. * Return the number of good triplets. * * Constraints: * 3 <= arr.length <= 100 // small array size. Can brute force * 0 <= arr[i] <= 1000 * 0 <= a, b, c <= 1000 */ fun countGoodTriplets(arr: IntArray, a: Int, b: Int, c: Int): Int { fun matched(i: Int, j: Int, k: Int): Boolean { return Math.abs(arr[i] - arr[j]) <= a && Math.abs(arr[j] - arr[k]) <= b && Math.abs(arr[i] - arr[k]) <= c } var matched = 0 for (i in arr.indices) { for (j in i + 1 until arr.size) { if (Math.abs(arr[i] - arr[j]) > a) { continue } for (k in j + 1 until arr.size) { if (matched(i, j, k)) { matched++ } } } } return matched } fun main() { println(countGoodTriplets(intArrayOf(3, 0, 1, 1, 9, 7), 7, 2, 3)) println(countGoodTriplets(intArrayOf(1, 1, 2, 2, 3), 0, 0, 1)) }
1
Java
3
6
eac3328ecd1c434b1e9aae2cdbec05a44fad4430
1,449
code-samples
MIT License
src/main/kotlin/dev/bogwalk/batch6/Problem66.kt
bog-walk
381,459,475
false
null
package dev.bogwalk.batch6 import kotlin.math.sqrt import kotlin.math.truncate /** * Problem 66: Diophantine Equation * * https://projecteuler.net/problem=66 * * Goal: Given a quadratic Diophantine equation of the form, x^2 - Dy^2 = 1, find the value of * D <= N in minimal solutions of x for which the largest value of x is obtained. There are no * solutions in positive integers when D is square. * * Constraints: 7 <= N <= 1e4 * * Pell-Fermat Equation: Any Diophantine equation of the form x^2 - ny^2 = 1, where n is a given * positive non-square integer. As long as n is not a perfect square, this equation has * infinitely many distinct integer solutions that can be used to approximate sqrt(n) by rational * numbers of the form x/y. * * e.g.: N = 7 * D = 2 -> 3^2 - 2 * 2^2 = 1 * D = 3 -> 2^2 - 3 * 1^2 = 1 * D = 5 -> 9^2 - 5 * 4^2 = 1 * D = 6 -> 5^2 - 6 * 2^2 = 1 * D = 7 -> 8^2 - 7 * 3^2 = 1 * largest x = 9 when D = 5 */ class DiophantineEquation { /** * Solution is similar to that in Problem 64, which solves continuous fractions based on the * formulae below: * * n_k = d_{k-1} * a_{k-1} - n_{k-1} * d_k = floor((x - (n_k)^2)/d_{k-1}) * a_k = floor((a_0 + n_k)/d_k) * * The fundamental solution is found by performing this continued fraction expansion, then * applying the recursive relation to the successive convergents using the formulae: * * h_n = a_n * h_{n-1} + h_{n-2} * k_n = a_n * k_{n-1} + k_{n-2} * * with h_n representing numerators & k_n representing denominators. * * When h_n & k_n satisfy the Pell equation, this pair becomes the fundamental solution * (x_1, y_1) for the value D, with h_n = x_1 and k_n = y_1. */ fun largestDiophantineX(n: Int): Int { var maxValue = 2 to 3.toBigInteger() // smallest fundamental D = 2 for (d in 3..n) { val dBI = d.toBigInteger() val root = sqrt(1.0 * d) val a0 = truncate(root).toInt() if (root - a0 == 0.0) continue // skip perfect squares var a = a0 var numerator = 0 var denominator = 1 // represents [hNMinus2, hNMinus1, a * hNMinus1 + hNMinus2] val hN = arrayOf(0.toBigInteger(), 1.toBigInteger(), a0.toBigInteger()) // represents [kNMinus2, kNMinus1, a * kNMinus1 + kNMinus2] val kN = arrayOf(1.toBigInteger(), 0.toBigInteger(), 1.toBigInteger()) while (true) { numerator = denominator * a - numerator denominator = (d - numerator * numerator) / denominator a = (a0 + numerator) / denominator hN[0] = hN[1] hN[1] = hN[2] hN[2] = a.toBigInteger() * hN[1] + hN[0] kN[0] = kN[1] kN[1] = kN[2] kN[2] = a.toBigInteger() * kN[1] + kN[0] if (1.toBigInteger() == hN[2].pow(2) - dBI * kN[2].pow(2)) break } if (hN[2] > maxValue.second) maxValue = d to hN[2] } return maxValue.first } }
0
Kotlin
0
0
62b33367e3d1e15f7ea872d151c3512f8c606ce7
3,195
project-euler-kotlin
MIT License
src/AOC2022/Day03/Day03.kt
kfbower
573,519,224
false
{"Kotlin": 44562}
package AOC2022.Day03 import AOC2022.readInput fun main() { fun part1(input: List<String>): Int { val priorityValueMap: MutableMap<Char, Int> = buildPriorityList() val priorityList: MutableList<Int> = mutableListOf() input.forEachIndexed { i, s -> val list1: MutableList<Char> = mutableListOf() val list2: MutableList<Char> = mutableListOf() val length = s.length val firstHalfEnd = (length / 2) var j: Int = 0 while (j < length) { if (j < firstHalfEnd) { list1.add(s[j]) ++j } else if (j in firstHalfEnd until length) { list2.add(s[j]) ++j } } val common = list1.intersect(list2.toSet()) val commonChar = common.first() val priorityValue = priorityValueMap[commonChar] if (priorityValue != null) { priorityList.add(priorityValue) } } return priorityList.sum() } fun part2(input: List<String>): Int { val priorityValueMap: MutableMap<Char, Int> = buildPriorityList() val priorityList: MutableList<Int> = mutableListOf() var h = 0 var j = 0 var k = 0 var l = 0 while (h<input.size){ var first: MutableList<String> = mutableListOf() var second: MutableList<String> = mutableListOf() var third: MutableList<String> = mutableListOf() val list1: MutableList<Char> = mutableListOf() val list2: MutableList<Char> = mutableListOf() val list3: MutableList<Char> = mutableListOf() first.add(input[h]) second.add(input[h+1]) third.add(input[h+2]) first.forEachIndexed { i, s -> while (j<s.length){ list1.add(s[j]) j++} } second.forEachIndexed { i, s -> while (k<s.length){ list2.add(s[k]) k++} } third.forEachIndexed { i, s -> while (l<s.length){ list3.add(s[l]) l++} } val oneby2 = list1.intersect(list2.toSet()) val oneby3 = list1.intersect(list3.toSet()) val common = oneby2.intersect(oneby3.toSet()) val commonChar = common.first() val priorityValue = priorityValueMap[commonChar] if (priorityValue != null) { priorityList.add(priorityValue) } h += 3 j=0 k=0 l=0 } return priorityList.sum() } val input = readInput("Day03") println(part1(input)) println(part2(input)) } fun buildPriorityList(): MutableMap<Char, Int> { val map = mutableMapOf<Char,Int>() var n = 1 var c = 'a' while (c <= 'z') { map[c] = n ++c ++n } var lC = 'A' while (lC <= 'Z') { map[lC] = n ++lC ++n } return map }
0
Kotlin
0
0
48a7c563ebee77e44685569d356a05e8695ae36c
3,188
advent-of-code-2022
Apache License 2.0
src/year2021/13/Day13.kt
Vladuken
573,128,337
false
{"Kotlin": 327524, "Python": 16475}
package year2021.`13` import readInput private data class Point( val x: Int, val y: Int ) private fun extractPoints(input: List<String>): Set<Point> { return input.takeWhile { it.isNotBlank() } .map { val (x, y) = it.split(",") .map { it.toInt() } Point(x, y) } .toSet() } private sealed class Command { data class FoldUp(val y: Int) : Command() data class FoldLeft(val x: Int) : Command() } private fun extractCommands(input: List<String>): List<Command> { return input.reversed() .takeWhile { it.isNotBlank() } .reversed() .map { val (coordindate, number) = it.split(" ").last() .split("=") when (coordindate) { "x" -> Command.FoldLeft(x = number.toInt()) "y" -> Command.FoldUp(y = number.toInt()) else -> error("Illegal parsed data coordinate:$coordindate number:$number") } } } private fun foldUp(points: Set<Point>, command: Command.FoldUp): Set<Point> { val y = command.y val (below, above) = points .partition { it.y > y } .let { (below, above) -> below.toSet() to above.toSet() } val resultSet = above.toMutableSet() below.forEach { val verticalDivide = it.y - y resultSet.add(it.copy(y = y - verticalDivide)) } return resultSet } private fun foldLeft(points: Set<Point>, command: Command.FoldLeft): Set<Point> { val x = command.x val (below, above) = points .partition { it.x > x } .let { (below, above) -> below.toSet() to above.toSet() } val resultSet = above.toMutableSet() below.forEach { val horizontalDivide = it.x - x resultSet.add(it.copy(x = x - horizontalDivide)) } return resultSet } private fun fold(points: Set<Point>, command: Command): Set<Point> { return when (command) { is Command.FoldUp -> foldUp(points, command) is Command.FoldLeft -> foldLeft(points, command) } } private fun Collection<Point>.height(): Long = maxOf { it.y }.toLong() private fun Collection<Point>.width(): Long = maxOf { it.x }.toLong() private fun printSet(set: Set<Point>) { val height = set.height() println() for (i in 0..height) { print("|") repeat(set.width().toInt() + 1) { val symbol = if (Point(it, i.toInt()) in set) "█" else "." print(symbol) } print("|") println() } println() } fun main() { fun part1(input: List<String>): Int { val points = extractPoints(input) val commands = extractCommands(input) var buff = points buff = fold(buff, commands.first()) return buff.size } fun part2(input: List<String>): Int { val points = extractPoints(input) val commands = extractCommands(input) var buff = points commands.forEach { buff = fold(buff, it) } printSet(buff) return buff.size } // test if implementation meets criteria from the description, like: val testInput = readInput("Day13_test") val part1Test = part1(testInput) println(part1Test.also { assert(it == 17) }) val input = readInput("Day13") println(part1(input).also { assert(it == 710) }) println(part2(input).also { assert(it == 97) }) }
0
Kotlin
0
5
c0f36ec0e2ce5d65c35d408dd50ba2ac96363772
3,430
KotlinAdventOfCode
Apache License 2.0
src/Day05.kt
jwalter
573,111,342
false
{"Kotlin": 19975}
fun main() { data class Cmd(val from: Int, val to: Int, val count: Int) fun parseInput(input: List<String>): Pair<List<MutableList<String>>, List<Cmd>> { val stackRows = input.takeWhile { it.contains("[") }.map { it.chunked(4) } val stackCount = stackRows.maxOf { it.size } val stacks = (0 until stackCount).map { mutableListOf<String>() } stackRows.forEach { row -> row.forEachIndexed { idx, crate -> if (crate.isNotBlank()) { stacks[idx].add(crate) } } } val instructions = input .dropWhile { !it.contains("move") } .map { it.split(" ") } .map { Cmd(it[3].toInt() - 1, it[5].toInt() - 1, it[1].toInt()) } return stacks to instructions } fun applyInstructions( stacks: List<MutableList<String>>, instructions: List<Cmd>, func: (MutableList<String>, MutableList<String>, Int) -> Unit ): String { instructions.forEach { func(stacks[it.from], stacks[it.to], it.count) } return stacks.map { it.first()[1] }.joinToString("") } fun part1(input: List<String>): String { val (stacks, instructions) = parseInput(input) return applyInstructions(stacks, instructions) { src, target, count -> repeat(count) { val crate = src.removeFirst() target.add(0, crate) } } } fun part2(input: List<String>): String { val (stacks, instructions) = parseInput(input) return applyInstructions(stacks, instructions) { src, target, count -> repeat(count) { val crate = src.removeFirst() target.add(it, crate) } } } 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
576aeabd297a7d7ee77eca9bb405ec5d2641b441
2,029
adventofcode2022
Apache License 2.0
src/Day05.kt
Olivki
573,156,936
false
{"Kotlin": 11297}
import java.util.LinkedList fun main() { val excessiveWhitespace = """\s+""".toRegex() data class CraneData(val cranes: List<LinkedList<Char>>, val instructions: List<List<Int>>) fun parseInput(input: List<String>): CraneData { val separatorIndex = input.indexOfFirst { it.isBlank() } val cranes = run { val craneCount = input[separatorIndex - 1] .trim() .splitToSequence(excessiveWhitespace) .count() val cranes = MutableList<LinkedList<Char>>(craneCount) { LinkedList() } input .take(separatorIndex - 1) .map { line -> line .windowed(size = 3, step = 4) .map { char -> char[1].takeIf { it != ' ' } } } .forEach { chars -> chars.forEachIndexed { i, crate -> if (crate != null) cranes[i].addLast(crate) } } cranes } val instructions = input .drop(separatorIndex + 1) .takeWhile { it.isNotBlank() } .map { line -> line .split(' ') .filterIndexed { i, _ -> i % 2 != 0 } .map(String::toInt) } return CraneData(cranes, instructions) } fun part1(input: List<String>): String { val (cranes, instructions) = parseInput(input) for ((amountToMove, from, to) in instructions) { val fromCrane = cranes[from - 1] val toCrane = cranes[to - 1] repeat(amountToMove) { toCrane.push(fromCrane.pop()) } } return cranes.joinToString(separator = "") { it.first().toString() } } fun part2(input: List<String>): String { val (cranes, instructions) = parseInput(input) for ((amountToMove, from, to) in instructions) { val fromCrane = cranes[from - 1] val toCrane = cranes[to - 1] val cratesToMove = fromCrane.subList(0, amountToMove) toCrane.addAll(0, cratesToMove) repeat(amountToMove) { fromCrane.pop() } } return cranes.joinToString(separator = "") { it.first().toString() } } val testInput = readTestInput("Day05") // p1 check(part1(testInput) == "CMZ") // p2 check(part2(testInput) == "MCD") val input = readInput("Day05") println(part1(input)) println(part2(input)) }
0
Kotlin
0
1
51c408f62589eada3d8454740c9f6fc378e2d09b
2,610
aoc-2022
Apache License 2.0
src/day15/Day15.kt
xxfast
572,724,963
false
{"Kotlin": 32696}
package day15 import geometry.* import readLines import kotlin.math.abs data class Record(val sensor: Point, val beacon: Point, val distance: Long = distance(sensor, beacon) + 1) val regex = Regex("""-?\d{1,7}""") fun format(inputs: List<String>): Set<Record> = inputs .map { line -> regex.findAll(line).toList() .map { it.value } .let { (x1, y1, x2, y2) -> (x1.toLong() to y1.toLong()) to (x2.toLong() to y2.toLong()) } .let { (sensor, beacon) -> Record(sensor, beacon) } } .toSet() fun distance(first: Point, second: Point): Long = abs(second.x - first.x) + abs(second.y - first.y) val Record.border: Sequence<Point> get() = sequence { val left = sensor.x - distance val top = sensor.y - distance val right = sensor.x + distance val bottom = sensor.y + distance ((left to sensor.y)..(sensor.x to top)).forEach { point -> yield(point) } ((sensor.x to top)..(right to sensor.y)).forEach { point -> yield(point) } ((right to sensor.y)..(sensor.x to bottom)).forEach { point -> yield(point) } ((sensor.x to bottom)..(left to sensor.y)).forEach { point -> yield(point) } } fun main() { fun part1(inputs: List<String>, y: Long): Int { val records = format(inputs) val minX = records.minOf { (sensor, beacon, distance) -> minOf(sensor.x, beacon.x, sensor.x - distance) } val maxX = records.maxOf { (sensor, beacon, distance) -> maxOf(sensor.x, beacon.x, sensor.x + distance) } return (minX..maxX) .map { x -> x to y } .count { point -> records.any { (sensor, beacon, distance) -> beacon != point && distance(sensor, point) < distance } } } fun part2(inputs: List<String>, range: LongRange): Long { val records = format(inputs) val beacon = records.flatMap { it.border } .filter { (x, y) -> x in range && y in range } .first { point -> records.none { (sensor, beacon, distance) -> distance(sensor, point) < distance } } return (beacon.x * 4000000) + beacon.y } val testInput = readLines("day15/test.txt") val input = readLines("day15/input.txt") check(part1(testInput, y = 10) == 26) println(part1(input, y = 2000000)) check(part2(testInput, 0..20L) == 56000011L) println(part2(input, 0..4000000L)) } @Deprecated("Debug only! - very very expensive to run") fun println(records: Set<Record>, range: LongRange? = null) { fun Record.empty() = buildSet { (sensor.x - distance..sensor.x + distance).forEach { x -> (sensor.y - distance..sensor.y + distance).forEach { y -> val point: Point = x to y val localDistance = distance(point, sensor) if (localDistance < distance && point !in listOf(beacon, sensor)) add(point) } } } val sensors: Set<Point> = records.map { it.sensor }.toSet() val beacons: Set<Point> = records.map { it.beacon }.toSet() val borders: Set<Point> = records.flatMap { it.border }.toSet() fun Set<Record>.empty() = flatMap { record -> record.empty() }.toSet() val empty = records.empty() val points = sensors + beacons + empty val minX = points.minOf { it.x } val maxX = points.maxOf { it.x } val minY = points.minOf { it.y } val maxY = points.maxOf { it.y } for (y in minY..maxY) { for (x in minX..maxX) { val symbol = when (x to y) { in sensors -> 'S' in beacons -> 'B' in empty -> "#" in borders -> '@' else -> '.' } if (range == null || (x in range && y in range)) print(symbol) } if (range == null || (y in range)) { print(" $y") println() } } }
0
Kotlin
0
1
a8c40224ec25b7f3739da144cbbb25c505eab2e4
3,581
advent-of-code-22
Apache License 2.0
src/main/kotlin/day08/Day08.kt
TheSench
572,930,570
false
{"Kotlin": 128505}
package day08 import runDay fun main() { fun part1(input: List<String>) = input.toGrid().visibilityMap.sumOf { row -> row.count { it } } fun part2(input: List<String>) = input.toGrid().let { grid -> grid.mapCellsIndexed { x, y, value -> grid.scenicScore(x, y, value) } }.maxOf { it.max() } (object {}).runDay( part1 = ::part1, part1Check = 21, part2 = ::part2, part2Check = 8, ) } private typealias Grid<T> = List<List<T>> private typealias MutableGrid<T> = MutableList<MutableList<T>> private fun Grid<Int>.scenicScore(x: Int, y: Int, value: Int) = this[y].countHigher(value, (0 until x).reversed()) * this[y].countHigher(value, (x + 1 until this[y].size)) * this.countHigher(x, value, (0 until y).reversed()) * this.countHigher(x, value, (y + 1 until this[y].size)) private fun Grid<Int>.countHigher(x: Int, value: Int, yVals: IntProgression): Int { var count = 0 for (i in yVals) { count++ if (this[x, i] >= value) break } return count } private fun List<Int>.countHigher(value: Int, xVals: IntProgression): Int { var count = 0 for (i in xVals) { count++ if (this[i] >= value) break } return count } private fun List<String>.toGrid() = map(String::toHeights) private val Grid<Int>.visibilityMap get() = visibleFromTop() .or(visibleFromBottom()) .or(visibleFromLeft()) .or(visibleFromRight()) private fun Grid<Int>.emptyVisibilityMap() = MutableList(this.size) { MutableList(this[0].size) { false } } private fun Grid<Boolean>.or(other: Grid<Boolean>) = this.mapCellsIndexed { x, y, cell -> cell || other[x, y] } private operator fun <T> Grid<T>.get(x: Int, y: Int): T = this[y][x] private operator fun <T> MutableGrid<T>.set(x: Int, y: Int, value: T) { this[y][x] = value } private fun <T, U> Grid<T>.mapCellsIndexed(transform: (x: Int, y: Int, value: T) -> U) = this.mapIndexed { y, row -> row.mapIndexed { x, cell -> transform(x, y, cell) } } private fun Grid<Int>.visibleFromTop(): Grid<Boolean> = emptyVisibilityMap() .also { visibilityMap -> List(this[0].size) { x -> this.foldIndexed(-1) { y, highest, row -> visibilityMap[x, y] = row[x] > highest maxOf(row[x], highest) } } } private fun Grid<Int>.visibleFromBottom(): Grid<Boolean> = emptyVisibilityMap() .also { visibilityMap -> List(this[0].size) { x -> this.foldRightIndexed(-1) { y, row, highest -> visibilityMap[x, y] = row[x] > highest maxOf(row[x], highest) } } } private fun Grid<Int>.visibleFromLeft(): Grid<Boolean> = emptyVisibilityMap() .also { visibilityMap -> this.mapIndexed { y, row -> row.foldIndexed(-1) { x, highest, height -> visibilityMap[x, y] = height > highest maxOf(height, highest) } } } private fun Grid<Int>.visibleFromRight(): Grid<Boolean> = emptyVisibilityMap() .also { visibilityMap -> this.mapIndexed { y, row -> row.foldRightIndexed(-1) { x, height, highest -> visibilityMap[x, y] = height > highest maxOf(height, highest) } } } private const val ZERO = '0'.code private fun String.toHeights() = map { it.code - ZERO }
0
Kotlin
0
0
c3e421d75bc2cd7a4f55979fdfd317f08f6be4eb
3,706
advent-of-code-2022
Apache License 2.0
src/main/kotlin/Day05.kt
zychu312
573,345,747
false
{"Kotlin": 15557}
import java.util.Stack class Day05 { data class MoveOperation(val howMany: Int, val fromStack: Int, val toStack: Int) private fun parseStacks(allLines: List<String>): List<Stack<Char>> { val stacksInput = allLines .takeWhile { !it.trim().startsWith("1") } .map { line -> line .chunked(4) .map { it.trim() } .map { it.ifBlank { null } } .map { it?.find { c -> c.isLetter() } } } return buildList { val noOfStacks = stacksInput.first().size repeat(noOfStacks) { this.add(Stack()) } stacksInput .asReversed() .forEach { line -> line.forEachIndexed { stackIndex, char -> if (char != null) this[stackIndex].push(char) } } } } private fun parseOperations(allLines: List<String>): List<MoveOperation> { return allLines .dropWhile { line -> !line.trim().startsWith("move") } .map { line -> line .split(" ") .map { it.trim() } .filterIndexed { index, s -> index % 2 == 1 } .map { str -> str.toInt() } } .map { (first, second, third) -> MoveOperation(howMany = first, second - 1, third - 1) } } private fun parseData(allLines: List<String>) = parseStacks(allLines) to parseOperations(allLines) private fun interface Strategy { fun solve(stacks: List<Stack<Char>>, operations: List<MoveOperation>): Unit } private val problemOneStrategy = Strategy { stacks, operations -> operations.forEach { (howMany, from, to) -> repeat(howMany) { stacks[to].push(stacks[from].pop()) } } } private val problemTwoStrategy = Strategy { stacks, operations -> operations.forEach { (howMany, from, to) -> val temp = Stack<Char>() repeat(howMany) { temp.push(stacks[from].pop()) } while (temp.isNotEmpty()) { stacks[to].push(temp.pop()) } } } private fun solveUsing(strategy: Strategy): String { val (stacks, operations) = loadFile("Day05Input.txt") .readLines() .let(::parseData) strategy.solve(stacks, operations) return stacks .map { stack -> stack.peek() } .joinToString("") } fun solve() { listOf(problemOneStrategy, problemTwoStrategy) .map(::solveUsing) .forEachIndexed { i, s -> println("Problem ${i + 1}: $s") } } } fun main() { Day05().solve() }
0
Kotlin
0
0
3e49f2e3aafe53ca32dea5bce4c128d16472fee3
2,875
advent-of-code-kt
Apache License 2.0
src/y2023/d01/Day01.kt
AndreaHu3299
725,905,780
false
{"Kotlin": 31452}
package y2023.d01 import println import readInput fun main() { val classPath = "y2023/d01" fun part1(input: List<String>): Int { return input.sumOf { line -> val firstDigit = line.find { it.isDigit() }?.toString() ?: "0" val lastDigit = line.findLast { it.isDigit() }?.toString() ?: "0" "$firstDigit$lastDigit".toInt() } } val lookupTable = mapOf( "one" to 1, "two" to 2, "three" to 3, "four" to 4, "five" to 5, "six" to 6, "seven" to 7, "eight" to 8, "nine" to 9, 1 to 1, 2 to 2, 3 to 3, 4 to 4, 5 to 5, 6 to 6, 7 to 7, 8 to 8, 9 to 9, ) fun part2(input: List<String>): Int { return input.sumOf { val first = lookupTable.keys .mapNotNull { key -> it.indexOf(key.toString()).let { if (it == -1) null else Pair(key, it) } } .minBy { it.second } .let { lookupTable[it.first] } val last = lookupTable.keys .mapNotNull { key -> it.lastIndexOf(key.toString()).let { if (it == -1) null else Pair(key, it) } } .maxBy { it.second } .let { lookupTable[it.first] } listOf(first, last).joinToString(separator = "") .toInt() } } // test if implementation meets criteria from the description, like: val testInput = readInput("${classPath}/test") part1(testInput).println() part2(testInput).println() val input = readInput("${classPath}/input") part1(input).println() part2(input).println() }
0
Kotlin
0
0
f883eb8f2f57f3f14b0d65dafffe4fb13a04db0e
1,704
aoc
Apache License 2.0
app/src/main/kotlin/day02/Day02.kt
StylianosGakis
434,004,245
false
{"Kotlin": 56380}
package day02 import common.InputRepo import common.readSessionCookie import common.solve fun main(args: Array<String>) { val day = 2 val input = InputRepo(args.readSessionCookie()).get(day = day) solve(day, input, ::solveDay02Part1, ::solveDay02Part2) } enum class SubmarineAction { Forward, Down, Up, ; companion object { fun fromInput(input: String): SubmarineAction = when (input) { "forward" -> Forward "down" -> Down "up" -> Up else -> throw IllegalArgumentException("Wrong input format") } } } data class ActionWithMagnitude(val submarineAction: SubmarineAction, val magnitude: Int) { companion object { fun fromInput(input: String): ActionWithMagnitude = input .split(" ") .let { ActionWithMagnitude(SubmarineAction.fromInput(it[0]), it[1].toInt()) } } } data class Position(val x: Int, val y: Int) { fun plus(action: ActionWithMagnitude) = when(action.submarineAction) { SubmarineAction.Forward -> Position(x + action.magnitude, y) SubmarineAction.Down -> Position(x, y + action.magnitude) SubmarineAction.Up -> Position(x, y - action.magnitude) } } data class SubmarineData( val position: Position, val aim: Int, ) { fun plus(action: ActionWithMagnitude) = when(action.submarineAction) { SubmarineAction.Forward -> copy( position = position.copy( x = position.x + action.magnitude, y = position.y + (aim * action.magnitude) ) ) SubmarineAction.Down -> copy(aim = aim + action.magnitude) SubmarineAction.Up -> copy(aim = aim - action.magnitude) } } fun solveDay02Part1(input: List<String>): Int { return input .map(ActionWithMagnitude::fromInput) .fold(Position(0, 0), Position::plus) .let { position -> position.x * position.y } } fun solveDay02Part2(input: List<String>): Int { return input .map(ActionWithMagnitude::fromInput) .fold(SubmarineData(Position(0, 0), 0), SubmarineData::plus) .let { submarineData -> submarineData.position.x * submarineData.position.y } }
0
Kotlin
0
0
a2dad83d8c17a2e75dcd00651c5c6ae6691e881e
2,222
advent-of-code-2021
Apache License 2.0
src/Day03.kt
Redstonecrafter0
571,787,306
false
{"Kotlin": 19087}
fun main() { fun prioritize(common: List<Char>): Int { return common.sumOf { if (it in 'a'..'z') { it - 'a' + 1 } else { it - 'A' + 27 } } } fun part1(input: List<String>): Int { val rucksacks = input.map { it.substring(0, it.length / 2) to it.substring(it.length / 2, it.length) } val common = rucksacks.map { (first, second) -> for (i in first) { if (i in second) { return@map i } } error("no common item") } return prioritize(common) } fun part2(input: List<String>): Int { val groups = input.chunked(3) val common = groups.map { for (i in it[0]) { if (i in it[1] && i in it[2]) { return@map i } } error("no common item") } return prioritize(common) } // test if implementation meets criteria from the description, like: val testInput = readInput("Day03_test") check(part1(testInput) == 157) check(part2(testInput) == 70) val input = readInput("Day03") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
e5dbabe247457aabd6dd0f0eb2eb56f9e4c68858
1,283
Advent-of-Code-2022
Apache License 2.0
src/Day03.kt
akunowski
573,109,101
false
{"Kotlin": 5413}
fun main() { fun compartmentsItems(items: String): Pair<Set<Char>, Set<Char>> { val leftCompartment = HashSet<Char>() val rightCompartment = HashSet<Char>() for (i: Int in 0 until items.length / 2) { leftCompartment.add(items[i]) rightCompartment.add(items[items.length - i - 1]) } return leftCompartment to rightCompartment } fun priority(it: Char): Int = if (it.isLowerCase()) it - 'a' + 1 else it - 'A' + 27 fun priority(it: Set<Char>): Int = it.sumOf { priority(it) } fun intersectAll(it: List<Set<Char>>): Set<Char> = it.reduce { first, second -> first intersect second } fun part1(input: List<String>): Int = input .map { compartmentsItems(it) } .map { it.first intersect it.second } .sumOf { priority(it) } fun part2(input: List<String>): Int = input .map { compartmentsItems(it) } .map { it.first + it.second } .windowed(3, 3) { intersectAll(it) } .sumOf { priority(it) } val input = readInput("inputs/day3") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
b306b779386c793f5bf9d8a86a59a7d0755c6159
1,223
aoc-2022
Apache License 2.0
src/year2022/day05/Day05.kt
kingdongus
573,014,376
false
{"Kotlin": 100767}
package year2022.day05 import partitionBy import readInputFileByYearAndDay import readTestFileByYearAndDay fun main() { fun moveCrates(input: List<String>, multipleAtOnce: Boolean = false): Array<String> { val cratesAndInstructions = input.partitionBy { it.isBlank() } val initialCrates = cratesAndInstructions.first() val numStacks = initialCrates.last().split(" ").last().toInt() val workspace: Array<String> = Array(numStacks) { "" } // we treat piles of crates as single strings initialCrates .dropLast(1)// excludes numberings .map { it.chunked(4) } .forEach { it.forEachIndexed { index, s -> if (s.isNotBlank()) workspace[index] = workspace[index] + s[1] } } // process instructions cratesAndInstructions.last() .map { Regex("[0-9]+").findAll(it) } .map { it.map { v -> v.value } } .map { it.toList() } .map { it.map { i -> i.toInt() } }.toList() .forEach { val count = it[0] val from = it[1] - 1 val to = it[2] - 1 val toMove = if (multipleAtOnce) workspace[from].take(count) else workspace[from].take(count).reversed() // one-at-a-time reverses the order workspace[from] = workspace[from].drop(count) workspace[to] = toMove + workspace[to] } return workspace } fun part1(input: List<String>): String = moveCrates(input).map { it.first() }.joinToString(separator = "") fun part2(input: List<String>): String = moveCrates(input, multipleAtOnce = true).map { it.first() }.joinToString(separator = "") val testInput = readTestFileByYearAndDay(2022, 5) check(part1(testInput) == "CMZ") check(part2(testInput) == "MCD") val input = readInputFileByYearAndDay(2022, 5) println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
aa8da2591310beb4a0d2eef81ad2417ff0341384
2,025
advent-of-code-kotlin
Apache License 2.0
src/main/kotlin/day11/Day11.kt
jankase
573,187,696
false
{"Kotlin": 70242}
package day11 import Day import extractAllIntegers import extractAllLongs import lcm import product import solve typealias WorryLevel = Long fun String.toWorryLevel(): WorryLevel? = toLongOrNull() infix fun WorryLevel.divisibleBy(divisor: Int) = this % divisor == 0L class Day11 : Day(11, 2022, "Monkey in the Middle") { private val monkeys = inputAsGroups.mapIndexed(::createMonkeyIndexed) private val startItems: List<List<WorryLevel>> = inputAsGroups.map { it[1].extractAllLongs() } private val commonModulus = monkeys.map { it.testDivisor }.lcm().toInt() private fun playWithItemWorryLevel(monkey: Monkey, worryLevel: WorryLevel): MonkeyPlayResult { val newWorryLevel = monkey.inspectionOperation(worryLevel) / 3 val throwTo = if (newWorryLevel divisibleBy monkey.testDivisor) monkey.ifTrueDestinationID else monkey.ifFalseDestinationID return MonkeyPlayResult(newWorryLevel, throwTo) } private fun playWithItemWorryLevelWithoutLimits(monkey: Monkey, worryLevel: WorryLevel): MonkeyPlayResult { val newWorryLevel = monkey.inspectionOperation(worryLevel) % commonModulus val throwTo = if (newWorryLevel divisibleBy monkey.testDivisor) monkey.ifTrueDestinationID else monkey.ifFalseDestinationID return MonkeyPlayResult(newWorryLevel, throwTo) } private fun letMonkeysPlay(rounds: Int, playOperation: (Monkey, WorryLevel) -> MonkeyPlayResult): IntArray { val inspections = IntArray(monkeys.size) val currentState = startItems.map { it.toMutableList() } repeat(rounds) { monkeys.zip(currentState).forEach { (monkey, currentlyHolds) -> currentlyHolds.forEach { val (newLevel, toMonkey) = playOperation(monkey, it) currentState[toMonkey] += newLevel } inspections[monkey.id] += currentlyHolds.size currentlyHolds.clear() } } return inspections } private fun createMonkeyIndexed(index: Int, description: List<String>): Monkey { val (operation, test, ifTrue, ifFalse) = description.drop(2) return Monkey( index, createOperation(operation.substringAfter("new = ")), test.extractAllIntegers().single(), ifTrue.extractAllIntegers().single(), ifFalse.extractAllIntegers().single(), ) } private fun createOperation(input: String): (WorryLevel) -> WorryLevel { val (_, operator, operand) = input.split(" ") return when (operator) { "+" -> { old -> old + (operand.toWorryLevel() ?: old) } "*" -> { old -> old * (operand.toWorryLevel() ?: old) } else -> error(input) } } override fun part1(): Long { val inspections = letMonkeysPlay(20, ::playWithItemWorryLevel) return inspections.sortedDescending().take(2).product() } override fun part2(): Long { val inspections = letMonkeysPlay(10000, ::playWithItemWorryLevelWithoutLimits) return inspections.sortedDescending().take(2).product() } } fun main() { solve<Day11> { day11DemoInput part1 10605 part2 2713310158 } } private val day11DemoInput = """ Monkey 0: Starting items: 79, 98 Operation: new = old * 19 Test: divisible by 23 If true: throw to monkey 2 If false: throw to monkey 3 Monkey 1: Starting items: 54, 65, 75, 74 Operation: new = old + 6 Test: divisible by 19 If true: throw to monkey 2 If false: throw to monkey 0 Monkey 2: Starting items: 79, 60, 97 Operation: new = old * old Test: divisible by 13 If true: throw to monkey 1 If false: throw to monkey 3 Monkey 3: Starting items: 74 Operation: new = old + 3 Test: divisible by 17 If true: throw to monkey 0 If false: throw to monkey 1 """.trimIndent()
0
Kotlin
0
0
0dac4ec92c82a5ebb2179988fb91fccaed8f800a
3,905
adventofcode2022
Apache License 2.0
src/main/kotlin/dev/bogwalk/batch6/Problem68.kt
bog-walk
381,459,475
false
null
package dev.bogwalk.batch6 import dev.bogwalk.util.combinatorics.permutations /** * Problem 68: Magic 5-Gon Ring * * https://projecteuler.net/problem=68 * * Goal: Given N, representing a magic N-gon ring, and S, representing the total to which each * ring's line sums, return all concatenated strings (in lexicographic order) representing the N * sets of solutions. * * Constraints: 3 <= N <= 10 * * Magic 3-Gon Ring (as seen in above link): The ring has 3 external nodes, each ending a line of * 3 nodes (6 nodes total representing digits 1 to 6). The ring can be completed so the lines * reach 4 different totals, [9, 12], so there are 8 solutions in total: * 9 -> [{4,2,3}, {5,3,1}, {6,1,2}], [{4,3,2}, {6,2,1}, {5,1,3}] * 10 -> [{2,3,5}, {4,5,1}, {6,1,3}], [{2,5,3}, {6,3,1}, {4,1,5}] * 11 -> [{1,4,6}, {3,6,2}, {5,2,4}], [{1,6,4}, {5,4,2}, {3,2,6}] * 12 -> [{1,5,6}, {2,6,4}, {3,4,5}], [{1,6,5}, {3,5,4}, {2,4,6}] * So the maximum concatenated string for a magic 3-gon is "432621513". * * e.g.: N = 3, S = 9 * solutions = ["423531612", "432621513"] */ class Magic5GonRing { /** * Project Euler specific implementation that requests the maximum 16-digit string solution * from all solutions for a magic 5-gon ring that uses numbers 1 to 10 in its nodes. * * For the solution to have 16 digits, the number 10 has to be an external node, as, if it * were placed on the internal ring, it would be used by 2 unique lines & would create a * 17-digit concatenation. So, at minimum, the line with 10 as an external node will sum to 13. * * To create the largest lexicographic concatenation, larger numbers ideally should be placed * first. Based on the magic 3-gon ring example detailed in the problem description, if the * largest numbers are external nodes and the smallest numbers are ring nodes, the maximum * solution occurs at the lowest total achieved by the following: * * (externalNodes.sum() + 2 * internalNodes.sum()) / N * * e.g. ([4, 5, 6].sum() + 2 * [1, 2, 3].sum()) / 3 = 9 * * The maximum solution indeed occurs when S = 14 with the largest numbers on the external * nodes, but all totals up to 27 were explored given the speed of the recursive solution below. * * N.B. Solutions exist for the following totals: [14, 16, 17, 19]. */ fun maxMagic5GonSolution(): String { val solutions = mutableListOf<List<String>>() for (s in 13..27) { val solution = magicRingSolutionsOptimised(5, s) if (solution.isNotEmpty()) { solutions.add(solution) } } return solutions.flatten().filter { it.length == 16 }.sortedDescending()[0] } /** * Solution uses recursion to search through all permutations ([n] * 2 digits choose 3) from an * increasingly smaller set of remaining digits. Permutations are checked to see if they sum * to [s] & if their middle digit matches the last digit of the permutation found previously. * * A stack of the remaining digits to use is cached so the search can continue if a solution * that cannot close the ring is reached. This is done by adding the elements of the last * permutation back to the stack if the solution becomes invalid. * * Rather than searching for a final permutation that completes the ring, the expected list is * generated based on the remaining digits possible & checked to see if it complements the * starter list & adds up to [s]. * * SPEED (WORST) 1.57s for N = 7, S = 23 */ fun magicRingSolutions(n: Int, s: Int): List<String> { val solutions = mutableListOf<String>() val allDigits = (1..n * 2).toMutableSet() fun nextRingLine(solution: MutableList<List<Int>>) { if (allDigits.size == 2) { val expected = listOf( (allDigits - setOf(solution.last()[2])).first(), solution.last()[2], solution[0][1] ) if (expected[0] > solution[0][0] && expected.sum() == s) { solutions.add( solution.flatten().joinToString("") + expected.joinToString("") ) } } else { for (perm in permutations(allDigits, 3)) { if ( perm[1] != solution.last()[2] || perm[0] < solution[0][0] || perm.sum() != s ) continue solution.add(perm) allDigits.removeAll(perm.toSet() - setOf(perm[2])) nextRingLine(solution) } } allDigits.addAll(solution.removeLast()) } // starter must have the lowest external node, which limits the digits it can have val starterMax = n * 2 - n + 1 for (starter in permutations(allDigits, 3)) { if (starter[0] > starterMax || starter.sum() != s) continue allDigits.removeAll(starter.toSet() - setOf(starter[2])) nextRingLine(mutableListOf(starter)) allDigits.clear() allDigits.addAll((1..n * 2).toMutableSet()) } return solutions.sorted() } /** * While still using recursion, the solution is optimised by not generating all permutations * of 3-digit lines. Instead, nodes on the internal ring alone are recursively generated from * an increasingly smaller set of available digits and the corresponding external node for * every pair of ring nodes is calculated. * * SPEED (BETTER) 66.16ms for N = 7, S = 23 */ fun magicRingSolutionsImproved(n: Int, s: Int): List<String> { val solutions = mutableListOf<String>() val allDigits = (1..n * 2) val remainingDigits = allDigits.toMutableSet() val ringNodes = IntArray(n) val externalNodes = IntArray(n) fun nextRingNode(i: Int) { if (i == n - 1) { externalNodes[i] = s - ringNodes[i] - ringNodes[0] if ( externalNodes[i] in remainingDigits && // first external node must be smallest of all external nodes externalNodes[0] == externalNodes.minOrNull() ) { var solution = "" for (j in 0 until n) { solution += "${externalNodes[j]}${ringNodes[j]}${ringNodes[(j+1)%n]}" } solutions.add(solution) } } else { for (digit in allDigits) { if (digit !in remainingDigits) continue val nextExternal = s - ringNodes[i] - digit if (nextExternal == digit || nextExternal !in remainingDigits) continue ringNodes[i+1] = digit externalNodes[i] = nextExternal val justUsed = setOf(digit, nextExternal) remainingDigits.removeAll(justUsed) nextRingNode(i + 1) // solution found or not; either way backtrack to try a different ring node remainingDigits.addAll(justUsed) } } } for (digit in allDigits) { ringNodes[0] = digit remainingDigits.remove(digit) nextRingNode(0) // solutions found or not; either way backtrack to start ring with a novel node remainingDigits.clear() remainingDigits.addAll(allDigits.toMutableSet()) } return solutions.sorted() } /** * This solution is identical to the above improved solution but cuts speed in half by taking * advantage of the pattern that all solutions present in pairs. * * e.g. when N = 4, S = 12, the 1st solution will be found when the starter digit = 2, with * * ringNodes = [2, 6, 1 ,3] and externalNodes = [4, 5, 8, 7] -> "426561813732" * * If the 1st 2 elements of ringNodes are swapped & the rest reversed, and all elements of * externalNodes, except the static lowest external, are also reversed, the arrays become: * * ringNodes = [6, 2, 3, 1] and externalNodes = [4, 7, 8, 5] -> "462723831516" * * This latter solution would have been eventually found when the starter digit = 6. * * Instead, any duplicate searches are eliminated by reversing all solutions when found & not * allowing starter digits to explore adjacent ring digits that are smaller (as these would * already have been found by previous iterations). So the starter digit 6 would only end up * searching through ringNodes = [6, [7, 12], X, X] * * Lastly, neither digit 1 nor digit n need to be assessed as they will be found in later or * earlier iterations. * * SPEED (BEST) 36.84ms for N = 7, S = 23 */ fun magicRingSolutionsOptimised(n: Int, s: Int): List<String> { val solutions = mutableListOf<String>() val allDigits = (1..n * 2) val remainingDigits = allDigits.toMutableSet() val ringNodes = IntArray(n) val externalNodes = IntArray(n) fun nextRingNode(i: Int) { if (i == n - 1) { externalNodes[i] = s - ringNodes[i] - ringNodes[0] if ( externalNodes[i] in remainingDigits && externalNodes[0] == externalNodes.minOrNull() ) { var solution1 = "" var solution2 = "" for (j in 0 until n) { solution1 += "${externalNodes[j]}${ringNodes[j]}${ringNodes[(j+1)%n]}" solution2 += "${externalNodes[(n-j)%n]}${ringNodes[(n-j+1)%n]}${ringNodes[(n-j)%n]}" } solutions.add(solution1) solutions.add(solution2) } } else { val searchRange = if (i == 0) (ringNodes[0] + 1)..(n * 2) else allDigits for (digit in searchRange) { if (digit !in remainingDigits) continue val nextExternal = s - ringNodes[i] - digit if (nextExternal == digit || nextExternal !in remainingDigits) continue ringNodes[i+1] = digit externalNodes[i] = nextExternal val justUsed = setOf(digit, nextExternal) remainingDigits.removeAll(justUsed) nextRingNode(i + 1) remainingDigits.addAll(justUsed) } } } for (digit in 2 until n * 2) { ringNodes[0] = digit remainingDigits.remove(digit) nextRingNode(0) remainingDigits.clear() remainingDigits.addAll(allDigits.toMutableSet()) } return solutions.sorted() } }
0
Kotlin
0
0
62b33367e3d1e15f7ea872d151c3512f8c606ce7
11,230
project-euler-kotlin
MIT License
src/Day09.kt
oleksandrbalan
572,863,834
false
{"Kotlin": 27338}
import kotlin.math.abs fun main() { val input = readInput("Day09") .filterNot { it.isEmpty() } .map { val (direction, count) = it.split(" ") List(count.toInt()) { direction } } .flatten() val part1Rope = Array(2) { Coordinate(0, 0) } val part1Positions = part1Rope.move(input) val part1 = part1Positions.toSet().size println("Part1: $part1") val part2Rope = Array(10) { Coordinate(0, 0) } val part2Positions = part2Rope.move(input) val part2 = part2Positions.toSet().size println("Part2: $part2") } private fun Array<Coordinate>.move(directions: List<String>): List<Coordinate> { val tailPositions = mutableListOf<Coordinate>() tailPositions.add(last()) directions.forEach { direction -> this[0] = this[0].move(direction) (1 until size).forEach { this[it] = this[it].keepUp(this[it - 1]) } tailPositions.add(last()) } return tailPositions } private fun Coordinate.move(direction: String): Coordinate = when (direction) { "L" -> Coordinate(x - 1, y) "R" -> Coordinate(x + 1, y) "U" -> Coordinate(x, y + 1) "D" -> Coordinate(x, y - 1) else -> error("Direction is not supported: $direction") } private fun Coordinate.keepUp(head: Coordinate): Coordinate { val dx = head.x - x val dy = head.y - y if (abs(dx) <= 1 && abs(dy) <= 1) return this return Coordinate(x + dx.coerceIn(-1, 1), y + dy.coerceIn(-1, 1)) } private data class Coordinate(val x: Int, val y: Int)
0
Kotlin
0
2
1493b9752ea4e3db8164edc2dc899f73146eeb50
1,588
advent-of-code-2022
Apache License 2.0
src/Day14.kt
iam-afk
572,941,009
false
{"Kotlin": 33272}
import kotlin.math.max import kotlin.math.min fun main() { class Rocks(input: List<String>) { private val horizontal: Map<Int, List<IntRange>> private val vertical: Map<Int, List<IntRange>> val maxY: Int init { val h = mutableMapOf<Int, MutableList<IntRange>>() val v = mutableMapOf<Int, MutableList<IntRange>>() var maxY = 0 for (line in input) { for ((p1, p2) in line.split(",", " -> ").map { it.toInt() }.chunked(2).windowed(2)) { val (x1, y1) = p1 val (x2, y2) = p2 if (y1 == y2) { h.computeIfAbsent(y1) { mutableListOf() } += min(x1, x2)..max(x1, x2) } else if (x1 == x2) { v.computeIfAbsent(x1) { mutableListOf() } += min(y1, y2)..max(y1, y2) } maxY = max(maxY, y1) maxY = max(maxY, y2) } } h.put(maxY + 2, mutableListOf(Int.MIN_VALUE..Int.MAX_VALUE)) this.horizontal = h this.vertical = v this.maxY = maxY } private val sands = mutableSetOf<Pair<Int, Int>>() fun isEmpty(x: Int, y: Int): Boolean = x to y !in sands && horizontal.getOrDefault(y, emptyList()).none { x in it } && vertical.getOrDefault(x, emptyList()).none { y in it } private fun addSand(x: Int, y: Int) { sands += x to y } fun simulate(condition: Rocks.(Int, Int) -> Boolean): Int { var count = 0 while (true) { var (x, y) = 500 to 0 while (condition(x, y)) { when { isEmpty(x, y + 1) -> y += 1 isEmpty(x - 1, y + 1) -> { x -= 1; y += 1 } isEmpty(x + 1, y + 1) -> { x += 1; y += 1 } else -> { addSand(x, y) break } } } if (!condition(x, y)) return count count += 1 } } } fun part1(input: List<String>): Int = Rocks(input).simulate { _, y -> y < maxY } fun part2(input: List<String>): Int = Rocks(input).simulate { _, _ -> isEmpty(500, 0) } + 1 // test if implementation meets criteria from the description, like: val testInput = readInput("Day14_test") check(part1(testInput) == 24) check(part2(testInput) == 93) val input = readInput("Day14") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
b30c48f7941eedd4a820d8e1ee5f83598789667b
2,817
aockt
Apache License 2.0
src/main/java/com/ncorti/aoc2021/Exercise05.kt
cortinico
433,486,684
false
{"Kotlin": 36975}
package com.ncorti.aoc2021 import kotlin.math.max import kotlin.math.min object Exercise05 { private fun getInput() = getInputAsTest("05") { split("\n") }.map { it.split(",", " -> ").map(String::toInt) }.map { (i0, i1, i2, i3) -> if (i2 < i0) { listOf(i2, i3, i0, i1) } else { listOf(i0, i1, i2, i3) } } fun part1(): Int { val input = getInput() val size = input.maxOf { it.maxOrNull() ?: 0 } + 1 val grid = Array(size) { IntArray(size) { 0 } } input.forEach { if (it[0] == it[2]) { (min(it[1], it[3])..max(it[1], it[3])).forEach { i -> grid[i][it[0]] += 1 } } else if (it[1] == it[3]) { (it[0]..it[2]).forEach { i -> grid[it[1]][i] += 1 } } } return grid.sumOf { line -> line.count { it >= 2 } } } fun part2(): Int { val input = getInput() val size = input.maxOf { it.maxOrNull() ?: 0 } + 1 val grid = Array(size) { IntArray(size) { 0 } } input.forEach { (i0, i1, i2, i3) -> if (i0 == i2) { (min(i1, i3)..max(i1, i3)).forEach { i -> grid[i][i0] += 1 } } else if (i1 == i3) { (i0..i2).forEach { i -> grid[i1][i] += 1 } } else if (i0 < i2 && i1 < i3) { // Straight diagonal case (i0..i2).forEachIndexed { index, _ -> grid[i1 + index][i0 + index] += 1 } } else { // Inverse diagonal case (i0..i2).forEachIndexed { index, _ -> grid[i1 - index][i0 + index] += 1 } } } return grid.sumOf { line -> line.count { it >= 2 } } } } fun main() { println(Exercise05.part1()) println(Exercise05.part2()) }
0
Kotlin
0
4
af3df72d31b74857201c85f923a96f563c450996
1,846
adventofcode-2021
MIT License
2k23/aoc2k23/src/main/kotlin/05.kt
papey
225,420,936
false
{"Rust": 88237, "Kotlin": 63321, "Elixir": 54197, "Crystal": 47654, "Go": 44755, "Ruby": 24620, "Python": 23868, "TypeScript": 5612, "Scheme": 117}
package d05 import input.raw import java.util.concurrent.atomic.AtomicLong import kotlin.math.min import kotlin.streams.asStream fun main() { println("Part 1: ${part1(raw("05.txt").trim())}") println("Part 2: ${part2(raw("05.txt").trim())}") } fun part1(input: String): Long { val (seeds, maps) = parse(input) return seeds.minOf { seed -> findLocation(maps, seed) } } fun part2(input: String): Long { val (seeds, maps) = parse(input) val seedRanges = seeds.chunked(2).map { (start, range) -> start..<(start + range) } val result = AtomicLong(Long.MAX_VALUE) for (range in seedRanges) { range.asSequence().asStream().parallel().forEach { seed -> result.getAndAccumulate(findLocation(maps, seed), ::min) } } return result.get() } private fun findLocation(maps: List<List<MapRange>>, seed: Long) = maps.fold(seed) { s, map -> val match = map.find { s >= it.srcStart && s <= it.srcStart + it.length }?.let { it.dstStart + (s - it.srcStart) } match ?: s } private fun parse(input: String): Pair<List<Long>, List<List<MapRange>>> { val parts = input.split("\n\n") val seeds = parts[0].replace("seeds: ", "").split(" ").map { it.toLong() } val maps = parts.drop(1).map { map -> map.split("\n").drop(1).map { line -> val values = line.split(" ").filter { it.isNotBlank() }.map { it.toLong() } MapRange(values[1], values[0], values[2]) } } return Pair(seeds, maps) } class MapRange(val srcStart: Long, val dstStart: Long, val length: Long) {}
0
Rust
0
3
cb0ea2fc043ebef75aff6795bf6ce8a350a21aa5
1,620
aoc
The Unlicense
src/AoC19.kt
Pi143
317,631,443
false
null
import java.io.File fun main() { println("Starting Day 19 A Test 1") calculateDay19PartA("Input/2020_Day19_Rules_Test1", "Input/2020_Day19_A_Messages_Test1") println("Starting Day 19 A Real") calculateDay19PartA("Input/2020_Day19_Rules", "Input/2020_Day19_A_Messages") println("Starting Day 19 B Test 1") //calculateDay19PartB("Input/2020_Day19_A_Test1") println("Starting Day 19 B Real") calculateDay19PartA("Input/2020_Day19_Rules_B", "Input/2020_Day19_A_Messages") } fun calculateDay19PartA(ruleFile: String, messageFile: String): Int { var rules = readDay19Data(ruleFile) var messages = readDay19Data(messageFile) var ruleDepth = 10 var ruleMap = mutableMapOf<String, String>() for (rule in rules) { val ruleName = rule.split(": ")[0] val ruleDef = rule.split(": ")[1] ruleMap[ruleName] = ruleDef.removeSurrounding("\"") } for (i in 0 until ruleDepth) { var ruleName = "0" val ruleDef = ruleMap[ruleName]!! val singleRuleParts = ruleDef.split(" ") println(i) for (singleRulePartIterator in singleRuleParts) { val singleRulePart = singleRulePartIterator.replace("(","").replace(")","").replace("+","").replace("?","") if (singleRulePart != "|" && singleRulePart != "a" && singleRulePart != "b" && singleRulePart.isNotBlank()) { val singleRule = ruleMap[singleRulePart]!! ruleMap[ruleName] = ruleMap[ruleName]!!.replace("(?<=(^|\\())$singleRulePart(?=(\\+| |\\)))".toRegex(), "($singleRule) ") ruleMap[ruleName] = ruleMap[ruleName]!!.replace("(?<=( |\\())$singleRulePart(?=(\\+| |\\)))".toRegex(), " ($singleRule) ") ruleMap[ruleName] = ruleMap[ruleName]!!.replace("(?<=( |\\())$singleRulePart(?=(\\+|$|\\)))".toRegex(), " ($singleRule)") ruleMap[ruleName] = ruleMap[ruleName]!!.replace("(?<=(^|\\())$singleRulePart(?=(\\+|$|\\)))".toRegex(), "($singleRule)") } } } val allPossibilities = ruleMap["0"] println("$allPossibilities is the config for the valid regEx") var allSpacelessPossibilities = allPossibilities?.replace("\\s".toRegex(), "") println("$allSpacelessPossibilities is the valid regEx") var validMessages = 0 for (message in messages) { if (message.matches(allSpacelessPossibilities!!.toRegex())) { validMessages++ } } println("$validMessages are valid") return validMessages } fun calculateDay19PartB(file: String): Long { var calculations = readDay19Data(file) return -1 } fun readDay19Data(input: String): List<String> { return File(localdir + input).readLines() }
0
Kotlin
0
1
fa21b7f0bd284319e60f964a48a60e1611ccd2c3
2,727
AdventOfCode2020
MIT License
src/main/kotlin/ru/timakden/aoc/year2023/Day03.kt
timakden
76,895,831
false
{"Kotlin": 321649}
package ru.timakden.aoc.year2023 import ru.timakden.aoc.util.measure import ru.timakden.aoc.util.readInput /** * [Day 3: Gear Ratios](https://adventofcode.com/2023/day/3). */ object Day03 { @JvmStatic fun main(args: Array<String>) { measure { val input = readInput("year2023/Day03") println("Part One: ${part1(input)}") println("Part Two: ${part2(input)}") } } fun part1(input: List<String>): Int { val digits = "\\d+".toRegex() val partNumbers = mutableListOf<Int>() input.forEachIndexed { row, s -> val numbers = digits.findAll(s) .map { it.range to it.value.toInt() } .filter { (range, _) -> val adjacentCells = (range.first - 1..range.last + 1).flatMap { listOf(row - 1 to it, row to it, row + 1 to it) } adjacentCells.forEach { (x, y) -> runCatching { if (!input[x][y].isDigit() && input[x][y] != '.') return@filter true } } false } partNumbers += numbers.map { it.second } } return partNumbers.sum() } fun part2(input: List<String>): Int { val digits = "\\d+".toRegex() val numbersWithCoordinates = input.flatMapIndexed { row, s -> digits.findAll(s).map { (row to it.range) to it.value.toInt() } }.toMap() val gearRatios = mutableListOf<Int>() input.forEachIndexed { row, s -> val asteriskIndexes = s.mapIndexedNotNull { index: Int, c: Char -> if (c == '*') index else null } asteriskIndexes.forEach { index -> val adjacentNumbers = numbersWithCoordinates.filterKeys { (x, range) -> x in row - 1..row + 1 && range.any { it in index - 1..index + 1 } } if (adjacentNumbers.values.size == 2) { gearRatios += adjacentNumbers.values.fold(1) { acc, i -> i * acc } } } } return gearRatios.sum() } }
0
Kotlin
0
3
acc4dceb69350c04f6ae42fc50315745f728cce1
2,213
advent-of-code
MIT License
src/year2022/day16/Solution.kt
TheSunshinator
572,121,335
false
{"Kotlin": 144661}
package year2022.day16 import io.kotest.matchers.shouldBe import java.util.LinkedList import kotlin.math.ceil import utils.Graph import utils.Identifiable import utils.Identifier import utils.cartesianProduct import utils.combinations import utils.findShortestRoute import utils.readInput fun main() { val testInput = readInput("16", "test_input").parseGraph().simplify() val realInput = readInput("16", "input").parseGraph().simplify() findOptimalRoute(testInput, 30) .also(::println) shouldBe 1651 findOptimalRoute(realInput, 30) .let(::println) findOptimalTeamWork(testInput) .also(::println) shouldBe 1707 findOptimalTeamWork(realInput) .let(::println) } private fun List<String>.parseGraph(): Graph<Valve> { val valveToNeighborIds = asSequence() .mapNotNull(parsingRegex::matchEntire) .map { it.destructured } .associate { (identifier, flowRate, multipleNeighbors, singleNeighbor) -> Valve( identifier = Identifier(identifier), flowRate = flowRate.toInt() ) to identifierRegex.findAll(multipleNeighbors.ifEmpty { singleNeighbor }) .map { it.value } .mapTo(mutableSetOf(), ::Identifier) } return Graph( nodes = valveToNeighborIds.keys, neighbors = valveToNeighborIds.mapKeys { it.key.identifier }, costs = valveToNeighborIds.flatMap { (valve, neighbors) -> neighbors.map { valve.identifier to it to 1L } }.toMap() ) } private fun Graph<Valve>.simplify(): Graph<Valve> { val valveWithFlows = nodes.filterTo(mutableSetOf()) { it.flowRate > 0 || it.identifier.value == "AA" } return Graph( nodes = valveWithFlows, neighbors = valveWithFlows.associate { valve -> valve.identifier to valveWithFlows.asSequence() .filterNot { it.identifier == valve.identifier } .mapTo(mutableSetOf()) { it.identifier } }, costs = valveWithFlows.asSequence() .map { it.identifier } .let { it.cartesianProduct(it) } .mapNotNull { (start, end) -> findShortestRoute(this, start, end) } .associate { metadata -> metadata.route.let { it.first() to it.last() } to metadata.cost.toLong() }, ) } private val parsingRegex = "\\AValve ([A-Z]{2}) has flow rate=(\\d+)(?:; tunnels lead to valves ([A-Z]{2}(?:, [A-Z]{2})+)|; tunnel leads to valve ([A-Z]{2}))\\z".toRegex() private val identifierRegex = "[A-Z]{2}".toRegex() private data class Valve( override val identifier: Identifier, val flowRate: Int, ) : Identifiable private fun findOptimalRoute( input: Graph<Valve>, maxCycles: Int, ): Int { val (start, toVisit) = input.nodes.partition { it.identifier.value == "AA" } val metadataQueue = LinkedList<SearchMetadata>() .apply { add(SearchMetadata(start, maxCycles, emptyMap(), toVisit.toSet())) } return generateSequence { metadataQueue.poll() } .flatMap { currentSearchMetadata -> val origin = currentSearchMetadata.path.last() currentSearchMetadata.unreleasedValves .asSequence() .mapNotNull { destination -> val movementCost = input.cost(origin, destination).toInt() val releaseCycle = currentSearchMetadata.currentCycle + movementCost + 1 if (releaseCycle >= maxCycles) null else SearchMetadata( path = currentSearchMetadata.path + destination, maxCycles = maxCycles, releaseCycles = currentSearchMetadata.releaseCycles + (destination to releaseCycle), unreleasedValves = currentSearchMetadata.unreleasedValves - destination, ) } .ifEmpty { sequenceOf(currentSearchMetadata.copy(unreleasedValves = emptySet())) } } .filter { routeMetadata -> val isDone = routeMetadata.unreleasedValves.isEmpty() if (!isDone) metadataQueue.add(routeMetadata) isDone } .maxOf { it.totalReleased } } private data class SearchMetadata( val path: List<Valve>, val maxCycles: Int, val releaseCycles: Map<Valve, Int>, val unreleasedValves: Set<Valve>, ) { val totalReleased = releaseCycles.asSequence().fold(0) { total, (valve, cycleReleased) -> val valveTotalRelease = (maxCycles - cycleReleased) * valve.flowRate total + valveTotalRelease } val currentCycle = releaseCycles.getOrDefault(path.last(), 0) } private fun findOptimalTeamWork(input: Graph<Valve>): Int { val start = input.nodes.first { it.identifier.value == "AA" } val maxNodeCount = ceil(input.nodes.size / 2.0).toInt() val minNodeCount = maxNodeCount / 2 return input.nodes .filterNot { it == start } .run { (minNodeCount..maxNodeCount).asSequence() .flatMap { size -> combinations(size) } } .map { myValves -> val associateValves = input.nodes - myValves.toSet() + start input.copy(nodes = myValves + start) to input.copy(nodes = associateValves) } .maxOf { (myValves, assistantValve) -> findOptimalRoute(myValves, 26) + findOptimalRoute(assistantValve, 26) } }
0
Kotlin
0
0
d050e86fa5591447f4dd38816877b475fba512d0
5,474
Advent-of-Code
Apache License 2.0
advent2021/src/main/kotlin/year2021/Day04.kt
bulldog98
572,838,866
false
{"Kotlin": 132847}
package year2021 import AdventDay import year2021.day04.Board import year2021.day04.toGameInput private fun Board.isWinning(drawn: Collection<Int>): Boolean { val rowIsWinning = rows.any { row -> row.cells.count { drawn.contains(it) } == 5 } val columnIsWinning = columns.any { column -> column.count { drawn.contains(it) } == 5 } return rowIsWinning || columnIsWinning } private fun Board.score(lastNumber: Int, drawn: Collection<Int>) = lastNumber * cells.filter { !drawn.contains(it) }.sum() object Day04 : AdventDay(2021, 4) { override fun part1(input: List<String>): Int { val gameInput = input.toGameInput() val (drawn, last) = gameInput.drawnNumbers .scan(setOf<Int>() to -1) { (acc, _), curr -> acc + curr to curr } .first { (drawn) -> gameInput.boards.any { it.isWinning(drawn) } } val winningBoard = gameInput.boards.find { it.isWinning(drawn) } ?: throw Error("no winning board found") return winningBoard.score(last, drawn) } override fun part2(input: List<String>): Int { val gameInput = input.toGameInput() val (drawn, _, last) = gameInput.drawnNumbers .scan(Triple(setOf<Int>(),-1, -1)) { (acc, _, last), curr -> Triple(acc + curr, last, curr) } .first { (drawn) -> gameInput.boards.none { !it.isWinning(drawn) } } val losingBoard = gameInput.boards.find { !it.isWinning(drawn - last) } ?: throw Error("no losing board found") return losingBoard.score(last, drawn) } } fun main() = Day04.run()
0
Kotlin
0
0
02ce17f15aa78e953a480f1de7aa4821b55b8977
1,671
advent-of-code
Apache License 2.0
2022/src/day02/Day02.kt
scrubskip
160,313,272
false
{"Kotlin": 198319, "Python": 114888, "Dart": 86314}
package day02 import java.io.File fun main() { val input = File("src/day02/day2input.txt").readLines() println(input.sumOf { calculateScore(it) }) println(input.sumOf { calculateSecretScore(it) }) } fun getWinTable(): Map<String, Int> { return mapOf( "A X" to 0, "A Y" to 1, "A Z" to -1, "B X" to -1, "B Y" to 0, "B Z" to 1, "C X" to 1, "C Y" to -1, "C Z" to 0 ) } fun getMatchTable(): Map<String, String> { return mapOf( "A X" to "Z", "A Y" to "X", "A Z" to "Y", "B X" to "X", "B Y" to "Y", "B Z" to "Z", "C X" to "Y", "C Y" to "Z", "C Z" to "X" ) } /** * Parses "[A,B,C] [X, Y, Z]" into a pair */ fun parseMatch(input: String): Pair<String, String> { val match = input.split(" ") return Pair(match[0], match[1]) } fun calculateScore(match: String): Int { val (opponent, player) = parseMatch(match) return calculatePlayerScore(match, player) } fun calculateSecretScore(match: String): Int { val (opponent, outcome) = parseMatch(match) val player = getMatchTable().getOrDefault(match, "") return calculatePlayerScore("$opponent $player", player); } fun calculatePlayerScore(match: String, player: String): Int { val playScore = when (player) { "X" -> 1 "Y" -> 2 "Z" -> 3 else -> throw Exception("invalid player value $player") } return playScore + ((getWinTable().getOrDefault(match, 0) + 1) * 3) }
0
Kotlin
0
0
a5b7f69b43ad02b9356d19c15ce478866e6c38a1
1,553
adventofcode
Apache License 2.0
src/Day04.kt
Redstonecrafter0
571,787,306
false
{"Kotlin": 19087}
fun main() { fun part1(input: List<String>): Int { return input .map { it.split(",").map { i -> i.split("-").map { j -> j.toInt() } } } .map { it.map { i -> i[0]..i[1] } } .map { it[0] to it[1] } .count { (first, second) -> (first.first in second && first.last in second) || (second.first in first && second.last in first) } } fun part2(input: List<String>): Int { return input .map { it.split(",").map { i -> i.split("-").map { j -> j.toInt() } } } .map { it.map { i -> i[0]..i[1] } } .map { it[0] to it[1] } .count { (first, second) -> first.first in second || first.last in second || second.first in first || second.last in first } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day04_test") check(part1(testInput) == 2) check(part2(testInput) == 4) val input = readInput("Day04") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
e5dbabe247457aabd6dd0f0eb2eb56f9e4c68858
1,097
Advent-of-Code-2022
Apache License 2.0
kotlin/src/main/kotlin/year2021/Day06.kt
adrisalas
725,641,735
false
{"Kotlin": 130217, "Python": 1548}
package year2021 private fun solve(input: String, days: Int): Long { val lanternFishes = lanternFishes(input) simulateDays(lanternFishes, days) return lanternFishes.countLanterfishs() } private fun part1(input: String): Long { return solve(input, 80) } private fun part2(input: String): Long { return solve(input, 256) } private fun lanternFishes(input: String): MutableMap<Int, Long> { val lanternFishes: MutableMap<Int, Long> = HashMap() input .split(",") .map { Integer.valueOf(it) } .forEach { lanternFishes[it] = lanternFishes.getOrDefault(it, 0) + 1 } return lanternFishes } private fun MutableMap<Int, Long>.countLanterfishs(): Long { return this.values.fold(0L) { acc, i -> acc + i } } private fun simulateDays(lanternfishs: MutableMap<Int, Long>, days: Int) { for (i in 0 until days) { val reproduced: Long = lanternfishs.getOrDefault(0, 0L) lanternfishs[0] = lanternfishs.getOrDefault(1, 0L) lanternfishs[1] = lanternfishs.getOrDefault(2, 0L) lanternfishs[2] = lanternfishs.getOrDefault(3, 0L) lanternfishs[3] = lanternfishs.getOrDefault(4, 0L) lanternfishs[4] = lanternfishs.getOrDefault(5, 0L) lanternfishs[5] = lanternfishs.getOrDefault(6, 0L) lanternfishs[6] = lanternfishs.getOrDefault(7, 0L) + reproduced lanternfishs[7] = lanternfishs.getOrDefault(8, 0L) lanternfishs[8] = reproduced } } fun main() { val testInput = readInput("Day06_test")[0] check(solve(testInput, 18).toInt() == 26) val input = readInput("Day06")[0] println(part1(input)) println(part2(input)) }
0
Kotlin
0
2
6733e3a270781ad0d0c383f7996be9f027c56c0e
1,668
advent-of-code
MIT License
src/Day02.kt
kipwoker
572,884,607
false
null
enum class Figure(val score: Int) { Rock(1), Paper(2), Scissors(3) } fun main() { fun createFigure(value: String): Figure { return when (value) { "A" -> Figure.Rock "B" -> Figure.Paper "C" -> Figure.Scissors "X" -> Figure.Rock "Y" -> Figure.Paper "Z" -> Figure.Scissors else -> throw Exception("Value unsupported $value") } } fun compare(f1: Figure, f2: Figure): Int { if (f1 == f2) { return 3 } if ( f1 == Figure.Paper && f2 == Figure.Scissors || f1 == Figure.Rock && f2 == Figure.Paper || f1 == Figure.Scissors && f2 == Figure.Rock ) { return 6 } return 0 } fun readTurns(lines: List<String>): List<Pair<Figure, Figure>> { return lines.map { val parts = it.split(' ') Pair(createFigure(parts[0]), createFigure(parts[1])) } } fun createFigure2(first: Figure, value: String): Figure { if (value == "Y") { return first } if (value == "X") { return when (first) { Figure.Rock -> Figure.Scissors Figure.Paper -> Figure.Rock Figure.Scissors -> Figure.Paper } } return when (first) { Figure.Rock -> Figure.Paper Figure.Paper -> Figure.Scissors Figure.Scissors -> Figure.Rock } } fun readTurns2(lines: List<String>): List<Pair<Figure, Figure>> { return lines.map { val parts = it.split(' ') val first = createFigure(parts[0]) Pair(first, createFigure2(first, parts[1])) } } fun play(turns: List<Pair<Figure, Figure>>): Long { var result = 0L turns.map { compare(it.first, it.second) + it.second.score }.forEach { result += it } return result } fun part1(input: List<String>): Long { return play(readTurns(input)) } fun part2(input: List<String>): Long { return play(readTurns2(input)) } // test if implementation meets criteria from the description, like: val testInput = readInput("Day02_test") check(part1(testInput) == 15L) check(part2(testInput) == 12L) val input = readInput("Day02") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
d8aeea88d1ab3dc4a07b2ff5b071df0715202af2
2,496
aoc2022
Apache License 2.0
src/main/kotlin/day3.kt
noamfree
433,962,392
false
{"Kotlin": 93533}
private val testInput1 = """ 00100 11110 10110 10111 10101 01111 00111 11100 10000 11001 00010 01010 """.trimIndent() private fun tests() { assertEquals(gammaRate(parseInput(testInput1)), "10110") assertEquals(gammaRateDecimal(parseInput(testInput1)), 22) assertEquals(epsilonRate(parseInput(testInput1)), "01001") assertEquals(epsilonRateDecimal(parseInput(testInput1)), 9) assertEquals(part1(testInput1), 198) assertEquals(oxygenRating(parseInput(testInput1)), 23) assertEquals(co2Rating(parseInput(testInput1)), 10) } private fun main() { tests() val input = readInputFile("input3") println("part 1:") println(part1(input)) println("part 2:") println(part2(input)) println() println("day3") } private fun part1(input: String): Int { val numbers = parseInput(input) return gammaRateDecimal(numbers) * epsilonRateDecimal(numbers) } private fun parseInput(input: String): List<String> { return input.lines() } fun epsilonRateDecimal(numbers: List<String>): Int = epsilonRate(numbers).toInt(2) fun epsilonRate(numbers: List<String>): String = gammaRate(numbers).map { if (it == '0') '1' else '0' }.joinToString("") fun gammaRateDecimal(numbers: List<String>): Int = gammaRate(numbers).toInt(2) fun gammaRate(numbers: List<String>): String { val len = numbers.first().length return (0 until len).map { index -> numbers.count { it[index].toString().toInt() == 1 } }.map { if (it > numbers.size / 2) 1 else 0 }.joinToString("") } private fun oxygenRating(numbers: List<String>): Int { var candidates = numbers var criteriaIndex = 0 while (candidates.size > 1) { val zeroCount = candidates.count { it[criteriaIndex] == '0' } val criteria = if (zeroCount > candidates.size / 2) '0' else '1' candidates = candidates.filter { it[criteriaIndex] == criteria } criteriaIndex++ } require(candidates.size == 1) return candidates.first().toInt(2) } private fun co2Rating(numbers: List<String>): Int { var candidates = numbers var criteriaIndex = 0 while (candidates.size > 1) { val zeroCount = candidates.count { it[criteriaIndex] == '0' } val criteria = if (zeroCount <= candidates.size / 2) '0' else '1' candidates = candidates.filter { it[criteriaIndex] == criteria } criteriaIndex++ } require(candidates.size == 1) return candidates.first().toInt(2) } private fun part2(input: String): Int { val numbers = parseInput(input) return co2Rating(numbers) * oxygenRating(numbers) }
0
Kotlin
0
0
566cbb2ef2caaf77c349822f42153badc36565b7
2,656
AOC-2021
MIT License
src/main/kotlin/_2022/Day23.kt
novikmisha
572,840,526
false
{"Kotlin": 145780}
package _2022 import readInput fun main() { fun parseElves(input: List<String>): Set<MutablePair<Int, Int>> { val elves = mutableSetOf<MutablePair<Int, Int>>() input.forEachIndexed { index, str -> str.forEachIndexed { strIndex, char -> if (char == '#') elves.add(MutablePair(index, strIndex)) } } return elves.toSet() } fun solve(input: List<String>, maxSteps: Int): Int { var elves = parseElves(input) val directions = listOf( setOf(Pair(-1, -1), Pair(-1, 0), Pair(-1, 1)), setOf(Pair(1, -1), Pair(1, 0), Pair(1, 1)), setOf(Pair(-1, -1), Pair(0, -1), Pair(1, -1)), setOf(Pair(-1, 1), Pair(0, 1), Pair(1, 1)), ) for (step in 0 until maxSteps) { val futureSteps = mutableMapOf<MutablePair<Int, Int>, MutableList<MutablePair<Int, Int>>>() for (elf in elves) { val allPositions = directions.flatten().map { MutablePair(elf.first + it.first, elf.second + it.second) } if (allPositions.intersect(elves).isEmpty()) { continue } for (i in directions.indices) { val direction = directions[(i + step).mod(directions.size)] val positionsToCheck = direction.map { MutablePair(elf.first + it.first, elf.second + it.second) } if (positionsToCheck.intersect(elves).isEmpty()) { futureSteps.computeIfAbsent(positionsToCheck[1]) { mutableListOf() }.add(elf) break } } } val filterValues = futureSteps.filterValues { it.size == 1 } if (filterValues.isEmpty()) { return step + 1 } else { filterValues.forEach { (position, elvesToMove) -> elvesToMove.forEach { it.first = position.first it.second = position.second } } } // recalculate all hashes elves = elves.toSet() } val minX = elves.minOf { it.first } val maxX = elves.maxOf { it.first } val minY = elves.minOf { it.second } val maxY = elves.maxOf { it.second } return (maxX - minX + 1) * (maxY - minY + 1) - elves.size } fun part1(input: List<String>): Int { return solve(input, 10) } fun part2(input: List<String>): Int { return solve(input, Int.MAX_VALUE) } // test if implementation meets criteria from the description, like: val testInput = readInput("Day23_test") println(part1(testInput)) println(part2(testInput)) val input = readInput("Day23") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
0c78596d46f3a8bf977bf356019ea9940ee04c88
3,005
advent-of-code
Apache License 2.0
src/Day10.kt
p357k4
573,068,508
false
{"Kotlin": 59696}
sealed interface Command { object MicroNoop : Command data class MicroAddX(val v: Int) : Command } fun main() { fun commands(input: List<String>) = input .flatMap { line -> val split = line.split(' ') when (split[0]) { "noop" -> sequenceOf(Command.MicroNoop) "addx" -> sequenceOf(Command.MicroNoop, Command.MicroAddX(split[1].toInt())) else -> throw IllegalStateException() } } fun part1(input: List<String>): Int { val result = commands(input) .foldIndexed(Pair(1, 0)) { idx, acc, command -> val cycle = idx + 1 val strength = cycle * if ((cycle - 20) % 40 == 0) acc.first else 0 val delta = when (command) { is Command.MicroAddX -> command.v is Command.MicroNoop -> 0 } Pair(acc.first + delta, acc.second + strength) } return result.second } fun part2(input: List<String>): String { val result = commands(input) .foldIndexed(Pair(0, "")) { idx, acc, command -> val pixel = idx % 40 val v = acc.first val c = if (v <= pixel && pixel <= v + 2) "#" else "." val delta = when (command) { is Command.MicroAddX -> command.v is Command.MicroNoop -> 0 } Pair(acc.first + delta, acc.second + c) } return result.second.chunked(40).joinToString("\n") } // test if implementation meets criteria from the description, like: val testInputExample = readInput("Day10_example") check(part1(testInputExample) == 13140) println(part2(testInputExample)) val testInput = readInput("Day10_test") println(part1(testInput)) println(part2(testInput)) }
0
Kotlin
0
0
b9047b77d37de53be4243478749e9ee3af5b0fac
1,932
aoc-2022-in-kotlin
Apache License 2.0
src/Day05.kt
Akhunzaada
573,119,655
false
{"Kotlin": 23755}
import java.io.File import java.util.Stack data class Cargo(val stacks: List<Stack<Char>>) { fun peekStacks() = buildString { stacks.forEach { append(it.peek()) } } } data class ArrangeCrates(val quantity: Int, private val _fromStack: Int, private val _toStack: Int) { val fromStack = _fromStack get() = field - 1 val toStack = _toStack get() = field - 1 } interface Crane { fun arrange(cargo: Cargo, procedure: List<ArrangeCrates>) } class Crane9000 : Crane { override fun arrange(cargo: Cargo, procedure: List<ArrangeCrates>) { procedure.forEach { for (i in 1..it.quantity) cargo.stacks[it.toStack].push(cargo.stacks[it.fromStack].pop()) } } } class Crane9001 : Crane { override fun arrange(cargo: Cargo, procedure: List<ArrangeCrates>) { val tempStack = Stack<Char>() procedure.forEach { for (i in 1..it.quantity) tempStack.push(cargo.stacks[it.fromStack].pop()) for (i in 1..it.quantity) cargo.stacks[it.toStack].push(tempStack.pop()) tempStack.clear() } } } fun main() { fun parseStacks(input: String): List<Stack<Char>> { val columnInput = input.lines().last() val columns = columnInput .trim() .split("\\s+".toRegex()) .map { it.toInt() } val stacks = MutableList(columns.size) { Stack<Char>() } input.lines().reversed().drop(1).forEach { stacksRow -> columns.forEach { val crate = stacksRow.elementAt(columnInput.indexOf("$it")) if (crate.isLetter()) stacks[it - 1].add(crate) } } return stacks } fun parseProcedure(input: String) = input.lines().map { it.split(' ').let { ArrangeCrates(it[1].toInt(), it[3].toInt(), it[5].toInt()) } } fun parseInput(input: String) = input.split("\n\n") .let { (stacksInput, procedureInput) -> Pair(Cargo(parseStacks(stacksInput)), parseProcedure(procedureInput)) } fun part1(input: String): String { return parseInput(input) .let { (cargo, procedure) -> Crane9000().arrange(cargo, procedure) cargo.peekStacks() } } fun part2(input: String): String { return parseInput(input) .let { (cargo, procedure) -> Crane9001().arrange(cargo, procedure) cargo.peekStacks() } } // test if implementation meets criteria from the description, like: val testInput = File("src", "Day05_test.txt").readText() check(part1(testInput) == "CMZ") check(part2(testInput) == "MCD") val input = File("src", "Day05.txt").readText() println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
b2754454080989d9579ab39782fd1d18552394f0
2,936
advent-of-code-2022
Apache License 2.0
kotlin/src/main/kotlin/com/github/jntakpe/aoc2022/days/Day24.kt
jntakpe
572,853,785
false
{"Kotlin": 72329, "Rust": 15876}
import Day24.Direction.* import com.github.jntakpe.aoc2022.shared.Day import com.github.jntakpe.aoc2022.shared.readInputLines import kotlin.math.abs object Day24 : Day { override val input = readInputLines(24) override fun part1(): Int { return Terrain.from(input).run { optimalPath(this, State(start, 0, listOf(end))).last().time } } override fun part2(): Int { return if (isTest()) TODO("understand why StackOverflow") else { Terrain.from(input) .run { optimalPath(this, State(start, 0, listOf(end, start, end))).last().time } } } private fun timeToPath( terrainMap: MutableMap<Int, Terrain>, visitedStates: MutableSet<State>, states: List<State>, minTime: Int ): List<State>? { fun next(time: Int): Terrain = terrainMap.computeIfAbsent(time) { next(time - 1).next() } val lastState = states.last() val targets = lastState.destinations if (targets.isEmpty()) return states val next = next(lastState.time + 1) val nextStates = movePriority(lastState.position, targets.first()) .map { val position = lastState.position + it.vector State( position, lastState.time + 1, if (position == targets.first()) { targets.drop(1) } else targets ) } .plus(State(lastState.position, lastState.time + 1, lastState.destinations)) .filter { val notVisited = !visitedStates.contains(it) val betterPath = optimisticTime(it, targets) < minTime val isStartOrEnd = it.position == next.end || it.position == next.start val isValid = next.isValid(it.position) && !next.blizzards.containsKey(it.position) notVisited && betterPath && (isStartOrEnd || isValid) } visitedStates += nextStates var currentTime = minTime return nextStates .asSequence() .mapNotNull { timeToPath(terrainMap, visitedStates, states + it, currentTime) } .onEach { currentTime = it.lastIndex } .minByOrNull { it.lastIndex } } private fun movePriority(position: Position, target: Position): List<Direction> { return values().sortedByDescending { d -> ((target - position) * d.vector).let { it.x + it.y } } } private fun optimisticTime(state: State, targets: List<Position>): Int { return targets.fold(state.position to state.time) { (last, total), next -> next to total + (next - last).let { abs(it.x) + abs(it.y) } }.second } private fun optimalPath(map: Terrain, state: State): List<State> { return timeToPath(mutableMapOf(0 to map), mutableSetOf(state), listOf(state), Int.MAX_VALUE).orEmpty() } private fun isTest() = input.size <= 7 data class State(val position: Position, val time: Int, val destinations: List<Position>) data class Terrain( val start: Position, val end: Position, val max: Position, val blizzards: Map<Position, List<Direction>>, ) { companion object { fun from(input: List<String>): Terrain { return Terrain( Position(1, 0), Position(input.first().lastIndex - 1, input.lastIndex), Position(input.first().lastIndex, input.lastIndex), input.flatMapIndexed { y, line -> line.mapIndexedNotNull { x, char -> val location = Position(x, y) when (char) { '<' -> location to listOf(LEFT) '>' -> location to listOf(RIGHT) '^' -> location to listOf(UP) 'v' -> location to listOf(DOWN) else -> null } } }.toMap() ) } } fun next(): Terrain = Terrain(start, end, max, blizzards.flatMap { (location, blizzards) -> blizzards.map { val candidate = location + it.vector if (!isValid(candidate)) { when (it) { LEFT -> Position(max.x - 1, candidate.y) RIGHT -> Position(1, candidate.y) UP -> Position(candidate.x, max.y - 1) DOWN -> Position(candidate.x, 1) } to it } else { candidate to it } } }.groupBy({ it.first }) { it.second }) fun isValid(position: Position) = (position.x > 0 && position.y > 0 && position.x < max.x && position.y < max.y) } enum class Direction(val vector: Position) { RIGHT(Position(x = 1)), DOWN(Position(y = 1)), LEFT(Position(x = -1)), UP(Position(y = -1)); } data class Position(val x: Int = 0, val y: Int = 0) { operator fun plus(other: Position) = Position(x + other.x, y + other.y) operator fun minus(other: Position) = Position(x - other.x, y - other.y) operator fun times(other: Position) = Position(x * other.x, y * other.y) operator fun rangeTo(other: Position): Sequence<Sequence<Position>> = (minOf(y, other.y)..maxOf(y, other.y)).asSequence().map { y -> (minOf(x, other.x)..maxOf(x, other.x)).asSequence().map { x -> Position(x, y) } } } }
1
Kotlin
0
0
63f48d4790f17104311b3873f321368934060e06
5,752
aoc2022
MIT License
src/main/kotlin/com/briarshore/aoc2022/day09/RopeBridgePuzzle.kt
steveswing
579,243,154
false
{"Kotlin": 47151}
package com.briarshore.aoc2022.day09 import com.briarshore.aoc2022.day09.Direction.* import println import readInput import kotlin.math.abs enum class Direction(val move: Move) { UP(Move(0, 1)), DOWN(Move(0, -1)), LEFT(Move(-1, 0)), RIGHT(Move(1, 0)) } data class Pos(val x: Int, val y: Int) data class Move(val dx: Int, val dy: Int) { val distance: Int get() = maxOf(abs(dx), abs(dy)) } operator fun Pos.plus(move: Move): Pos = copy(x = x + move.dx, y = y + move.dy) operator fun Pos.minus(other: Pos): Move = Move(x - other.x, y - other.y) fun main() { fun String.toMovements(): List<Direction> { val (dir, len) = split(" ") val direction = when (dir) { "U" -> UP "D" -> DOWN "L" -> LEFT "R" -> RIGHT else -> error("oops") } return List(len.toInt()) { direction } } fun tailTrack(head: Pos, tail: Pos): Move { val rope = head - tail return if (rope.distance > 1) { Move(rope.dx.coerceIn(-1..1), rope.dy.coerceIn(-1..1)) } else { Move(0, 0) } } fun part1(lines: List<String>): Int { var head = Pos(0, 0) var tail = head val tailVisited = mutableSetOf(tail) lines.flatMap { it.toMovements() }.forEach { head += it.move tail += tailTrack(head, tail) tailVisited += tail } return tailVisited.size } fun part2(lines: List<String>): Int { val knotsNbr = 10 val knots = MutableList(knotsNbr) { Pos(0, 0) } val tailVisited = mutableSetOf(knots.last()) for (d in lines.flatMap { it.toMovements() }) { knots[0] = knots[0] + d.move for ((headIndex, tailIndex) in knots.indices.zipWithNext()) { knots[tailIndex] = knots[tailIndex] + tailTrack(knots[headIndex], knots[tailIndex]) } tailVisited += knots.last() } return tailVisited.size } val sampleInput = readInput("d9p1-sample") val samplePart1 = part1(sampleInput) "samplePart1 $samplePart1".println() check(samplePart1 == 13) val sampleInput2 = readInput("d9p2-sample") val samplePart2 = part2(sampleInput2) "samplePart2 $samplePart2".println() check(samplePart2 == 36) val input = readInput("d9-input") val part1 = part1(input) "part1 $part1".println() check(part1 == 6190) val part2 = part2(input) "part2 $part2".println() check(part2 == 2516) }
0
Kotlin
0
0
a0d19d38dae3e0a24bb163f5f98a6a31caae6c05
2,550
2022-AoC-Kotlin
Apache License 2.0
src/main/kotlin/com/hj/leetcode/kotlin/problem712/Solution.kt
hj-core
534,054,064
false
{"Kotlin": 619841}
package com.hj.leetcode.kotlin.problem712 /** * LeetCode page: [712. Minimum ASCII Delete Sum for Two Strings](https://leetcode.com/problems/minimum-ascii-delete-sum-for-two-strings/); */ class Solution { /* Complexity: * Time O(MN) and Space O(MN) where M and N are the length of s1 and s2 respectively; */ fun minimumDeleteSum(s1: String, s2: String): Int { // dp[lengthPrefix1][lengthPrefix2] ::= minimumDeleteSum(s1[:lengthPrefix1], s2[:lengthPrefix2]) val dp = Array(s1.length + 1) { IntArray(s2.length + 1) } // Base cases that all characters of s1[:lengthPrefix1] are deleted since s2[:0] is empty for (lengthPrefix1 in 1..s1.length) { dp[lengthPrefix1][0] = s1[lengthPrefix1 - 1].ascii() + dp[lengthPrefix1 - 1][0] } // Base cases that all characters of s2[:lengthPrefix2] are deleted since s1[:0] is empty for (lengthPrefix2 in 1..s2.length) { dp[0][lengthPrefix2] = s2[lengthPrefix2 - 1].ascii() + dp[0][lengthPrefix2 - 1] } for (lengthPrefix1 in 1..s1.length) { for (lengthPrefix2 in 1..s2.length) { /* If s1[lengthPrefix1-1] and s2[lengthPrefix2-1] are the same, there is a minimumDeleteSum * case that keeps both characters; otherwise, one of the two characters must be deleted. */ dp[lengthPrefix1][lengthPrefix2] = if (s1[lengthPrefix1 - 1] == s2[lengthPrefix2 - 1]) { dp[lengthPrefix1 - 1][lengthPrefix2 - 1] } else { minOf( s1[lengthPrefix1 - 1].ascii() + dp[lengthPrefix1 - 1][lengthPrefix2], s2[lengthPrefix2 - 1].ascii() + dp[lengthPrefix1][lengthPrefix2 - 1] ) } } } return dp[s1.length][s2.length] } private fun Char.ascii(): Int { require(this in 'a'..'z') return 97 + (this - 'a') } }
1
Kotlin
0
1
14c033f2bf43d1c4148633a222c133d76986029c
2,002
hj-leetcode-kotlin
Apache License 2.0
src/main/kotlin/com/github/ferinagy/adventOfCode/aoc2015/2015-21.kt
ferinagy
432,170,488
false
{"Kotlin": 787586}
package com.github.ferinagy.adventOfCode.aoc2015 import com.github.ferinagy.adventOfCode.println import com.github.ferinagy.adventOfCode.readInputText fun main() { val input = readInputText(2015, "21-input") println("Part1:") part1(input).println() println() println("Part2:") part2(input).println() } private fun part1(input: String) = solve(input, true, naturalOrder<Loadout>().reversed()) private fun part2(input: String) = solve(input, false, naturalOrder()) private fun solve(input: String, winning: Boolean, comparator: Comparator<Loadout>): Int { val (hp, dmg, arm) = input.lines().map { it.split(": ") }.map { it[1].toInt() } val boss = Warrior(hp, dmg, arm) val player = Warrior(100, 0, 0) val results = simulateFights(player, boss) val best = results.filter { it.second == winning }.map { it.first }.maxWithOrNull(comparator)!! return best.cost } private fun simulateFights(player: Warrior, boss: Warrior): MutableList<Pair<Loadout, Boolean>> { val results = mutableListOf<Pair<Loadout, Boolean>>() weapons.forEach { weapon -> armors.forEach { armor -> for (i in 0 until rings.lastIndex) { for (j in i + 1..rings.lastIndex) { val loadout = Loadout(weapon, armor, rings[i], rings[j]) results += loadout to player.withLoadout(loadout).fight(boss) } } } } return results } private data class Warrior(val hp: Int, val damage: Int, val armor: Int) private data class Equipment(val name: String, val cost: Int, val damage: Int, val armor: Int) private data class Loadout( val weapon: Equipment, val armor: Equipment, val ring1: Equipment, val ring2: Equipment ) : Comparable<Loadout> { val cost: Int get() = weapon.cost + armor.cost + ring1.cost + ring2.cost override fun compareTo(other: Loadout) = cost - other.cost } private fun Warrior.fight(other: Warrior): Boolean { var hp1 = hp var hp2 = other.hp while (true) { hp2 -= (damage - other.armor).coerceAtLeast(1) if (hp2 <= 0) return true hp1 -= (other.damage - armor).coerceAtLeast(1) if (hp1 <= 0) return false } } private fun Warrior.withLoadout(loadout: Loadout): Warrior = copy( damage = damage + loadout.weapon.damage + loadout.ring1.damage + loadout.ring2.damage, armor = armor + loadout.armor.armor + loadout.ring1.armor + loadout.ring2.armor ) private val weapons = listOf( Equipment("Dagger", 8, 4, 0), Equipment("Shortsword", 10, 5, 0), Equipment("Warhammer", 25, 6, 0), Equipment("Longsword", 40, 7, 0), Equipment("Greataxe", 74, 8, 0), ) private val armors = listOf( Equipment("Naked", 0, 0, 0), Equipment("Leather", 13, 0, 1), Equipment("Chainmail", 31, 0, 2), Equipment("Splintmail", 53, 0, 3), Equipment("Bandedmail", 75, 0, 4), Equipment("Platemail", 102, 0, 5), ) private val rings = listOf( Equipment("Unequipped 1", 0, 0, 0), Equipment("Unequipped 2", 0, 0, 0), Equipment("Damage +1", 25, 1, 0), Equipment("Damage +2", 50, 2, 0), Equipment("Damage +3", 100, 3, 0), Equipment("Defense +1", 20, 0, 1), Equipment("Defense +2", 40, 0, 2), Equipment("Defense +3", 80, 0, 3), )
0
Kotlin
0
1
f4890c25841c78784b308db0c814d88cf2de384b
3,311
advent-of-code
MIT License
src/Day04.kt
bjornchaudron
574,072,387
false
{"Kotlin": 18699}
fun String.toIntRanges(): Pair<IntRange, IntRange> { fun String.toIntRange(): IntRange { val (start, end) = split("-").map { it.toInt() } return start..end } val (first, second) = split(",") return Pair(first.toIntRange(), second.toIntRange()) } fun IntRange.contains(other: IntRange) = start <= other.first && endInclusive >= other.last fun IntRange.overlaps(other: IntRange) = intersect(other).isNotEmpty() fun main() { fun part1(pairLines: List<String>) = pairLines.map { it.toIntRanges() } .count { pair -> pair.first.contains(pair.second) || pair.second.contains(pair.first) } fun part2(pairLines: List<String>) = pairLines.map { it.toIntRanges() } .count { pair -> pair.first.overlaps(pair.second) || pair.second.overlaps(pair.first) } // test if implementation meets criteria from the description, like: val day = "04" val testInput = readLines("Day${day}_test") check(part1(testInput) == 2) check(part2(testInput) == 4) val input = readLines("Day$day") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
f714364698966450eff7983fb3fda3a300cfdef8
1,124
advent-of-code-2022
Apache License 2.0
src/leetcodeProblem/leetcode/editor/en/ReplaceWords.kt
faniabdullah
382,893,751
false
null
//In English, we have a concept called root, which can be followed by some //other word to form another longer word - let's call this word successor. For example, // when the root "an" is followed by the successor word "other", we can form a //new word "another". // // Given a dictionary consisting of many roots and a sentence consisting of //words separated by spaces, replace all the successors in the sentence with the root //forming it. If a successor can be replaced by more than one root, replace it //with the root that has the shortest length. // // Return the sentence after the replacement. // // // Example 1: // Input: dictionary = ["cat","bat","rat"], sentence = "the cattle was rattled //by the battery" //Output: "the cat was rat by the bat" // Example 2: // Input: dictionary = ["a","b","c"], sentence = "aadsfasf absbs bbab cadsfafs" //Output: "a a b c" // Example 3: // Input: dictionary = ["a", "aa", "aaa", "aaaa"], sentence = "a aa a aaaa aaa //aaa aaa aaaaaa bbb baba ababa" //Output: "a a a a a a a a bbb baba a" // Example 4: // Input: dictionary = ["catt","cat","bat","rat"], sentence = "the cattle was //rattled by the battery" //Output: "the cat was rat by the bat" // Example 5: // Input: dictionary = ["ac","ab"], sentence = "it is abnormal that this //solution is accepted" //Output: "it is ab that this solution is ac" // // // Constraints: // // // 1 <= dictionary.length <= 1000 // 1 <= dictionary[i].length <= 100 // dictionary[i] consists of only lower-case letters. // 1 <= sentence.length <= 10^6 // sentence consists of only lower-case letters and spaces. // The number of words in sentence is in the range [1, 1000] // The length of each word in sentence is in the range [1, 1000] // Each two consecutive words in sentence will be separated by exactly one //space. // sentence does not have leading or trailing spaces. // // Related Topics Array Hash Table String Trie 👍 1212 👎 148 package leetcodeProblem.leetcode.editor.en import java.lang.StringBuilder import kotlin.math.sign class ReplaceWords { fun solution() { } //below code will be used for submission to leetcode (using plugin of course) //leetcode submit region begin(Prohibit modification and deletion) class Solution { // one line fun replaceWords2( d: List<String>, s: String ) = s.split(" ").joinToString(" ") { w -> d.filter { w.startsWith(it) }.minByOrNull { it.length } ?: w } fun replaceWords(dictionary: List<String>, sentence: String): String { val splitString = sentence.split(" ") val result = StringBuilder() for (s in splitString) { for (i in s.indices) { val subString = s.substring(0, i + 1) if (!dictionary.contains(subString)) { if (i == s.lastIndex) { result.append("$subString ") } } else { result.append("$subString ") break } } } val resultString = result.toString() return resultString.substring(0, resultString.length - 1) } } //leetcode submit region end(Prohibit modification and deletion) } fun main() { val result = ReplaceWords.Solution().replaceWords( listOf( "cat", "bat", "rat" ), "aadsfasf absbs bbab cadsfafs" ) println(result) }
0
Kotlin
0
6
ecf14fe132824e944818fda1123f1c7796c30532
3,552
dsa-kotlin
MIT License
src/day03/Day03.kt
commanderpepper
574,647,779
false
{"Kotlin": 44999}
package day03 import readInput fun main() { // list of items currently in each rucksack (puzzle input) val day3Input = readInput("day03") partOne(day3Input) partTwo(day3Input) } private fun partTwo(day3Input: List<String>) { val elfGroups = day3Input.chunked(3).map { ElfGroup(it[0], it[1], it[2]) } val commonBadges = elfGroups.map { it.commonBadge } val badgePrios = commonBadges.map { it.determinePriority() } println(badgePrios.sum()) } private fun partOne(day3Input: List<String>) { val rucksacks = day3Input.map { val c1 = it.slice(0 until it.length / 2) val c2 = it.slice((it.length / 2) until it.length) Rucksack(c1, c2) } val commonItems = rucksacks.map { it.commonItems } val commonItemsPrio = commonItems.map { it.determinePriority() } println(commonItemsPrio.sum()) } data class ElfGroup(val groupOne: String, val groupTwo: String, val groupThree: String){ val commonBadge = groupOne.toList().intersect(groupTwo.toList()).intersect(groupThree.toList()).first() } data class Rucksack(val compartmentOne: String, val compartmentTwo: String){ val commonItems = compartmentOne.toList().intersect(compartmentTwo.toList()).first() } fun Char.determinePriority(): Int { return when { this.isLowerCase() -> { this.code - 96 } this.isUpperCase() -> { this.code - 64 + 26 } else -> 0 } }
0
Kotlin
0
0
fef291c511408c1a6f34a24ed7070ceabc0894a1
1,467
advent-of-code-kotlin-2022
Apache License 2.0
src/Day07.kt
l8nite
573,298,097
false
{"Kotlin": 105683}
class File( val path: String, val isDirectory: Boolean = false, var size: Int = 0, var parent: File? = null ) { fun addFile(file: File) { increaseSize(file) } fun increaseSize(file: File) { size += file.size this.parent?.increaseSize(file) } } fun pathify(it: String): String { return it.replace("//", "/") } fun main() { val root = "/" fun parse(input: List<String>): MutableMap<String, File> { val tree = mutableMapOf<String, File>() tree[root] = File("/", true, 0, null) var currentDirectory = root fun cd(arg: String) { currentDirectory = when(arg) { "/" -> root ".." -> tree[currentDirectory]!!.parent!!.path else -> pathify("$currentDirectory/$arg") } if (!tree.containsKey(currentDirectory)) { throw Exception("No directory $currentDirectory found!") } } val cmdPattern = "\\$ (cd|ls)\\s?(.*)$".toRegex() val filePattern = "(dir|\\d+)\\s+(.+?)$".toRegex() input.forEach { cmdPattern.find(it)?.destructured?.let { (cmd, arg) -> if (cmd == "cd") { cd(arg) } // ignore "ls" commands... they're assumed } ?: run { // assume everything else is the output of "ls" in the current directory filePattern.find(it)?.destructured?.let { (a, b) -> if (a == "dir") { val path = pathify("$currentDirectory/$b") tree[currentDirectory]!!.addFile( tree.getOrPut(path) { File(path, true, 0, tree[currentDirectory]) } ) } else { val path = pathify("$currentDirectory/$b") tree[currentDirectory]!!.addFile( tree.getOrPut(path) { File(path, false, a.toInt(), tree[currentDirectory]) } ) } } } } return tree } fun part1(input: List<String>): Int { val tree = parse(input) return tree.filterValues { it.isDirectory && it.size <= 100000 }.values.sumOf { it.size } } fun part2(input: List<String>): Int { val tree = parse(input) val unused = 70000000 - tree[root]!!.size val toFree = 30000000 - unused return tree.filterValues { it.isDirectory && it.size >= toFree }.values.minOf { it.size } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day07_test") check(part1(testInput) == 95437) check(part2(testInput) == 24933642) val input = readInput("Day07") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
f74331778fdd5a563ee43cf7fff042e69de72272
2,999
advent-of-code-2022
Apache License 2.0
src/main/kotlin/org/deep/quined/algo/quine.kt
RedDocMD
347,395,585
false
null
package org.deep.quined.algo fun partitionCubesByOneCount(cubes: List<Cube>): Map<Int, List<Cube>> { val partitions = mutableMapOf<Int, MutableList<Cube>>() for (cube in cubes) { partitions.getOrPut(cube.oneCount, { mutableListOf() }).add(cube) } return partitions } data class ReductionStepResult(val newCubes: List<Cube>, val oldPrimes: List<Cube>) fun reduceOneStep(partitionedCubes: Map<Int, List<Cube>>, termCount: Int): ReductionStepResult { val newCubes = mutableListOf<Cube>() val cubesCovered = mutableMapOf<Cube, Boolean>() for ((_, cubes) in partitionedCubes) { for (cube in cubes) { cubesCovered[cube] = false } } for (i in 0 until termCount) { val lowerList = partitionedCubes[i] val higherList = partitionedCubes[i + 1] if (lowerList != null && higherList != null) { for (lowerCube in lowerList) { for (higherCube in higherList) { if (lowerCube.canJoin(higherCube)) { newCubes.add(lowerCube.joinCube(higherCube)) cubesCovered[lowerCube] = true cubesCovered[higherCube] = true } } } } } val cubesNotCovered = mutableListOf<Cube>() for ((cube, covered) in cubesCovered) { if (!covered) cubesNotCovered.add(cube) } return ReductionStepResult(newCubes, cubesNotCovered) } class Cover(private val cubes: List<Cube>) : Comparable<Cover> { val termsCovered: Set<Int> get(): Set<Int> { val minTerms = mutableSetOf<Int>() for (cube in cubes) minTerms.addAll(cube.minTerms) return minTerms } val size: Int get() = cubes.size override fun compareTo(other: Cover): Int { return cubes.size.compareTo(other.cubes.size) } override fun toString() = cubes.joinToString(", ", "{", "}") { cube -> cube.terms.joinToString( " ", "(", ")" ) { term -> term.toString() } } } fun findMinCovers(implicants: List<Cube>, minTerms: List<Int>, dcTerms: List<Int>): List<Cover> { val minTermsSet = minTerms.toSet() val dcTermSet = dcTerms.toSet() val allPossibleCovers = 1 shl implicants.size val validCovers = mutableListOf<Cover>() for (i in 0 until allPossibleCovers) { val implicantsSelected = mutableListOf<Cube>() for ((idx, cube) in implicants.withIndex()) if ((1 shl idx).and(i) != 0) implicantsSelected.add(cube) val cover = Cover(implicantsSelected) if (cover.termsCovered.subtract(dcTermSet) == minTermsSet) validCovers.add(cover) } validCovers.sort() val minSize = validCovers[0].size return validCovers.takeWhile { it.size == minSize } }
0
Kotlin
1
3
22e0783bcc257ffad15cbf3008ab59b623787920
2,910
QuinedAgain
MIT License
code-sample-kotlin/algorithms/src/main/kotlin/com/codesample/leetcode/medium/907_subOfSubarrayMinimums.kt
aquatir
76,377,920
false
{"Java": 674809, "Python": 143889, "Kotlin": 112192, "Haskell": 57852, "Elixir": 33284, "TeX": 20611, "Scala": 17065, "Dockerfile": 6314, "HTML": 4714, "Shell": 387, "Batchfile": 316, "Erlang": 269, "CSS": 97}
package com.codesample.leetcode.medium /** 907. Sum of Subarray Minimums Given an array of integers arr, find the sum of min(b), where b ranges over every * (contiguous) subarray of arr. Since the answer may be large, return the answer modulo 10^9 + 7. * * Input: arr = [3,1,2,4] * Output: 17 * Explanation: * Subarrays are [3], [1], [2], [4], [3,1], [1,2], [2,4], [3,1,2], [1,2,4], [3,1,2,4]. * Minimums are 3, 1, 2, 4, 1, 1, 2, 1, 1, 1. * Sum is 17. * */ fun sumSubarrayMins1(arr: IntArray): Int { // brute force solution -> split into arrays, calculate each subarray minimum -> sum minimums val modulo = 1_000_000_000L + 7L var sum = 0L fun arraysOfElements(arr: IntArray, numberOfElements: Int): List<IntArray> { var left = 0 var right = numberOfElements - 1 val listOfArrays = mutableListOf<IntArray>() while (right < arr.size) { val anotherArray = mutableListOf<Int>() for (i in left..right) { anotherArray.add(arr[i]) } listOfArrays.add(anotherArray.toIntArray()) left++ right++ } return listOfArrays } for (numOfElementsInArray in 1..arr.size) { val arrays = arraysOfElements(arr, numOfElementsInArray) sum += arrays.map { it.min() ?: 0 }.sum() } return (sum % modulo).toInt() } fun sumSubarrayMins2(arr: IntArray): Int { // slightly smarted solution -> do not create extra arrays, just return their indexes // -> calculate each subarray minimum -> sum minimums val modulo = 1_000_000_000L + 7L var sum = 0L fun arraysOfElements(arr: IntArray, numberOfElements: Int): List<Pair<Int, Int>> { var left = 0 var right = numberOfElements - 1 val listOfArrays = mutableListOf<Pair<Int, Int>>() while (right < arr.size) { listOfArrays.add(Pair(left, right)) left++ right++ } return listOfArrays } fun minOfElements(arr: IntArray, left: Int, right: Int): Int { var min = Int.MAX_VALUE for (i in left..right) { if (min > arr[i]) { min = arr[i] } } return min } for (numOfElementsInArray in 1..arr.size) { val arrays = arraysOfElements(arr, numOfElementsInArray) sum += arrays.map { minOfElements(arr, it.first, it.second) }.sum() } return (sum % modulo).toInt() } fun sumSubarrayMins3(arr: IntArray): Int { // slightly smarted solution -> do not return indexes, just calculate sum of mins // -> sum minimums val modulo = 1_000_000_000L + 7L var sum = 0L fun minOfElements(arr: IntArray, left: Int, right: Int): Int { var min = Int.MAX_VALUE for (i in left..right) { if (min > arr[i]) { min = arr[i] } } return min } fun arraysOfElements(arr: IntArray, numberOfElements: Int): Int { var left = 0 var right = numberOfElements - 1 var sumOfMinSubArrays = 0 while (right < arr.size) { val minOfSum = minOfElements(arr, left, right) sumOfMinSubArrays += minOfSum left++ right++ } return sumOfMinSubArrays } for (numOfElementsInArray in 1..arr.size) { sum += arraysOfElements(arr, numOfElementsInArray) } return (sum % modulo).toInt() } //fun sumSubarrayMins4(arr: IntArray): Int { // // // let's try remembering what where the minimums between elements // val modulo = 1_000_000_000L + 7L // var sum = 0L // // fun minOfElements(arr: IntArray, left: Int, right: Int): Int { // var min = Int.MAX_VALUE // for (i in left..right) { // if (min > arr[i]) { // min = arr[i] // } // } // return min // } // // fun arraysOfElements(arr: IntArray, numberOfElements: Int): Int { // var left = 0 // var right = numberOfElements - 1 // // var sumOfMinSubArrays = 0 // // while (right < arr.size) { // val minOfSum = minOfElements(arr, left, right) // sumOfMinSubArrays += minOfSum // left++ // right++ // } // return sumOfMinSubArrays // } // // // for (numOfElementsInArray in 1..arr.size) { // sum += arraysOfElements(arr, numOfElementsInArray) // } // // return (sum % modulo).toInt() //} fun main() { println(sumSubarrayMins3(intArrayOf(3, 1, 2, 4))) // expected: 17 println(sumSubarrayMins3(intArrayOf(11, 81, 94, 43, 3))) // expected: 444 }
1
Java
3
6
eac3328ecd1c434b1e9aae2cdbec05a44fad4430
4,693
code-samples
MIT License
src/Day11.kt
rod41732
572,917,438
false
{"Kotlin": 85344}
private typealias Operand = (v: Long) -> Long // ALL calculations use Long to prevent integer overflow private enum class Operator { ADD, MUL } private data class Expression(val left: Operand, val op: Operator, val right: Operand) { fun evaluate(old: Long): Long { val lhs = left(old) val rhs = right(old) return when (op) { Operator.ADD -> lhs + rhs Operator.MUL -> lhs * rhs } } } private data class Monkey( val items: MutableList<Long>, val inspectExpression: Expression, val testMod: Long, val trueMonkeyNo: Int, val falseMonkeyNo: Int, var inspectionCount: Long = 0, ) { lateinit var trueMonkey: Monkey lateinit var falseMonkey: Monkey lateinit var afterInspect: (v: Long) -> Long fun receiveItem(item: Long) { items.add(item) } fun inspectAllItems() { inspectionCount += items.size items.map { afterInspect(inspectExpression.evaluate(it)) }.forEach { val targetMonkey = if (it % testMod == 0L) trueMonkey else falseMonkey targetMonkey.receiveItem(it) } items.clear() } } private fun parseMonkey(lines: List<String>): Monkey { val items = lines[1].substringAfter(": ").split(", ").map { it.toLong() }.toMutableList() val expression = lines[2].substringAfter("= ").split(" ").map { it }.let { (l, m, r) -> Expression( if (l == "old") { old -> old } else { old -> l.toLong() }, if (m == "*") Operator.MUL else Operator.ADD, if (r == "old") { old -> old } else { old -> r.toLong() }, ) } val testMod = lines[3].substringAfter("by ").toLong() val trueMonkeyNo = lines[4].substringAfter("monkey ").toInt() val falseMonkeyNo = lines[5].substringAfter("monkey ").toInt() return Monkey( items = items, inspectExpression = expression, testMod = testMod, trueMonkeyNo = trueMonkeyNo, falseMonkeyNo = falseMonkeyNo, ) } fun main() { val input = readInput("Day11") val inputTest = readInput("Day11_test") fun part1(input: List<String>): Int { val monkeys = input.chunked(7).map { parseMonkey(it) }.also { monkeys -> monkeys.forEach { it -> it.trueMonkey = monkeys[it.trueMonkeyNo]; it.falseMonkey = monkeys[it.falseMonkeyNo] it.afterInspect = { it / 3 } } } repeat(20) { monkeys.forEach { it.inspectAllItems() } } return monkeys.map { it.inspectionCount }.sortedDescending().take(2).reduce { acc, it -> acc * it }.toInt() } fun part2(input: List<String>, iterations: Int): Long { val monkeys = input.chunked(7).map { parseMonkey(it) }.also { monkeys -> // this is actually LCM of all monkeys' mod, but since all monkey's are all prime, the calculation is much easier val mod = monkeys.fold(1L) { acc, monkey -> acc * monkey.testMod } monkeys.forEach { it -> it.trueMonkey = monkeys[it.trueMonkeyNo]; it.falseMonkey = monkeys[it.falseMonkeyNo] it.afterInspect = { it % (mod) } } } repeat(iterations) { monkeys.forEach { it.inspectAllItems() } } return monkeys.map { it.inspectionCount }.sortedDescending().take(2) .fold(1) { acc, it -> acc * it } } check(part1(inputTest) == 10605) check(part2(inputTest, 1) == 6L * 4) check(part2(inputTest, 20) == 103L * 99) check(part2(inputTest, 1000) == 5204L * 5192L) println("Part 1") println(part1(input)) println("Part 2") println(part2(input, 10000)) }
0
Kotlin
0
0
1d2d3d00e90b222085e0989d2b19e6164dfdb1ce
3,672
advent-of-code-kotlin-2022
Apache License 2.0
src/Day09.kt
bananer
434,885,332
false
{"Kotlin": 36979}
typealias Heightmap = Array<Array<Int>> fun Heightmap.get(x: Int, y: Int) = this[y][x] val Heightmap.width: Int get() = this[0].size val Heightmap.height: Int get() = this.size fun Heightmap.getAdjacentCoordinates(x: Int, y: Int): List<Pair<Int, Int>> { val result = mutableListOf<Pair<Int, Int>>() if (x > 0) { result.add(Pair(x - 1, y)) } if (x < this.width - 1) { result.add(Pair(x + 1, y)) } if (y > 0) { result.add(Pair(x, y - 1)) } if (y < this.height - 1) { result.add(Pair(x, y + 1)) } return result } fun Heightmap.getAdjacentHeights(x: Int, y: Int) = this.getAdjacentCoordinates(x, y) .map { (x, y) -> this.get(x, y) } fun Heightmap.isLowPoint(x: Int, y: Int) = this.getAdjacentHeights(x, y).all { it > this.get(x, y) } fun Heightmap.coordinates(): Iterable<Pair<Int, Int>> { return Iterable { object : Iterator<Pair<Int, Int>> { private var x = -1 private var y = 0 override fun hasNext(): Boolean { return y < height - 1 || x < width - 1 } override fun next(): Pair<Int, Int> { if (x < width - 1) { x++ } else { x = 0 y++ } return Pair(x, y) } } } } fun Heightmap.lowPoints(): Iterable<Pair<Int, Int>> = coordinates().filter { (x, y) -> this.isLowPoint(x, y) } fun Heightmap.riskLevel(x: Int, y: Int) = this.get(x, y) + 1 fun Heightmap.lowPointsRiskLevelSum() = lowPoints().sumOf { (x, y) -> this.riskLevel(x, y) } fun main() { fun parseInput(input: List<String>): Heightmap = input .map { line -> line.chunked(1).map { it.toInt() }.toTypedArray() } .also { lines -> // verify same size of all lines lines.forEach { check(it.size == lines[0].size) } } .toTypedArray() fun part1(input: List<String>) = parseInput(input).lowPointsRiskLevelSum() fun part2(input: List<String>): Int { val heightmap = parseInput(input) val coordinates = heightmap.coordinates() .filter { (x, y) -> heightmap.get(x, y) < 9 } .toMutableSet() val basins = mutableListOf<Set<Pair<Int, Int>>>() while (coordinates.isNotEmpty()) { // start with any point val point = coordinates.first() val basin = mutableSetOf(point) while(true) { val basinExpansion = basin.flatMap { (x, y) -> heightmap.getAdjacentCoordinates(x, y) } .filter { (x, y) -> heightmap.get(x, y) < 9 } .filter { !basin.contains(it) } .toList() if (basinExpansion.isEmpty()) { break } else { basinExpansion.forEach { basin.add(it) } } } basins.add(basin) coordinates.removeAll(basin) } return basins.sortedByDescending { it.size } .subList(0, 3) .map { it.size } .reduce { acc, i -> acc * i } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day09_test") val testOutput1 = part1(testInput) println("test output1: $testOutput1") check(testOutput1 == 15) val testOutput2 = part2(testInput) println("test output2: $testOutput2") check(testOutput2 == 1134) val input = readInput("Day09") println("output part1: ${part1(input)}") println("output part2: ${part2(input)}") }
0
Kotlin
0
0
98f7d6b3dd9eefebef5fa3179ca331fef5ed975b
3,774
advent-of-code-2021
Apache License 2.0
src/Day03.kt
sgc109
576,491,331
false
{"Kotlin": 8641}
fun main() { fun getPriority(ch: Char): Long = if (ch.isLowerCase()) { ch - 'a' + 1 } else { ch - 'A' + 1 + 26 }.toLong() fun part1(input: List<String>): Long { return input.sumOf { line -> val halfLen = line.length / 2 val left = line.take(halfLen).toSet() val right = line.takeLast(halfLen).toSet() left.filter { right.contains(it) }.sumOf { getPriority(it) } } } fun findBadgePrior(threeBags: List<String>): Long { require(threeBags.size == 3) val sets = threeBags.map { it.toSet() } return sets.reduce { a, b -> a.filter { b.contains(it) } .toSet() }.also { require(it.size == 1) }.sumOf { getPriority(it) } } fun part2(input: List<String>): Long { return input.windowed(size = 3, step = 3).sumOf { findBadgePrior(it) } } val testInput = readLines("Day03_test") val ans = part2(testInput) check(ans == 70L) val input = readLines("Day03") part1(input).println() part2(input).println() }
0
Kotlin
0
0
03e4e85283d486430345c01d4c03419d95bd6daa
1,246
aoc-2022-in-kotlin
Apache License 2.0
src/main/kotlin/com/ginsberg/advent2019/Day14.kt
tginsberg
222,116,116
false
null
/* * Copyright (c) 2019 by <NAME> */ /** * Advent of Code 2019, Day 14 - Space Stoichiometry * Problem Description: http://adventofcode.com/2019/day/14 * Blog Post/Commentary: https://todd.ginsberg.com/post/advent-of-code/2019/day14/ */ package com.ginsberg.advent2019 import kotlin.math.ceil import kotlin.math.sign class Day14(input: List<String>) { private val cost: Map<String, Pair<Long, List<Pair<Long, String>>>> = parseInput(input) fun solvePart1(): Long = calculateCost() fun solvePart2(): Long = (0L..one_trillion).binarySearchBy { one_trillion.compareTo(calculateCost(amount = it)) } private fun calculateCost(material: String = "FUEL", amount: Long = 1, inventory: MutableMap<String, Long> = mutableMapOf()): Long = if (material == "ORE") amount else { val inventoryQuantity = inventory.getOrDefault(material, 0L) val needQuantity = if (inventoryQuantity > 0) { // We have some in inventory, check it out of inventory and reduce our need. inventory[material] = (inventoryQuantity - amount).coerceAtLeast(0) amount - inventoryQuantity } else amount if (needQuantity > 0) { val recipe = cost.getValue(material) val iterations: Int = ceil(needQuantity.toDouble() / recipe.first).toInt() val actuallyProduced = recipe.first * iterations if (needQuantity < actuallyProduced) { // Put excess in inventory inventory[material] = inventory.getOrDefault(material, 0) + actuallyProduced - needQuantity } // Go produce each of our dependencies recipe.second.map { calculateCost(it.second, it.first * iterations, inventory) }.sum() } else { 0 } } private fun LongRange.binarySearchBy(fn: (Long) -> Int): Long { var low = this.first var high = this.last while (low <= high) { val mid = (low + high) / 2 when (fn(mid).sign) { -1 -> high = mid - 1 1 -> low = mid + 1 0 -> return mid // Exact match } } return low - 1 // Our next best guess } private fun parseInput(input: List<String>): Map<String, Pair<Long, List<Pair<Long, String>>>> = input.map { row -> val split: List<String> = row.split(" => ") val left: List<Pair<Long, String>> = split.first().split(",") .map { it.trim() } .map { it.split(" ").let { r -> Pair(r.first().toLong(), r.last()) } } val (amount, type) = split.last().split(" ") type to Pair(amount.toLong(), left) }.toMap() companion object { private const val one_trillion = 1_000_000_000_000L } }
0
Kotlin
2
23
a83e2ecdb6057af509d1704ebd9f86a8e4206a55
3,073
advent-2019-kotlin
Apache License 2.0
src/Day02.kt
topr
572,937,822
false
{"Kotlin": 9662}
import HandShape.Companion.handShape enum class HandShape(val shapeScore: Int) { ROCK(1), PAPER(2), SCISSORS(3); fun defeats(other: HandShape) = when (this) { ROCK -> other == SCISSORS PAPER -> other == ROCK SCISSORS -> other == PAPER } companion object { fun of(char: Char) = when (char) { 'A', 'X' -> ROCK 'B', 'Y' -> PAPER 'C', 'Z' -> SCISSORS else -> throw IllegalArgumentException("$char") } fun handShape(predicate: (HandShape) -> Boolean) = values().find(predicate)!! } } enum class NeededResult { DRAW, LOSE, WIN; fun resolveBy(other: HandShape) = when (this) { DRAW -> other LOSE -> handShape { other.defeats(it) } WIN -> handShape { it.defeats(other) } } companion object { private val neededResults = mapOf('X' to LOSE, 'Y' to DRAW, 'Z' to WIN) fun of(char: Char) = neededResults[char]!! } } fun main() { fun play(opponent: HandShape, me: HandShape) = if (opponent.defeats(me)) 0 else if (me.defeats(opponent)) 6 else 3 fun roundScore(opponent: HandShape, me: HandShape) = play(opponent, me) + me.shapeScore fun part1(input: List<String>) = input.sumOf { val opponent = HandShape.of(it.first()) val me = HandShape.of(it.last()) roundScore(opponent, me) } fun part2(input: List<String>) = input.sumOf { val opponent = HandShape.of(it.first()) val me = NeededResult.of(it.last()).resolveBy(opponent) roundScore(opponent, me) } val testInput = readInputLines("Day02_test") check(part1(testInput) == 15) check(part2(testInput) == 12) val input = readInputLines("Day02") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
8c653385c9a325f5efa2895e94830c83427e5d87
1,853
advent-of-code-kotlin-2022
Apache License 2.0
src/main/kotlin/days/Day13.kt
butnotstupid
433,717,137
false
{"Kotlin": 55124}
package days class Day13 : Day(13) { override fun partOne(): Any { val delimiter = inputList.indexOfFirst { it.isEmpty() } return inputList.withIndex().partition { it.index < delimiter }.let { (coord, directions) -> val initialPoints = coord.map { it.value.split(",").map { it.toInt() } }.map { (x, y) -> x to y }.toSet() directions.drop(1).map { it.value.removePrefix("fold along ").split("=").let { (dir, num) -> dir to num.toInt() } } .take(1) .fold(initialPoints, ::foldXY) }.size } override fun partTwo(): Any { val delimiter = inputList.indexOfFirst { it.isEmpty() } inputList.withIndex().partition { it.index < delimiter }.let { (coord, directions) -> val initialPoints = coord.map { it.value.split(",").map { it.toInt() } }.map { (x, y) -> x to y }.toSet() directions.drop(1).map { it.value.removePrefix("fold along ").split("=").let { (dir, num) -> dir to num.toInt() } } .fold(initialPoints, ::foldXY) .let { points -> val (lx, gx) = points.map { it.first }.let { it.minOrNull()!! to it.maxOrNull()!! } val (ly, gy) = points.map { it.second }.let { it.minOrNull()!! to it.maxOrNull()!! } for (y in ly..gy) { for (x in lx..gx) { print(if (x to y in points) "#" else ".") } println() } } } return "EPUELPBR" } private fun foldXY(points: Set<Pair<Int, Int>>, direction: Pair<String, Int>): Set<Pair<Int, Int>> { val (dir, num) = direction return when (dir) { "x" -> { points.partition { (x, _) -> x < num }.let { (left, right) -> left.union(right.map { (x, y) -> 2 * num - x to y }) } } "y" -> { points.partition { (_, y) -> y < num }.let { (up, down) -> up.union(down.map { (x, y) -> x to 2 * num - y }) } } else -> { throw IllegalArgumentException("Fold direction $dir is unknown") } } } }
0
Kotlin
0
0
a06eaaff7e7c33df58157d8f29236675f9aa7b64
2,367
aoc-2021
Creative Commons Zero v1.0 Universal
src/Day13.kt
ech0matrix
572,692,409
false
{"Kotlin": 116274}
fun main() { fun compareOrder(p1: Packet, p2: Packet): Int { //println("- Compare $p1 vs $p2") var i = 0 while(true) { if (i >= p1.items.size && i >= p2.items.size) { // Both sides out of items. Go back up a level return 0 } else if (i >= p1.items.size) { //println(" - The left list ran out of items first, the inputs are in the right order.") return -1 } else if (i >= p2.items.size) { //println(" - The right list ran out of items first, the inputs are NOT in the right order.") return 1 } val isP1List = p1.items[i][0] == '[' val isP2List = p2.items[i][0] == '[' if (!isP1List && !isP2List) { // both values are integers val int1 = p1.items[i].toInt() val int2 = p2.items[i].toInt() //println(" - Compare $int1 vs $int2") if (int1 < int2) { //println (" - Left side is smaller, so inputs are in the right order") return -1 } else if (int1 > int2) { //println (" - Right side is smaller, so inputs are NOT in the right order") return 1 } } else if (isP1List && isP2List) { // both values are lists val result = compareOrder(Packet(p1.items[i]), Packet(p2.items[i])) if (result != 0) { return result } } else if (isP1List) { // exactly one value is an integer val result = compareOrder(Packet(p1.items[i]), Packet("[${p2.items[i]}]")) if (result != 0) { return result } } else if (isP2List) { // exactly one value is an integer val result = compareOrder(Packet("[${p1.items[i]}]"), Packet(p2.items[i])) if (result != 0) { return result } } i++ } } fun part1(input: List<String>): Int { val pairs = input.chunked(3) var sumOfIndicies = 0 for(i in pairs.indices) { val p1 = Packet(pairs[i][0]) val p2 = Packet(pairs[i][1]) //println("== Pair ${i+1} ==") val result = compareOrder(p1,p2) check(result != 0) if(result < 0) { //println("***Adding to sum: ${i+1}") sumOfIndicies += (i+1) } //println() } return sumOfIndicies } fun part2(input: List<String>): Int { val packets = (input.filter { it.isNotEmpty() } + "[[2]]" + "[[6]]").map { Packet(it) } val sorted = packets.sortedWith(::compareOrder) var product = 1 for(i in sorted.indices) { if (sorted[i].toString() == "[[2]]" || sorted[i].toString() == "[[6]]") { product *= (i + 1) } } return product } val testInput = readInput("Day13_test") check(part1(testInput) == 13) check(part2(testInput) == 140) val input = readInput("Day13") println(part1(input)) println(part2(input)) } class Packet( input: String ) { val items: List<String> init { val itemBuilder = mutableListOf<String>() var level = 0 var currentItem = "" for(i in input.indices) { if (input[i] == '[') { if (level > 0) { currentItem += input[i] } level++ } else if (input[i] == ']') { level-- if (level > 0) { currentItem += input[i] } } else if (level == 1 && input[i] == ',') { itemBuilder.add(currentItem) currentItem = "" } else { currentItem += input[i] } } if (currentItem.isNotEmpty()) { itemBuilder.add(currentItem) } items = itemBuilder.toList() } override fun toString(): String { return items.toString() } }
0
Kotlin
0
0
50885e12813002be09fb6186ecdaa3cc83b6a5ea
4,333
aoc2022
Apache License 2.0
src/day20/second/Solution.kt
verwoerd
224,986,977
false
null
package day20.second import day20.first.Maze import day20.first.Portals import day20.first.parseMaze import tools.timeSolution fun main() = timeSolution { val (maze, portals) = parseMaze() println(maze.findPath(portals)) } private fun Maze.findPath(portals: Portals): Int { val startCoordinate = portals.getValue(day20.first.START).first val endCoordinate = portals.getValue(day20.first.END).first val seen = mutableSetOf(0 to startCoordinate) val portalIndexes = portals.values.filter { it.second != tools.origin } .flatMap { listOf(it.first to it.second, it.second to it.first) } .toMap() val yMax = indexOfLast { it.contains('#') } val xMax = get(yMax).indexOfLast { it == '#' } val outerPortals = portalIndexes.keys.partition { (x, y) -> x == 2 || x == xMax || y == 2 || y == yMax }.first // greedily search the paths with lower levels first val queue = tools.priorityQueueOf( Comparator { o1, o2 -> when (val result = o1.third.compareTo(o2.third)) { 0 -> o1.second.compareTo(o2.second) else -> result } }, Triple(startCoordinate, 0, 0) ) while (queue.isNotEmpty()) { val (coordinate, distance, level) = queue.poll() when { coordinate == endCoordinate && level == 0 -> return distance } tools.adjacentCoordinates(coordinate).filter { seen.add(level to it) } .filter { (x, y) -> get(y)[x] == '.' } .filter { level != 0 || it !in outerPortals } .map { target -> when (target) { in portalIndexes.keys -> Triple( portalIndexes.getValue(target), distance + 2, when (target) { in outerPortals -> level - 1 else -> level + 1 } ) else -> Triple(target, distance + 1, level) } }.toCollection(queue) } error("No path found") }
0
Kotlin
0
0
554377cc4cf56cdb770ba0b49ddcf2c991d5d0b7
1,937
AoC2019
MIT License
src/main/kotlin/nl/dirkgroot/adventofcode/year2020/Day21.kt
dirkgroot
317,968,017
false
{"Kotlin": 187862}
package nl.dirkgroot.adventofcode.year2020 import nl.dirkgroot.adventofcode.util.Input import nl.dirkgroot.adventofcode.util.Puzzle class Day21(input: Input) : Puzzle() { private val foodRegex = "(.*) \\(contains (.*)\\)".toRegex() class Food(val ingredients: List<String>, val allergents: List<String>) private val foods by lazy { input.lines() .map { val match = foodRegex.matchEntire(it)!! Food(match.groupValues[1].split(" "), match.groupValues[2].split(", ")) } } override fun part1() = ingredientPerAllergent() .map { (_, ingredients) -> ingredients } .let { ingredientsWithAllergent -> foods.sumOf { food -> food.ingredients.count { it !in ingredientsWithAllergent } } } override fun part2() = ingredientPerAllergent().sortedBy { (allergent, _) -> allergent } .joinToString(",") { (_, ingredient) -> ingredient } private fun ingredientPerAllergent(): List<Pair<String, String>> { val allAllergents = foods.flatMap { it.allergents }.toSet() val foodsPerAllergent = allAllergents.map { allergent -> allergent to foods.filter { it.allergents.contains(allergent) } }.toMap() val ingredientsPerAllergent = allAllergents.map { allergent -> allergent to foods .filter { it.allergents.contains(allergent) } .flatMap { it.ingredients } .distinct() } val allergentIngredient = ingredientsPerAllergent.map { (allergent, ingredients) -> allergent to ingredients.filter { ingredient -> foodsPerAllergent[allergent]!!.all { food -> food.ingredients.contains(ingredient) } }.toMutableList() } while (!allergentIngredient.all { it.second.size == 1 }) { allergentIngredient.forEach { (_, ingredients) -> if (ingredients.size == 1) { val excludeFromRest = ingredients[0] allergentIngredient .filter { (_, ingredients) -> ingredients.size > 1 } .forEach { (_, ingredients) -> ingredients.remove(excludeFromRest) } } } } return allergentIngredient.map { (allergent, ingredients) -> allergent to ingredients[0] } } }
1
Kotlin
1
1
ffdffedc8659aa3deea3216d6a9a1fd4e02ec128
2,424
adventofcode-kotlin
MIT License
2022/13/13.kt
LiquidFun
435,683,748
false
{"Kotlin": 40554, "Python": 35985, "Julia": 29455, "Rust": 20622, "C++": 1965, "Shell": 1268, "APL": 191}
fun String.parseLists(): Any { val stack: MutableList<MutableList<Any>> = mutableListOf(mutableListOf()) this.replace("]", ",}").replace("[", "{,").replace(",,", ",").split(",").forEach { when (it) { "{" -> { val m: MutableList<Any> = mutableListOf(); stack.last().add(m); stack.add(m) } "}" -> stack.removeLast() else -> stack.last().add(it.toInt()) } } return stack[0][0] } fun cmp(a: Any, b: Any): Int { if (a is Int && b is Int) return when { a < b -> -1; a > b -> 1; else -> 0 } val aList = if (a is MutableList<*>) a else mutableListOf(a) val bList = if (b is MutableList<*>) b else mutableListOf(b) for ((u, v) in aList zip bList) if (cmp(u!!, v!!) != 0) return cmp(u, v) return cmp(aList.size, bList.size) } fun main() { var lists = generateSequence(::readlnOrNull) .filter { !it.isEmpty() } .map { it.parseLists() } .toMutableList() lists .chunked(2) .withIndex() .filter { (_, pair) -> cmp(pair[0], pair[1]) <= 0 } .sumOf { (i, _) -> i+1 } .also(::println) val distress = listOf(listOf(listOf(2)), listOf(listOf(6))) lists .also { it.addAll(distress) } .sortedWith(::cmp) .withIndex() .filter { it.value in distress } .fold(1) { acc, (i, _) -> (i+1) * acc } .also(::println) }
0
Kotlin
7
43
7cd5a97d142780b8b33b93ef2bc0d9e54536c99f
1,436
adventofcode
Apache License 2.0
app/src/main/kotlin/advent/of/code/twentytwenty/Day4.kt
obarcelonap
320,300,753
false
null
package advent.of.code.twentytwenty fun main() { val input = getResourceAsText("/day4-input") val part1Count = countValidPassports(input, ::requiredFieldsValidator) println("Part1: count of valid passwords is $part1Count") val part2Count = countValidPassports(input, ::fieldsValidator) println("Part2: count of valid passwords is $part2Count") } fun countValidPassports(input: String, validator: (passport: Map<String, String>) -> Boolean): Int { val passports = parsePassports(input) return passports.filter { validator(it) } .count() } fun fieldsValidator(passport: Map<String, String>): Boolean { return requiredFieldsValidator(passport) && passport.all { (name, value) -> when (name) { "byr" -> digits(value, 4) && between(value, 1920 to 2002) "iyr" -> digits(value, 4) && between(value, 2010 to 2020) "eyr" -> digits(value, 4) && between(value, 2020 to 2030) "hgt" -> (value.endsWith("cm") && between(value, 150 to 193)) || (value.endsWith("in") && between(value, 59 to 76)) "hcl" -> Regex("#[a-f0-9]{6}").containsMatchIn(value) "ecl" -> listOf("amb", "blu", "brn", "gry", "grn", "hzl", "oth").contains(value) "pid" -> digits(value, 9) "cid" -> true else -> true } } } private fun between(value: String, bounds: Pair<Int, Int>): Boolean = between(value.stripNonNumeric().toIntOrNull() ?: 0, bounds) private fun String.stripNonNumeric(): String = Regex("[^0-9]").replace(this, "") private fun between(value: Int, bounds: Pair<Int, Int>): Boolean = value in bounds.first..bounds.second private fun digits(value: String, length: Int) = value.length == length && value.toIntOrNull() != null fun requiredFieldsValidator(passport: Map<String, String>): Boolean { val requiredFields = listOf("byr", "iyr", "eyr", "hgt", "hcl", "ecl", "pid") return requiredFields.all { passport.keys.contains(it) } && passport.values.all { it.isNotEmpty() } } private fun parsePassports(input: String): List<Map<String, String>> = input.lines() .splitByEmptyLines() .map { toPassport(it) } private fun toPassport(lines: List<String>) = lines.flatMap { line -> toPassportFields(line) } .toMap() private fun toPassportFields(line: String): List<Pair<String, String>> = line.split(" ") .map { field -> val (key, value) = field.split(":") Pair(key.trim(), value.trim()) } private fun List<String>.splitByEmptyLines(): List<List<String>> { val result = mutableListOf<MutableList<String>>() for (line in this) { when { line.isEmpty() -> result.add(result.size, mutableListOf()) result.isEmpty() -> result.add(0, mutableListOf(line)) else -> result[result.size - 1].add(line) } } return result }
0
Kotlin
0
0
a721c8f26738fe31190911d96896f781afb795e1
2,958
advent-of-code-2020
MIT License
src/aoc2022/Day05.kt
miknatr
576,275,740
false
{"Kotlin": 413403}
package aoc2022 fun main() { class Command(val howMany: Int, val from: Int, val to: Int) class Warehouse( val initState: List<ArrayDeque<String>>, val commands: List<Command>, ) { val topLetters get() = initState.map { it.last() }.joinToString("") fun execute9000() = commands .forEach { command -> repeat(command.howMany) { val movement = initState[command.from - 1].removeLast() initState[command.to - 1].addLast(movement) } } fun execute9001() = commands .forEach { command -> val movement = initState[command.from - 1].takeLast(command.howMany) initState[command.to - 1].addAll(movement) repeat(command.howMany) { initState[command.from - 1].removeLast() } } } fun parseCommands(strCommands: String) = strCommands .split("\n") .filter { it != "" } .map { line -> line.split(" ") } // example: move 1 from 8 to 1 .map { tokens -> Command(tokens[1].toInt(), tokens[3].toInt(), tokens[5].toInt()) } fun parseInitState(strInitState: String): List<ArrayDeque<String>> { val lines = strInitState.split("\n").reversed() val numberStacks = lines.first().trim().split(" ").last().toInt() val stacks = List(numberStacks) { ArrayDeque<String>() } lines .drop(1) .forEach { containersLine -> containersLine .chunked(4) .map { it.trim(' ', '[', ']') } .withIndex() .forEach { if (it.value.isNotEmpty()) stacks[it.index].addLast(it.value) } } return stacks } fun part1(input: String): String { val strStateAndCommands= input.split("\n\n") val warehouse = Warehouse(parseInitState(strStateAndCommands[0]), parseCommands(strStateAndCommands[1])) warehouse.execute9000() return warehouse.topLetters } fun part2(input: String): String { val strStateAndCommands= input.split("\n\n") val warehouse = Warehouse(parseInitState(strStateAndCommands[0]), parseCommands(strStateAndCommands[1])) warehouse.execute9001() return warehouse.topLetters } val testInput = readText("Day05_test") part1(testInput).println() part2(testInput).println() val input = readText("Day05") part1(input).println() part2(input).println() }
0
Kotlin
0
0
400038ce53ff46dc1ff72c92765ed4afdf860e52
2,607
aoc-in-kotlin
Apache License 2.0
src/Day08.kt
marosseleng
573,498,695
false
{"Kotlin": 32754}
fun main() { fun part1(input: List<String>): Int { return countVisibleTrees(constructMap(input)) } fun part2(input: List<String>): Int { return getMaxScenicScore(constructMap(input)) } val testInput = readInput("Day08_test") check(part1(testInput) == 21) check(part2(testInput) == 8) val input = readInput("Day08") println(part1(input)) println(part2(input)) } fun constructMap(input: List<String>): List<List<Int>> { val result = mutableListOf<List<Int>>() input.mapTo(result) { row -> row.map { it.toString().toInt() } } return result } fun countVisibleTrees(map: List<List<Int>>): Int { val visibleTrees = mutableSetOf<Pair<Int, Int>>() fun checkRows() { map.forEachIndexed { rowIndex, row -> var highestFromStart = -1 var highestFromEnd = -1 for (treeIndex in (0..row.lastIndex)) { val fromStart = row[treeIndex] if (fromStart > highestFromStart) { val position = rowIndex to treeIndex highestFromStart = fromStart visibleTrees.add(position) } val endIndex = row.lastIndex - treeIndex val fromEnd = row[endIndex] if (fromEnd > highestFromEnd) { val position = rowIndex to endIndex highestFromEnd = fromEnd visibleTrees.add(position) } } } } fun checkColumns() { val columnCount = map.first().size for (treeIndex in 0 until columnCount) { var highestFromStart = -1 var highestFromEnd = -1 for (rowIndex in 0..map.lastIndex) { val fromStart = map[rowIndex][treeIndex] if (fromStart > highestFromStart) { val position = rowIndex to treeIndex highestFromStart = fromStart visibleTrees.add(position) } val endIndex = map.size - 1 - rowIndex val fromEnd = map[endIndex][treeIndex] if (fromEnd > highestFromEnd) { val position = endIndex to treeIndex highestFromEnd = fromEnd visibleTrees.add(position) } } } } checkRows() checkColumns() return visibleTrees.size } fun getMaxScenicScore(map: List<List<Int>>): Int { var scenicScore = -1 val maxX = map.first().lastIndex val maxY = map.lastIndex for ((y, row) in map.withIndex()) { for ((x, tree) in row.withIndex()) { val score = getScenicScore(tree, x, y, maxX, maxY, map) if (score > scenicScore) { scenicScore = score } } } return scenicScore } fun getScenicScore(myself: Int, x: Int, y: Int, maxX: Int, maxY: Int, map: List<List<Int>>): Int { if (x == 0 || y == 0 || x == maxX || y == maxY) { // edge trees return 0 } // same y, x in (0 until x) var start = 0 for (startX in ((x - 1) downTo 0)) { start++ if (map[y][startX] >= myself) { break } } // same x, y in (0 until x) var top = 0 for (topY in (y - 1) downTo 0) { top++ if (map[topY][x] >= myself) { break } } // same y, x in (x+1 until maxX) var end = 0 for (endX in (x + 1)..maxX) { end++ if (map[y][endX] >= myself) { break } } // same x, y in (y+1 until maxY) var bottom = 0 for (bottomY in (y + 1)..maxY) { bottom++ if (map[bottomY][x] >= myself) { break } } return start * top * end * bottom }
0
Kotlin
0
0
f13773d349b65ae2305029017490405ed5111814
3,848
advent-of-code-2022-kotlin
Apache License 2.0
src/Day05.kt
MarkTheHopeful
572,552,660
false
{"Kotlin": 75535}
fun main() { fun readCrates(input: List<String>): List<MutableList<Char>> { val crates: List<MutableList<Char>> = List((input.last().length + 2) / 4) { mutableListOf() } for (line in input) { line.chunked(4).forEachIndexed { index, part -> if (part[1].isLetter()) crates[index].add(part[1]) } } for (i in crates.indices) { crates[i].reverse() } return crates } fun workOnCrates(input: List<String>, moveOperation: (List<MutableList<Char>>, Int, Int, Int) -> Unit): String { val (cratesLines, commandLines) = input.joinToString("/n").split("/n/n").map { it.split("/n") } val crates = readCrates(cratesLines) for (command in commandLines) { val (amount, from, to) = command.split(" ").mapNotNull(String::toIntOrNull) moveOperation(crates, amount, from - 1, to - 1) } return crates.map { x -> x.lastOrNull() ?: " " }.joinToString("", "", "") } fun part1(input: List<String>): String { return workOnCrates(input) { crates: List<MutableList<Char>>, amount, from, to -> repeat(amount) { crates[to].add(crates[from].removeLast()) } } } fun part2(input: List<String>): String { return workOnCrates(input) { crates: List<MutableList<Char>>, amount, from, to -> val tail = crates[from].takeLast(amount) repeat(amount) { crates[from].removeLast() } crates[to].addAll(tail) } } // 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
8218c60c141ea2d39984792fddd1e98d5775b418
1,857
advent-of-kotlin-2022
Apache License 2.0
src/main/kotlin/Day10.kt
Ostkontentitan
434,500,914
false
{"Kotlin": 73563}
fun puzzleDayTenPartOne() { val inputs = readInput(10) val score = inputs.mapNotNull { findFirstIllegalChar(it) }.sumOf { ERROR_SCORE_MAP[it]!! } println("Syntax error score: $score") } fun puzzleDayTenPartTwo() { val inputs = readInput(10) val sortedCompleteScores = calculateCompletionScoresAndSort(inputs) val middleIndex = sortedCompleteScores.size / 2 val middleScore = sortedCompleteScores[middleIndex] println("Autocompletion score: $middleScore") } fun calculateCompletionScoresAndSort(inputs: List<String>) = inputs.filter { findFirstIllegalChar(it) == null }.map { openBracketsFor(it).reversed().fold(0L) { acc, bracket -> acc * 5 + bracket.autoCompleteScore } }.sorted() fun findFirstIllegalChar(line: String): Char? { val openBrackets: MutableList<OpenBracket> = mutableListOf() line.forEach { currentChar -> when { isClosingChar(currentChar) -> { if (currentChar == openBrackets.last().closingChar) { openBrackets.removeAt(openBrackets.lastIndex) } else { return@findFirstIllegalChar currentChar } } isOpenChar(currentChar) -> { openBrackets += bracketFor(currentChar) } } } return null } fun openBracketsFor(line: String): List<OpenBracket> { val openBrackets: MutableList<OpenBracket> = mutableListOf() line.forEach { currentChar -> when { isClosingChar(currentChar) -> { if (currentChar == openBrackets.last().closingChar) { openBrackets.removeAt(openBrackets.lastIndex) } } isOpenChar(currentChar) -> { openBrackets += bracketFor(currentChar) } } } return openBrackets } fun bracketFor(char: Char): OpenBracket = when (char) { '(' -> OpenBracket.ROUND '{' -> OpenBracket.CURLY '[' -> OpenBracket.RECTY '<' -> OpenBracket.POINTY else -> throw IllegalArgumentException("Unhandled bracked type: $char") } private val CLOSING_CHARS = setOf(')', ']', '}', '>') private val OPEN_CHARS = setOf('(', '[', '{', '<') fun isClosingChar(char: Char) = CLOSING_CHARS.contains(char) fun isOpenChar(char: Char) = OPEN_CHARS.contains(char) enum class OpenBracket(val closingChar: Char, val autoCompleteScore: Int) { CURLY('}', 3), RECTY(']', 2), ROUND(')', 1), POINTY('>', 4); } private val ERROR_SCORE_MAP: Map<Char, Int> = mapOf( ')' to 3, ']' to 57, '}' to 1197, '>' to 25137 )
0
Kotlin
0
0
e0e5022238747e4b934cac0f6235b92831ca8ac7
2,646
advent-of-kotlin-2021
Apache License 2.0
advent-of-code-2017/src/test/java/Day7RecursiveCircus.kt
yuriykulikov
159,951,728
false
{"Kotlin": 1666784, "Rust": 33275}
import org.assertj.core.api.Assertions.assertThat import org.junit.Test data class Node( val name: String, val ownWeight: Int, val children: List<String> ) class Day7RecursiveCircus { @Test fun star1Test() { val nodes = parseInput(testInput) assertThat(findRoot(nodes).name).isEqualTo("tknk") } @Test fun star1() { val nodes = parseInput(taskInput) assertThat(findRoot(nodes).name).isEqualTo("gynfwly") } @Test fun star2() { val nodes = parseInput(taskInput) val nodesByName: Map<String, Node> = nodes.groupBy { it.name }.mapValues { (k, v) -> v.first() } fun String.node(): Node = nodesByName.getValue(this) fun Node.weight(): Int = ownWeight + children.map { child -> child.node().weight() }.sum() val root = findRoot(nodes) fun Node.correctedNodeWeight(): Int? { println("calc supposedWeight of $this") require(children.isNotEmpty()) { "Node $this has no children!" } val weights = children.map { it.node().weight() } return if (weights.distinct().size == 1) { println("Children of node $this are balanced") null } else { val unbalancedWeight = weights.first { weight -> weights.count { it == weight } == 1 } // val unbalancedWeight = weights.groupBy { it }.values.first { it.size == 1 }.first() val unbalanced = children.first { it.node().weight() == unbalancedWeight }.node() unbalanced.correctedNodeWeight() ?: run { // children of unbalanced node are balanced, this means this node has wrong weight. It has to have another weight! val balancedWeight = children.first { it != unbalanced.name }.node().weight() val unbalancedChildrenWeight = unbalanced.children.map { it.node().weight() }.sum() balancedWeight - unbalancedChildrenWeight } } } assertThat(root.correctedNodeWeight()).isEqualTo(1526) } private fun findRoot(nodes: List<Node>): Node { val candidates = nodes .filter { it.children.isNotEmpty() } val allChildren = candidates.flatMap { node -> node.children } .distinct() return candidates.first { node -> !allChildren.contains(node.name) } } private fun parseInput(input: String): List<Node> { return input .lines() .map { line -> val split = line .split(" ", "(", ")", "->", ",") .filterNot { it.isBlank() } Node(split[0], split[1].toInt(), split.subList(2, split.size)) } } private val testInput = """ pbga (66) xhth (57) ebii (61) havc (66) ktlj (57) fwft (72) -> ktlj, cntj, xhth qoyq (66) padx (45) -> pbga, havc, qoyq tknk (41) -> ugml, padx, fwft jptl (61) ugml (68) -> gyxo, ebii, jptl gyxo (61) cntj (57) """.trimIndent() private val taskInput = """ jlbcwrl (93) fzqsahw (256) -> lybovx, pdmhva rxivjo (206) -> mewof, hrncqs, qgfstpq jhldwxy (26) bpzxjg (62) lahain (70) enbnfw (39) uzsytm (45) gmcsy (16) rsqyvy (99) lsbsfge (163) -> ldxgz, mksan husmkc (29) ootidjt (63) pjhry (38) kvlbq (22) rdrad (6) -> gwyfm, fozyip, uotzz, fmkkz oqbfkud (470) -> rnbqhk, mepez, mnksdxf, mjsck, bbfaxid, nglea pgchejz (54) -> ifelr, rdkvtq zzjyw (91) yftjdo (12) eqnvty (87) adbolgz (38) rcjqzp (65) -> mkyam, apdfe, avzljw, hxgidsw, fkgxak, wzsbsf, woczl ksrsmjx (72) wfdlusw (49) rpoep (38) jesiypo (78) jjxvns (56) syyfs (35) otplae (91) epsjj (17) utgxfsh (959) -> mupbrv, borbd, jmieet pxzdv (15) ksybvgt (213) tywzhc (243) sbdja (16) ctynr (63) vwbjuvx (99) aidknm (97) qlgme (21) -> ehjnzn, cdbkci zetvslt (99) ferzy (65) dssdiok (97) gexdb (6) bbzmsv (87) mepez (126) -> uqvyau, witovp pubtsp (70) -> jlvwibm, uvvdw, okmqiy gjcxbx (44) mogwb (84) qwiekvk (65) kwbovke (74) offjbb (15) -> dvoja, jteju, wuybunc, qzpzi cwdmlj (86) ojpok (88) lytcy (2662) -> bkmvwp, uyrwi antcinm (178) -> dmthn, ycacj, wkhggv kstvq (69) ibysnvc (79) xulwh (71) zgqzrc (459) -> wlajxb, mfywm, jqmlxr uyrwi (11) qirjqsm (96) fnoteku (2482) -> mbezs, kcuygjx, bymkeq, opsqjx leeyi (88) pcodkpi (95) tetdx (224) -> nshbwn, rpoep, fbqpk ajhctd (18) yhzuh (72) dmvjz (39) zdgwmi (24) vprkzya (37) ipryqov (24) pdxylvu (86) -> etscle, bqtawf ehrqn (23) -> njabgq, fyzeso, jrgwnfh, fxasat ekszr (148) -> gnmydtk, wchxl izkaqg (26) lovypfn (53) sztqzfl (98) ckwopo (43) -> yurfpj, bgrxlxe, tohrp muksdck (48) -> gwtcgyo, tfpuqgs tlfsn (21) hrvztx (57) psulm (1838) -> rhbouej, urhlfju, obfet dbufjl (95) -> faihy, oyamw ucfhxsv (65) ietfhkq (31) psvjtka (29) wzxei (51) swurfm (64) oybwhs (18) dmdiy (1601) -> lazjlns, ygvol, rljjjo, whnjtp, jilomb jteju (54) rdnpoms (177) -> eskdbe, fbhidp, xtkxwd rdhwx (62) hxgidsw (332) -> fukgfu, skkatyg pcewixh (109) -> iekurr, xspxxb gsiypfp (1146) -> bhwca, qhcolun igpabio (53) -> mlqxueo, lhsncv vdjmhb (39) pwdpe (42) -> leeyi, rhlpt, dtexqt, skpcerk ciejakr (43) -> hcqnhm, anmeg, melsryt yehxck (2391) -> boygd, kayqqz, iajslqp sofve (139) asifeu (278) -> rtsajcq, dcouu mgqfa (75) -> cipgxee, jscjw kbppnh (99) apwsmv (31) dzjyzd (39) uobgj (488) -> akidv, sofve, wblhx qngfv (8) kledju (95) besihsl (86) zqnmsyb (73) csqfv (14) ubgrma (1059) -> ymhxg, yvxuom, aeyykn ufyqf (77) llventw (308) -> lsbsfge, itxycu, nddymc zfhwfsw (53) kigdvl (31) fiufzkb (1194) -> ysigfem, bchfd, hgsmlsi vaubjz (233) -> erfnrn, gqzva, goxfpk yhpiqn (99) wzsbsf (222) -> mwztduj, hkpvwpa mjaol (281) -> dnazkh, jkamtqv mufnw (106) -> yxdld, obkhwze, nkssh mhapqqy (16) brztp (27) ebmjz (68) -> xfydt, eqnvty hkjwio (322) -> hdzxuz, zdgwmi, ipryqov eszxg (18) qwzac (908) -> uiioczf, qjdpk, ylpuaf ndsub (75) xcqwjrm (63) glsrg (74) -> maiimn, ufyqf mtcxdod (80) ygmhxm (129) -> pljyyn, njdmj ijcojo (1042) -> dxboqki, ikplh, pubtsp, omergh urhlfju (249) -> csqfv, rnddnj lgefkp (17) bmmmp (90) rjzrh (360) -> hbkujf, mzwbtsa, oywob, dmxhbe khiom (117) -> hpaggeh, lqumiws zlgpmfs (143) -> ilxfa, nhpcp fozyip (293) -> kvlbq, pfqbht ylpuaf (64) -> mdzkkjf, tfdbdq, kiauwpn xekimqs (65) bekxoxk (87) zybeuh (197) -> wonxzkm, jzuvrtp pudyrbw (76) bcyarwn (65) saowgr (367) -> gbnxgny, krmphks, yftjdo, zmpwz tgmle (73) -> prcjhey, thzwwh, cxhipq, tgvpi ezxsv (90) -> qzqyveb, dfmlo rayez (17) ujjpxe (56) efsrz (93) xaifomj (53) ayury (23) zavef (69) qonfiro (190) -> cotvk, evqkdq puurcu (1689) -> awagc, ajhctd omergh (208) padxpdx (192) -> psvjtka, husmkc cxhipq (92) jhgsgy (39) leyiz (74) -> fvfek, njrfnvt kdcvwyf (52) zyympz (887) -> pxteg, amnoi, amzwex jbbmcxg (34) uvmqarq (751) -> muyodod, nclwgga, oeqvt duepwu (683) -> hbueku, zbcra, yxtjx aatagmv (44) zsvuw (11) fynniwm (35) fjzpjk (88) -> uvsny, aatagmv rulhhsl (90) fcscdg (276) -> twvib, skjtvyz, oybwhs, rdmggka vwotlbl (61) ijyoy (24) jpenh (186) -> kdcvwyf, rjxvbkb qzpzi (54) nshbwn (38) foyfb (50) kbyot (337) -> jhldwxy, izkaqg bhxdhmr (65) netsm (53) tgffx (75) -> kstvq, cjmfqbo msthql (7) hgscccv (62) dbnelj (212) -> jzcmf, sqiac, ijyoy, jjqguew jxfqev (99) elmog (32) ygvol (202) -> mszzq, tzzdbi gjrqs (159) -> iprkb, cgouh rabxkov (84) wenii (79) -> qsrpqe, zdhqhh, jpenh, hwrxn, vtvnn, mpgixa, fbjbwv jkqvg (28) kzdugfh (90) mhkcp (17) tfhdccw (93) qzakfh (62) hrncqs (12) tzmndkd (221) -> lixsvp, ofyxhb cjmfqbo (69) ikplh (98) -> bqifoq, pjedtl berje (87) ikbqz (9) avzljw (234) -> vdbihjp, zavef ibiwh (26) -> ndsub, moihbcu vdvadz (38) yirnxk (158) -> lgefkp, rayez vbnlfuo (169) -> pppxrv, rdhwx lgxjr (238) -> mhkba, bsrkr ynayo (71) uvvdw (46) udkyxw (48) zotwsb (170) -> wlufwnr, frksv tohdgsa (30) bqtawf (45) wrfxdc (25) vjxmbzm (69) opmmmd (32) -> pcodkpi, xhonf hkpvwpa (75) uflldd (39) oelrlp (23) lptkbzc (151) -> unvje, bzsiwp ecdieu (23) pxhwecw (57) ryulu (61) uplweb (127) -> bpzxjg, utivde wblhx (97) -> xayglgm, pddllsa grcox (91) xergqq (99) tgujvov (59) -> rhpco, ojpok, trbnpf sdnkg (1381) -> gyutarg, gcwcs, mfjeyx oydxsh (67) pxihdrd (50) cizehi (7) zhopeqm (80) frksv (89) qvbfob (266) -> oejqkp, ocgkcxp ldfsxw (17) wltpv (260) -> nlndxah, etyyw pddteg (52) -> lwwyx, mhnlgyl, mvfhc, dzggd, opqoq, mufrkl, inghbu kybsigz (80) hgsmlsi (31) -> bqqwmry, lqavsk cbyvzkp (99) tjpatnk (44) srneoo (11) -> dhlrq, ivwcuc, laxoeu piouhkc (95) tgfgem (33) egrfvic (49) jmieet (137) -> ckwooig, stkodp cldbz (15) gylsj (52) ecoqyk (35) pnhibed (75) -> gmdsb, gijtd fksxl (5) rhpco (88) eklahxm (51) ftzht (8102) -> dmdiy, sfrbkzf, hlcnxe, zwsrt cykvxs (84) ccckie (201) -> tgkusb, alztgi hbueku (10) -> ohcszyk, szutvca cztikzk (174) -> wxdpcvv, lpbayb lprmau (27) -> rqymw, dssdiok, dydwqz, eyale zorvynv (176) -> mqybmn, jaxidl laxoeu (88) nvvxl (93) duophdw (72) qjwfsfk (11) tzzdbi (8) kwmam (184) -> wdybaj, cyielpd, hhifd, gexdb ujktzrv (71) dvoja (54) opsqjx (71) hlrjgro (63) oqjkafl (32) -> iwyjkz, auneqme, awccm vuyeiv (65) qhmyi (130) -> dvfuz, scruak tnayomw (62) ezdhr (179) ypfsjd (60) -> rdmrzdv, yhpiqn, cbyvzkp auneqme (86) kabixkr (73) jntohm (41) oyamw (65) utivde (62) qhcolun (76) qjcbye (535) -> fetkt, pcewixh, vaubjz, ojhlp, mnvgaqh, rcjiwg rfdpm (80) -> wcevmtt, tlayc ovvrx (84) zdhqhh (200) -> ylyef, onogiv, tohdgsa ofidu (349) -> pjxqt, cytlm zqmlv (59) uzuawb (47) unvje (71) osbbt (1214) -> gqmscj, vyriv, bkkop tmyhhql (51) zxson (61) rhlllw (11) xtkxwd (17) lijeejc (57) -> mgkkyx, thzyz crhho (1255) -> rfcfgg, chnfm, tuekps jqkaucw (53) rerckg (63) kgevjdx (84) muyodod (19) -> wolet, zzjyw zjzoo (65) evqkdq (91) mecyei (75) bvfcsls (227) -> knpwsi, ypfsjd, eilzvpr ntabiof (365) -> rfohgya, yoqbgjb gqmscj (155) -> kjlmdi, scaec bkmvwp (11) tuekps (169) mksan (18) apmdcz (16) plumb (89) gcmio (126) -> ujjpxe, jjxvns uqvyau (6) bdkoa (125) -> ctynr, tvnco xseshzl (76) mnpvutr (39) lghzki (27) citugfl (14) vxgwku (16) jwaskb (251) olkopyn (66) -> qjcbye, cstgeia, uojcup, ycctk, dkhuccj jscjw (72) xatyg (71) xpfxwd (8) jjjks (7331) -> qpefm, dlhiqh, gtervu, pcnroj, jijwa, bgbnlki ewvvi (53) ycbgx (1531) -> tzmndkd, fpynzz, tywzhc cstgeia (613) -> ckwopo, sjiel, akwfu, ehvqyl, wtyfb, gcmio ursjc (45) mabkbom (57) lafoho (250) xmvbzka (49) oasspz (67) epumc (86) -> pcdjo, rerckg, dwknfpc cyielpd (6) lmqaxz (146) -> ghobhlm, qvvcx ydqjoa (84) zfkfhfn (33) -> txapm, pygfz, ekszr, nbivp, wltpv, jsjaxjk sslltlv (45) tifqyde (2264) -> koxiwk, psulm, rcjqzp vonzkut (76) -> bdafpm, nvlxqp, gxsbt blagy (338) cluxnul (15) kdevmnr (77) cmxulaj (44) -> mnkqevh, mkbgt, nrcbc tygwtg (25) wpnqifq (11) jilomb (68) -> uduan, mecyei kytnz (52) gynfwly (66) -> lynvd, dxhcxko, xaatl, leulsg, zworz, fkbrmim, jjjks msfxkn (130) -> ietfhkq, kigdvl wewzb (164) -> yzptgez, ctytfj hdzxuz (24) ghbfyqe (5) hbkujf (133) -> ukghke, aplbnbx iwsjla (38) dnalt (35) gmdsb (75) pcnroj (2553) -> oljci, losdis, sdnkg, zchulv, crhho dzrkq (94) cjcapa (292) dzohgiq (43) rhlpt (88) dkvzre (99) -> mieecfc, nvdouwn, dbnelj, onlwq, ayaouxu, xrhsy, bvrlaep zpntow (72) vohta (58) jqmlxr (173) -> eiyxf, fydjnl lxhkgs (85) qoiuwmf (1008) -> vbnlfuo, wjyreb, sdbksb, lptkbzc, wopfs, khiom btgrhku (24) nnhsuja (16) jgwvp (84) vdpmvm (28) iimfrx (59) oyfma (21) sqypc (7) txapm (272) -> isggu, yookz zhbiaq (45) -> rqzfef, kplegas, ayejq, xevhcxq bkcghv (35) yjakrqa (70) lmwrf (51) uwhjd (94) bpphw (49) vtvnn (114) -> uadnb, huunb blmfs (52) rtsajcq (6) lazjlns (190) -> xbyjur, edjwkkk rnddnj (14) vobeup (41) kifer (53) jdzbqlz (15) wlufwnr (89) bqznix (75) -> stiln, duophdw, yhzuh aovlz (45) dyrvvfn (340) -> prxseo, vxgwku ukghke (28) lnczb (69) -> tzntd, cfnce qllluo (57) asbzj (89) -> yjxyb, hsifo, fhasacf, vwojb, gcbcyn sruyra (47) ohplzu (58) fmkkz (319) -> owigu, ikbqz zimrsr (223) -> dxympe, fhpaqmd, ayury cdbkci (79) tchbf (93) wdybaj (6) bexvn (39) rcsfkrb (11) bgbnlki (2277) -> oqbfkud, qsqis, xhyqtqz, qorkez, qwzac, oewlch, gsiypfp zworz (41633) -> ootkqm, wfovakv, inldh dwknfpc (63) xjcprt (87) ghobhlm (41) erfndpf (89) -> kwbovke, adxhax, cipwzoy setrric (31) erggh (197) -> fksxl, ghbfyqe pzksun (873) -> vyozfv, jxfqev, kbppnh pddllsa (21) xeomb (44) -> vuyeiv, bwrpskq, qwiekvk, gxzkde dfmlo (80) guvuihw (39) khqhd (42) fphgbca (59) fhasacf (269) -> fovilf, rjnzany oyamsv (38) kjjyu (65) pfqbht (22) amzwex (218) -> vprkzya, wxixtqj, oktfn lwljcg (85) hpeaki (35) rcjiwg (35) -> odckjtb, jlfgvr, tdbne ktazkb (57) tgvpi (92) sdhqlxw (1239) -> eklahxm, ejzeqxz, kabcmf aonfaf (52) mlqxueo (67) akidv (21) -> cnvyxm, fphgbca bozlg (67) ewpbnsk (64) thzwwh (92) tuieolg (7624) -> ldnrw, cfuqhip, rjzrh tzrppo (51) -> tfhdccw, kbses, jlbcwrl, efsrz fbjbwv (290) dmthn (25) witovp (6) ugjzag (24) agliie (844) -> qjaywg, rridl, myaiu, antcinm, izhdt ebgdslc (31) abmqz (31) hsfjd (21) ootkqm (9535) -> uplweb, bdkoa, ehrqn, fpqudx, assuj, rjguqr, jwaskb ldxgz (18) atfhgyu (57) hbzju (71) rrywqx (69) dxqqhhd (188) -> pzewv, oelrlp ixtrjm (92) njeff (28) dxboqki (78) -> nstdz, ferzy mnwefbn (65) bugfhhx (357) -> abbnh, intfltq qorkez (1280) -> euqiok, ibvaekj anbcmt (17) iprkb (26) vflyupn (34) ruwzkz (362) xrxseqy (94) mszzq (8) thzyz (77) xyxtm (92) qeubhb (65) fmtyy (35) hpowmso (1854) -> jhysc, xeomb, nzwxd ywvmghy (63) rridl (131) -> nqvflzq, vwotlbl dydwqz (97) mhnlgyl (1185) -> qntstgd, qzpgle, aozygag uycjl (292) -> xcqvne, ruxnrix ohcszyk (32) gtervu (88) -> dkvzre, awufxne, osbbt, ycbgx, wdjzjlk xcqvne (35) moihbcu (75) wpoga (57) rjxvbkb (52) bihsr (21) -> kyjkjy, hgscccv, yonjpz vmmjgy (742) -> vdkxk, yhyxv, cpfbmv gwnipjd (24) brcpgz (57) dczcz (1862) -> wszghwt, navhthp, lsfggz wmaywuo (87) vrfkofp (49) nrcbij (64) -> pudyrbw, ghdime, xseshzl yxtjx (74) dnzdqz (179) gxsbt (58) oqrmida (222) -> lixqwd, dnalt nddymc (93) -> ewvvi, netsm iekurr (71) tcghqr (43) -> mnhojtk, ruwzkz, veksns, wrochvi, uycjl, umtfn, qgvsuqv ikfihh (140) -> tygwtg, vlmhyer ziypsz (84) ehjnzn (79) exwxepj (175) -> jszpe, guvuihw, ykruy capxp (68) nhpcp (34) qzpgle (77) -> gwnipjd, mrcoxnt edjwkkk (14) uteosk (65) ofyxhb (11) tulxgem (213) -> mabkbom, btcjg, ktazkb, evcdf dkttrfw (219) -> ahqfoz, kytnz mttvnpg (9) tzntd (59) euqiok (9) wgypwo (290) -> btgrhku, aqkdlo chnfm (169) vlmhyer (25) urjwj (78) miijab (49) faihy (65) skkatyg (20) zfnoo (18) dcmxxd (35) evnlr (1175) -> erfndpf, hicuenj, zybeuh qzqyveb (80) wpdbejb (90) trbnpf (88) yxxpgv (70) wyomko (184) -> tgfgem, clnkvox dxhcxko (45) -> ftzht, ypsme, rmtbjn, pjyld lixsvp (11) mofkvq (126) -> ejuiv, abmqz, xqobg zqtkn (79) -> ugjzag, dtzyg xhonf (95) kiauwpn (22) nmstp (44) hsifo (210) -> wfdlusw, myonh, qunldzi whnjtp (146) -> zswyy, bmugsve txkgx (60) icjur (76) -> lwaeqm, rhdudt fpynzz (24) -> kepkgvf, kabixkr, jbexk qunldzi (49) ucxedq (84) wndpfac (55) hicuenj (122) -> ootidjt, hlrjgro, ywvmghy kkdaw (65) dmxhbe (141) -> myhrxc, jbbivz, behncf borbd (21) -> ujktzrv, hbzju, xulwh, xatyg adxhax (74) zwsrt (2544) -> xmvbzka, egrfvic, fovkc hhqlfj (81) -> xqgwwr, zmlmsuf jiuuhl (78) dcouu (6) yetcvhx (71) rfcfgg (28) -> sruyra, bqmqbi, uzuawb pygfz (92) -> kledju, upevl etscle (45) pzjbbdd (93) fjpgybt (21) mjsck (90) -> mkkpihe, fmqjogk cfuqhip (57) -> ixkicz, yqnihs, vifwkwa jkamtqv (80) ulvncs (172) -> bexvn, jzsmy cytlm (46) axikbt (9) -> tjffhqh, mogwb, cykvxs, ydqjoa lageym (228) jmlznjh (50) wszghwt (160) -> brcpgz, wryfov yxdld (38) fukgfu (20) mjlnaz (72) -> zcgfj, jiuuhl bchfd (109) -> ccityq, nmvvgr ogvod (1281) -> bihsr, erggh, dqgfb, xguhm gcxrx (91) ttnnyy (92) -> lhsccbq, dpdjpal kxflpnl (16) ehvqyl (192) -> zjgok, ecdieu lsfggz (94) -> itttb, wpdbejb aacegb (8) wxdpcvv (8) viufoq (25) -> bekxoxk, wmaywuo pqnte (70) rmtbjn (78) -> lytcy, aiunuvn, hfvhp, dczcz, kqaoir, ekihql, qkrydu imjutr (187) -> wgeig, wqbhby swpfak (21) vmvxwar (38) uxrrjqx (205) mddejh (441) fbhidp (17) vunam (90) rnbqhk (62) -> rdwkvr, oyamsv bezvr (55) kbses (93) dqgfb (43) -> hpuyku, rycmr uadnb (88) dnrfjv (55) wykkwa (67) kyjkjy (62) wrochvi (150) -> kifer, xaifomj, usodrg, jqkaucw krmphks (12) jbzaips (36) qjaywg (94) -> khpat, jcpavmj, bchlcqs kayqqz (77) -> kdqjj, sbdja, gmcsy zjgok (23) mrcoxnt (24) wopfs (159) -> oasspz, zgssy herqgqi (36) zcdzv (11) assuj (137) -> atfhgyu, pxhwecw cvgbj (48) lywkfsn (127) cpfbmv (204) scruak (30) lsteeu (162) -> tatubv, rprjk, tgblta, uxrrjqx, pweea, sgieno hhlxxzt (96) -> ixtrjm, tknmww, cnbekc gmwtl (49) sjiel (238) pweea (51) -> eggmj, clpekkm cnnrj (78) eilzvpr (213) -> ksrsmjx, zpntow cipwzoy (74) apdfe (184) -> xrxseqy, leegl bkkop (347) cuhrgp (81) -> ohtply, vrfkofp kepkgvf (73) odkzxae (91) qmqrpcl (92) bgrxlxe (65) xqobg (31) awccm (86) slhitu (27) dihzy (79) jfdscql (362) -> amrbhgv, rfdpm, ecxfenj, dxqqhhd eqsxuaq (49) hlcnxe (1998) -> fcpde, zyniqni, offjbb pdmhva (18) dtzyg (24) xpker (36) gqzva (6) thqkxpl (38) avelbqj (31) mrigsjh (55) ltbpi (17) -> vwcygm, herqgqi odckjtb (72) tdniuai (39) tohrp (65) wryfov (57) vhrtptr (139) -> bpqhqbg, pacsxn ohrraic (94) eyale (97) beraw (14) mfywm (79) -> erkarx, vscjrx knpwsi (261) -> cvgbj, uzjejte wjyreb (41) -> rabxkov, rxqfv, gcomv rdwkvr (38) mmerpi (5) cbgyk (43) oxyof (44) tjhmz (51) zmqom (42) -> grazu, yxkldyi rxanas (210) -> ctfjb, ifbxvs lynvd (42593) -> tuieolg, pddteg, pixmx scaec (96) zbcra (38) -> rjeunph, edkigpl ciogjt (375) -> tygnc, vhrtptr, ccckie uvsny (44) mpgixa (110) -> bmmmp, btxepbv aqkdlo (24) yjxyb (77) -> tceog, pqnte, yxxpgv, aokpx tlayc (77) kjlmdi (96) rqhhyc (214) -> cizehi, sqypc tgkusb (32) xguhm (102) -> syyfs, hpeaki, fynniwm koane (8) -> rawuoi, hkjwio, vpynuf, exxcrj, ljhtov, pwdpe, bdymucv phmtqf (175) -> aodnlv, jancm rjguqr (183) -> fgdqr, ccsrkny mnhojtk (218) -> kvdrnf, nkjgwn ejuiv (31) rijipom (107) -> ijmfnt, ymduw, vdpmvm, njeff bbfaxid (138) yoqbgjb (25) bymzb (68) -> zneumoh, zhopeqm qntstgd (103) -> bbkfiz, zonni ahqfoz (52) gfqtz (98) yvxuom (154) -> jbbmcxg, ppiiyuy zxkvs (12) -> bclicjl, yfruc, axikbt, nglji vwojb (97) -> qeubhb, kkdaw, ucfhxsv, rythrvz akpnwc (90) rawuoi (166) -> dzouqwl, vztyfp, dqgivj, cssov eggmj (77) isggu (5) jszpe (39) kmarvbs (90) btxepbv (90) hjjfdj (11) sfrbkzf (45) -> tgmle, mddejh, tulxgem, ofidu, mjaol, dhqzt ibvaekj (9) leegl (94) lfjtmkg (6095) -> lsteeu, zxkvs, sdhqlxw itttb (90) wlajxb (201) -> tgyavjg, eszxg jlvwibm (46) hcqnhm (58) iqygrur (44) bqifoq (55) fovkc (49) aozygag (125) prcjhey (92) fetkt (203) -> nnhsuja, kxflpnl, xumsm qjzol (15) rufvv (162) -> qzcbtes, xekimqs dhlrq (88) mwztduj (75) ydumax (61) boygd (13) -> wiayzvp, mdhhd, jkqvg, wouprxh uyrght (80) -> hvcii, lxhkgs nglji (311) -> cfaniht, anbcmt pfutotv (44) zvwkjew (60) miftchq (21) xaatl (56147) -> dgjls, qoiuwmf, koane, fnoteku, pavwo, hpowmso, yehxck oejqkp (13) oewlch (659) -> tgffx, eiwjrxx, ksybvgt dwpqell (35) mnksdxf (138) obfet (87) -> iolmgs, piouhkc kazqnjr (391) -> qngfv, aacegb kmogwi (1139) -> hkjtym, tgujvov, dkttrfw behncf (16) ofosgz (80) xejner (239) -> jmlznjh, foyfb, pxihdrd ylyef (30) lqumiws (88) jancm (58) rdkvtq (77) alztgi (32) myhrxc (16) ycctk (1381) -> qtgibw, lkorngt, mufnw wfovakv (48) -> lppvxfk, tznwmc, utgxfsh, zyympz, asbzj, ijcojo lhsccbq (42) tglnkgk (81) -> wrxiwgy, wrfxdc ptkqcl (41) cipgxee (72) ecjdzpq (35) ykpdiav (51) wdjzjlk (1631) -> iplyhhc, pgchejz, kwmam ymhxg (48) -> vohta, ohplzu, edpjix vuetjdb (157) -> pbxjvnl, jdzbqlz, xhnmlcw, vipurf skpcerk (88) hfvhp (2018) -> wewzb, opmmmd, zmqom afrywlt (80) amrbhgv (126) -> xpker, gkkrlg, jbzaips qsrpqe (236) -> brztp, kwwsxez cdpfk (92) oksoj (51) eiwjrxx (45) -> hbsmlf, dlabh, rcjxcou pzewv (23) zonni (11) nkssh (38) nmvvgr (34) iteizf (21) dvfuz (30) scmiv (54) qqishhq (14) egsil (38) iipqh (299) icqjyqd (16) zktnjab (87) nkskfx (94) leulsg (44696) -> tifqyde, olkopyn, lfjtmkg eskdbe (17) dkhuccj (96) -> kbyot, zhbiaq, hhmavd, xejner, cqlwzk mkyam (372) wxixtqj (37) ilxfa (34) woczl (60) -> okseah, afeqhu, cnnrj, cmaxybh rjnzany (44) lppvxfk (1001) -> nrnmjo, phmtqf, bqznix uzjxd (196) -> zfnoo, wlaslo, tijkvua ekihql (1184) -> ezxsv, vonzkut, dkyswuu, uyrght, uzjxd, yjomyth rljjjo (192) -> sobzsd, ykljt mfjeyx (49) -> tdniuai, vdjmhb qjdpk (28) -> wzxei, jopyit liamld (25) rjeunph (18) vscjrx (79) gwyfm (287) -> liamld, ucqdz gnmydtk (67) xspxxb (71) mwirmq (188) -> mnpvutr, dmvjz myonh (49) mupbrv (218) -> phkwq, hrjgaqj, bwvemo kztkiqt (13) -> egsil, mjugqpu khpat (53) wchlcja (190) tjffhqh (84) geqwvx (129) -> acxlck, zqnmsyb, ojnziip ufyavk (1838) -> vunam, kmarvbs, kzdugfh nvlxqp (58) izhdt (57) -> gfqtz, sztqzfl zfhxg (345) -> srneoo, ygmhxm, epumc wkhggv (25) jjvxxtt (194) -> ldfsxw, mhkcp mhzgkxx (156) -> qzakfh, tnayomw bchlcqs (53) ymduw (28) grazu (90) fgdqr (34) swrkuc (199) -> gylsj, cyzzsc, blmfs, aonfaf zrpqdzn (62) dkyswuu (120) -> zjzoo, bhxdhmr mjugqpu (38) gijtd (75) huhoda (191) -> bpphw, eqsxuaq, gmwtl vdkxk (90) -> hrvztx, fjhqmnv huunb (88) stiln (72) exxcrj (316) -> dzjyzd, pkoww bdymucv (304) -> uzsytm, sslltlv dyscpqo (49) tremw (94) uotzz (61) -> xyxtm, cdpfk, qmqrpcl vlpop (64) -> hshyx, tchbf rdmggka (18) owigu (9) bpqhqbg (63) aeyykn (66) -> lrkfnoy, ltdrusl kwwsxez (27) jgtpw (84) -> cxnjv, zelucu, ygurya, mrsrl oljci (892) -> asifeu, aoehbj, oqjkafl xqgwwr (23) ctfjb (20) cxnjv (66) nrnmjo (105) -> pzjbbdd, nvvxl wydbqai (65) -> ryulu, ydumax ghdime (76) cnvyxm (59) xffvy (59) qtgibw (52) -> ovvrx, ziypsz ukkaxy (211) yurfpj (65) qvvcx (41) ygurya (66) zchulv (72) -> cmxulaj, tetdx, huhoda, blagy, wgypwo rqzfef (86) drgtn (84) goxfpk (6) bcjecw (80) njabgq (57) gcwcs (93) -> dokgk, epsjj fhzhqie (65) ccsrkny (34) onlwq (59) -> ekxxsqa, jlfho, ekabfx ldnrw (760) -> plumb, yvhilh, kztkiqt, ltbpi nnxfo (63) -> xffvy, zqmlv, krcoaft, iimfrx mrsrl (66) vztyfp (57) pacsxn (63) maiimn (77) usodrg (53) rzphpv (48) pavwo (1890) -> mofkvq, fmxtg, rijipom, mgqfa gcomv (84) pjxqt (46) oywob (47) -> ynayo, ixxkvtz fovilf (44) ypsme (11966) -> zfkfhfn, fiufzkb, ubgrma, puurcu etyyw (11) ccityq (34) hrjgaqj (29) dhqzt (305) -> capxp, pttij dpdjpal (42) fbqpk (38) qkrydu (1886) -> leyiz, mwirmq, hhwngc mufrkl (60) -> wyomko, lafoho, rxanas, vlpop, ulvncs, padxpdx cssov (57) wgeig (15) rythrvz (65) juptypm (14) dxympe (23) ckwooig (84) zgimdwb (107) -> znucug, mrigsjh bbhyth (53) -> xcqwjrm, kgmwfq vyriv (50) -> vwbjuvx, xergqq, wlpfcsr qzcbtes (65) kgmwfq (63) losdis (1165) -> vhmijln, lteyo, viufoq iplyhhc (122) -> cbgyk, dzohgiq fpqudx (187) -> iuxgzr, icqjyqd, apmdcz, mhapqqy jaxidl (86) xhyqtqz (77) -> swrkuc, ncfuru, kazqnjr rznnmp (70) jvhxfl (39) gxzkde (65) uiwaf (97) cfnce (59) fkgxak (328) -> wpnqifq, xbucnh, qjwfsfk, rcsfkrb nrcbc (98) aodnlv (58) yvhilh (89) cyzzsc (52) pjedtl (55) bvrlaep (143) -> dnrfjv, wndpfac, bezvr clpekkm (77) wnyxznj (65) wonxzkm (57) vifwkwa (173) -> zvwkjew, txkgx, vvqpffs qroirmg (45) mdzkkjf (22) pmfkdn (14) qgfstpq (12) mhydkla (7) yekjlfd (106) -> ecjdzpq, dcmxxd gxiwcqv (186) -> zfhwfsw, lovypfn ifbxvs (20) lwwyx (41) -> vuetjdb, ciejakr, imjutr, zgimdwb, sdnlegj, gzixhdc, tlvkwlx tfdbdq (22) dzggd (663) -> iipqh, nnxfo, veggtf xwltxk (2001) -> yirnxk, baawtw, msfxkn tznwmc (1199) -> dnfvldg, dbufjl, pnhibed uiioczf (130) rcjxcou (56) tatubv (205) vvqpffs (60) bugwblt (14) umtfn (80) -> hbylau, dzrkq, rugltaa cqlwzk (217) -> besihsl, cwdmlj pxteg (56) -> odkzxae, gcxrx, cotpovw nbivp (106) -> ndnku, gjcxbx, iqygrur, oxyof twvib (18) fyzeso (57) nlndxah (11) wolet (91) pixmx (4482) -> hrgbkby, bvfcsls, tzvawqb, jfdscql, gqggcxb ctytfj (29) lwaeqm (83) cnbekc (92) ekzvjj (35) zgssy (67) hbylau (94) yonjpz (62) btcjg (57) tdbne (72) edkigpl (18) amnoi (141) -> noxvvva, dfeyr gwtcgyo (24) zrnlo (42) ndnku (44) etwwy (16) hsoxt (62) kdqjj (16) cgouh (26) mnvgaqh (128) -> jntohm, vobeup, ptkqcl ocgkcxp (13) ayaouxu (200) -> ksyewek, gpfrztg baawtw (50) -> nnguamj, yetcvhx ykljt (13) znucug (55) ypqxs (31) pmgrf (21) anmeg (58) fmxtg (84) -> ursjc, eqhxqxm, qroirmg dgjls (1926) -> lgxjr, hrphtyk, mhzgkxx prxseo (16) vhxlart (70) zyniqni (147) -> khqhd, zrnlo dtexqt (88) mqybmn (86) pljyyn (73) jzibybz (248) -> zrpqdzn, hsoxt dokgk (17) bclicjl (217) -> dxufd, jhcsmc tlvkwlx (133) -> fjpgybt, miftchq, oyfma, ytivjxk qsqis (1208) -> aovlz, mxusu mhkba (21) kvdrnf (72) fcpde (175) -> beraw, qqishhq, citugfl, pmfkdn jcpavmj (53) bbkfiz (11) wqbhby (15) mfvkd (21) hhifd (6) ibonrqn (50) jzuvrtp (57) zelucu (66) zneumoh (80) ljhtov (394) okmqiy (46) cmaxybh (78) phkwq (29) mvfhc (420) -> wchlcja, ikfihh, ybnvm, cztikzk, qhmyi, uebnns jzsmy (39) edpjix (58) myaiu (129) -> pqmrmke, iizbmoz, rhkbrsr, apwsmv mnkqevh (98) noxvvva (94) ncfuru (87) -> bcjecw, kybsigz, mtcxdod, ofosgz pttij (68) eutcl (77) mzwbtsa (119) -> eceocsy, ecoqyk wrxiwgy (25) fydjnl (32) bsixe (80) oxcuf (80) -> crobb, xpfxwd yqnihs (56) -> wqoucl, rsqyvy, zetvslt mqhkd (100) -> pjhry, ljhxxd bwvemo (29) hbsmlf (56) sduuog (9) nnguamj (71) xrhsy (266) -> qbrrjg, juptypm, bugwblt rxqfv (84) bqqwmry (73) gyutarg (51) -> adbolgz, vdvadz vyozfv (99) njrfnvt (96) ruxnrix (35) sgieno (107) -> miijab, zryrfnw vpynuf (214) -> akpnwc, rulhhsl mkbgt (98) iwyjkz (86) itxycu (45) -> eutcl, kdevmnr ytspbx (184) -> nkskfx, ohrraic ayejq (86) fhpaqmd (23) jjqguew (24) mnfqc (789) -> zqtkn, hhqlfj, lywkfsn aplbnbx (28) hshyx (93) ozfzz (11) rhbouej (181) -> udkyxw, rzphpv wchxl (67) inghbu (1167) -> vcvypf, ljqmiu, tglnkgk fticuc (1360) -> vleydj, lnczb, igpabio, wydbqai ivwcuc (88) peuppj (29) -> oqrmida, txxnutu, fzqsahw ppiiyuy (34) mgkkyx (77) akwfu (50) -> tremw, uwhjd tceog (70) acxlck (73) woves (32) veksns (308) -> slhitu, lghzki ljhxxd (38) dqgivj (57) sdbksb (171) -> hbkjjtt, zxson erfnrn (6) nclwgga (201) mdhhd (28) rhzimzq (74) -> drgtn, raqjoxn rqymw (97) nkjgwn (72) vwcygm (36) acfyjc (85) iajslqp (32) -> avelbqj, ebgdslc, vzqnfs dlhiqh (7301) -> rdrad, vmmjgy, uvmqarq koxiwk (929) -> fcscdg, geqwvx, jgtpw, zorvynv, zotwsb yjomyth (97) -> oksoj, lmwrf, tjhmz hhwngc (138) -> ewpbnsk, swurfm ikdsvc (1609) -> icjur, ebmjz, rxivjo, rhzimzq mewof (12) bmugsve (36) zcgfj (78) dyimc (54) iuxgzr (16) fxasat (57) ixkicz (353) fvfek (96) rycmr (82) xfydt (87) ybnvm (50) -> dwpqell, fmtyy, bkcghv, ekzvjj abbnh (33) pbxjvnl (15) lrkfnoy (78) lpbayb (8) oeqvt (19) -> grcox, otplae bdafpm (58) upevl (95) jijwa (3632) -> xwltxk, ikdsvc, tcghqr tgyavjg (18) bwrpskq (65) lhsncv (67) kqaoir (80) -> ytspbx, dyrvvfn, bkldmro, qonfiro, hhlxxzt, jzibybz, slrfd dlabh (56) drfwgmu (249) -> zktnjab, cmfkxo qbrrjg (14) tijkvua (18) stkodp (84) zunhob (79) dnfvldg (85) -> yjakrqa, lahain pjyld (10676) -> zfhxg, oenxsfm, ciogjt, ebmcu, mnfqc, zgqzrc, pzksun dxufd (64) zryrfnw (49) ycacj (25) smmgkir (31) bymkeq (71) bzsiwp (71) wqoucl (99) njdmj (73) tzvawqb (1010) -> qirjqsm, muksdck, oxcuf ljqmiu (31) -> ibonrqn, imezigo pppxrv (62) xbyjur (14) hkjtym (247) -> iwsjla, thqkxpl ucqdz (25) ekxxsqa (83) jbexk (73) mkkpihe (24) evcdf (57) sobzsd (13) rfohgya (25) ahmitv (11) wtyfb (238) inldh (4965) -> ogvod, agliie, wenii mieecfc (138) -> lwljcg, acfyjc yrlks (44) gcbcyn (289) -> vflyupn, mbwenqu xevhcxq (86) xayglgm (21) hdlovco (5) awagc (18) zqnul (38) rhkbrsr (31) ejzeqxz (51) onogiv (30) ltdrusl (78) yzptgez (29) bkldmro (212) -> bsixe, afrywlt zksmijj (189) -> zsvuw, hjjfdj pqmrmke (31) gzixhdc (124) -> ypqxs, setrric, smmgkir ytivjxk (21) wiayzvp (28) hbkjjtt (61) rhdudt (83) eqhxqxm (45) gpfrztg (54) slrfd (340) -> etwwy, qldijf iolmgs (95) ckhip (88) -> vhxlart, rznnmp pcdjo (63) ojnziip (73) nvdouwn (161) -> llibmc, jkfob, dyscpqo gbnxgny (12) vzqnfs (31) lixqwd (35) crobb (8) vdbihjp (69) llibmc (49) lkorngt (132) -> tjpatnk, nmstp ecxfenj (78) -> urjwj, jesiypo ekabfx (83) opqoq (648) -> mjlnaz, bymzb, lmqaxz, lageym yfruc (303) -> pmgrf, hsfjd fkbrmim (71889) -> peuppj, uobgj, llventw, duepwu nzwxd (103) -> wykkwa, oydxsh, bozlg kcuygjx (71) hvcii (85) fjhqmnv (57) txxnutu (97) -> bcyarwn, uteosk, kjjyu hrgbkby (53) -> saowgr, lprmau, ntabiof xhnmlcw (15) clnkvox (33) bhwca (76) uojcup (985) -> ttnnyy, yekjlfd, pdxylvu, fjzpjk, mqhkd, ibiwh mxusu (45) ixxkvtz (71) gqggcxb (29) -> tzrppo, bugfhhx, drfwgmu bsrkr (21) erkarx (79) kabcmf (51) tknmww (92) qgvsuqv (206) -> jhgsgy, enbnfw, uflldd, jvhxfl cfaniht (17) jrgwnfh (57) rdmrzdv (99) krcoaft (59) ifelr (77) hpaggeh (88) wlaslo (18) wouprxh (28) hhmavd (359) -> pxzdv, qjzol bqmqbi (47) aokpx (70) lteyo (157) -> mfvkd, swpfak hrphtyk (19) -> xjcprt, bbzmsv, berje pkoww (39) jsjaxjk (88) -> aidknm, uiwaf uebnns (127) -> iteizf, lzxrfk, tlfsn wcevmtt (77) yxkldyi (90) qpefm (823) -> kmogwi, ufyavk, evnlr, rmlddp, fticuc cmfkxo (87) qldijf (16) nstdz (65) aoehbj (182) -> dyimc, scmiv eceocsy (35) hwrxn (53) -> dihzy, ibysnvc, zunhob nglea (50) -> pfutotv, yrlks fmqjogk (24) tgblta (141) -> elmog, woves jkfob (49) vcvypf (113) -> mttvnpg, sduuog wlpfcsr (99) lybovx (18) mbwenqu (34) obkhwze (38) vleydj (173) -> mhydkla, msthql uduan (75) ykruy (39) aiunuvn (1629) -> gjrqs, ukkaxy, lijeejc, zlgpmfs, zksmijj lqavsk (73) afeqhu (78) veggtf (104) -> wnyxznj, mnwefbn, fhzhqie jbbivz (16) uzjejte (48) jhysc (274) -> cldbz, cluxnul vhmijln (97) -> tmyhhql, ykpdiav nqvflzq (61) cotpovw (91) yookz (5) skjtvyz (18) szutvca (32) navhthp (136) -> rrywqx, vjxmbzm okseah (78) ebmcu (30) -> glsrg, ckhip, rqhhyc, jjvxxtt, rdnpoms wuybunc (54) oktfn (37) tvnco (63) tfpuqgs (24) ijmfnt (28) zswyy (36) sqiac (24) xbucnh (11) zmpwz (12) cotvk (91) ohtply (49) ysigfem (177) jlfgvr (72) kplegas (86) mbezs (71) rprjk (205) jlfho (83) melsryt (58) oenxsfm (275) -> cuhrgp, qlgme, bbhyth, dnzdqz, ezdhr sdnlegj (207) -> hdlovco, mmerpi dzouqwl (57) rugltaa (94) imezigo (50) iizbmoz (31) vipurf (15) awufxne (2141) -> qllluo, wpoga gkkrlg (36) dfeyr (94) zmlmsuf (23) lzxrfk (21) jhcsmc (64) ksyewek (54) jzcmf (24) xumsm (16) eiyxf (32) intfltq (33) yhyxv (160) -> ahmitv, ozfzz, zcdzv, rhlllw jopyit (51) rmlddp (64) -> rufvv, gxiwcqv, cjcapa, exwxepj, qvbfob, zimrsr, nrcbij dnazkh (80) raqjoxn (84) cgfykiv (38) tygnc (13) -> ucxedq, jgwvp, kgevjdx ojhlp (137) -> zqnul, vmvxwar, cgfykiv hpuyku (82) """.trimIndent() }
0
Kotlin
0
1
f5efe2f0b6b09b0e41045dc7fda3a7565cb21db3
31,323
advent-of-code
MIT License
src/main/kotlin/Robots.kt
alebedev
573,733,821
false
{"Kotlin": 82424}
fun main() = Robots.solve() private object Robots { const val MAX_TURNS = 32 fun solve() { val blueprints = readInput().take(3) // println("1st: ${maxGeodes(blueprints.first())}") val score = blueprints.map { maxGeodes(it) }.reduce { x, y -> x * y } println("Total score: ${score}") } private fun readInput(): List<Blueprint> = generateSequence(::readLine).map { line -> val match = "Blueprint (\\d+):(.+)".toRegex().matchEntire(line)!! val id = match.groupValues[1].toInt(10) val recipes = buildMap<Resource, Recipe> { match.groupValues[2].split(".").filterNot { it.isEmpty() }.forEach { recipe -> val match = "\\s*Each (\\w+) robot costs (.+)".toRegex().matchEntire(recipe) ?: throw Error("Recipe match failed") val resource = parseResource(match.groupValues[1]) val ingredients = parseIngredients(match.groupValues[2]) put(resource, Recipe(resource, ingredients)) } } Blueprint(id, recipes) }.toList() private fun parseIngredients(string: String): Map<Resource, Int> { return buildMap { string.split(" and ".toRegex()).forEach { val values = "(\\d+) (\\w+)".toRegex().matchEntire(it)!!.groupValues put(parseResource(values[2]), values[1].toInt(10)) } } } private fun maxGeodes(blueprint: Blueprint): Int { println("Max for ${blueprint}...") val maxCost = buildMap { Resource.values().forEach { resource -> put(resource, blueprint.recipes.maxOf { it.value.cost.getOrDefault(resource, 0) }) } }.plus(Pair(Resource.Geode, Int.MAX_VALUE)) println("Max costs $maxCost") fun isGoodStep(step: Step, resource: Resource): Boolean { // println("$resource, $maxCost") if (resource === Resource.Geode) { return true } if (step.robots.getOrDefault(resource, 0) > maxCost[resource]!!) { return false } return true } fun normalizeNextStep(nextStep: Step): Step { val resources = nextStep.resources.mapValues { it -> minOf(it.value, maxCost[it.key]!! * 3) } return Step(resources, nextStep.robots, nextStep.time) } fun nextSteps(step: Step): List<Step> { val result = mutableListOf<Step>() for (resource in Resource.values()) { val cost = blueprint.recipes[resource]!!.cost if (step.hasEnough(cost) && isGoodStep(step, resource)) { val nextStep = normalizeNextStep(step.nextStepWithBuild(resource, cost)) if (resource == Resource.Geode) { return listOf(nextStep) } else { result.add(nextStep) } } } if (result.size < Resource.values().size) { result.add(step.nextStepWithIdle()) } return result } val stack = mutableListOf<Step>( Step(mapOf(), mapOf(Pair(Resource.Ore, 1)), 1) ) val seenStates = mutableSetOf<String>() val maxGeodesAtStep = mutableMapOf<Int, Int>() var maxGeodes = 0 var i = 0 while (stack.isNotEmpty()) { val step = stack.removeLast() if (step.fingerprint() in seenStates) { continue } i += 1 seenStates.add(step.fingerprint()) if (i % 1_000_000 == 0) { println("step ${i / 1_000_000}M, depth=${step.time}, max=$maxGeodes, stack size=${stack.size}") } val oldMax = maxGeodes val geodes = step.resources.getOrDefault(Resource.Geode, 0) maxGeodes = maxOf(maxGeodes, geodes) maxGeodesAtStep[step.time] = maxOf(geodes, maxGeodesAtStep.getOrDefault(step.time, 0)) if (maxGeodes > oldMax && step.time == MAX_TURNS + 1) { println("New best found $i ${step.robots} -> $maxGeodes") } val remainingTime = 1 + MAX_TURNS - step.time if (remainingTime <= 0) { continue } val maxPossibleGeodes = geodes + step.robots.getOrDefault(Resource.Geode, 0) * remainingTime + (1..remainingTime).sum() if (maxPossibleGeodes <= maxGeodes) { continue } if (maxGeodesAtStep[step.time]!! > geodes + 2) { continue } // if (geodes + 2 < maxGeodes) { // continue // } stack.addAll(nextSteps(step)) } println("$maxGeodesAtStep") println("max= ${maxGeodes}") return maxGeodes } private data class Blueprint(val id: Int, val recipes: Map<Resource, Recipe>) private data class Recipe(val robotType: Resource, val cost: Map<Resource, Int>) private enum class Resource { Ore, Clay, Obsidian, Geode, } private fun parseResource(string: String): Resource = when (string) { "ore" -> Resource.Ore "clay" -> Resource.Clay "obsidian" -> Resource.Obsidian "geode" -> Resource.Geode else -> throw Error("Failed to parse resource: $string") } private data class Step(val resources: Map<Resource, Int>, val robots: Map<Resource, Int>, val time: Int) { fun nextStepWithIdle(): Step = Step( nextResources(), robots, time + 1 ) fun nextStepWithBuild(robotType: Resource, cost: Map<Resource, Int>): Step { val resources = nextResources().mapValues { it.value - cost.getOrDefault(it.key, 0) } val nextRobots = robots.toMutableMap() nextRobots[robotType] = robots.getOrDefault(robotType, 0) + 1 return Step(resources, nextRobots, time + 1) } fun hasEnough(cost: Map<Resource, Int>): Boolean = cost.entries.all { resources.getOrDefault(it.key, 0) >= it.value } private fun nextResources(): Map<Resource, Int> = buildMap { Resource.values().forEach { put(it, resources.getOrDefault(it, 0) + robots.getOrDefault(it, 0)) } } fun fingerprint(): String = "$time.${ Resource.values().map { robots.getOrDefault(it, 0) }.joinToString("_") }.${ Resource.values().map { resources.getOrDefault(it, 0) }.joinToString("_") }" } }
0
Kotlin
0
0
d6ba46bc414c6a55a1093f46a6f97510df399cd1
6,778
aoc2022
MIT License
kotlin/src/main/kotlin/com/github/jntakpe/aoc2021/days/day14/Day14.kt
jntakpe
433,584,164
false
{"Kotlin": 64657, "Rust": 51491}
package com.github.jntakpe.aoc2021.days.day14 import com.github.jntakpe.aoc2021.shared.Day import com.github.jntakpe.aoc2021.shared.readInputSplitOnBlank object Day14 : Day { override val input = Instructions.from(readInputSplitOnBlank(14).map { it.lines() }) override fun part1() = input.result(10) override fun part2() = input.result(40) class Instructions(private val frequency: Map<String, Long>, private val rules: Map<String, List<String>>, private val last: Char) { companion object { fun from(lines: List<List<String>>): Instructions { val firstLine = lines.first().first() return Instructions(firstLine.parseFrequency(), lines.last().parseRules(), firstLine.last()) } private fun String.parseFrequency() = windowed(2).groupingBy { it }.eachCount().mapValues { it.value.toLong() } private fun List<String>.parseRules(): Map<String, List<String>> { return map { it.split(" -> ") }.map { it.first() to it.last() } .associate { (r, c) -> r to listOf("${r.first()}$c", "$c${r.last()}") } } } fun result(steps: Int): Long { val chars = afterStep(steps).toList().groupBy({ it.first.first() }, { it.second }).mapValues { it.value.sum() }.toMutableMap() chars.compute(last) { _, v -> (v ?: 0) + 1 } return chars.maxOf { it.value } - chars.minOf { it.value } } private fun afterStep(steps: Int) = (0 until steps).fold(frequency) { a, _ -> next(a) } private fun next(frequency: Map<String, Long>): Map<String, Long> { return frequency.toList() .fold(mutableMapOf()) { a, c -> a.apply { rules[c.first]!!.forEach { compute(it) { _, i -> c.second + (i ?: 0) } } } } } } }
0
Kotlin
1
5
230b957cd18e44719fd581c7e380b5bcd46ea615
1,847
aoc2021
MIT License
src/Day05.kt
Shykial
572,927,053
false
{"Kotlin": 29698}
private val DIGIT_REGEX = Regex("""\D+""") fun main() { fun part1(input: List<String>): String { val parsedInput = parseInput(input) val stacks = parsedInput.initialState.map(::ArrayDeque) parsedInput.instructions.forEach { instruction -> repeat(instruction.numberOfCrates) { stacks[instruction.to - 1].addLast(stacks[instruction.from - 1].removeLast()) } } return stacks.map { it.last() }.joinToString("") } fun part2(input: List<String>): String { val parsedInput = parseInput(input) val stacks = parsedInput.initialState.map(::ArrayDeque) parsedInput.instructions.forEach { instruction -> stacks[instruction.to - 1] += stacks[instruction.from - 1].removeLast(instruction.numberOfCrates) } return stacks.map { it.last() }.joinToString("") } val input = readInput("Day05") println(part1(input)) println(part2(input)) } private fun parseInput(input: List<String>): ParsedInput { val (stacksInput, movesInput) = input.chunkedBy { it.isEmpty() } return ParsedInput( initialState = parseStacks(stacksInput), instructions = parseMoves(movesInput) ) } private fun parseMoves(movesInput: List<String>) = movesInput.asSequence() .map { it.split(DIGIT_REGEX).filter(String::isNotBlank).map(String::toInt) } .map { MoveInstruction(it[0], it[1], it[2]) } .toList() private fun parseStacks(stacksInput: List<String>): List<List<Char>> { val numberOfContainers = stacksInput.last().trimEnd().last().digitToInt() val stacks = List(numberOfContainers) { mutableListOf<Char>() } stacksInput .dropLast(1) .map { line -> line.chunked(4).map { it[1] } } .asReversed() .forEach { line -> line.forEachIndexed { index, c -> if (c.isLetter()) stacks[index] += c } } return stacks } private data class ParsedInput( val initialState: List<List<Char>>, val instructions: List<MoveInstruction> ) private data class MoveInstruction( val numberOfCrates: Int, val from: Int, val to: Int )
0
Kotlin
0
0
afa053c1753a58e2437f3fb019ad3532cb83b92e
2,158
advent-of-code-2022
Apache License 2.0
src/Day05.kt
benwicks
572,726,620
false
{"Kotlin": 29712}
import java.util.* fun main() { fun part1(input: List<String>): String { val (stacks, steps) = parseInput(input) for (step in steps) { val (numToMove, stackFromIndex, stackToIndex) = parseStep(step) for (i in 1..numToMove) { stacks[stackToIndex].push(stacks[stackFromIndex].pop()) } } return getTopsOfEachStack(stacks) } fun part2(input: List<String>): String { val (stacks, steps) = parseInput(input) for (step in steps) { val (numToMove, stackFromIndex, stackToIndex) = parseStep(step) val tempStack = mutableListOf<Char>() for (i in 1..numToMove) { tempStack += stacks[stackFromIndex].pop() } for (crateIndex in tempStack.size - 1 downTo 0) { stacks[stackToIndex].push(tempStack[crateIndex]) } } return getTopsOfEachStack(stacks) } // 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)) } fun parseInput(input: List<String>): Pair<List<Stack<Char>>, List<String>> { val indexOfEmptyLine = input.indexOfFirst { it.isEmpty() } // parse starting config val stacks = parseStacks(input.subList(0, indexOfEmptyLine)) // parse & execute steps val steps = input.subList(indexOfEmptyLine + 1, input.size) return Pair(stacks, steps) } fun parseStacks(initialConfig: List<String>): List<Stack<Char>> { val numStacks = initialConfig.last().split(" ").last().toInt() val stacks = buildList<Stack<Char>> { for (i in 1..numStacks) { this += Stack<Char>() } } for (i in initialConfig.size - 2 downTo 0) { val row = initialConfig[i] for (j in row.length - 2 downTo 1 step 4) { val c = row[j] if (c != ' ') { stacks[((j - 1) / 4)].push(c) } } } return stacks } fun parseStep(step: String): Triple<Int, Int, Int> { val parts = step.split(" from ") val numToMove = parts[0].split(" ").last().toInt() val fromTo = parts[1].split(" to ") val stackFromIndex = fromTo.first().toInt() - 1 val stackToIndex = fromTo.last().toInt() - 1 return Triple(numToMove, stackFromIndex, stackToIndex) } fun getTopsOfEachStack(stacks: List<Stack<Char>>) = stacks.map { it.pop() }.joinToString("")
0
Kotlin
0
0
fbec04e056bc0933a906fd1383c191051a17c17b
2,612
aoc-2022-kotlin
Apache License 2.0
src/Day03.kt
Xacalet
576,909,107
false
{"Kotlin": 18486}
/** * ADVENT OF CODE 2022 (https://adventofcode.com/2022/) * * Solution to day 3 (https://adventofcode.com/2022/day/3) * */ private typealias Rucksack = List<Char> private val charToPriorityMap: Map<Char, Int> = (('a'..'z') + ('A'..'Z')).withIndex().associate { (index, value) -> value to index + 1 } private val Char.priority: Int get() = charToPriorityMap[this] ?: 0 fun main() { fun part1(rucksacks: List<Rucksack>): Int { return rucksacks .map { rucksack -> rucksack.chunked(rucksack.size / 2) } .sumOf { (compartment1, compartment2) -> compartment1.intersect(compartment2.toSet()).first().priority } } fun part2(rucksacks: List<Rucksack>): Int { return rucksacks.chunked(3).sumOf { (r1, r2, r3) -> r1.intersect(r2).intersect(r3).first().priority } } val rucksacks = readInputLines("day03_dataset").map { line -> line.toList()} part1(rucksacks).println() part2(rucksacks).println() }
0
Kotlin
0
0
5c9cb4650335e1852402c9cd1bf6f2ba96e197b2
1,037
advent-of-code-2022
Apache License 2.0
2020/src/main/kotlin/sh/weller/adventofcode/twentytwenty/Day7.kt
Guruth
328,467,380
false
{"Kotlin": 188298, "Rust": 13289, "Elixir": 1833}
package sh.weller.adventofcode.twentytwenty fun List<String>.countBagsThatAreContained(color: String): Long { val parsedInput = this.parseBaggageInput() val rootBag = ContainedBag(color).appendLevel(parsedInput) return rootBag!!.getNumOfContainedBags() } private fun ContainedBag.getNumOfContainedBags(): Long { if (this.containedBags.isEmpty()) { return 0 } return this.containedBags.map { it.getNumOfContainedBags() + 1 }.sum() } private fun ContainedBag.appendLevel(parsedInput: List<List<Pair<String, Int>>>): ContainedBag? { if (this.color == "other") { return null } val containedBagsLine = parsedInput.find { it.first().first == this.color }!!.drop(1) containedBagsLine .forEach { val tmpBag = ContainedBag(it.first).appendLevel(parsedInput) if (tmpBag != null) { repeat((1..it.second).count()) { this.containedBags.add(tmpBag) } } } return this } private data class ContainedBag( val color: String, var containedBags: MutableList<ContainedBag> = mutableListOf() ) fun List<String>.countBagsWhichContain(color: String): Int { val parsedInput = this.parseBaggageInput() val foundColors = mutableListOf<String>() var searchColors = listOf(color) var foundOther = true do { val tmpColors = parsedInput.findWhichContain(searchColors) if (tmpColors.isEmpty()) { foundOther = false } else { searchColors = tmpColors foundColors.addAll(tmpColors) } } while (foundOther) return foundColors.distinct().size } private fun List<List<Pair<String, Int>>>.findWhichContain(colors: List<String>): List<String> { val canContain = mutableListOf<String>() this.forEach { if (it.drop(1).map { bag -> bag.first }.containsOneOf(colors)) { canContain.add(it.first().first) } } return canContain } private fun List<String>.containsOneOf(others: List<String>): Boolean { var contains = false others.forEach { other -> this.forEach { if (it.contains(other)) { contains = true } } } return contains } private fun List<String>.parseBaggageInput(): List<List<Pair<String, Int>>> { val parsedBags = mutableListOf<List<Pair<String, Int>>>() var currentLine = mutableListOf<Pair<String, Int>>() this.forEach { val bagsList = it.removeSuffix(".").split(Regex("contain|,")) bagsList.forEach { bag -> val splitBag = bag.trim().split(" ") val number: Int val color: String when { splitBag[0].toIntOrNull() != null -> { number = splitBag[0].toInt() color = splitBag[1] + " " + splitBag[2] } splitBag[0] == "no" -> { number = 0 color = "other" } else -> { number = 1 color = splitBag[0] + " " + splitBag[1] } } currentLine.add(Pair(color, number)) } parsedBags.add(currentLine) currentLine = mutableListOf() } return parsedBags }
0
Kotlin
0
0
69ac07025ce520cdf285b0faa5131ee5962bd69b
3,316
AdventOfCode
MIT License
src/Day13.kt
dakr0013
572,861,855
false
{"Kotlin": 105418}
import kotlin.math.min import kotlin.test.assertEquals fun main() { fun part1(input: List<String>): Int { return parsePairsOfPackets(input) .mapIndexedNotNull { index, pair -> if (pair.isInRightOrder()) { index + 1 } else { null } } .sum() } fun part2(input: List<String>): Int { val dividerPackets = listOf("[[2]]", "[[6]]").map { PacketParser(it).parse() } val packets = input.filter { it.isNotEmpty() }.map { PacketParser(it).parse() } val allPackets = (packets + dividerPackets).sorted() val index1 = allPackets.indexOf(dividerPackets.first()) + 1 val index2 = allPackets.indexOf(dividerPackets.last()) + 1 return index1 * index2 } // test if implementation meets criteria from the description, like: val testInput = readInput("Day13_test") assertEquals(13, part1(testInput)) assertEquals(140, part2(testInput)) val input = readInput("Day13") println(part1(input)) println(part2(input)) } private fun parsePairsOfPackets(input: List<String>): List<Pair<Packet, Packet>> { return input.chunked(3).map { val first = PacketParser(it[0]).parse() val second = PacketParser(it[1]).parse() first to second } } private class PacketParser(val input: String) { private var index = 1 fun parse(): Packet { val currentNumber = StringBuilder() val packetValues = mutableListOf<PacketValue>() while (index <= input.lastIndex) { val char = input[index++] when { char.isDigit() -> currentNumber.append(char) char == ',' -> { if (currentNumber.isNotEmpty()) { packetValues.add(IntValue(currentNumber.toString().toInt())) currentNumber.clear() } } char == '[' -> packetValues.add(parse()) char == ']' -> { if (currentNumber.isNotEmpty()) { packetValues.add(IntValue(currentNumber.toString().toInt())) currentNumber.clear() } return Packet(packetValues) } } } error("there was no closing bracket, should not happen") } } private fun Pair<Packet, Packet>.isInRightOrder(): Boolean = first <= second private typealias Packet = ListValue private sealed interface PacketValue : Comparable<PacketValue> private data class ListValue(val value: List<PacketValue>) : PacketValue { constructor(vararg values: PacketValue) : this(values.toList()) override fun compareTo(other: PacketValue): Int { when (other) { is IntValue -> return this.compareTo(ListValue(other)) is ListValue -> { for (i in 0..min(value.lastIndex, other.value.lastIndex)) { when { value[i] < other.value[i] -> return -1 value[i] > other.value[i] -> return +1 else -> { // continue checking list } } } return value.size.compareTo(other.value.size) } } } override fun toString() = value.toString() } private data class IntValue(val value: Int) : PacketValue { override fun compareTo(other: PacketValue): Int { return when (other) { is IntValue -> value.compareTo(other.value) is ListValue -> ListValue(this).compareTo(other) } } override fun toString() = value.toString() }
0
Kotlin
0
0
6b3adb09f10f10baae36284ac19c29896d9993d9
3,334
aoc2022
Apache License 2.0
src/day_3/kotlin/Day3.kt
Nxllpointer
573,051,992
false
{"Kotlin": 41751}
// AOC Day 3 data class Rucksack(val items: String) { val firstCompartment = items.drop(items.length / 2) val secondCompartment = items.dropLast(items.length / 2) val misorderedItem by lazy { firstCompartment.first { secondCompartment.contains(it) } } } const val priorities = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" fun itemToPriority(itemType: Char): Int = priorities.indexOf(itemType) + 1 fun part1(rucksacks: List<Rucksack>) { val misorderedItemsPrioritySum = rucksacks.sumOf { itemToPriority(it.misorderedItem) } println("Part 1: The priority sum of misordered items is $misorderedItemsPrioritySum") } fun part2(rucksacks: List<Rucksack>) { val groups = rucksacks.chunked(3) val groupPrioritiesSum = groups .map { group -> // Get character contained by all rucksacks group[0].items.first { group[1].items.contains(it) && group[2].items.contains(it) } } .sumOf { itemToPriority(it) } println("Part 2: The priority sum of all groups is $groupPrioritiesSum") } fun main() { val rucksacks = getAOCInput { rawInput -> rawInput .trim() .split("\n") .map { Rucksack(it) } } part1(rucksacks) part2(rucksacks) }
0
Kotlin
0
0
b6d7ef06de41ad01a8d64ef19ca7ca2610754151
1,303
AdventOfCode2022
MIT License
src/year2023/day02/Day.kt
tiagoabrito
573,609,974
false
{"Kotlin": 73752}
package year2023.day02 import year2023.solveIt fun main() { val day = "02" fun i(index: Int) = index val expectedTest1 = 8L val expectedTest2 = 2286L val minimum = mapOf("red" to 12, "green" to 13, "blue" to 14) fun canPlay(s: String): Boolean { val map = s.substringAfter(":").split(";").flatMap { it -> it.split(",").map { val (c, color) = it.trim().split(" ") color to c } }.all { a -> minimum[a.first]!! >= Integer.valueOf(a.second) } return map } fun part1(input: List<String>): Long { return input.mapIndexedNotNull { index, s -> when(canPlay(s)){ true -> index +1 false-> null } }.sum().toLong() } fun cubes(line: String): Int { val flatMap = line.substringAfter(":").split(";").flatMap { it -> it.split(",").map { val (c, color) = it.trim().split(" ") color to c } }.groupBy { it.first }.mapValues { it -> it.value.maxOfOrNull { Integer.valueOf(it.second) } } return flatMap.values.filterNotNull().reduceRight{a,b -> a*b} } fun part2(input: List<String>): Long { return input.sumOf { cubes(it) }.toLong() } solveIt(day, ::part1, expectedTest1, ::part2, expectedTest2) }
0
Kotlin
0
0
1f9becde3cbf5dcb345659a23cf9ff52718bbaf9
1,359
adventOfCode
Apache License 2.0
src/Lesson9MaximumSliceProblem/MaxSliceSum.kt
slobodanantonijevic
557,942,075
false
{"Kotlin": 50634}
/** * 100/100 * Kadane's algorithm * @param A * @return */ fun solution(A: IntArray): Int { var maxSlice = A[0] var maxEnding = A[0] /** * For each position, we compute the largest sum that ends in that position * If we assume that the maximum sum of a slice ending in position i equals maxEnding * then the maximum slice ending in position i equals max(A[i], maxEnding + A[i]) * All this is basically an implementation of Kadane’s algorithm: * https://en.wikipedia.org/wiki/Maximum_subarray_problem#Kadane's_algorithm */ for (i in 1 until A.size) { maxEnding = Math.max(A[i], maxEnding + A[i]) maxSlice = Math.max(maxEnding, maxSlice) } return maxSlice } /** * A non-empty array A consisting of N integers is given. A pair of integers (P, Q), such that 0 ≤ P ≤ Q < N, is called a slice of array A. The sum of a slice (P, Q) is the total of A[P] + A[P+1] + ... + A[Q]. * * Write a function: * * class Solution { public int solution(int[] A); } * * that, given an array A consisting of N integers, returns the maximum sum of any slice of A. * * For example, given array A such that: * * A[0] = 3 A[1] = 2 A[2] = -6 * A[3] = 4 A[4] = 0 * the function should return 5 because: * * (3, 4) is a slice of A that has sum 4, * (2, 2) is a slice of A that has sum −6, * (0, 1) is a slice of A that has sum 5, * no other slice of A has sum greater than (0, 1). * Write an efficient algorithm for the following assumptions: * * N is an integer within the range [1..1,000,000]; * each element of array A is an integer within the range [−1,000,000..1,000,000]; * the result will be an integer within the range [−2,147,483,648..2,147,483,647]. */
0
Kotlin
0
0
155cf983b1f06550e99c8e13c5e6015a7e7ffb0f
1,747
Codility-Kotlin
Apache License 2.0
src/Day03.kt
mvanderblom
573,009,984
false
{"Kotlin": 25405}
fun String.inHalf(): List<String> = listOf( this.substring(0, this.length/2), this.substring(this.length/2, this.length) ) fun List<String>.intersection(): Set<Char> = this .map { it.toSet() } .reduceIndexed { i, acc, it -> if (i == 0) it else acc.intersect(it) } val allLetters = ('a'..'z') + ('A'..'Z') fun Char.toPriority(): Int = allLetters.indexOf(this) + 1 fun main() { val dayName = 3.toDayName() fun part1(input: List<String>): Int = input .map { it.inHalf() } .map { it.intersection().single() } .sumOf { it.toPriority() } fun part2(input: List<String>): Int = input .chunked(3) .map { it.intersection().single() } .sumOf { it.toPriority() } val testInput = readInput("${dayName}_test") val testOutputPart1 = part1(testInput) testOutputPart1 isEqualTo 157 val input = readInput(dayName) val outputPart1 = part1(input) outputPart1 isEqualTo 7716 val testOutputPart2 = part2(testInput) testOutputPart2 isEqualTo 70 val outputPart2 = part2(input) outputPart2 isEqualTo 2973 }
0
Kotlin
0
0
ba36f31112ba3b49a45e080dfd6d1d0a2e2cd690
1,157
advent-of-code-kotlin-2022
Apache License 2.0
src/main/kotlin/day7.kt
Arch-vile
572,557,390
false
{"Kotlin": 132454}
package day7 import aoc.utils.* data class File(val name: String, val size: Int) data class Directory( val name: String, val parent: Directory?, val dirs: MutableList<Directory> = mutableListOf(), val files: MutableList<File> = mutableListOf() ) { fun cd(dirName: String): Directory { return this.dirs.first { it.name == dirName } } fun size(): Int { val fileSizes = files.sumOf { it.size } val dirSizes = dirs.sumOf { it.size() } return fileSizes + dirSizes } } fun part1(): Int { val root = buildFileSystem() val sizes = listSizes(root) return sizes.filter { it.size <= 100000 }.sumOf { it.size } } fun part2(): Int { val root = buildFileSystem() val sizes = listSizes(root) val sizeAvailable = 70000000 - root.size() val sizeNeeded = 30000000 - sizeAvailable return sizes.filter { it.size >= sizeNeeded } .sortedBy { it.size } .first().size } fun buildFileSystem(): Directory { val input = readInput("day7-input.txt").drop(1) var currentDir = Directory("/", null, mutableListOf()) val root = currentDir input.forEach { if (it.firstPart() == "dir") { currentDir.dirs.add(Directory(it.secondPart(), currentDir)) } if (it.firstPart().matches("\\d*".toRegex())) { currentDir.files.add(File(it.secondPart(), it.firstAsInt())) } if (it.startsWith("$ cd")) { val dirName = it.thirdPart() if (dirName == "..") currentDir = currentDir.parent!! else currentDir = currentDir.cd(dirName) } } return root } data class DirSize(val name: String, val size: Int) fun listSizes(dir: Directory): List<DirSize> { val thisSize = DirSize(dir.name, dir.size()) val others = dir.dirs.map { listSizes(it) }.flatten() return others.plus(thisSize) }
0
Kotlin
0
0
e737bf3112e97b2221403fef6f77e994f331b7e9
1,932
adventOfCode2022
Apache License 2.0
src/year2015/day11/Day11.kt
lukaslebo
573,423,392
false
{"Kotlin": 222221}
package year2015.day11 import check import readInput fun main() { // test if implementation meets criteria from the description, like: val testInput = readInput("2015", "Day11_test") check(part1(testInput), "abcdffaa") val input = readInput("2015", "Day11") println(part1(input)) println(part2(input)) } private fun part1(input: List<String>) = incrementPassword(input.first()) private fun part2(input: List<String>) = incrementPassword(incrementPassword(input.first())) private fun incrementPassword(input: String): String { val oldPassword = input.map { it - 'a' } val password = oldPassword.toMutableList() val confusingLetters = setOf('i' - 'a', 'o' - 'a', 'l' - 'a') while (true) { val cond1 = password.windowed(3).any { it[0] + 1 == it[1] && it[1] + 1 == it[2] } val cond2 = password.none { it in confusingLetters } val cond3 = password.windowed(2).windowed(2).count { (a, b) -> (a[0] == a[1] && a[0] != b[0]) || (b[0] == b[1] && a[0] != b[0]) } >= 2 if (cond1 && cond2 && cond3 && password != oldPassword) return password.toText() password[7] = password[7] + 1 for (i in password.indices.reversed()) { if (password[i] > 25) { password[i] = 0 password[i - 1] = password[i - 1] + 1 } else break } } } private fun List<Int>.toText() = joinToString("") { ('a' + it).toString() }
0
Kotlin
0
1
f3cc3e935bfb49b6e121713dd558e11824b9465b
1,466
AdventOfCode
Apache License 2.0
src/Day07.kt
makohn
571,699,522
false
{"Kotlin": 35992}
fun main() { class TreeNode<T>(val name: String, val value: T, val parent: TreeNode<T>? = null) { val children = mutableListOf<TreeNode<T>>() fun add(child: TreeNode<T>) = children.add(child) } fun TreeNode<Int>.getDirSize(): Int { return children.fold(0) { acc, treeNode -> acc + if (treeNode.value == -1) treeNode.getDirSize() else treeNode.value } } fun getDirs(input: List<String>): List<TreeNode<Int>> { val tree = TreeNode("/", -1) val dirs = mutableListOf(tree) var curDir = tree for (command in input) { val c = command.split(" ") when (c[0]) { "$" -> when (c[1]) { "cd" -> curDir = if (c[2] == "..") curDir.parent!! else { val newDir = TreeNode(c[1], -1, curDir) dirs.add(newDir) curDir.add(newDir) newDir } } "dir" -> Unit else -> curDir.add(TreeNode(c[1], c[0].toInt(), curDir)) } } return dirs } fun part1(input: List<String>) = getDirs(input) .map { it.getDirSize() } .filter { it <= 100_000 } .sum() fun part2(input: List<String>): Int { val dirs = getDirs(input) val root = dirs.first { it.name == "/" } val used = root.getDirSize() val total = 70_000_000 val needed = 30_000_000 val actuallyNeeded = needed - (total - used) return dirs .map { it.getDirSize() } .filter { it >= actuallyNeeded } .min() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day07_test") check(part1(testInput) == 95437) check(part2(testInput) == 24933642) val input = readInput("Day07") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
2734d9ea429b0099b32c8a4ce3343599b522b321
2,005
aoc-2022
Apache License 2.0
src/main/kotlin/aoc/year2023/Day10.kt
SackCastellon
573,157,155
false
{"Kotlin": 62581}
package aoc.year2023 import aoc.Puzzle /** * [Day 10 - Advent of Code 2023](https://adventofcode.com/2023/day/10) */ object Day10 : Puzzle<Int, Int> { override fun solvePartOne(input: String): Int { val (connectionMap, start) = getConnectionMap(input) return connectionMap.getValue(start) .filter { start in connectionMap.getValue(it) } .map { getPath(start to it, connectionMap) } .let { (a, b) -> a zip b } .takeWhile { (a, b) -> a != b } .count() + 1 } override fun solvePartTwo(input: String): Int { val (connectionMap, start) = getConnectionMap(input) val loopPoints = connectionMap.getValue(start) .first { start in connectionMap.getValue(it) } .let { getPath(start to it, connectionMap) } .takeWhile { it != start } .toSet() + start val loopConnectionMap = connectionMap.filterKeys { it in loopPoints }.withDefault { listOf() } val cleanField = input.cleanField(loopConnectionMap) return cleanField.sumOf { it.getContainedTiles() } } private fun getConnectionMap(input: String): Pair<Map<Point, List<Point>>, Point> { lateinit var start: Point return input.lines() .flatMapIndexed { y, line -> line.mapIndexed { x, pipe -> val p = Point(x, y) when (pipe) { '|' -> p to listOf(p.north(), p.south()) '-' -> p to listOf(p.east(), p.west()) 'L' -> p to listOf(p.north(), p.east()) 'J' -> p to listOf(p.north(), p.west()) '7' -> p to listOf(p.south(), p.west()) 'F' -> p to listOf(p.south(), p.east()) '.' -> p to listOf() 'S' -> p to listOf(p.north(), p.south(), p.east(), p.west()).also { start = p } else -> error("Unexpected pipe shape '$pipe'") } } } .toMap() .withDefault { listOf() } .let { it to start } } private fun String.cleanField(connectionMap: Map<Point, List<Point>>): List<List<Char>> { return lines().mapIndexed { y, line -> line.mapIndexed { x, pipe -> val point = Point(x, y) when (val size = connectionMap.getValue(point).size) { 0 -> '.' 2 -> pipe 4 -> { point.getPipe(connectionMap) } else -> error("Unexpected number of connections $size") } } } } private fun Point.getPipe(connectionMap: Map<Point, List<Point>>): Char { val startConnections = connectionMap.getValue(this) .filter { connectionMap.getValue(it).any(::equals) } .toSortedSet() return when (startConnections) { sortedSetOf(north(), south()) -> '|' sortedSetOf(east(), west()) -> '-' sortedSetOf(north(), east()) -> 'L' sortedSetOf(north(), west()) -> 'J' sortedSetOf(south(), west()) -> '7' sortedSetOf(south(), east()) -> 'F' else -> error(startConnections) } } private fun List<Char>.getContainedTiles(): Int { var inside = false var lastCorner: Char? = null var count = 0 for (pipe in this) { if (pipe in setOf('|', 'L', 'J', '7', 'F')) inside = !inside when (pipe) { 'L', 'F' -> lastCorner = pipe '7' -> { if (lastCorner == 'L') inside = !inside lastCorner = null } 'J' -> { if (lastCorner == 'F') inside = !inside lastCorner = null } } if (pipe == '.' && inside) count++ } return count } private fun getPath(direction: Pair<Point, Point>, connections: Map<Point, List<Point>>): Sequence<Point> { return generateSequence(direction) { (prev, curr) -> connections.getValue(curr) .single { it != prev && curr in connections.getValue(it) } .let { curr to it } }.map { it.second } } private data class Point(val x: Int, val y: Int) : Comparable<Point> { fun north() = copy(y = y - 1) fun south() = copy(y = y + 1) fun east() = copy(x = x + 1) fun west() = copy(x = x - 1) override fun compareTo(other: Point): Int = comparator.compare(this, other) companion object { private val comparator = Comparator.comparingInt(Point::x).thenComparingInt(Point::y) } } }
0
Kotlin
0
0
75b0430f14d62bb99c7251a642db61f3c6874a9e
4,911
advent-of-code
Apache License 2.0
src/day04/Day04.kt
skempy
572,602,725
false
{"Kotlin": 13581}
package day04 import readInputAsPairs fun main() { fun part1(input: List<Pair<String, String>>): Int { val ranges = input.map { Pair( it.first.substringBefore('-').toInt()..it.first.substringAfter('-').toInt(), it.second.substringBefore('-').toInt()..it.second.substringAfter('-').toInt() ) } return ranges.count { it.first.min() <= it.second.min() && it.first.max() >= it.second.max() || it.second.min() <= it.first.min() && it.second.max() >= it.first.max() } } fun part2(input: List<Pair<String, String>>): Int { val ranges = input.map { Pair( it.first.substringBefore('-').toInt()..it.first.substringAfter('-').toInt(), it.second.substringBefore('-').toInt()..it.second.substringAfter('-').toInt() ) } return ranges.count { it.first.min() <= it.second.max() && it.second.min() <= it.first.max() } } // test if implementation meets criteria from the description, like: val testInput = readInputAsPairs("Day04", "_test", ',') println("Test Part1: ${part1(testInput)}") check(part1(testInput) == 2) val input = readInputAsPairs("Day04", breakPoint = ',') println("Actual Part1: ${part1(input)}") check(part1(input) == 524) println("Test Part2: ${part2(testInput)}") check(part2(testInput) == 4) println("Actual Part2: ${part2(input)}") check(part2(input) == 798) }
0
Kotlin
0
0
9b6997b976ea007735898083fdae7d48e0453d7f
1,551
AdventOfCode2022
Apache License 2.0
cz.wrent.advent/Day11.kt
Wrent
572,992,605
false
{"Kotlin": 206165}
package cz.wrent.advent fun main() { val result = partOne(input, 20, 3) println("10a: $result") println(result == 51075L) println("10b: ${partOne(input, 10000, 1)}") } private fun partOne(input: String, rounds: Int, divisor: Long): Long { val monkeys = input.split("\n\n").map { it.parseMonkey() } val allMod = monkeys.map { it.testDivisor }.reduce { acc, l -> acc * l } for (i in 1..rounds) { monkeys.forEach { it.turn(monkeys, divisor, allMod) } } val sortedMonkeys = monkeys.sortedByDescending { it.inspections } return (sortedMonkeys.get(0).inspections * sortedMonkeys.get(1).inspections) } private class Monkey( val operation: (Long) -> Long, val testDivisor: Long, val trueMonkey: Int, val falseMonkey: Int, ) { val items = mutableListOf<Long>() var inspections = 0L fun add(item: Long) { items.add(item) } fun turn(monkeys: List<Monkey>, divisor: Long, allMod: Long?) { items.forEach { val worry = (operation(it) / divisor).let { w -> if (allMod != null) w % allMod else w } if (worry % testDivisor == 0L) { monkeys[trueMonkey].add(worry) } else { monkeys[falseMonkey].add(worry) } inspections++ } items.clear() } } private fun String.parseMonkey(): Monkey { val lines = this.split("\n") val startingItems = lines.get(1).replace(" Starting items: ", "").split(", ").map { it.toLong() } val operationData = lines.get(2).replace(" Operation: new = old ", "").split(" ") val operationNum = if (operationData.get(1) == "old") null else operationData.get(1).toLong() val operation: (Long) -> Long = if (operationData.first() == "*") { { it * (operationNum ?: it) } } else { { it + (operationNum ?: it) } } val testDivisor = lines.get(3).replace(" Test: divisible by ", "").toLong() val trueMonkey = lines.get(4).replace(" If true: throw to monkey ", "").toInt() val falseMonkey = lines.get(5).replace(" If false: throw to monkey ", "").toInt() val monkey = Monkey(operation, testDivisor, trueMonkey, falseMonkey) startingItems.forEach { monkey.add(it) } return monkey } private const val input = """Monkey 0: Starting items: 66, 79 Operation: new = old * 11 Test: divisible by 7 If true: throw to monkey 6 If false: throw to monkey 7 Monkey 1: Starting items: 84, 94, 94, 81, 98, 75 Operation: new = old * 17 Test: divisible by 13 If true: throw to monkey 5 If false: throw to monkey 2 Monkey 2: Starting items: 85, 79, 59, 64, 79, 95, 67 Operation: new = old + 8 Test: divisible by 5 If true: throw to monkey 4 If false: throw to monkey 5 Monkey 3: Starting items: 70 Operation: new = old + 3 Test: divisible by 19 If true: throw to monkey 6 If false: throw to monkey 0 Monkey 4: Starting items: 57, 69, 78, 78 Operation: new = old + 4 Test: divisible by 2 If true: throw to monkey 0 If false: throw to monkey 3 Monkey 5: Starting items: 65, 92, 60, 74, 72 Operation: new = old + 7 Test: divisible by 11 If true: throw to monkey 3 If false: throw to monkey 4 Monkey 6: Starting items: 77, 91, 91 Operation: new = old * old Test: divisible by 17 If true: throw to monkey 1 If false: throw to monkey 7 Monkey 7: Starting items: 76, 58, 57, 55, 67, 77, 54, 99 Operation: new = old + 6 Test: divisible by 3 If true: throw to monkey 2 If false: throw to monkey 1"""
0
Kotlin
0
0
8230fce9a907343f11a2c042ebe0bf204775be3f
3,369
advent-of-code-2022
MIT License
src/main/kotlin/ru/timakden/aoc/year2022/Day13.kt
timakden
76,895,831
false
{"Kotlin": 321649}
package ru.timakden.aoc.year2022 import ru.timakden.aoc.util.measure import ru.timakden.aoc.util.readInput /** * [Day 13: Distress Signal](https://adventofcode.com/2022/day/13). */ object Day13 { @JvmStatic fun main(args: Array<String>) { measure { val input = readInput("year2022/Day13") println("Part One: ${part1(input)}") println("Part Two: ${part2(input)}") } } fun part1(input: List<String>): Int { var pairIndex = 0 return (0..input.lastIndex step 3).map { i -> val list1 = buildList(input[i]) val list2 = buildList(input[i + 1]) pairIndex++ pairIndex to compare(list1, list2) }.filter { it.second == -1 }.sumOf { it.first } } fun part2(input: List<String>) = input.filter { it.isNotBlank() } .map { buildList(it) } .toMutableList() .also { it.add(buildList("[[2]]")) it.add(buildList("[[6]]")) }.sortedWith { o1, o2 -> compare(o1, o2) } .mapIndexed { index, anies -> index + 1 to anies } .filter { it.second == listOf(listOf(2)) || it.second == listOf(listOf(6)) } .fold(1) { acc, i -> acc * i.first } private fun buildList(input: String): List<Any> { val stack = ArrayDeque<MutableList<Any>>() var currentList: MutableList<Any>? = null var string = input while (string.isNotEmpty()) { when { string.first() == '[' -> { currentList?.let { stack.addLast(it) } currentList = mutableListOf() string = string.drop(1) } string.first() == ']' -> { stack.removeLastOrNull()?.let { previousList -> previousList.add(currentList as Any) currentList = previousList } string = string.drop(1) } string.first() == ',' -> string = string.drop(1) else -> { "\\d+".toRegex().find(string)?.value?.toIntOrNull()?.let { currentList?.add(it) string = if (it > 9) string.drop(2) else string.drop(1) } } } } return currentList!! } private fun compare(left: Any, right: Any): Int { if (left is Int && right is Int) return left.compareTo(right) val leftIterator = (if (left is List<*>) left else listOf(left)).iterator() val rightIterator = (if (right is List<*>) right else listOf(right)).iterator() while (true) { val hasLeft = leftIterator.hasNext() val hasRight = rightIterator.hasNext() if (!hasLeft && !hasRight) return 0 else if (!hasLeft) return -1 else if (!hasRight) return 1 else { val result = compare(checkNotNull(leftIterator.next()), checkNotNull(rightIterator.next())) if (result != 0) return result } } } }
0
Kotlin
0
3
acc4dceb69350c04f6ae42fc50315745f728cce1
3,163
advent-of-code
MIT License
src/main/kotlin/solutions/CHK/CheckoutSolution.kt
DPNT-Sourcecode
748,885,607
false
{"Kotlin": 21624, "Shell": 2184}
package solutions.CHK object CheckoutSolution { fun checkout(skus: String): Int { val skuList = skus.map { it.toString() } if (containsInvalidSkus(skuList)) { return -1 } val checkoutItemsMap = getCheckoutItemsMap(skuList) val items = setupItems() return getSumOfItems(checkoutItemsMap, items) } private fun getSumOfItems(checkoutItemsMap: Map<Char, Int>, items: List<Item>): Int { val remainingCheckoutItemsMap = removeFreeItems(checkoutItemsMap, items).toMutableMap() val totalBundlePrice = setupBundleOffers().sumOf { applyMostExpensiveBundle(remainingCheckoutItemsMap, items, it) } val remainingItemsSum = remainingCheckoutItemsMap.entries.sumOf { (sku, quantity) -> calculateItemCost(sku, quantity, items) ?: return -1 } return totalBundlePrice + remainingItemsSum } private fun calculateItemCost(sku: Char, quantity: Int, items: List<Item>): Int? { val item = items.find { it.sku == sku } ?: return null return calculateCostWithSpecialOffers(item, quantity) } private fun calculateCostWithSpecialOffers(item: Item, quantity: Int): Int { val sortedSpecialOffers = item.specialOffers.sortedByDescending { it.quantity } var totalCost = 0 var remainingQuantity = quantity for (specialOffer in sortedSpecialOffers) { if (specialOffer.price != null) { val applicableTimes = remainingQuantity / specialOffer.quantity totalCost += applicableTimes * specialOffer.price remainingQuantity -= applicableTimes * specialOffer.quantity } else if (specialOffer.freeSku != null) { remainingQuantity -= specialOffer.quantity totalCost += item.price * specialOffer.quantity } } totalCost += remainingQuantity * item.price return totalCost } private fun applyMostExpensiveBundle(checkoutItemsMap: MutableMap<Char, Int>, items: List<Item>, bundleOffer: BundleOffer): Int { var totalBundlePrice = 0 while (canFormBundle(checkoutItemsMap, bundleOffer.skus, bundleOffer.quantity)) { val sortedEligibleItems = items.filter { it.sku in bundleOffer.skus && checkoutItemsMap.getOrDefault(it.sku, 0) > 0 } .sortedByDescending { it.price } val selectedItems = selectItemsForBundle(checkoutItemsMap, sortedEligibleItems, bundleOffer.quantity) if (selectedItems.isNotEmpty()) { selectedItems.forEach { sku -> checkoutItemsMap[sku] = checkoutItemsMap[sku]!! - 1 if (checkoutItemsMap[sku]!! <= 0) { checkoutItemsMap.remove(sku) } } totalBundlePrice += bundleOffer.price } else { break } } return totalBundlePrice } private fun canFormBundle(checkoutItemsMap: Map<Char, Int>, skus: List<Char>, bundleQuantity: Int): Boolean { return checkoutItemsMap.filterKeys { it in skus }.values.sum() >= bundleQuantity } private fun selectItemsForBundle(checkoutItemsMap: Map<Char, Int>, sortedItems: List<Item>, bundleQuantity: Int): List<Char> { val selectedItems = mutableListOf<Char>() var count = 0 for (item in sortedItems) { val availableQuantity = checkoutItemsMap.getOrDefault(item.sku, 0) val quantityToAdd = minOf(availableQuantity, bundleQuantity - count) repeat(quantityToAdd) { selectedItems.add(item.sku) } count += quantityToAdd if (count >= bundleQuantity) break } return if (count >= bundleQuantity) selectedItems else listOf() } private fun removeFreeItems(checkoutItemsMap: Map<Char, Int>, items: List<Item>): Map<Char, Int> { val updatedCheckoutItemsMap = checkoutItemsMap.toMutableMap() checkoutItemsMap.forEach { (sku, quantity) -> items.find { it.sku == sku }?.let { item -> processItemForFreeOffers(updatedCheckoutItemsMap, item, quantity) } } return updatedCheckoutItemsMap.filter { it.value > 0 } } private fun processItemForFreeOffers(updatedCheckoutItemsMap: MutableMap<Char, Int>, item: Item, quantity: Int) { item.specialOffers.sortedByDescending { it.quantity } .forEach { offer -> applySpecialOffer(updatedCheckoutItemsMap, offer, quantity) } } private fun applySpecialOffer(updatedCheckoutItemsMap: MutableMap<Char, Int>, offer: SpecialOffer, quantity: Int) { var applicableTimes = quantity / offer.quantity while (applicableTimes > 0 && offer.freeSku != null) { val freeItemQuantity = updatedCheckoutItemsMap[offer.freeSku] if (freeItemQuantity != null && freeItemQuantity > 0) { updatedCheckoutItemsMap[offer.freeSku] = freeItemQuantity - 1 applicableTimes-- } else { break } } } private fun getCheckoutItemsMap(skuList: List<String>): Map<Char, Int> { return skuList .flatMap { it.toList() } .groupingBy { it } .eachCount() } private fun containsInvalidSkus(skuList: List<String>): Boolean { return skuList.any { it.none(Char::isLetter) } } private fun setupItems(): List<Item> { return listOf( Item('A', 50, listOf(SpecialOffer(3, 130), SpecialOffer(5, 200))), Item('B', 30, listOf(SpecialOffer(2, 45))), Item('C', 20), Item('D', 15), Item('E', 40, listOf(SpecialOffer(2, freeSku = 'B'))), Item('F', 10, listOf(SpecialOffer(3, freeSku = 'F'))), Item('G', 20), Item('H', 10, listOf(SpecialOffer(5, price = 45), SpecialOffer(10, price = 80))), Item('I', 35), Item('J', 60), Item('K', 70, listOf(SpecialOffer(2, price = 120))), Item('L', 90), Item('M', 15), Item('N', 40, listOf(SpecialOffer(3, freeSku = 'M'))), Item('O', 10), Item('P', 50, listOf(SpecialOffer(5, price = 200))), Item('Q', 30, listOf(SpecialOffer(3, price = 80))), Item('R', 50, listOf(SpecialOffer(3, freeSku = 'Q'))), Item('S', 20), Item('T', 20), Item('U', 40, listOf(SpecialOffer(4, freeSku = 'U'))), Item('V', 50, listOf(SpecialOffer(2, price = 90), SpecialOffer(3, price = 130))), Item('W', 20), Item('X', 17), Item('Y', 20), Item('Z', 21), ) } private fun setupBundleOffers(): List<BundleOffer> { return listOf( BundleOffer( 3, 45, listOf('S', 'T', 'X', 'Y', 'Z'), ), ) } } data class Item( val sku: Char, val price: Int, val specialOffers: List<SpecialOffer> = emptyList(), ) data class SpecialOffer( val quantity: Int, val price: Int? = null, val freeSku: Char? = null ) data class BundleOffer( val quantity: Int, val price: Int, val skus: List<Char> = emptyList(), )
0
Kotlin
0
0
326235b3112d321afbce5aaeb84a60a51cc09b0e
7,413
CHK-cvvr01
Apache License 2.0
src/main/kotlin/Day8.kt
cbrentharris
712,962,396
false
{"Kotlin": 171464}
import kotlin.String import kotlin.collections.List object Day8 { data class Node(var left: Node?, var right: Node?, val key: String) data class DesertMap(val directions: CharArray, val root: Node?) { companion object { fun parse(input: List<String>): DesertMap { val directions = input.first().toCharArray() val nodes = parseNodes(input.drop(2)) val root = nodes.find { it.key == "AAA" } return DesertMap(directions, root) } fun parsePart2(input: List<String>): List<DesertMap> { val directions = input.first().toCharArray() val nodes = parseNodes(input.drop(2)) val roots = nodes.filter { it.key.endsWith("A") } return roots.map { DesertMap(directions, it) } } private fun parseNodes(input: List<String>): List<Node> { val index = mutableMapOf<String, Node>() val nodePattern = "(\\w+) = \\((\\w+), (\\w+)\\)".toRegex() for (line in input) { val (key, left, right) = nodePattern.matchEntire(line)!!.destructured val leftNode = index.getOrPut(left) { Node(null, null, left) } val rightNode = index.getOrPut(right) { Node(null, null, right) } val keyNode = index.getOrPut(key) { Node(null, null, key) } keyNode.left = leftNode keyNode.right = rightNode } return index.values.toList() } } } fun part1(input: List<String>): String { val desertMap = DesertMap.parse(input) return followUntilExit(desertMap.directions, desertMap.root, 0).toString() } private tailrec fun followUntilExit( directions: CharArray, currentNode: Node?, currentSteps: Long, exitCondition: (Node) -> Boolean = { it.key == "ZZZ" } ): Long { if (currentNode == null || exitCondition(currentNode)) { return currentSteps } val nextNode = if (directions.first() == 'L') { currentNode.left } else { currentNode.right } return followUntilExit(directions.rotate(1), nextNode, currentSteps + 1, exitCondition) } fun part2(input: List<String>): String { val desertMaps = DesertMap.parsePart2(input) return followUntilAllExit(desertMaps).toString() } private fun followUntilAllExit(desertMaps: List<DesertMap>): Long { val requiredStepsUntilExit = desertMaps.map { followUntilExit(it.directions, it.root, 0) { it.key.endsWith("Z") } } return leastCommonMultiple(requiredStepsUntilExit) } private fun leastCommonMultiple(requiredStepsUntilExit: List<Long>): Long { return requiredStepsUntilExit.reduce { a, b -> lcm(a, b) } } private fun lcm(a: Long, b: Long): Long { return a * b / gcd(a, b) } private fun gcd(a: Long, b: Long): Long { return if (b == 0L) a else gcd(b, a % b) } private fun CharArray.rotate(n: Int) = let { sliceArray(n..<size) + sliceArray(0..<n) } }
0
Kotlin
0
1
f689f8bbbf1a63fecf66e5e03b382becac5d0025
3,243
kotlin-kringle
Apache License 2.0
2017/src/main/kotlin/Day24.kt
dlew
498,498,097
false
{"Kotlin": 331659, "TypeScript": 60083, "JavaScript": 262}
import utils.splitNewlines object Day24 { fun part1(input: String): Int { return strongestBridge(0, parseComponents(input)) } fun part2(input: String): Int { return longestAndStrongestBridge(0, parseComponents(input)).strength } private fun strongestBridge(port: Int, components: List<Component>): Int { return components .filter { it.head == port || it.tail == port } .map { it.strength + strongestBridge(it.connect(port), components - it) } .max() ?: 0 } private fun longestAndStrongestBridge(port: Int, components: List<Component>): Bridge { return components .filter { it.head == port || it.tail == port } .map { longestAndStrongestBridge(it.connect(port), components - it).withComponent(it) } .maxBy { it.comparable } ?: Bridge(0, 0) } private data class Component(val head: Int, val tail: Int) { val strength = head + tail fun connect(port: Int) = if (port == head) tail else head } private data class Bridge(val length: Int, val strength: Int) { val comparable = length * 10000 + strength fun withComponent(component: Component) = Bridge(length + 1, strength + component.strength) } private fun parseComponents(input: String): List<Component> { return input.splitNewlines().map { val split = it.split("/") Component(split[0].toInt(), split[1].toInt()) } } }
0
Kotlin
0
0
6972f6e3addae03ec1090b64fa1dcecac3bc275c
1,404
advent-of-code
MIT License
src/Day02.kt
ShuffleZZZ
572,630,279
false
{"Kotlin": 29686}
private const val RPS_SIZE = 3 private fun String.toInt() = when (this) { "A", "X" -> 1 "B", "Y" -> 2 "C", "Z" -> 3 else -> error("Incorrect input") } private fun Pair<Int, Int>.game1() = second + when { first % RPS_SIZE + 1 == second -> 6 first == second -> 3 (first + 1) % RPS_SIZE + 1 == second -> 0 else -> error("Incorrect input game 1") } private fun Pair<Int, Int>.game2() = when (second) { 1 -> (first + 1) % RPS_SIZE + 1 2 -> 3 + first 3 -> 6 + first % RPS_SIZE + 1 else -> error("Incorrect input game 2") } private fun parseInput(input: List<String>) = input.map { it.trim().split(' ', limit = 2) }.map { it.first().toInt() to it.last().toInt() } fun main() { fun part1(input: List<String>) = parseInput(input).sumOf { it.game1() } fun part2(input: List<String>) = parseInput(input).sumOf { it.game2() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day02_test") check(part1(testInput) == 15) check(part2(testInput) == 12) val input = readInput("Day02") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
5a3cff1b7cfb1497a65bdfb41a2fe384ae4cf82e
1,156
advent-of-code-kotlin
Apache License 2.0
src/day14.kt
skuhtic
572,645,300
false
{"Kotlin": 36109}
import kotlin.math.max import kotlin.math.min fun main() { day14.execute(onlyTests = false, forceBothParts = true) } val day14 = object : Day<Int>(14, 24, 93) { // 93 override val testInput: InputData get() = """ 498,4 -> 498,6 -> 496,6 503,4 -> 502,4 -> 502,9 -> 494,9 """.trimIndent().lines() override fun part1(input: InputData): Int = solution(input) override fun part2(input: InputData): Int = solution(input, true) fun solution(input: InputData, floorInsteadAbyss: Boolean = false): Int { val (cave, abyss) = parseCave(input) val work = cave.toMutableSet() val px = listOf(0, -1, 1) fun drop(floorInsteadAbyss: Boolean): Rock? { var y = 0 var x = 500 while (true) { val dx = px.firstOrNull { !work.contains(Rock(x + it, y + 1)) } if (dx == null && y == 0 && !work.contains(Rock(x, y))) { "full".logIt() return Rock(x, y) } x += dx ?: return Rock(x, y) if (floorInsteadAbyss && y == abyss + 1) return Rock(x, y) if (++y == abyss && !floorInsteadAbyss) break } return null } while (true) { val new = drop(floorInsteadAbyss) ?: break // work.debugPrint(cave) if (!work.add(new)) break } work.debugPrint(cave) return work.size - cave.size } fun parseCave(input: InputData): Pair<Set<Rock>, Int> { var abyss = 0 return buildSet { input.forEach { line -> line.split(" -> ").map { p -> p.split(',').let { it.first().toInt() to it.last().toInt() } }.windowed(2) { (from, to) -> abyss = max(abyss, max(from.second, to.second)) when { from.first == to.first -> { val f = min(from.second, to.second) val t = max(from.second, to.second) (f..t).map { from.first to it } } from.second == to.second -> { val f = min(from.first, to.first) val t = max(from.first, to.first) (f..t).map { it to to.second } } else -> error("Input: $line") }.forEach { add(it) } } } } to abyss } } private typealias Rock = Pair<Int, Int> private fun Set<Rock>.debugPrint(init: Set<Rock>) { var xMax = 500 var xMin = 500 var yMin = 0 var yMax = 0 forEach { xMin = min(xMin, it.first) xMax = max(xMax, it.first + 1) yMin = min(yMin, it.second) yMax = max(yMax, it.second + 1) } val board = (yMin..yMax).map { ".".repeat(xMax - xMin).toCharArray() } forEach { (x, y) -> board[y - yMin][x - xMin] = 'o' } init.forEach { (x, y) -> board[y - yMin][x - xMin] = '#' } println(board.joinToString("\n", "\n") { it.joinToString("") }) }
0
Kotlin
0
0
8de2933df90259cf53c9cb190624d1fb18566868
3,217
aoc-2022
Apache License 2.0
year2022/src/main/kotlin/net/olegg/aoc/year2022/day8/Day8.kt
0legg
110,665,187
false
{"Kotlin": 511989}
package net.olegg.aoc.year2022.day8 import net.olegg.aoc.someday.SomeDay import net.olegg.aoc.utils.Directions.Companion.NEXT_4 import net.olegg.aoc.utils.Vector2D import net.olegg.aoc.utils.fit import net.olegg.aoc.utils.get import net.olegg.aoc.year2022.DayOf2022 /** * See [Year 2022, Day 8](https://adventofcode.com/2022/day/8) */ object Day8 : DayOf2022(8) { override fun first(): Any? { val trees = matrix.map { line -> line.map { Tree( height = it.digitToInt(), ) } } trees.forEach { row -> row.fold(-1) { height, tree -> tree.left = tree.height > height maxOf(tree.height, height) } row.asReversed().fold(-1) { height, tree -> tree.right = tree.height > height maxOf(tree.height, height) } } trees.first().indices.forEach { column -> trees.indices.fold(-1) { height, row -> val tree = trees[row][column] tree.up = tree.height > height maxOf(tree.height, height) } } trees.first().indices.forEach { column -> trees.indices.reversed().fold(-1) { height, row -> val tree = trees[row][column] tree.down = tree.height > height maxOf(tree.height, height) } } return trees.sumOf { row -> row.count { it.visible } } } override fun second(): Any? { val trees = matrix.map { line -> line.map { Tree( height = it.digitToInt(), ) } } val scenicScores = trees.mapIndexed { y, row -> row.mapIndexed { x, tree -> val start = Vector2D(x, y) NEXT_4 .map { dir -> val line = generateSequence(start) { it + dir.step } .drop(1) .takeWhile { trees.fit(it) } .mapNotNull { trees[it] } .toList() val distance = line.indexOfFirst { it.height >= tree.height } if (distance == -1) line.size else distance + 1 } .map { it.toLong() } .reduce(Long::times) } } return scenicScores.maxOf { it.max() } } data class Tree( val height: Int, var left: Boolean = false, var right: Boolean = false, var up: Boolean = false, var down: Boolean = false, ) { val visible: Boolean get() = left || right || up || down } } fun main() = SomeDay.mainify(Day8)
0
Kotlin
1
7
e4a356079eb3a7f616f4c710fe1dfe781fc78b1a
2,410
adventofcode
MIT License
kotlin/src/commonMain/kotlin/y2016/Day1.kt
emmabritton
358,239,150
false
{"Rust": 18706, "Kotlin": 13302, "JavaScript": 8960}
package y2016 import kotlin.math.abs fun runY2016D1(input: String): Pair<String, String> { val steps = input.split(",") .map { parse(it.trim()) } val (distance, firstRepeat) = travel(steps) return Pair(distance.toString(), firstRepeat.toString()) } fun parse(input: String): Move { if (input.length == 1) { throw IllegalArgumentException("Too short: $input") } val number = input.substring(1).toIntOrNull() ?: throw IllegalArgumentException("Invalid number: $input") return when (input.first()) { 'R' -> Move.Right(number) 'L' -> Move.Left(number) else -> throw IllegalArgumentException("Invalid letter: $input") } } fun travel(moves: List<Move>): Pair<Int, Int> { val visited = HashSet<Coord>() val pos = Coord(0,0) var dir = Direction.North var firstRepeat: Coord? = null for (move in moves) { dir = dir.update(move) val walked = pos.walk(dir, move) for (step in walked) { if (firstRepeat == null) { if (visited.contains(step)) { firstRepeat = step } println("Visited ${step.x},${step.y}"); visited.add(step) } } } return Pair(pos.distance(), firstRepeat?.distance() ?: 0) } data class Coord( var x: Int, var y: Int ) { fun distance(): Int { return abs(x) + abs(y) } fun walk(dir: Direction, move: Move): List<Coord> { var list = listOf<Coord>() when (dir) { Direction.North -> { list = (1..move.dist).map { Coord(this.x, this.y + it) } this.y += move.dist } Direction.East -> { list = (1..move.dist).map { Coord(this.x + it, this.y) } this.x += move.dist } Direction.South -> { list = (1..move.dist).map { Coord(this.x, this.y - it) } this.y -= move.dist } Direction.West -> { list = (1..move.dist).map { Coord(this.x - it, this.y) } this.x -= move.dist } } return list } } enum class Direction { North, East, South, West; fun update(move: Move): Direction { return when (this) { North -> if (move is Move.Left) West else East East -> if (move is Move.Left) North else South South -> if (move is Move.Left) East else West West -> if (move is Move.Left) South else North } } } sealed class Move(val dist: Int) { class Left(dist: Int): Move(dist) class Right(dist: Int): Move(dist) }
0
Rust
0
0
c041d145c9ac23ce8d7d7f48e419143c73daebda
2,721
advent-of-code
MIT License
src/Day07.kt
HenryCadogan
574,509,648
false
{"Kotlin": 12228}
fun main() { // val input = readInput("Day07") val input = readInput("Day07") fun part1(input: List<String>): Int { val directoryWalker = DirectoryWalker(input) val rootDirectory = directoryWalker.walkDirectory() val allDirectories= rootDirectory.getAllSubDirectories() return allDirectories.filter { it.size() < 100000 }.sumOf { it.size() } } fun part2(input: List<String>): Int { val directoryWalker = DirectoryWalker(input) val rootDirectory = directoryWalker.walkDirectory() val allDirectories= rootDirectory.getAllSubDirectories() val sizeNeeded = 30000000 - (70000000 - rootDirectory.size()) return allDirectories.filter{it.size() > sizeNeeded}.minBy { it.size() }.size() } println(part1(input)) println(part2(input)) } class DirectoryWalker(private val instructions: List<String>) { private val rootDirectory = Directory("Root") private var currentDirectory: Directory = rootDirectory fun walkDirectory(): Directory { instructions.forEach { command -> when { command.startsWith("$ cd") -> handleDirMove(command) command.startsWith("$ ls") -> {} command.startsWith("dir") -> addInnerDirectory(command.drop(4).trim()) else -> { addFile(command) } } } return rootDirectory } private fun handleDirMove(command: String) { val location = command.drop(5) when (location) { "/" -> gotToOuterMostDirectory() ".." -> currentDirectory = currentDirectory.parent ?: error("Directory ${currentDirectory.name} has no parent") else -> { currentDirectory = currentDirectory.childDirectories.single { it.name == location } } } } private fun gotToOuterMostDirectory() { currentDirectory = generateSequence(currentDirectory){ it.parent }.last() } private fun addInnerDirectory(name: String) { currentDirectory.childDirectories.add(Directory(name, parent = currentDirectory)) } private fun addFile(definition: String) { val size = definition.takeWhile { it.isDigit() }.toInt() val name = definition.dropWhile { it.isDigit() }.trim() currentDirectory.files.add(ContentFile(name = name, size = size)) } } interface AFile { val name: String fun size(): Int } data class Directory( override val name: String, val parent: Directory? = null, val childDirectories: MutableList<Directory> = mutableListOf(), val files: MutableList<ContentFile> = mutableListOf(), ) : AFile{ override fun toString(): String { return "Directory($name)" } override fun size(): Int { return files.sumOf{it.size} + childDirectories.fold(0) { acc, directory -> acc + directory.size() } } } fun Directory.getAllSubDirectories(): List<Directory>{ return if (this.childDirectories.isEmpty()) { listOf(this) } else { val directories = this.childDirectories.flatMap { it.getAllSubDirectories() }.toMutableList() directories.add(this) directories } } data class ContentFile( override val name: String, val size: Int, ) : AFile { override fun size(): Int = size }
0
Kotlin
0
0
0a0999007cf16c11355fcf32fc8bc1c66828bbd8
3,404
AOC2022
Apache License 2.0
src/main/kotlin/days/y2023/day11_a/Day11.kt
jewell-lgtm
569,792,185
false
{"Kotlin": 161272, "Jupyter Notebook": 103410, "TypeScript": 78635, "JavaScript": 123}
package days.y2023.day11_a import util.InputReader import util.timeIt import kotlin.math.abs typealias PuzzleLine = String typealias PuzzleInput = List<PuzzleLine> class Day11(val input: PuzzleInput) { private val galaxyPositions = input.galaxyPositions() private val galaxyYs = galaxyPositions.map { it.y }.toSet() private val galaxyXs = galaxyPositions.map { it.x }.toSet() private val emptyYs = input.indices.toSet() - galaxyYs private val emptyXs = input[0].indices.toSet() - galaxyXs fun partOne(): ULong { return galaxyPositions.pairwise().sumOf { (a, b) -> a.nonManhattanDistance(b, 2).toULong() } } fun partTwo(): ULong { return galaxyPositions.pairwise().sumOf { (a, b) -> a.nonManhattanDistance(b, 1000000).toULong() } } private fun List<Int>.dilateSpacetime(factor: Int): Int = size * factor private fun Position.nonManhattanDistance(other: Position, universeAge: Int) = (nonManhattanX(other, universeAge) + nonManhattanY(other, universeAge)) private fun Position.emptyColsBetween(other: Position): List<Int> = emptyXs.whereIn(xRange(other)) private fun Position.emptyRowsBetween(other: Position): List<Int> = emptyYs.whereIn(yRange(other)) private fun Position.nonManhattanY( other: Position, universeAge: Int ) = manhattanY(other) + emptyRowsBetween(other).dilateSpacetime(universeAge - 1) private fun Position.nonManhattanX( other: Position, universeAge: Int ) = manhattanX(other) + emptyColsBetween(other).dilateSpacetime(universeAge - 1) } private data class Position(val y: Int, val x: Int) private fun PuzzleInput.galaxyPositions(): List<Position> = allCharPositionsWhere { char -> char == '#' } private fun PuzzleInput.allCharPositionsWhere(predicate: (c: Char) -> Boolean): List<Position> = this.flatMapIndexed { y, row -> row.mapIndexedNotNull { x, c -> if (predicate(c)) Position(y, x) else null } } private fun Position.manhattanX(other: Position): Int = abs(this.x - other.x) private fun Position.manhattanY(other: Position): Int = abs(this.y - other.y) private fun Position.xRange(other: Position): IntRange = if (this.x < other.x) this.x..other.x else other.x..this.x private fun Position.yRange(other: Position): IntRange = if (this.y < other.y) this.y..other.y else other.y..this.y private fun Collection<Int>.whereIn(range: IntRange) = this.filter { it in range } private fun <E> List<E>.fromIndex(i: Int) = subList(i, size) private fun <E> List<E>.pairwise(): Sequence<Pair<E, E>> = asSequence().flatMapIndexed { i, e -> fromIndex(i + 1).asSequence().map { j -> Pair(e, j) } } fun main() { timeIt { val year = 2023 val day = 11 val exampleInput: PuzzleInput = InputReader.getExampleLines(year, day) val puzzleInput: PuzzleInput = InputReader.getPuzzleLines(year, day) fun partOne(input: PuzzleInput) = Day11(input).partOne() fun partTwo(input: PuzzleInput) = Day11(input).partTwo() println("Example 1: ${partOne(exampleInput)}") println("Part 1: ${partOne(puzzleInput)}") println("Example 2: ${partTwo(exampleInput)}") println("Part 2: ${partTwo(puzzleInput)}") } }
0
Kotlin
0
0
b274e43441b4ddb163c509ed14944902c2b011ab
3,295
AdventOfCode
Creative Commons Zero v1.0 Universal
src/main/kotlin/days/Day09.kt
julia-kim
569,976,303
false
null
package days import Point import readInput import kotlin.math.absoluteValue fun main() { fun printTail(visited: List<Point>) { var rows = visited.maxOf { it.y } while (rows >= visited.minOf { it.y }) { var cols = visited.minOf { it.x } while (cols <= visited.maxOf { it.x }) { if (visited.contains(Point(cols, rows))) { if (rows == 0 && cols == 0) { print("s") } else print("#") } else print(".") cols++ } println() rows-- } } fun moveTail(x: Int, y: Int, tail: Point): Point { val dx = (x - tail.x) val dy = (y - tail.y) if (dx.absoluteValue <= 1 && dy.absoluteValue <= 1) return tail when { (dx == 2 && dy >= 1) || (dx >= 1 && dy == 2) -> { tail.x += 1 tail.y += 1 } (dx == 2 && dy <= -1) || (dx >= 1 && dy == -2) -> { tail.x += 1 tail.y -= 1 } (dx == -2 && dy <= -1) || (dx <= -1 && dy == -2) -> { tail.x -= 1 tail.y -= 1 } (dx == -2 && dy >= 1) || (dx <= -1 && dy == 2) -> { tail.x -= 1 tail.y += 1 } (dx == -2) -> { tail.x -= 1 } (dx == 2) -> { tail.x += 1 } (dy == 2) -> { tail.y += 1 } (dy == -2) -> { tail.y -= 1 } } return Point(tail.x, tail.y) } fun part1(input: List<String>): Int { val head = Point(0, 0) val tail = Point(0, 0) val visitedPoints: MutableList<Point> = mutableListOf(tail) input.forEach { val direction = it.take(1) var steps = it.split(" ").last().toInt() while (steps > 0) { when (direction) { "R" -> head.x += 1 "L" -> head.x -= 1 "U" -> head.y += 1 "D" -> head.y -= 1 } val newTail = moveTail(head.x, head.y, tail.copy()) tail.x = newTail.x tail.y = newTail.y visitedPoints.add(newTail) steps-- } } return visitedPoints.distinctBy { it.x to it.y }.size } fun part2(input: List<String>): Int { val rope = (0 until 10).map { Point(0, 0) }.toMutableList() val visitedPoints = mutableListOf(rope[9]) input.forEach { val direction = it.take(1) var steps = it.split(" ").last().toInt() while (steps > 0) { when (direction) { "R" -> rope[0].x += 1 "L" -> rope[0].x -= 1 "U" -> rope[0].y += 1 "D" -> rope[0].y -= 1 } (1..9).forEach { i -> val tail = moveTail(rope[i - 1].x, rope[i - 1].y, rope[i].copy()) rope[i] = tail } visitedPoints.add(rope[9]) steps-- } } val visited = visitedPoints.distinctBy { it.x to it.y } printTail(visited) return visited.size } val testInput = readInput("Day09_test") check(part1(testInput) == 88) check(part2(testInput) == 36) val input = readInput("Day09") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
65188040b3b37c7cb73ef5f2c7422587528d61a4
3,663
advent-of-code-2022
Apache License 2.0
src/main/kotlin/days/Day12.kt
hughjdavey
725,972,063
false
{"Kotlin": 76988}
package days import xyz.hughjd.aocutils.Collections.stackOf import xyz.hughjd.aocutils.Strings.indicesOf class Day12 : Day(12) { override fun partOne(): Any { return inputList.map { ConditionRecord(it) }.sumOf { it.possibleArrangements().size } } override fun partTwo(): Any { return 0 //return inputList.map { ConditionRecord(unfold(it)) }.sumOf { it.possibleArrangements().size } } fun unfold(record: String): String { val (springsStr, sizesStr) = record.split(' ') return "${springsStr}?".repeat(5).dropLast(1) + ' ' + "${sizesStr},".repeat(5).dropLast(1) } class ConditionRecord(private val record: String) { val springs: List<SpringCondition> val sizes: List<Int> init { val (springsStr, sizesStr) = record.split(' ') springs = springsStr.map { when (it) { '.' -> SpringCondition.OPERATIONAL '#' -> SpringCondition.DAMAGED else -> SpringCondition.UNKNOWN } } sizes = sizesStr.split(',').map { it.toInt() } } fun possibleArrangements(): List<String> { val questionMarkIndices = record.indicesOf('?') val possibleStrings = allPossibleStrings(questionMarkIndices.size) return possibleStrings.map { val charStack = stackOf(it.toList()) record.mapIndexed { index, c -> if (questionMarkIndices.contains(index)) charStack.pop() else c } .joinToString("") }.filter(ConditionRecord::isValidArrangement) } companion object { fun isValidArrangement(arrangement: String): Boolean { val cr = ConditionRecord(arrangement) return cr.springs.none { it == SpringCondition.UNKNOWN } && cr.springs.filter { it == SpringCondition.DAMAGED }.size == cr.sizes.sum() && validDamageRanges(arrangement, cr) } private fun validDamageRanges(arrangement: String, conditionRecord: ConditionRecord): Boolean { val damageRanges = Regex("#+").findAll(arrangement).toList().map { it.range } return damageRanges.map { it.count() } == conditionRecord.sizes } // see https://www.geeksforgeeks.org/print-all-combinations-of-given-length fun allPossibleStrings(length: Int, charset: List<Char> = listOf('.', '#'), prefix: String = "", strings: List<String> = emptyList()): List<String> { if (length == 0) { return strings + prefix } return charset.flatMap { char -> allPossibleStrings(length - 1, charset, prefix + char, strings) } } } } enum class SpringCondition { OPERATIONAL, DAMAGED, UNKNOWN } }
0
Kotlin
0
0
330f13d57ef8108f5c605f54b23d04621ed2b3de
2,895
aoc-2023
Creative Commons Zero v1.0 Universal
src/main/kotlin/days/Day5Data.kt
yigitozgumus
572,855,908
false
{"Kotlin": 26037}
package days import utils.SolutionData import java.util.* fun main() { Day5Data().solvePart1() Day5Data().solvePart2() } data class Operation(val times: Int, val from: Int, val to: Int) class Day5Data : SolutionData(inputFile = "inputs/day5.txt") { private val separation = rawData.indexOf("") private val data = rawData.subList(0, separation - 1) private val numOfStacks = rawData[separation - 1].trim().split(" ").last().toInt() val moves = rawData.subList(separation + 1, rawData.size) val stackList = buildList<Stack<String>> { repeat(numOfStacks) { add(Stack()) } }.also { stackList -> data.reversed().forEach { it.chunked(4).forEachIndexed { index, line -> line.trim(' ', '[', ']').takeIf { it.isNotEmpty() }?.let { stackList[index].push(it) } } } } fun mapOperations(command: String): Operation = with(command.split(" ")) { return Operation(this[1].toInt(), this[3].toInt() - 1, this[5].toInt() - 1) } } fun Day5Data.solvePart1() { moves.map { mapOperations(it) }.forEach { operation -> repeat(operation.times) { val element = stackList[operation.from].pop() stackList[operation.to].push(element) } } println(stackList.joinToString("") { it.pop() }) } fun Day5Data.solvePart2() { moves.map { mapOperations(it) }.forEach { operation -> val tempStack = Stack<String>() repeat(operation.times) { tempStack.push(stackList[operation.from].pop()) } repeat(operation.times) { stackList[operation.to].push(tempStack.pop())} } println(stackList.joinToString("") { it.pop() }) }
0
Kotlin
0
0
9a3654b6d1d455aed49d018d9aa02d37c57c8946
1,531
AdventOfCode2022
MIT License
2021/src/day07/Day07.kt
Bridouille
433,940,923
false
{"Kotlin": 171124, "Go": 37047}
package day07 import readInput import kotlin.math.abs fun part1(lines: List<String>) : Int { val crabsPos = lines.first().split(",").map{ it.toInt() } val min = crabsPos.minOrNull() ?: return -1 val max = crabsPos.maxOrNull() ?: return -1 var minFuel = Integer.MAX_VALUE for (i in min..max) { var fuel = 0 for (pos in crabsPos) { fuel += abs(i - pos) } if (fuel <= minFuel) minFuel = fuel } return minFuel } fun calcFuel(steps: Int, memo: MutableMap<Int, Int>) : Int { return if (steps <= 1) { steps } else { if (!memo.containsKey(steps)) { memo[steps] = steps + calcFuel(steps - 1, memo) } memo[steps]!! } } fun part2(lines: List<String>) : Int { val crabsPos = lines.first().split(",").map{ it.toInt() } val min = crabsPos.minOrNull() ?: return -1 val max = crabsPos.maxOrNull() ?: return -1 val memo = mutableMapOf<Int, Int>() // steps => fuel required map var minFuel = Integer.MAX_VALUE for (i in min..max) { var fuel = 0 for (pos in crabsPos) { fuel += calcFuel(abs(i - pos), memo) } if (fuel <= minFuel) minFuel = fuel } return minFuel } fun main() { val testInput = readInput("day07/test") println("part1(testInput) => " + part1(testInput)) println("part2(testInput) => " + part2(testInput)) val input = readInput("day07/input") println("part1(input) => " + part1(input)) println("part1(input) => " + part2(input)) }
0
Kotlin
0
2
8ccdcce24cecca6e1d90c500423607d411c9fee2
1,563
advent-of-code
Apache License 2.0
2021/src/day17/Day17.kt
Bridouille
433,940,923
false
{"Kotlin": 171124, "Go": 37047}
package day17 import readInput data class Point(val x: Int, val y: Int) data class Area(val start: Int, val end: Int) { fun contains(pos: Int) = this.start <= pos && this.end >= pos } fun List<String>.toAreas() : List<Area> { val area = first().substringAfter("target area: ").split(" ") val areaX = area.first().substringAfter("x=").dropLast(1).let { Area(it.split("..")[0].toInt(), it.split("..")[1].toInt()) } val areaY = area.last().substringAfter("y=").let { Area(it.split("..")[0].toInt(), it.split("..")[1].toInt()) } return listOf(areaX, areaY) } val memoX = mutableMapOf<String, Int>() // key = "xVelocity/x/steps" val memoY = mutableMapOf<String, Int>() // key = "yVelocity/y/steps" fun calcX(x: Int, xVelocity: Int, steps: Int): Int { if (xVelocity <= 0 || steps <= 0) return x val key = "$xVelocity/$x/$steps" if (!memoX.containsKey(key)) { memoX[key] = x + xVelocity + calcX(x,xVelocity - 1, steps - 1) } return memoX[key]!! } fun calcY(y: Int, yVelocity: Int, steps: Int): Int { if (steps <= 0) return y val key = "$yVelocity/$y/$steps" if (!memoY.containsKey(key)) { memoY[key] = y + yVelocity + calcY(y, yVelocity - 1, steps - 1) } return memoY[key]!! } fun posAfterSteps(xVelocity: Int, yVelocity: Int, steps: Int) = Point(calcX(0, xVelocity, steps), calcY(0, yVelocity, steps)) // result = null means we never hit the target with the provided xVelocity and yVelocity fun getMaxYForVelocity(xVelocity: Int, yVelocity: Int, areaX: Area, areaY: Area): Int? { var step = 1 var currentPos = Point(0, 0) // Start in 0,0 var maxY = 0 var hitTargetArea = false while (currentPos.x <= areaX.end && currentPos.y >= areaY.start) { if (areaX.contains(currentPos.x) && areaY.contains(currentPos.y)) { // we found a hit hitTargetArea = true } currentPos = posAfterSteps(xVelocity, yVelocity, step) maxY = maxOf(maxY, currentPos.y) step++ } return if (hitTargetArea) maxY else null } fun part1(lines: List<String>): Int { val (areaX, areaY) = lines.toAreas() var maxY = 0 // starting in 0,0 the maxY is always 0 for (xVelocity in areaX.end downTo 0) { for (yVelocity in areaY.start..areaX.start) { getMaxYForVelocity(xVelocity, yVelocity, areaX, areaY)?.let { maxY = maxOf(it, maxY) } } } return maxY } fun part2(lines: List<String>): Int { val (areaX, areaY) = lines.toAreas() var numberOfHits = 0 for (xVelocity in areaX.end downTo 0) { for (yVelocity in areaY.start..areaX.start) { getMaxYForVelocity(xVelocity, yVelocity, areaX, areaY)?.let { numberOfHits++ } } } return numberOfHits } fun main() { val testInput = readInput("day17/test") println("part1(testInput) => " + part1(testInput)) println("part2(testInput) => " + part2(testInput)) val input = readInput("day17/input") println("part1(input) => " + part1(input)) println("part2(input) => " + part2(input)) }
0
Kotlin
0
2
8ccdcce24cecca6e1d90c500423607d411c9fee2
3,146
advent-of-code
Apache License 2.0
src/main/kotlin/net/navatwo/adventofcode2023/day5/Day5Solution.kt
Nava2
726,034,626
false
{"Kotlin": 100705, "Python": 2640, "Shell": 28}
package net.navatwo.adventofcode2023.day5 import com.github.nava2.interval_tree.Interval import com.github.nava2.interval_tree.IntervalTree import net.navatwo.adventofcode2023.framework.ComputedResult import net.navatwo.adventofcode2023.framework.Solution import java.util.Objects sealed class Day5Solution : Solution<Day5Solution.Almanac> { data object Part1 : Day5Solution() { override fun solve(input: Almanac): ComputedResult { val result = input.seeds.minOf { seed -> input.computeSeedLocation(seed) } return ComputedResult.Simple(result) } private fun Almanac.computeSeedLocation(seed: Almanac.Seed): Long { var value = seed.id var mapping: Almanac.Mapping? = mappingsBySourceType.getValue(Almanac.Type.Seed) while (mapping != null) { value = mapping.map(value) mapping = mappingsBySourceType[mapping.destType] } return value } } data object Part2 : Day5Solution() { override fun solve(input: Almanac): ComputedResult { val seeds = (0 until input.seeds.size step 2) .asSequence() .map { i -> input.seeds[i] to input.seeds[i + 1].id } .map { (seed, range) -> Almanac.Entry( sourceRange = seed.id until (seed.id + range), destRange = seed.id until (seed.id + range), ) } val result = seeds.minOf { seed -> input.computeMinimumSeedLocation(seed) } return ComputedResult.Simple(result) } private fun Almanac.computeMinimumSeedLocation(interval: Almanac.Entry): Long { var mapping: Almanac.Mapping? = mappingsBySourceType.getValue(Almanac.Type.Seed) var intervals = listOf<Interval>(interval) while (mapping != null) { intervals = computeNextIntervals(mapping, intervals) mapping = mappingsBySourceType[mapping.destType] } return intervals.minOf { it.start } } private fun computeNextIntervals(mapping: Almanac.Mapping, intervals: List<Interval>): List<Interval> { val next = intervals.flatMap { mapping.mapRange(it) } check(next.sumOf { it.length } == intervals.sumOf { it.length }) { "wat: input: $intervals, next: $next" } return next } } override fun parse(lines: Sequence<String>): Almanac { val seeds = mutableListOf<Almanac.Seed>() val mappingsBySourceType = mutableMapOf<Almanac.Type, Almanac.Mapping>() var currentPair: Pair<Almanac.Type, Almanac.Type>? = null for (line in lines.filter { it.isNotBlank() }) { when { seeds.isEmpty() -> { val seedValues = line.subSequence("seeds: ".length, line.length) .splitToSequence(' ') seeds.addAll( seedValues .map { it.trim().toLong() } .map { Almanac.Seed(it) }, ) } currentPair == null || !line.first().isDigit() -> { val (sourceTypeString, destTypeString) = line.subSequence(0, line.length - " map:".length) .split("-to-", limit = 2) val sourceType = Almanac.Type.lowerValueOf(sourceTypeString) val destType = Almanac.Type.lowerValueOf(destTypeString) currentPair = sourceType to destType } else -> { val (sourceType, destType) = currentPair val (destStart, sourceStart, length) = line.split(' ', limit = 3).map { it.toLong() } mappingsBySourceType.compute(sourceType) { _, mapping -> val nextMapping = mapping ?: Almanac.Mapping(sourceType, destType) nextMapping.addEntry( Almanac.Entry( sourceRange = sourceStart until (sourceStart + length), destRange = destStart until (destStart + length), ) ) nextMapping } } } } return Almanac(seeds = seeds, mappingsBySourceType = mappingsBySourceType) } data class Almanac( val seeds: List<Seed>, val mappingsBySourceType: Map<Type, Mapping>, ) { class Mapping( val sourceType: Type, val destType: Type, entries: Collection<Entry> = listOf(), ) { private val intervalTree = IntervalTree<Entry>().apply { insertAll(entries) } fun addEntry(entry: Entry) { intervalTree.insert(entry) } fun map(value: Long): Long { val overlapper = intervalTree.minimumOverlapper(Interval.Simple(value, 1)) return overlapper.map { it.map(value) }.orElse(value) } fun mapRange(interval: Interval): Sequence<Interval> { val overlappers = intervalTree.overlappers(interval) return sequence { var value = interval.start for (overlapper in overlappers) { if (overlapper.start > value) { yield(Interval.Simple(value, overlapper.start - value)) } val truncated = overlapper.intersect(interval) ?: error("wat") val destOffset = overlapper.destRange.first - overlapper.sourceRange.first val destStart = truncated.start + destOffset yield( Interval.Simple(destStart, truncated.length) ) value = truncated.endExclusive } if (value != interval.endExclusive) { yield(Interval.Simple(value, interval.endExclusive - value)) } } } override fun toString(): String { return "Mapping(sourceType=$sourceType, destType=$destType, intervalTree=${intervalTree.toList()})" } override fun hashCode(): Int { return Objects.hash( sourceType, destType, intervalTree.toSet(), ) } override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is Mapping) return false return sourceType == other.sourceType && destType == other.destType && intervalTree.toSet() == other.intervalTree.toSet() } } data class Entry( val sourceRange: LongRange, val destRange: LongRange, ) : Interval { override val start: Long = sourceRange.first override val endExclusive: Long = sourceRange.endExclusive fun map(value: Long): Long { return destRange.first + (value - sourceRange.first) } } enum class Type { Seed, Soil, Fertilizer, Water, Light, Temperature, Humidity, Location, ; companion object { private val lowered = entries.associateBy { it.name.lowercase() } fun lowerValueOf(name: String): Type { return lowered.getValue(name) } } } @JvmInline value class Seed(val id: Long) } } fun Interval.intersect(other: Interval): Interval? { if (start > other.endInclusive || endInclusive < other.start) { return null } val truncatedStart = maxOf(start, other.start) val truncatedEndExclusive = minOf(endExclusive, other.endExclusive) val truncatedLength = truncatedEndExclusive - truncatedStart return Interval.Simple(truncatedStart, truncatedLength) }
0
Kotlin
0
0
4b45e663120ad7beabdd1a0f304023cc0b236255
7,206
advent-of-code-2023
MIT License
src/main/kotlin/day7/main.kt
janneri
572,969,955
false
{"Kotlin": 99028}
package day7 import util.readTestInput open class Command class ListCurrentDir: Command() class ChangeDir(val arg: String): Command() class ChangeDirOut: Command() open class Result data class MyFile(val size: Int, val name: String): Result() data class MyDir(val name: String): Result() fun parseCommand(str: String): Command? { return when { str.startsWith("$ ls") -> ListCurrentDir() str.startsWith("$ cd ..") -> ChangeDirOut() str.startsWith("$ cd") -> ChangeDir(str.substringAfterLast(" ")) else -> null } } fun parseResult(str: String): Result? { return when { // "123 abc" means a file with size 123 str.first().isDigit() -> str.split(" ").let {(size, name) -> MyFile(size.toInt(), name)} // "dir xyz" meas a dir named xyz str.startsWith("dir") -> MyDir(str.substringAfterLast(" ")) else -> null } } val ROOT_DIR = "." fun parseDirectorySizes(inputLines: List<String>): MutableMap<String, Int> { var currentPath = ROOT_DIR val directorySizes = mutableMapOf<String, Int>() for (line in inputLines) { when (val command = parseCommand(line)) { is ChangeDir -> {currentPath += "/${command.arg}"} is ChangeDirOut -> {currentPath = currentPath.substringBeforeLast("/")} } when (val result = parseResult(line)) { is MyFile -> { // increase current dir size val currentDirSize = directorySizes.getOrPut(currentPath) { 0 } directorySizes[currentPath] = currentDirSize + result.size // update parent directory sizes (unless inside the root dir) if (currentPath != ROOT_DIR) { var dirPath = currentPath do { dirPath = dirPath.substringBeforeLast("/") directorySizes[dirPath] = directorySizes.getOrPut(dirPath) { 0 } + result.size } while (dirPath != ROOT_DIR) } } } } return directorySizes } fun part1(inputLines: List<String>): Int { val directorySizes = parseDirectorySizes(inputLines) directorySizes.remove(".") return directorySizes.values.filter { it <= 100000 }.sum() } fun part2(inputLines: List<String>): Int { val directorySizes = parseDirectorySizes(inputLines) val usedSize = directorySizes["."]!! val unusedSize = 70000000 - usedSize val spaceNeeded = 30000000 val shouldFreeSize = spaceNeeded - unusedSize return directorySizes.filterValues { it >= shouldFreeSize }.values.min() } fun main() { // Solution for https://adventofcode.com/2022/day/7 // Downloaded the input from https://adventofcode.com/2022/day/7/input // first command is cd / and ls, we can safely skip them val inputLines = readTestInput("day7").drop(2) println(part1(inputLines)) // for testinput 95 437 println(part2(inputLines)) // for testinput 24 933 642 }
0
Kotlin
0
0
1de6781b4d48852f4a6c44943cc25f9c864a4906
3,006
advent-of-code-2022
MIT License
src/main/kotlin/day03/Problem.kt
xfornesa
572,983,494
false
{"Kotlin": 18402}
package day03 fun solveProblem01(input: List<String>): Int { val commonTypes = mutableListOf<Char>() input.forEach { val first = it.substring(0 until it.length/2) val second = it.substring((it.length / 2) until it.length) val commonType = commonType(first, second) commonTypes.add(commonType) } return commonTypes.sumOf { toScore(it) } } fun toScore(it: Char): Int { return if (it.isLowerCase()) it.minus('a') + 1 else it.minus('A') + 27 } fun commonType(first: String, second: String): Char { val occurrencesFirst = HashSet<Char>() first.forEach { occurrencesFirst.add(it) } val occurrencesSecond = HashSet<Char>() second.forEach { occurrencesSecond.add(it) } val common = first.asIterable().toSet() intersect second.asIterable().toSet() return common.first() } fun solveProblem02(input: List<String>): Int { val windowed = input.windowed(3, 3) return windowed.map { findCommonTypes(it) }.sumOf { toScore(it) } } fun findCommonTypes(it: List<String>): Char { val (first, second, third) = it val occurrencesFirst = HashSet<Char>() first.forEach { occurrencesFirst.add(it) } val occurrencesSecond = HashSet<Char>() second.forEach { occurrencesSecond.add(it) } val occurrencesThird = HashSet<Char>() third.forEach { occurrencesThird.add(it) } val common = first.toSet() intersect second.toSet() intersect third.toSet() return common.first() }
0
Kotlin
0
0
dc142923f8f5bc739564bc93b432616608a8b7cd
1,578
aoc2022
MIT License
src/Day03.kt
gillyobeast
574,413,213
false
{"Kotlin": 27372}
import utils.appliedTo import utils.readInput private fun <E> List<E>.toTriple(): Triple<E, E, E> { assert(this.size == 3) return Triple(this[0], this[1], this[2]) } fun main() { val lowerPriorities = ("abcdefghijklmnopqrstuvwxyz".toCharArray()).zip((1..26).toList()).toMap() val upperPriorities = ("ABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray()).zip((27..52).toList()).toMap() fun splitBackpack(backpack: String): Pair<String, String> { val n = backpack.length / 2 return backpack.substring(0, n) to backpack.substring(n, backpack.length) } fun findCommonItem(backPack: Pair<String, String>): Char { for (i in backPack.first) { if (backPack.second.contains(i.toString().toRegex())) { return i } } throw IllegalStateException("No common character found between halves of [$backPack]!") } fun findCommonItem(backPacks: Triple<String, String, String>): Char { for (i in backPacks.first) { val regex = i.toString().toRegex() if (backPacks.second.contains(regex) && backPacks.third.contains(regex)) { return i } } throw IllegalStateException("No common character found between three parts of [$backPacks]!") } fun toPriority(c: Char): Int { return lowerPriorities[c] ?: upperPriorities[c] ?: throw IllegalStateException("No priority found for [$c]!") } fun part1(input: List<String>): Int { return input .map(::splitBackpack) .map(::findCommonItem) .map(::toPriority) .sum() } fun part2(input: List<String>): Int { return input .asSequence() .chunked(3) .map { it.toTriple() } .map(::findCommonItem) .map(::toPriority) .sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("input_test") val input = readInput("input") // part 1 ::part1.appliedTo(testInput, returns = 157) println("Part 1: ${part1(input)}") // part 2 ::part2.appliedTo(testInput, returns = 70) println("Part 2: ${part2(input)}") }
0
Kotlin
0
0
8cdbb20c1a544039b0e91101ec3ebd529c2b9062
2,277
aoc-2022-kotlin
Apache License 2.0
kotlin/src/main/kotlin/com/github/jntakpe/aoc2022/days/Day22.kt
jntakpe
572,853,785
false
{"Kotlin": 72329, "Rust": 15876}
package com.github.jntakpe.aoc2022.days import com.github.jntakpe.aoc2022.shared.Day import com.github.jntakpe.aoc2022.shared.readInputLines object Day22 : Day { override val input = readInputLines(22).let { it.dropLast(2) to instructions(it.last()) } operator fun List<String>.get(pos: Position): Char = getOrNull(pos.y)?.getOrNull(pos.x) ?: ' ' private fun limits(grid: List<String>): List<State> { val start = Position(grid[0].indexOf('.'), 0) return buildList { var pos = start var dir = 0 do { add(State(dir, pos)) val forward = pos.move(dir) if (grid[forward] == ' ') { dir = (dir + 1).mod(4) } else { val left = forward.move(dir - 1) if (grid[left] == ' ') { pos = forward } else { pos = left dir = (dir - 1).mod(4) } } } while (pos != start || dir != 0) } } private fun walkTree(nextMap: Map<State, State>): Int { return input.second.fold(State.START) { a, c -> when (c) { "L" -> a.copy(direction = (a.direction - 1).mod(4)) "R" -> a.copy(direction = (a.direction + 1).mod(4)) else -> forward(c.toInt(), a, nextMap) } }.run { 1000 * (position.y + 1) + 4 * (position.x + 1) + direction } } private fun forward(iterations: Int, start: State, nextMap: Map<State, State>): State { return (0 until iterations) .fold(start) { a, _ -> (nextMap[a] ?: a.copy(position = a.position.move(a.direction))) .takeIf { input.first[it.position] != '#' } ?: return a } } private fun instructions(input: String): List<String> { val forward = input.split('R', 'L') val turns = input.filter { it.isLetter() }.map { it.toString() } return forward.zip(turns).flatMap { (f, t) -> listOf(f, t) } + forward.last() } override fun part1(): Int { val (grid) = input val nextMap = limits(grid) .map { it.copy(direction = (it.direction - 1).mod(4)) } .associateWith { (dir, pos) -> val next = when (dir) { 0 -> pos.copy(x = grid[pos.y].indexOfFirst { it != ' ' }) 1 -> pos.copy(y = grid.indexOfFirst { pos.x in it.indices && it[pos.x] != ' ' }) 2 -> pos.copy(x = grid[pos.y].indexOfLast { it != ' ' }) 3 -> pos.copy(y = grid.indexOfLast { pos.x in it.indices && it[pos.x] != ' ' }) else -> error("") } State(dir, next) } return walkTree(nextMap) } override fun part2(): Int { val sideLength = if (input.second.size == 13) 4 else 50 val edges = limits(input.first).chunked(sideLength).map { it[0].direction to it }.toMutableList() val nextMap = buildMap { while (edges.isNotEmpty()) { var i = 0 while (i < edges.lastIndex) { val a = edges[i] val b = edges[i + 1] if ((a.first - b.first).mod(4) == 1) { edges.subList(i, i + 2).clear() for (j in i..edges.lastIndex) { val edge = edges[j] edges[j] = (edge.first - 1).mod(4) to edge.second } for (j in 0 until sideLength) { val (dir1, pos1) = a.second[j] val (dir2, pos2) = b.second[sideLength - j - 1] put(State((dir1 - 1).mod(4), pos1), State((dir2 + 1).mod(4), pos2)) put(State((dir2 - 1).mod(4), pos2), State((dir1 + 1).mod(4), pos1)) } } else { i++ } } } } return walkTree(nextMap) } data class State(val direction: Int, val position: Position) { companion object { val START = State(0, Position(input.first.first().indexOf('.'), 0)) } } data class Position(val x: Int, val y: Int) { fun move(direction: Int) = when (direction.mod(4)) { 0 -> copy(x = x + 1) 1 -> copy(y = y + 1) 2 -> copy(x = x - 1) 3 -> copy(y = y - 1) else -> error("Unknown direction") } } }
1
Kotlin
0
0
63f48d4790f17104311b3873f321368934060e06
4,735
aoc2022
MIT License
src/Day03.kt
illarionov
572,508,428
false
{"Kotlin": 108577}
fun main() { fun part1(input: List<String>): Int { return input.sumOf { s: String -> val leftSet = s.substring(0, s.length / 2).toSet() val rightSet = s.substring(s.length / 2).toSet() val intersect = leftSet.intersect(rightSet) check(intersect.size == 1) intersect.first().priority } } fun part2(input: List<String>): Int { return input.windowed(3, 3) { l: List<String> -> val badges = l.map(String::toSet).reduce(Set<Char>::intersect) val c = badges.first() check(badges.size == 1) c.priority }.sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day03_test") check(part1(testInput) == 157) val input = readInput("Day03") val result1 = part1(input) println(result1) val input2 = readInput("Day03_2") val result2 = part2(input2) println(result2) } val Char.priority get() = when(this) { in 'a' .. 'z' -> this - 'a' + 1 in 'A' .. 'Z' -> this - 'A' + 27 else -> error("Unknown symbol") }
0
Kotlin
0
0
3c6bffd9ac60729f7e26c50f504fb4e08a395a97
1,147
aoc22-kotlin
Apache License 2.0
src/Day02.kt
Ramo-11
573,610,722
false
{"Kotlin": 21264}
fun main() { // Part 1 // A and X are rock // B and Y are paper // C and Z are scissors // Part 2 // Y also means draw // X also means lose // Z also means win val opponentChoices: MutableList<String> = ArrayList() val myChoices: MutableList<String> = ArrayList() fun constructChoices(input: List<String>) { for (i in input.indices) { opponentChoices.add(input[i].split(" ")[0]) myChoices.add(input[i].split(" ")[1]) } } fun getChoiceScore(input: String): Int { val scoreMap = mapOf("Y" to 2, "X" to 1, "Z" to 3) return scoreMap[input]!! } fun getRoundScore(myChoice: String, opponentChoice: String): Int { if ((myChoice == "X" && opponentChoice == "C") || (myChoice == "Y" && opponentChoice == "A") || (myChoice == "Z" && opponentChoice == "B")) { return 6 } else if ((myChoice == "X" && opponentChoice == "A") || (myChoice == "Y" && opponentChoice == "B") || (myChoice == "Z" && opponentChoice == "C")) { return 3 } else { return 0 } } fun part1(): Int { var choiceScore = 0 var roundScore = 0 for (i in myChoices.indices) { choiceScore += getChoiceScore(myChoices[i]) roundScore += getRoundScore(myChoices[i], opponentChoices[i]) } return choiceScore + roundScore } fun calculateTotalScoreForPart2(myChoice: String, opponentChoice: String): Int { val losingMap = mapOf("A" to "Z", "B" to "X", "C" to "Y") val winningMap = mapOf("A" to "Y", "B" to "Z", "C" to "X") val drawMap = mapOf("A" to "X", "B" to "Y", "C" to "Z") if (myChoice == "X") { // Lose return getRoundScore(losingMap[opponentChoice]!!, opponentChoice) + getChoiceScore(losingMap[opponentChoice]!!) } else if (myChoice == "Y") { // Draw return getRoundScore(drawMap[opponentChoice]!!, opponentChoice) + getChoiceScore(drawMap[opponentChoice]!!) } else { // Win return getRoundScore(winningMap[opponentChoice]!!, opponentChoice) + getChoiceScore(winningMap[opponentChoice]!!) } } fun part2(): Int { var totalScore = 0 for (i in myChoices.indices) { totalScore += calculateTotalScoreForPart2(myChoices[i], opponentChoices[i]) } return totalScore } val input = readInput("Day02") constructChoices(input) val part1Answer = part1() val part2Answer = part2() println("Answer for part 1: $part1Answer") println("Answer for part 2: $part2Answer") }
0
Kotlin
0
0
a122cca3423c9849ceea5a4b69b4d96fdeeadd01
2,659
advent-of-code-kotlin
Apache License 2.0
src/main/kotlin/com/hj/leetcode/kotlin/problem2244/Solution.kt
hj-core
534,054,064
false
{"Kotlin": 619841}
package com.hj.leetcode.kotlin.problem2244 /** * LeetCode page: [2244. Minimum Rounds to Complete All Tasks](https://leetcode.com/problems/minimum-rounds-to-complete-all-tasks/); */ class Solution { /* Complexity: * Time O(|tasks|) and Space O(|tasks|); */ fun minimumRounds(tasks: IntArray): Int { val counts = countEachDifficulty(tasks) var minRounds = 0 for (count in counts.values) { if (count == 1) return -1 /* when count is not equal to 1, we will have the following cases: * 1) count = 3k + 1 then k < task.minRound <= k + 1 and task.minRound = 3 * (k - 1) + 2 * 2; * 2) count = 3k + 2 then k < task.minRound <= k + 1 and task.minRound = 3 * (k ) + 2 * 1; * 3) count = 3k + 3 then k < task.minRound <= k + 1 and task.minRound = 3 * (k + 1) + 2 * 0; * where k is non-negative integer. * task.minRound = (count + 2) / 3 is a shortcut for the above three cases. */ minRounds += (count + 2) / 3 } return minRounds } private fun countEachDifficulty(tasks: IntArray): Map<Int, Int> { val counts = hashMapOf<Int, Int>() for (task in tasks) { counts[task] = 1 + (counts[task] ?: 0) } return counts } }
1
Kotlin
0
1
14c033f2bf43d1c4148633a222c133d76986029c
1,343
hj-leetcode-kotlin
Apache License 2.0
src/main/kotlin/day05/day05.kt
andrew-suprun
725,670,189
false
{"Kotlin": 18354, "Python": 17857, "Dart": 8224}
package day05 import java.io.File import kotlin.math.max import kotlin.math.min fun main() { run(::part1) run(::part2) } data class Map(val range: LongRange, val inc: Long) data class Model(val seeds: List<LongRange>, val allMaps: List<List<Map>>) fun run(part: (String) -> List<LongRange>) { val model = parseInput(part) var mapped = model.seeds for (maps in model.allMaps) { mapped = mapLongRanges(mapped, maps) } println(mapped.minOfOrNull { it.first }) } fun mapLongRanges(ranges: List<LongRange>, maps: List<Map>): List<LongRange> { val result = mutableListOf<LongRange>() var unprocessed = mutableListOf<LongRange>() var toProcess = MutableList(ranges.size) { ranges[it] } for (map in maps) { for (range in toProcess) { if (range.first >= map.range.last || range.last <= map.range.first) { unprocessed += range } else { val start = max(range.first, map.range.first) val end = min(range.last, map.range.last) result += start + map.inc..<end + map.inc if (range.first < start) { unprocessed += range.first..<start } if (range.last > end) { unprocessed += end..<range.last } } } toProcess = unprocessed unprocessed = mutableListOf() } result += toProcess return result } fun parseInput(seeds: (String) -> List<LongRange>): Model { val lines = File("input.data").readLines() val ranges = seeds(lines[0]) val allMaps = mutableListOf<List<Map>>() var curMaps = mutableListOf<Map>() for (line in lines.drop(3)) { when { line == "" -> continue line.endsWith(" map:") -> { allMaps += curMaps curMaps = mutableListOf() } else -> { val numbers = line.split(" ").map { it.toLong() } curMaps += Map(range = numbers[1]..< numbers[1] + numbers[2], inc = numbers[0] - numbers[1]) } } } allMaps += curMaps return Model(seeds = ranges, allMaps = allMaps) } fun part1(line: String): List<LongRange> = line.split(" ").drop(1).map { val start = it.toLong() start..<start+1 } fun part2(line: String): List<LongRange> { val seedNumbers = line.split(" ").drop(1).map { it.toLong() } return seedNumbers.chunked(2).map { (start, len) -> start..<start + len } } // 993500720 // 4917124
0
Kotlin
0
0
dd5f53e74e59ab0cab71ce7c53975695518cdbde
2,585
AoC-2023
The Unlicense