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/Day07.kt
Sasikuttan2163
647,296,570
false
null
fun main() { val input = readInput("Day07") val root = Node( type = "dir", name = "/", parent = null ) var current = root var inls = false input.withIndex() .forEach { line -> if (line.value.startsWith("$ ls")) { inls = true } else if (line.value.startsWith("$ cd")) { inls = false current = line.value.substringAfterLast(" ").trim().let { if (it == "/") root else if (it == "..") current.parent else current.sub.first { node -> node.name == it && node.type == "dir" } }!! } else if (inls) { current.add( Node(parent = current).apply { name = line.value.substringAfter(" ") if (line.value.startsWith("dir")) { type = "dir" } else { type = "file" size = line.value.substringBefore(" ").toInt() } } ) } } val part1 = root.computeSum() part1.println() val sizeRequired = 30000000 - (70000000 - root.computeSize()) sizeRequired.println() val part2 = root.smallestDirWithSizeMoreThan(sizeRequired, root.size) part2.println() } data class Node (var type: String = "file", var size: Int = 0, var sub: MutableList<Node> = mutableListOf<Node>(), var name: String = "", var parent: Node?) { fun computeSize(): Int = if (type == "dir") { size = sub.sumOf { it.computeSize() } size } else size fun add(node: Node) { sub.add(node) } fun add(type: String = "file", size: Int = 0, name: String = "", parent: Node) { sub.add(Node( type = type, size = size, name = name, parent = parent )) } var part1 = 0 fun computeSum(): Int { var sum = 0 val size = this.computeSize() if (type == "dir" && size <= 100000) { sum += size } for (node in sub) { sum += node.computeSum() } return sum } fun smallestDirWithSizeMoreThan(min: Int, currentSmallest: Int): Int { if (size < min || type != "dir") { return currentSmallest } var smallest = this.size for (node in sub) { var small = node.smallestDirWithSizeMoreThan(min, smallest) if (small < smallest) { smallest = small } } return smallest } }
0
Kotlin
0
0
fb2ade48707c2df7b0ace27250d5ee240b01a4d6
2,768
AoC-2022-Solutions-In-Kotlin
MIT License
2023/src/day01/day01.kt
Bridouille
433,940,923
false
{"Kotlin": 171124, "Go": 37047}
package day01 import GREEN import RESET import printTimeMillis import readInput fun part1(input: List<String>): Int { return input.map<String, Int> { val one = it.first { it.isDigit() }.digitToInt() val two = it.last { it.isDigit() }.digitToInt() one * 10 + two }.sum() } val replaces = mapOf( "one" to "1", "two" to "2", "three" to "3", "four" to "4", "five" to "5", "six" to "6", "seven" to "7", "eight" to "8", "nine" to "9", ) fun String.substrIdx(str: String, fromEnd: Boolean) : Int? { val indexes = if (fromEnd) { indices.reversed() } else { indices } for (i in indexes) { if (length >= i + str.length && substring(i, i + str.length) == str) { return i } } return null } fun part2(input: List<String>): Int { return input.map<String, Int> { var firstWrittenDigit = "" var lastWrittenDigit = "" var minIdx: Int = Int.MAX_VALUE var maxIdx: Int = Int.MIN_VALUE for (e in replaces) { val first = it.substrIdx(e.key, fromEnd = false) val last = it.substrIdx(e.key, fromEnd = true) if (first != null && first < minIdx) { minIdx = first firstWrittenDigit = e.value } if (last != null && last > maxIdx) { maxIdx = last lastWrittenDigit = e.value } } val firstDigitIdx = it.indexOfFirst { it.isDigit() } val lastDigitIdx = it.indexOfLast { it.isDigit() } val one = if (firstDigitIdx != -1 && firstDigitIdx < minIdx) { it.first { it.isDigit() }.digitToInt() } else { firstWrittenDigit.toInt() } val two = if (lastDigitIdx != -1 && lastDigitIdx > maxIdx) { it.last { it.isDigit() }.digitToInt() } else { lastWrittenDigit.toInt() } one * 10 + two }.sum() } fun main() { val testInput = readInput("day01_example.txt") val testInput2 = readInput("day01_example2.txt") printTimeMillis { print("part1 example = $GREEN" + part1(testInput) + RESET) } printTimeMillis { print("part2 example = $GREEN" + part2(testInput2) + RESET) } val input = readInput("day01.txt") printTimeMillis { print("part1 input = $GREEN" + part1(input) + RESET) } printTimeMillis { print("part2 input = $GREEN" + part2(input) + RESET) } }
0
Kotlin
0
2
8ccdcce24cecca6e1d90c500423607d411c9fee2
2,492
advent-of-code
Apache License 2.0
src/Day13.kt
allwise
574,465,192
false
null
fun main() { fun part1(input: List<String>): Int { val distress = Distress(input) val res= distress.process() println("res=$res") return res } fun part2(input: List<String>): Int { val distress = Distress(input) val res= distress.process2() println("res=$res") return res } // test if implementation meets criteria from the description, like: val testInput = readInput("Day13_test") check(part1(testInput) == 13) check(part2(testInput) == 140) val input = readInput("Day13") println(part1(input)) println(part2(input)) } class Distress(val input:List<String>){ val packets:List<Pair<String,String>> = input.chunked(3).map{ it[0] to it[1]} fun process():Int{ return packets.mapIndexed { idx,it -> println("== Pair ${idx+1} ==") if(outOfOrder(it)){ println("Pair ${idx+1} is out of order") 0 } else{ println("Pair ${idx+1} is in order") idx+1 } }.sum() return 0 } fun process2():Int{ val key1 = listOf(listOf(2)) val key2 = listOf(listOf(6)) val signalList = listOf(key1,key2)+input.filterNot { it.trim().isEmpty() }.map(::processString).unzip().first println("SignnalList: ") val listComparator = Comparator{left: List<Any>, right:List<Any> -> compare(left,right)} val sortedList = signalList.sortedWith( listComparator) val index1= sortedList.indexOf(key1)+1.also (::println) val index2= sortedList.indexOf(key2)+1.also (::println) sortedList.forEach(::println) /* return packets.mapIndexed { idx,it -> println("== Pair ${idx+1} ==") if(outOfOrder(it)){ println("Pair ${idx+1} is out of order") 0 } else{ println("Pair ${idx+1} is in order") idx+1 } }.sum()*/ return index1*index2 } fun compare(first:List<Any>,second:List<Any>):Int{ val res = findDiff(first,second) if(res.contains("not")) return 1 return -1 } fun outOfOrder(signals:Pair<String,String>):Boolean{ val first = processString(signals.first).first val second = processString(signals.second).first val res = findDiff(first,second) if(res.contains("not")) return true return false //println("first: $first") //println("second: $second") } fun findDiff(left: Any?, right: Any?): String { println("Compare $left vs $right") if(left is Int && right is Int){ if(left<right) return "Left side is smaller, so inputs are in the right order" if(left>right) return "Right side is smaller, so inputs are not in the right order" return "next" } if(left is List<*> && right is List<*>){ for( i in 0 until left.size) { if(right.size<=i){ return "Right side ran out of items, so inputs are not in the right order" } val res = findDiff(left[i],right[i]) if(res!="next"){ return res } } if(left.size==right.size){ return "next" } return "Left side ran out of items, so inputs are in the right order" // return left.forEach{ idx, it -> findDiff(it,right.indexOf(idx)) }.toString() } if(left is List<*> && right is Int) { val rightList = listOf(right) println("Mixed types; convert right to $rightList and retry comparison") return findDiff(left,rightList) } if(left is Int && right is List<*>) { val leftList = listOf(left) println("Mixed types; convert left to $leftList and retry comparison") return findDiff(leftList,right) } return "" } fun processString(line:String): Pair<List<Any>,String> { var s = line.trim().let {it.substring(1) } val output= mutableListOf<Any>() while(s.length>0) { when (s.first()) { '[' -> { val o = processString(s) output.add(o.first) s = o.second } ',' -> s = s.drop(1) ']' -> { s = s.drop(1) return (output to s) } else ->{ var integer = "" while (s.first().isDigit()) { integer += s.first() s = s.drop(1) } output.add(integer.toInt()) } } } return (output to s) } fun handleList(listSignal:String):List<Any>{ //[1,[2],[3,4]] return TODO() } }
0
Kotlin
0
0
400fe1b693bc186d6f510236f121167f7cc1ab76
5,089
advent-of-code-2022
Apache License 2.0
src/Day02.kt
zdenekobornik
572,882,216
false
null
enum class Move(val score: Int) { ROCK(1), PAPER(2), SCISSORS(3); companion object { fun parse(value: String): Move { return when (value) { "A", "X" -> ROCK "B", "Y" -> PAPER "C", "Z" -> SCISSORS else -> throw IllegalStateException("Unknown move.") } } } } fun main() { fun part1(input: List<String>): Int { return input .map { it.split(' ', limit = 2).map(Move::parse) } .map { (oponnent, me) -> /* A - rock - 65 B - Paper - 66 C - Scissors - 67 X - rock - 88 Y - Paper - 89 Z - Scissors - 90 */ var score = me.score score += when { (oponnent == Move.ROCK && me == Move.PAPER) || (oponnent == Move.PAPER && me == Move.SCISSORS) || (oponnent == Move.SCISSORS && me == Move.ROCK) -> 6 oponnent == me -> 3 else -> 0 } score }.sum() } fun part2(input: List<String>): Int { return input .map { it.split(' ', limit = 2) } .map { (oponnent, need) -> /* A - rock B - Paper C - Scissors X - rock Y - Paper Z - Scissors Need X - Lose Y - Draw Z - Win */ val me = when (oponnent) { "A" -> when (need) { "X" -> "C" "Y" -> "A" "Z" -> "B" else -> throw IllegalStateException("Unknown move.") } "B" -> when (need) { "X" -> "A" "Y" -> "B" "Z" -> "C" else -> throw IllegalStateException("Unknown move.") } "C" -> when (need) { "X" -> "B" "Y" -> "C" "Z" -> "A" else -> throw IllegalStateException("Unknown move.") } else -> throw IllegalStateException("Unknown move.") } var score = when (me) { "A" -> 1 "B" -> 2 "C" -> 3 else -> throw IllegalStateException("Unknown move.") } score += when { (oponnent == "A" && me == "B") || (oponnent == "B" && me == "C") || (oponnent == "C" && me == "A") -> 6 oponnent == me -> 3 else -> 0 } score }.sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day02_test") println(part1(testInput)) check(part1(testInput) == 15) check(part2(testInput) == 12) val input = readInput("Day02") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
f73e4a32802fa43b90c9d687d3c3247bf089e0e5
3,369
advent-of-code-2022
Apache License 2.0
src/Day02.kt
izyaboi
572,898,317
false
{"Kotlin": 4047}
fun main() { fun part1(input: List<String>): Int { var totalScore = 0 input.forEach { val opponent = it.substringBefore(" ").mapToShape() val response = it.substringAfter(" ").mapToShape() totalScore += getPoints(opponent, response) + response.ordinal } return totalScore } fun part2(input: List<String>): Int { var totalScore = 0 input.forEach { val result = it.substringAfter(" ").mapToResult() totalScore += Result.fromInt(result.value).value+1 } return totalScore } /* // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") check(part1(testInput) == 0)*/ val input = readInput("Day02") println(part1(input)) println(part2(input)) } fun getPoints(opponent: Shape, response: Shape): Int { return when (opponent) { Shape.NONE -> 0 Shape.ROCK -> when (response) { Shape.NONE -> 0 Shape.ROCK -> 3 Shape.PAPER -> 6 Shape.SCISSOR -> 0 } Shape.PAPER -> when (response) { Shape.NONE -> 0 Shape.ROCK -> 0 Shape.PAPER -> 3 Shape.SCISSOR -> 6 } Shape.SCISSOR -> when (response) { Shape.NONE -> 0 Shape.ROCK -> 6 Shape.PAPER -> 0 Shape.SCISSOR -> 3 } } } enum class Shape(val value: Int) { NONE(0), ROCK(1), PAPER(2), SCISSOR(3); companion object { fun fromInt(value: Int) = Shape.values().first { it.value == value } } } enum class Result(val value: Int) { NONE(0), LOOSE(0), DRAW(3), WIN(6); companion object { fun fromInt(value: Int) = Result.values().first { it.value == value } } } fun String.mapToResult(): Result { return when { this == "Y" -> Result.DRAW this == "Z" -> Result.WIN this == "X" -> Result.LOOSE else -> Result.NONE } } fun String.mapToShape(): Shape { return when { this == "A" || this == "X" -> Shape.ROCK this == "B" || this == "Y" -> Shape.PAPER this == "C" || this == "Z" -> Shape.SCISSOR else -> Shape.NONE } }
0
Kotlin
0
1
b0c8cafc5fe610b088d7ca4d10e2deef8d418f96
2,322
advent-of-code-2022
Apache License 2.0
src/main/kotlin/be/tabs_spaces/advent2021/days/Day14.kt
janvryck
433,393,768
false
{"Kotlin": 58803}
package be.tabs_spaces.advent2021.days class Day14 : Day(14) { private val polymerizationEquipment = PolymerizationEquipment(inputList) override fun partOne() = polymerizationEquipment.diffPolymerizedOccurrences() override fun partTwo() = polymerizationEquipment.diffPolymerizedOccurrences(times = 40) class PolymerizationEquipment(rawInput: List<String>) { private val polymerTemplate: String = rawInput.first() private val pairInsertions: List<PairInsertionRule> = rawInput.drop(2) .map { it.split(" -> ") } .map { (pair, insertion) -> PairInsertionRule(pair[0] to pair[1], insertion[0]) } fun diffPolymerizedOccurrences(times: Int = 10) = countOccurrences(polymerize(times)) .let { occurrences -> occurrences.maxOf { it.value } - occurrences.minOf { it.value } } private fun polymerize(times: Int) = (1..times).fold(polymerPairs(polymerTemplate)) { current, _ -> polymerize(current) } private fun countOccurrences(polymerized: Map<Pair<Char, Char>, Long>) = polymerized.entries .flatMap { (pair, occurrences) -> listOf(pair.first to occurrences, pair.second to occurrences) } .groupBy({ it.first }, { it.second }) .mapValues { when (it.key) { in listOf(polymerTemplate.first(), polymerTemplate.last()) -> (it.value.sum() + 1) / 2 else -> it.value.sum() / 2 } } private fun polymerize(polymer: Map<Pair<Char, Char>, Long>) = polymer.entries .flatMap { (pair, occurrences) -> splitAndInsert(pair, occurrences) } .groupBy({ it.first }, { it.second }) .mapValues { it.value.sum() } private fun splitAndInsert(pair: Pair<Char, Char>, occurrences: Long) = listOf( (pair.first to insertionFor(pair)) to occurrences, (insertionFor(pair) to pair.second) to occurrences, ) private fun polymerPairs(polymer: String) = polymer.zipWithNext().groupingBy { it }.eachCount().mapValues { it.value.toLong() } private fun insertionFor(pair: Pair<Char, Char>) = pairInsertions.first { it.pair == pair }.insertion } data class PairInsertionRule(val pair: Pair<Char, Char>, val insertion: Char) }
0
Kotlin
0
0
f6c8dc0cf28abfa7f610ffb69ffe837ba14bafa9
2,371
advent-2021
Creative Commons Zero v1.0 Universal
src/main/kotlin/days/Day11.kt
jgrgt
575,475,683
false
{"Kotlin": 94368}
package days import java.lang.IllegalStateException import kotlin.math.sqrt class Day11 : Day(11) { override fun partOne(): Any { // return 0 val monkeys = inputList.windowed(7, 7, true) .map { monkeyLines -> Day11Monkey.parse(monkeyLines) } val game = Day11Game(monkeys) repeat(20) { game.round() } return game.monkeys.map { it.itemsInspected }.sortedDescending().take(2).reduce { x, y -> x * y } } override fun partTwo(): Any { val monkeys = inputList.windowed(7, 7, true) .map { monkeyLines -> Day11Monkey.parse(monkeyLines) } val game = Day11Game(monkeys) repeat(10000) { game.round() } val parts = game.monkeys.map { it.itemsInspected }.sortedDescending().take(2) return parts[0].toLong() * parts[1].toLong() } } // https://tutorialwing.com/kotlin-program-to-find-all-prime-factors-of-given-number/ fun primeFactors(number: Int): List<Int> { // Array that contains all the prime factors of given number . val arr: ArrayList<Int> = arrayListOf() var n = number // At first check for divisibility by 2.add it in arr till it is divisible while (n % 2 == 0) { arr.add(2) n /= 2 } val squareRoot = sqrt(n.toDouble()).toInt() // Run loop from 3 to square root of n. Check for divisibility by i. Add i in arr till it is divisible by i. for (i in 3..squareRoot step 2) { while (n % i == 0) { arr.add(i) n /= i } } // If n is a prime number greater than 2. if (n > 2) { arr.add(n) } return arr } class Day11Game(val monkeys: List<Day11Monkey>) { fun round() { monkeys.forEach { this.turn(it) } } private fun turn(monkey: Day11Monkey) { val toGive = monkey.items.map { item -> monkey.itemsInspected += 1 val newItem = monkey.operation.invoke(item) // for part 1 / 3 val toMonkeyIndex = if (newItem.isDivisibleBy(monkey.divTest)) { monkey.trueMonkeyIndex } else { monkey.falseMonkeyIndex } toMonkeyIndex to newItem } monkey.items.clear() toGive.forEach { (toMonkeyIndex, item) -> monkeys[toMonkeyIndex].give(item) } } } sealed interface Day11Number { operator fun times(i: Day11Number): Day11Number operator fun times(i: Int): Day11Number operator fun plus(i: Day11Number): Day11Number operator fun plus(i: Int): Day11Number fun isDivisibleBy(divTest: Int): Boolean } class SimpleFactorialNumber( // val number: Int, val moduli: Map<Int, Int> ) : Day11Number { companion object { val primes = listOf(2, 3, 5, 7, 11, 13, 17, 19, 23) fun from(i: Int): SimpleFactorialNumber { // val factors = primeFactors(i) return SimpleFactorialNumber( // i, primes.associateWith { prime -> i % prime } ) } } override fun times(i: Day11Number): Day11Number { // ((ax + m) * (ax + m) % a) // == (ax * ax + 2 * ax * m + m * m) % a == (m * m) % a val newModuli = moduli.map { (prime, modulo) -> prime to ((modulo * modulo) % prime) }.toMap() return when (i) { is SimpleFactorialNumber -> { SimpleFactorialNumber( // this.number * i.number, newModuli ) } } } override fun times(i: Int): Day11Number { // ((ax + m) * i) % a == (axi + mi) % a == mi % a val newModuli = moduli.map { (prime, modulo) -> prime to ((modulo * i) % prime) }.toMap() return SimpleFactorialNumber( // number * i, newModuli ) } override fun plus(i: Day11Number): Day11Number { // added to itself - does not happen in puzzle input? throw IllegalStateException() } override fun plus(i: Int): Day11Number { val newModuli = moduli.map { (prime, modulo) -> prime to ((modulo + i) % prime) }.toMap() return SimpleFactorialNumber( // number + i, newModuli ) } override fun isDivisibleBy(divTest: Int): Boolean { // val numberModulo = number % divTest val fastModulo = moduli[divTest]!! // if (numberModulo != fastModulo) { // throw IllegalStateException() // } return fastModulo == 0 } } data class Day11Monkey( val items: MutableList<Day11Number>, val operation: (Day11Number) -> Day11Number, val divTest: Int, val trueMonkeyIndex: Int, val falseMonkeyIndex: Int ) { fun give(newItem: Day11Number) { items.add(newItem) } var itemsInspected = 0 companion object { fun parse(lines: List<String>): Day11Monkey { check(lines[0].startsWith("Monkey ")) { "Unexpected input lines" } // check(lines[6].trim().isEmpty()) { "Unexpected end line" } val items = lines[1].trim().split(":")[1].trim().split(",").map { SimpleFactorialNumber.from(it.trim().toInt()) } val operator = lines[2][23] val amountString = lines[2].substring(25) val operation = when (operator) { '*' -> if (amountString == "old") { { i: Day11Number -> i * i } } else { { i: Day11Number -> i * amountString.toInt() } } '+' -> if (amountString == "old") { { i: Day11Number -> i + i } } else { { i: Day11Number -> i + amountString.toInt() } } else -> throw IllegalArgumentException("unknown operator $operator") } val divTest = lines[3].substring(21).toInt() val trueMonkeyIndex = lines[4].substring(29).toInt() val falseMonkeyIndex = lines[5].substring(30).toInt() return Day11Monkey(items.toMutableList(), operation, divTest, trueMonkeyIndex, falseMonkeyIndex) } } }
0
Kotlin
0
0
5174262b5a9fc0ee4c1da9f8fca6fb86860188f4
6,299
aoc2022
Creative Commons Zero v1.0 Universal
src/Day02.kt
jarmstrong
572,742,103
false
{"Kotlin": 5377}
fun main() { fun splitInput(input: List<String>): List<String> { return input.map { "${it.first()}${it.last()}" } } fun List<String>.sumScores(): Int { val choiceScoreTable = mapOf( 'X' to 1, 'Y' to 2, 'Z' to 3 ) val resultScores = mapOf( "AX" to 3, "AY" to 6, "AZ" to 0, "BX" to 0, "BY" to 3, "BZ" to 6, "CX" to 6, "CY" to 0, "CZ" to 3 ) return sumOf { val you = it.last() choiceScoreTable[you]!! + resultScores[it]!! } } fun part1(input: List<String>): Int { return splitInput(input).sumScores() } fun part2(input: List<String>): Int { val playbook = mapOf( "AX" to "AZ", "AY" to "AX", "AZ" to "AY", "BX" to "BX", "BY" to "BY", "BZ" to "BZ", "CX" to "CY", "CY" to "CZ", "CZ" to "CX" ) return splitInput(input) .map { playbook[it]!! } .sumScores() } 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
bba73a80dcd02fb4a76fe3938733cb4b73c365a6
1,380
aoc-2022
Apache License 2.0
src/Day14.kt
esp-er
573,196,902
false
{"Kotlin": 29675}
package patriker.day14 import patriker.utils.* fun main() { // test if implementation meets criteria from the description, like: val testInput = readInput("Day14_test") val input = readInput("Day14_input") check(solvePart1(testInput) == 24) println(solvePart1(input)) check(solvePart2(testInput) == 93) println(solvePart2(input)) } fun parsePath(line: String): List<Pair<Int,Int>>{ val points = line.replace(" ", "").split("->") val pointsPairs = points.map{ val (x,y) = it.split(",") x.toInt() to y.toInt() } return pointsPairs } fun updateRockWall(points: List<Pair<Int,Int>>, blockedMap: HashSet<Pair<Int,Int>>){ points.windowed(2).forEach{ wallSegment -> val (start,end) = wallSegment val horRange = if(start.first < end.first) start.first..end.first else start.first downTo end.first val vertRange = if(start.second < end.second) start.second..end.second else start.second downTo end.second horRange.forEach{xPoint -> vertRange.forEach{yPoint -> blockedMap.add(xPoint to yPoint) } } } } fun simulateFalling(startPos: Pair<Int,Int>, blockedMap: HashSet<Pair<Int,Int>>, floorLevel: Int): Pair<Int,Int>{ var currentPos = startPos while(true){ if(!blockedMap.contains(currentPos.first to currentPos.second + 1)) currentPos = currentPos.first to currentPos.second + 1 else if(!blockedMap.contains(currentPos.first - 1 to currentPos.second + 1)) currentPos = currentPos.first - 1 to currentPos.second + 1 else if(!blockedMap.contains(currentPos.first + 1 to currentPos.second + 1)) currentPos = currentPos.first + 1 to currentPos.second + 1 else break if(currentPos.second > floorLevel) break } return if(currentPos.second > floorLevel) -1 to -1 else currentPos } fun simulateFalling2(startPos: Pair<Int,Int>, blockedMap: HashSet<Pair<Int,Int>>, floorLevel: Int): Pair<Int,Int>{ var currentPos = startPos while(true){ if(currentPos.second + 1 < floorLevel) { if (!blockedMap.contains(currentPos.first to currentPos.second + 1)) currentPos = currentPos.first to currentPos.second + 1 else if (!blockedMap.contains(currentPos.first - 1 to currentPos.second + 1)) currentPos = currentPos.first - 1 to currentPos.second + 1 else if (!blockedMap.contains(currentPos.first + 1 to currentPos.second + 1)) currentPos = currentPos.first + 1 to currentPos.second + 1 else //sand comes to rest break } else { //reached floor break } } return currentPos } fun solvePart1(input: List<String>): Int{ val blockedMap = HashSet<Pair<Int,Int>>() input.forEach{ line -> val points = parsePath(line) updateRockWall(points, blockedMap) } val floorLevel = blockedMap.maxOf{ it.second } val wallUnits = blockedMap.size while(true){ val newSand = simulateFalling(500 to 0, blockedMap, floorLevel) if(newSand == -1 to - 1) break else blockedMap.add(newSand) } return blockedMap.size - wallUnits } fun solvePart2(input: List<String>): Int{ val blockedMap = HashSet<Pair<Int,Int>>() input.forEach{ line -> val points = parsePath(line) updateRockWall(points, blockedMap) } val floorLevel = blockedMap.maxOf{ it.second } + 2 val wallUnits = blockedMap.size do{ val newSand = simulateFalling2(500 to 0, blockedMap, floorLevel) blockedMap.add(newSand) } while(newSand != 500 to 0) return blockedMap.size - wallUnits }
0
Kotlin
0
0
f46d09934c33d6e5bbbe27faaf2cdf14c2ba0362
3,805
aoc2022
Apache License 2.0
src/Day12.kt
maewCP
579,203,172
false
{"Kotlin": 59412}
fun main() { val verbose = false val shortestPath = mutableMapOf<Pair<Int, Int>, Day12Solution>() val queue = mutableListOf<Day12Solution>() val map = mutableMapOf<Pair<Int, Int>, Char>() val aPositions = mutableListOf<Pair<Int, Int>>() lateinit var start: Pair<Int, Int> lateinit var goal: Pair<Int, Int> var maxR = 0 var maxC = 0 fun printSolution(solution: Day12Solution) { (0..maxR).forEach { r -> (0..maxC).forEach { c -> val curr = Pair(r, c) if (curr !in solution.path) print(".") else { val currStep = solution.path.indexOf(curr) if (currStep == solution.path.size - 1) print("E") else { val next = solution.path[currStep + 1] if (curr.first < next.first) print("v") else if (curr.first > next.first) print("^") else if (curr.second < next.second) print(">") else print("<") } } } println("") } } fun printMap() { (0..maxR).forEach { r -> (0..maxC).forEach { c -> print(map[Pair(r, c)]) } println("") } } fun tryNext(solution: Day12Solution, relativeR: Int, relativeC: Int) { val curr = solution.path[solution.path.size - 1] if (curr.first + relativeR < 0 || curr.first + relativeR > maxR) return if (curr.second + relativeC < 0 || curr.second + relativeC > maxC) return val next = Pair(curr.first + relativeR, curr.second + relativeC) if (next in solution.path) return if (map[next]!! - map[curr]!! > 1) return val newPath = solution.path.toMutableList() newPath.add(next) queue.add(Day12Solution(newPath)) } fun search() { val solution = queue.removeAt(0) val curr = solution.path[solution.path.size - 1] val bSolution = shortestPath[curr] if (bSolution == null) shortestPath[curr] = solution else if (solution.path.size < shortestPath[curr]!!.path.size) shortestPath[curr] = solution else return if (curr == goal) return tryNext(solution, -1, 0) tryNext(solution, 1, 0) tryNext(solution, 0, 1) tryNext(solution, 0, -1) } fun prepareInput(input: List<String>) { aPositions.clear() input.forEachIndexed { r, line -> line.toList().forEachIndexed { c, h -> if (h == 'S') { start = Pair(r, c) } else if (h == 'E') { goal = Pair(r, c) } if (h == 'a' || h == 'S') aPositions.add(Pair(r, c)) map[Pair(r, c)] = if (h == 'S') 'a' else if (h == 'E') 'z' else h maxC = maxC.coerceAtLeast(c) } maxR = r } } fun _process(startPoints: List<Pair<Int, Int>>) : Int { var globalSolution: Day12Solution? = null startPoints.forEach { startPoint: Pair<Int, Int> -> shortestPath.clear() queue.add(Day12Solution(mutableListOf(startPoint))) do { search() } while (queue.size > 0) if (shortestPath[goal] == null) return@forEach if (globalSolution == null || globalSolution!!.path.size > shortestPath[goal]!!.path.size) { globalSolution = shortestPath[goal]!! } } val solution = globalSolution!! if (verbose) println(solution.path) if (verbose) printMap() if (verbose) println("") if (verbose) printSolution(solution) if (verbose) println("") if (verbose) println(solution.path.size - 1) return solution.path.size - 1 } fun part1(input: List<String>): Int { prepareInput(input) return _process(listOf(start)) } fun part2(input: List<String>): Int { prepareInput(input) return _process(aPositions) } // test if implementation meets criteria from the description, like: val testInput = readInput("Day12_test") check(part1(testInput) == 31) check(part2(testInput) == 29) val input = readInput("Day12") part1(input).println() part2(input).println() } data class Day12Solution(val path: MutableList<Pair<Int, Int>>)
0
Kotlin
0
0
8924a6d913e2c15876c52acd2e1dc986cd162693
4,513
advent-of-code-2022-kotlin
Apache License 2.0
src/main/kotlin/io/github/clechasseur/adventofcode/y2015/Day19.kt
clechasseur
568,233,589
false
{"Kotlin": 242914}
package io.github.clechasseur.adventofcode.y2015 import io.github.clechasseur.adventofcode.y2015.data.Day19Data import kotlin.math.min object Day19 { private val transforms = Day19Data.transforms private const val molecule = Day19Data.molecule private val transformRegex = """^(\w+) => (\w+)$""".toRegex() fun part1(): Int = transforms.toTransformMap().allTransforms(molecule).distinct().count() fun part2(): Int { val transformsList = transforms.toTransformMap().reverse() return generateSequence(State(molecule)) { it.next(transformsList) ?: error("Could not find path to e") }.dropWhile { it.steps.last().mol != "e" }.first().steps.size - 1 } private fun String.toTransformMap(): Map<Regex, List<String>> = lines().map { line -> val match = transformRegex.matchEntire(line) ?: error("Wrong transform: $line") match.groupValues[1] to match.groupValues[2] }.fold(mutableMapOf<Regex, MutableList<String>>()) { acc, (from, to) -> acc.computeIfAbsent(from.toRegex()) { mutableListOf() }.add(to) acc } private fun Map<Regex, List<String>>.reverse(): List<Pair<Regex, String>> = flatMap { (from, toList) -> toList.map { to -> to.toRegex() to from.pattern } }.sortedByDescending { it.first.pattern.length } private fun Map<Regex, List<String>>.allTransforms(mol: String): Sequence<String> = asSequence().flatMap { (from, toList) -> toList.asSequence().flatMap { to -> from.findAll(mol).map { match -> mol.substring(0, match.range.first) + to + mol.substring(match.range.last + 1, mol.length) } } } private class Step(val mol: String, val path: List<Pair<Int, Int>>) { fun next(transforms: List<Pair<Regex, String>>, startingAt: Pair<Int, Int>?): Step? = transforms.asSequence().mapIndexed { i, (f, t) -> val match = f.find( mol, min(if (i == 0 && startingAt != null) startingAt.second + f.pattern.length else 0, mol.length) ) if (match != null) { val rep = mol.substring(0, match.range.first) + t + mol.substring(match.range.last + 1, mol.length) Step(rep, path + (i to match.range.first)) } else null }.drop(startingAt?.first ?: 0).filterNotNull().firstOrNull() } private class State(val steps: List<Step>) { constructor(initialMol: String) : this(listOf(Step(initialMol, emptyList()))) fun next(transforms: List<Pair<Regex, String>>, startingAt: Pair<Int, Int>? = null): State? = if (steps.isEmpty()) null else { val lastStep = steps.last() val stepNext = lastStep.next(transforms, startingAt) if (stepNext != null) { State(steps + stepNext) } else { val stepsBack = steps.subList(0, steps.indices.last) State(stepsBack).next(transforms, lastStep.path.last()) } } } }
0
Kotlin
0
0
e5a83093156cd7cd4afa41c93967a5181fd6ab80
3,056
adventofcode2015
MIT License
src/main/kotlin/day02/Solution.kt
TestaDiRapa
573,066,811
false
{"Kotlin": 50405}
package day02 import java.io.File import java.lang.Exception enum class MoveTypes { ROCK, PAPER, SCISSORS } fun getWinningMove(move: Move) = when(move.type) { MoveTypes.ROCK -> Move("B") MoveTypes.PAPER -> Move("C") MoveTypes.SCISSORS -> Move("A") } fun getLosingMove(move: Move) = when(move.type) { MoveTypes.ROCK -> Move("C") MoveTypes.PAPER -> Move("A") MoveTypes.SCISSORS -> Move("B") } class Move( code: String ): Comparable<Move> { val type = when(code) { "A" -> MoveTypes.ROCK "B" -> MoveTypes.PAPER "C" -> MoveTypes.SCISSORS "X" -> MoveTypes.ROCK "Y" -> MoveTypes.PAPER "Z" -> MoveTypes.SCISSORS else -> throw Exception() } override fun compareTo(other: Move): Int { if(type == other.type) return 0 return when(type) { MoveTypes.ROCK -> { if(other.type == MoveTypes.SCISSORS) return 1 else return -1 } MoveTypes.PAPER -> { if(other.type == MoveTypes.ROCK) return 1 else return -1 } MoveTypes.SCISSORS -> { if(other.type == MoveTypes.PAPER) return 1 else return -1 } } } fun value(): Int = when(type) { MoveTypes.ROCK -> 1 MoveTypes.PAPER -> 2 MoveTypes.SCISSORS -> 3 } } class Match( private val yourMove: Move, private val otherMove: Move ) { fun score(): Int { return if (yourMove < otherMove) yourMove.value() else if (yourMove > otherMove) 6 + yourMove.value() else 3 + yourMove.value() } } fun getListOfMatchesFromFile() = File("src/main/kotlin/day022/input.txt") .readLines() .fold(listOf<Pair<String, String>>()) { moves, it -> val (opponentMove, yourMove) = it.split(" ") moves + Pair(opponentMove, yourMove) } fun interpretPairsAsMatches() = getListOfMatchesFromFile() .map { Match( Move(it.second), Move(it.first) ) } fun interpretPairsAsResults() = getListOfMatchesFromFile() .map { when(it.second) { "X" -> Match(getLosingMove(Move(it.first)), Move(it.first)) "Y" -> Match(Move(it.first), Move(it.first)) "Z" -> Match(getWinningMove(Move(it.first)), Move(it.first)) else -> throw Exception() } } fun getTotalScore() = interpretPairsAsMatches().sumOf { it.score() } fun getTotalScoreWithOutcome() = interpretPairsAsResults().sumOf { it.score() } fun main() { println("The total score if the second row is the move is: ${getTotalScore()}") println("The total score if the second row is the outcome is: ${getTotalScoreWithOutcome()}") }
0
Kotlin
0
0
b5b7ebff71cf55fcc26192628738862b6918c879
2,781
advent-of-code-2022
MIT License
src/Day05.kt
Ajimi
572,961,710
false
{"Kotlin": 11228}
data class Action(val amount: Int, val from: Int, val to: Int) fun main() { fun performOperations( actions: List<Action>, stacks: List<MutableList<Char>>, shouldReverse: Boolean = true, ) { actions.forEach { (amount, from, to) -> val toAdd = stacks[from].take(amount) repeat(amount) { stacks[from].removeFirst() } stacks[to].addAll(0, if (shouldReverse) toAdd.reversed() else toAdd) } } fun part1(input: List<String>): String { val (first, second) = input val stacks = first.toStacks() val actions = second.toAction() performOperations(actions, stacks) return stacks.topStack() } fun part2(input: List<String>): String { val (first, second) = input val stacks = first.toStacks() val actions = second.toAction() performOperations(actions, stacks, false) return stacks.topStack() } // test if implementation meets criteria from the description, like: val testInput = readTextInput("Day05_test").split("\n\n") check(part1(testInput) == "CMZ") check(part2(testInput) == "MCD") val input = readTextInput("Day05").split("\n\n") println(part1(input)) println(part2(input)) } private fun List<List<Char>>.topStack(): String = map { it.first() }.joinToString("") private fun String.toStacks(): List<MutableList<Char>> { val stackRows = split("\n").takeWhile { it.contains('[') } return (1..stackRows.last().length step 4).map { index -> stackRows .mapNotNull { it.getOrNull(index) } .filter { it.isUpperCase() } .toMutableList() } } private fun String.toAction(): List<Action> { return split("\n") .map { action -> action.split(" ") .mapNotNull { it.toIntOrNull() } } .dropLast(1) .map { (amount, from, to) -> Action(amount, from - 1, to - 1) } }
0
Kotlin
0
0
8c2211694111ee622ebb48f52f36547fe247be42
2,012
adventofcode-2022
Apache License 2.0
src/Day04.kt
Tiebe
579,377,778
false
{"Kotlin": 17146}
fun main() { fun part1(input: List<String>): Int { return input.count { sectionList -> val sections = sectionList.split(',') val section1 = sections[0].split('-').map { it.toInt() } val section2 = sections[1].split('-').map { it.toInt() } ((section1[0] >= section2[0] && section1[1] <= section2[1]) || (section1[0] <= section2[0] && section1[1] >= section2[1])) } } fun part2(input: List<String>): Int { return input.count { sectionList -> val sections = sectionList.split(',') val section1 = sections[0].split('-').map { it.toInt() } val section2 = sections[1].split('-').map { it.toInt() } ((section1[0] >= section2[0] && section1[0] <= section2[1]) || (section1[1] >= section2[0] && section1[1] <= section2[1])) || ((section2[0] >= section1[0] && section2[0] <= section1[1]) || (section2[1] >= section1[0] && section2[1] <= section1[1])) } } // 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") part1(input).println() part2(input).println() }
1
Kotlin
0
0
afe9ac46b38e45bd400e66d6afd4314f435793b3
1,326
advent-of-code
Apache License 2.0
aoc2022/day15.kt
davidfpc
726,214,677
false
{"Kotlin": 127212}
package aoc2022 import utils.InputRetrieval import kotlin.math.abs fun main() { Day15.execute() } object Day15 { fun execute() { val input = readInput() println("Part 1: ${part1(input)}") println("Part 2: ${part2(input)}") } private fun part1(input: List<Sensor>, row: Int = 2_000_000): Int { val beaconPositions = input.map { it.closestBeacon.x to it.closestBeacon.y }.toSet() val coveredPositions = mutableSetOf<Pair<Int, Int>>() input.forEach { val coveredManhattanDistance = it.coveredManhattanDistance() val canReachTargetRow = it.y - coveredManhattanDistance <= row && row <= it.y + coveredManhattanDistance var x = 0 while (canReachTargetRow) { // Add all covered positions in the target Row to a set if (it.manhattanDistance(it.x + x, row) > coveredManhattanDistance) { break } coveredPositions.add(it.x + x to row) coveredPositions.add(it.x - x to row) x++ } } coveredPositions.removeAll(beaconPositions) return coveredPositions.filter { it.second == row }.size } private fun part2(input: List<Sensor>, maxValue: Int = 4_000_000): Long { // 4_000_000 input.forEach { sensor -> // Because there is just a single point, get the positions just outside its reach and check those val coveredManhattanDistance = sensor.coveredManhattanDistance() + 1 var x = coveredManhattanDistance var y = 0 while (x >= 0) { val pointsToCheck = listOf(sensor.x + x to sensor.y + y, sensor.x - x to sensor.y + y, sensor.x + x to sensor.y - y, sensor.x - x to sensor.y - y) pointsToCheck.filter { it.first in 0..maxValue && it.second in 0..maxValue } .forEach { pointToCheck -> var overlap = false for (sensorToValidate in input) { if (sensorToValidate.manhattanDistance(pointToCheck.first, pointToCheck.second) <= sensorToValidate.coveredManhattanDistance()) { overlap = true break } } if (!overlap) { println("Found point $pointToCheck!") return (pointToCheck.first * 4_000_000L) + pointToCheck.second } } // Check next point x-- y++ } } return -1 } private fun readInput(): List<Sensor> = InputRetrieval.getFile(2022, 15).readLines().map { input -> //Sensor at x=2, y=18: closest beacon is at x=-2, y=15 val (sensorInput, beaconInput) = input.split(": closest beacon is at ") val beacon = beaconInput.split(", ").map { it.removePrefix("x=").removePrefix("y=").toInt() }.let { val (beaconX, beaconY) = it Beacon(beaconX, beaconY) } sensorInput.split(", ").map { it.removePrefix("Sensor at x=").removePrefix("y=").toInt() }.let { val (sensorX, sensorY) = it Sensor(sensorX, sensorY, beacon) } } data class Sensor(val x: Int, val y: Int, val closestBeacon: Beacon) { fun coveredManhattanDistance(): Int = this.manhattanDistance(closestBeacon.x, closestBeacon.y) } data class Beacon(val x: Int, val y: Int) private fun Sensor.manhattanDistance(toX: Int, toY: Int): Int = abs(this.x - toX) + abs(this.y - toY) fun Set<Pair<Int, Int>>.print() { val minX = this.minOf { it.first } val maxX = this.maxOf { it.first } val minY = this.minOf { it.second } val maxY = this.maxOf { it.second } for (x in minX..maxX) { for (y in minY..maxY) { if (this.contains(x to y)) { print("#") } else { print(".") } } println() } println() } }
0
Kotlin
0
0
8dacf809ab3f6d06ed73117fde96c81b6d81464b
4,231
Advent-Of-Code
MIT License
src/Day04.kt
ajesh-n
573,125,760
false
{"Kotlin": 8882}
fun main() { fun part1(input: List<String>): Int { val sections: List<List<List<Int>>> = input.map { sectionPairs -> sectionPairs.split(",").map { it.split("-").map { section -> section.toInt() } } .map { (it.first()..it.last()).toList() } } return sections.count { it.first().containsAll(it.last()) || it.last().containsAll(it.first()) } } fun part2(input: List<String>): Int { val sections: List<List<List<Int>>> = input.map { sectionPairs -> sectionPairs.split(",").map { it.split("-").map { section -> section.toInt() } } .map { (it.first()..it.last()).toList() } } return sections.count { it.first().intersect(it.last().toSet()).isNotEmpty() } } 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
2545773d7118da20abbc4243c4ccbf9330c4a187
1,013
kotlin-aoc-2022
Apache License 2.0
src/main/kotlin/dec20/Main.kt
dladukedev
318,188,745
false
null
package dec20 import java.lang.IndexOutOfBoundsException fun <T> List<List<T>>.rotate90(): List<List<T>> { return this.mapIndexed { rowIndex, row -> row.mapIndexed { colIndex, _ -> this[row.count() - colIndex - 1][rowIndex] } } } fun <T> List<List<T>>.rotate180(): List<List<T>> { return this.reversed() } fun <T> List<List<T>>.rotate270(): List<List<T>> { return this.mapIndexed { rowIndex, row -> row.mapIndexed { colIndex, _ -> this[colIndex][this.count() - rowIndex - 1] } } } fun <T> List<List<T>>.flipH(): List<List<T>> { return this.map { it.reversed() } } fun <T> List<List<T>>.permutations(): List<List<List<T>>> { return listOf( this, this.rotate90(), this.rotate180(), this.rotate270(), this.flipH(), this.flipH().rotate90(), this.flipH().rotate180(), this.flipH().rotate270() ) } data class PuzzlePiece(val id: Int, val piece: List<List<Char>>) { val top = piece.first() val bottom = piece.last() val right = piece.map { it.last() } val left = piece.map { it.first() } val sides: List<List<Char>> = listOf( top, bottom, right, left ) fun rotate90(): PuzzlePiece { val pieces = piece.rotate90() return PuzzlePiece(id, pieces) } fun rotate180(): PuzzlePiece { val pieces = piece.rotate180() return PuzzlePiece(id, pieces) } fun rotate270(): PuzzlePiece { val pieces = piece.rotate270() return PuzzlePiece(id, pieces) } fun flipH(): PuzzlePiece { val pieces = piece.flipH() return PuzzlePiece(id, pieces) } fun removeBorder(): PuzzlePiece { val pieces = piece.drop(1).dropLast(1) .map { it.drop(1).dropLast(1) } return PuzzlePiece(id, pieces) } } fun puzzleSidePermutations(puzzlePiece: PuzzlePiece): List<List<Char>> { return listOf( puzzlePiece.sides, puzzlePiece.flipH().rotate90().sides ).flatten() } fun puzzlePiecePermutations(puzzlePiece: PuzzlePiece): List<PuzzlePiece> { return puzzlePiece.piece.permutations() .map { PuzzlePiece(puzzlePiece.id, it) } } fun parseInput(input: String): List<PuzzlePiece> { return input .lines() .filter { it.isNotEmpty() } .chunked(11) .map { val title = it.first().substring(5, 9).toInt() val piece = it.drop(1) .map { row -> row.toCharArray().toList() } PuzzlePiece(title, piece) } } fun getUniqueEdges(puzzlePieces: List<PuzzlePiece>): List<List<Char>> { return puzzlePieces.flatMap { puzzleSidePermutations(it) }.groupingBy { it } .eachCount() .filter { it.value == 1 } .map { it.key } } fun findCorners(puzzlePieces: List<PuzzlePiece>): List<PuzzlePiece> { val uniqueEdges = getUniqueEdges(puzzlePieces) return puzzlePieces.filter { piece -> val countOfEdges = uniqueEdges.count { edge -> piece.sides.contains(edge) } countOfEdges == 2 } } val ROW_MAX = 11 val COL_MAX = 11 fun buildPuzzleRecur( remainingPieces: List<PuzzlePiece>, outsideEdges: List<List<Char>>, location: Pair<Int, Int> = Pair(0, 0), puzzle: MutableList<MutableList<PuzzlePiece>> = mutableListOf() ): List<List<PuzzlePiece>> { if (remainingPieces.isEmpty()) { return puzzle } val (rowIndex, colIndex) = location val matchx = remainingPieces.flatMap { val matches = puzzlePiecePermutations(it) .filter { piece -> val topValid = if (rowIndex == 0) { outsideEdges.contains(piece.top) } else { puzzle[rowIndex - 1][colIndex].bottom == piece.top } val leftValid = if (colIndex == 0) { outsideEdges.contains(piece.left) } else { puzzle[rowIndex][colIndex - 1].right == piece.left } topValid && leftValid } matches } val match = matchx.first() if (colIndex == 0) { puzzle.add(mutableListOf(match)) } else { puzzle[rowIndex].add(match) } val newRemainPieces = remainingPieces.filter { it.id != match.id } val nextPoint = if(colIndex == COL_MAX) Pair(rowIndex + 1, 0) else Pair(rowIndex,colIndex + 1) return buildPuzzleRecur(newRemainPieces, outsideEdges, nextPoint, puzzle) } fun buildPuzzle(puzzlePieces: List<PuzzlePiece>): List<List<Char>> { val outsideEdges = getUniqueEdges(puzzlePieces) val assembledPieces = buildPuzzleRecur(puzzlePieces, outsideEdges) val puzzle = assembledPieces.map {row -> row.map { it.removeBorder() } } return puzzle.map {row -> (0 until 8).map { index -> row.fold(emptyList<Char>()) { acc, puzzlePiece -> acc + puzzlePiece.piece[index] } } }.flatten() .permutations() .single { countSeaSerpents(it) > 0 } } fun findSeaSerpentAtPoint(x: Int, y: Int, puzzle: List<List<Char>>): Boolean { return try { val points = listOf( Pair(x, y), Pair(x+1, y+1), Pair(x+4, y+1), Pair(x+5, y), Pair(x+6, y), Pair(x+7, y+1), Pair(x+10, y+1), Pair(x+11, y), Pair(x+12, y), Pair(x+13, y+1), Pair(x+16, y+1), Pair(x+17, y), Pair(x+18, y), Pair(x+18, y-1), Pair(x+19, y) ) points.all { puzzle[it.first][it.second] == '#' } } catch (e: IndexOutOfBoundsException) { false } } fun countSeaSerpents(puzzle: List<List<Char>>): Int { return puzzle.mapIndexed { index, row -> row.mapIndexed { colIndex, _ -> findSeaSerpentAtPoint(colIndex, index, puzzle) } }.flatten() .count { it } } fun main() { val pieces = parseInput(input) val corners = findCorners(pieces) val result = corners.fold(1L) { acc, corner -> acc * corner.id } println("------------ PART 1 ------------") println("result: $result") val puzzle = buildPuzzle(pieces) val countOfHashes = puzzle.sumBy { it.count { it == '#' } } val countOfSeaSerpents = countSeaSerpents(puzzle) val countOfSeaSerpentTiles = countOfSeaSerpents * 15 val nonSeaSerpentHashes = countOfHashes - countOfSeaSerpentTiles println("------------ PART 2 ------------") println("result: $nonSeaSerpentHashes") }
0
Kotlin
0
0
d4591312ddd1586dec6acecd285ac311db176f45
6,822
advent-of-code-2020
MIT License
src/main/kotlin/dev/tasso/adventofcode/_2022/day09/Day09.kt
AndrewTasso
433,656,563
false
{"Kotlin": 75030}
package dev.tasso.adventofcode._2022.day09 import dev.tasso.adventofcode.Solution import kotlin.math.abs class Day09 : Solution<Int> { override fun part1(input: List<String>): Int = input.map { inputLine -> inputLine.split(" ") } //Break each larger step of multiple moves in a specific direction into moves of only a single space each .flatMap { splitLine -> List(splitLine[1].toInt()) { splitLine[0].first() }} // Provide a list to hold the positions the rope will travel, starting with both the head and tail at 0,0 .fold( listOf(Rope(List(2){ Coords() })) ) { positions : List<Rope>, moveDirection : Char -> positions.plus(positions.last().movedTo(moveDirection)) }.distinctBy { position -> position.knotCoords.last()} .count() override fun part2(input: List<String>): Int = input.map { inputLine -> inputLine.split(" ") } //Break each larger step of multiple moves in a specific direction into moves of only a single space each .flatMap { splitLine -> List(splitLine[1].toInt()) { splitLine[0].first() }} // Provide a list to hold the positions the rope will travel, starting with both the head and tail at 0,0 .fold( listOf(Rope(List(10){ Coords() })) ) { positions : List<Rope>, moveDirection : Char -> positions.plus(positions.last().movedTo(moveDirection)) }.distinctBy { position -> position.knotCoords.last()} .count() private data class Coords(val x: Int = 0, val y: Int = 0) private data class Rope(val knotCoords: List<Coords>) private fun Rope.movedTo(direction : Char) : Rope { val headCoords = this.knotCoords.first() fun getNewHeadCoords(moveDirection: Char) : Coords = when(moveDirection) { 'U' -> Coords(headCoords.x, headCoords.y + 1) 'D' -> Coords(headCoords.x, headCoords.y - 1) 'R' -> Coords(headCoords.x + 1, headCoords.y) 'L' -> Coords(headCoords.x - 1, headCoords.y) else -> throw IllegalArgumentException("Unexpected direction encountered ($moveDirection)") } fun getNewKnotCoords(nextKnotCoords : Coords, prevKnotCoords : Coords) : Coords = if(abs(prevKnotCoords.x - nextKnotCoords.x) >= 2 && abs(prevKnotCoords.y - nextKnotCoords.y) >= 2) { Coords((nextKnotCoords.x + prevKnotCoords.x) / 2, (nextKnotCoords.y + prevKnotCoords.y) / 2) } else if(abs(prevKnotCoords.x - nextKnotCoords.x) >= 2) { if(prevKnotCoords.y == nextKnotCoords.y) { Coords((nextKnotCoords.x + prevKnotCoords.x) / 2, prevKnotCoords.y) } else { //if diagonal, bring the tail in line with the new position of the head Coords((nextKnotCoords.x + prevKnotCoords.x) / 2, nextKnotCoords.y) } } else if(abs(prevKnotCoords.y - nextKnotCoords.y) >= 2) { if(prevKnotCoords.y == nextKnotCoords.y) { Coords(prevKnotCoords.x, (nextKnotCoords.y + prevKnotCoords.y) / 2) } else { //if diagonal, bring the tail in line with the new position of the head Coords(nextKnotCoords.x, (nextKnotCoords.y + prevKnotCoords.y) / 2) } } else { prevKnotCoords } return this.knotCoords.drop(1) //Drop old head knot since the new list starts with the new head knot //Start the new rope with the new head coords and drag the remaining knots along for the ride .fold(listOf(getNewHeadCoords(direction))) { newKnotCoords, currOldKnotCoord -> newKnotCoords.plus(getNewKnotCoords(newKnotCoords.last(), currOldKnotCoord)) }.let { Rope(it) } } }
0
Kotlin
0
0
daee918ba3df94dc2a3d6dd55a69366363b4d46c
3,975
advent-of-code
MIT License
src/main/kotlin/com/hj/leetcode/kotlin/problem1680/Solution2.kt
hj-core
534,054,064
false
{"Kotlin": 619841}
package com.hj.leetcode.kotlin.problem1680 /** * LeetCode page: [1680. Concatenation of Consecutive Binary Numbers](https://leetcode.com/problems/concatenation-of-consecutive-binary-numbers/); * * Note: There is a solution posted by leetCode staff and claims to have time O((LogN)^2), see [HERE](https://leetcode.com/problems/concatenation-of-consecutive-binary-numbers/discuss/963886). * I cannot understand... */ class Solution2 { /* Complexity: * Time O((LogN)^2) and Space O(LogN) where N equals n; */ fun concatenatedBinary(n: Int): Int { /* The idea is to represent the concatenation through a series of matrix operations, which contains * multiplication of matrix powers. The improvement comes from algorithm that takes Log rather than * linear order complexity to calculate the power, which is similar to 2^16 = (2^2)^8 = (4^2)^4. * * Recursive relation via matrix operation: * | ans_n | | 2^k 1 0 | | ans_(n-1) | * mat ( | n + 1 | ) = mat ( | 0 1 1 | ) * mat ( | n | ) where k is the bitLength of n; * | 1 | | 0 0 1 | | 1 | */ var vector = listOf(longArrayOf(1L), longArrayOf(2L), longArrayOf(1L)) var prevBitValue = 2L val mod = 1_000_000_007 while (prevBitValue <= n) { val bitValue = prevBitValue shl 1 val base = getBaseMultiplier(bitValue) val pow = if (n < bitValue) n - prevBitValue + 1 else prevBitValue val multiplier = powerAndRem(base, pow, mod) vector = multiplyAndRem(vector, multiplier, mod) prevBitValue = bitValue } return vector[0][0].toInt() } private fun getBaseMultiplier(bitValue: Long): List<LongArray> { return listOf( longArrayOf(bitValue, 1L, 0), longArrayOf(0, 1L, 1L), longArrayOf(0, 0, 1L) ) } private fun powerAndRem(mat: List<LongArray>, pow: Long, mod: Int): List<LongArray> { require(pow > 0) val result = if (pow == 1L) { rem(mat, mod) } else { val square = multiplyAndRem(mat, mat, mod) val floorPow = powerAndRem(square, pow shr 1, mod) val isEven = pow and 1L == 0L if (isEven) floorPow else multiplyAndRem(mat, floorPow, mod) } return result } private fun rem(mat: List<LongArray>, mod: Int): List<LongArray> { return List(mat.size) { row -> LongArray(mat[row].size) { column -> mat[row][column] % mod } } } private fun multiplyAndRem(mat: List<LongArray>, multiplier: List<LongArray>, mod: Int): List<LongArray> { return List(multiplier.size) { row -> LongArray(mat[row].size) { column -> var value = 0L for (index in multiplier[row].indices) { value += multiplier[row][index] * mat[index][column] } value % mod } } } }
1
Kotlin
0
1
14c033f2bf43d1c4148633a222c133d76986029c
3,160
hj-leetcode-kotlin
Apache License 2.0
src/Day05.kt
gsalinaslopez
572,839,981
false
{"Kotlin": 21439}
fun main() { fun getCrates(input: List<String>): Array<ArrayDeque<Char>> { val reversedCratesString = input.filter { it.contains('[') }.reversed() val numOfCrates = reversedCratesString.first().count { it == '[' } val crates = Array<ArrayDeque<Char>>(numOfCrates) { ArrayDeque() } reversedCratesString.forEach { var cratesString = it var crateIndex = 0 while (cratesString.length >= 3) { val crate = cratesString.substring(0, 3) if (crate.contains('[') && crate.contains(']')) { crates[crateIndex].add(crate[1]) } if (cratesString.length >= 4) { cratesString = cratesString.substring(4) crateIndex += 1 } else { break } } } return crates } data class Instruction(val numOfCrates: Int, val source: Int, val dest: Int) fun getInstructions(input: String): Instruction { val instructions = input.split(" ") return Instruction( numOfCrates = instructions[1].toInt(), source = instructions[3].toInt() - 1, dest = instructions[5].toInt() - 1 ) } fun getTopCrates(crates: Array<ArrayDeque<Char>>): String = Array(crates.size) { i -> crates[i].last() }.joinToString(separator = "") { it.toString() } fun part1(input: List<String>): String { val crates = getCrates(input) input.filter { it.startsWith("move") }.forEach { instruction -> val (numOfCrates, source, dest) = getInstructions(instruction) for (i in 0 until numOfCrates) { crates[dest].add(crates[source].last()) crates[source].removeLast() } } return getTopCrates(crates) } fun part2(input: List<String>): String { val crates = getCrates(input) input.filter { it.startsWith("move") }.forEach { instruction -> val (numOfCrates, source, dest) = getInstructions(instruction) val tempCrate = ArrayDeque<Char>() for (i in 0 until numOfCrates) { tempCrate.add(crates[source].last()) crates[source].removeLast() } for (i in 0 until numOfCrates) { crates[dest].add(tempCrate.last()) tempCrate.removeLast() } } return getTopCrates(crates) } // 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
041c7c3716bfdfdf4cc89975937fa297ea061830
2,820
aoc-2022-in-kotlin
Apache License 2.0
src/main/kotlin/Day5.kt
amitdev
574,336,754
false
{"Kotlin": 21489}
fun solve(lines: Sequence<String>, part1: Boolean) = lines.fold(Input()) { acc, line -> acc.merge(acc.parse(line)) } .arrangeCrates() .rearrange(part1) .top() data class Input( val crates: Map<Int, List<String>> = mapOf(), val instructions: List<Instruction> = listOf(), private val parsedCrates: Boolean = false) { fun merge(that: Input) = when { parsedCrates -> copy(instructions = instructions + that.instructions) that.parsedCrates -> copy(parsedCrates = true) else -> Input( (this.crates.keys + that.crates.keys).associateWith { this.crates.getOrDefault(it, listOf()) + that.crates.getValue(it) }) } fun arrangeCrates() = copy( crates = crates.mapValues { it.value.filter { it.startsWith("[") } .map { it.substring(1,2) } } ) fun parse(line: String) = when { line.isBlank() -> Input(parsedCrates = true) parsedCrates -> Input(instructions = parseInstruction(line)) else -> Input(parseCrate(line)) } private fun parseInstruction(line: String) = listOf(line.split(" ").toInstruction()) fun parseCrate(line: String) = line.chunked(4).withIndex().associate { v -> (v.index + 1) to listOf(v.value.trim()) } fun rearrange(inOrder: Boolean) = instructions.fold(crates) { acc, next -> acc.mapValues { when (it.key) { next.from -> it.value.subList(next.count, it.value.size) next.to -> acc.getValue(next.from).subList(0, next.count).let { if (inOrder) it.reversed() else it } + it.value else -> it.value }}} } fun Map<Int, List<String>>.top() = values.mapNotNull { it.firstOrNull() }.joinToString("") private fun List<String>.toInstruction() = Instruction(this[1].toInt(), this[3].toInt(), this[5].toInt()) data class Instruction(val count: Int, val from: Int, val to: Int)
0
Kotlin
0
0
b2cb4ecac94fdbf8f71547465b2d6543710adbb9
1,822
advent_2022
MIT License
src/Day05.kt
brunojensen
572,665,994
false
{"Kotlin": 13161}
private data class Move(val amount: Int, val from: Int, val to: Int) { fun execute1(stacks: List<MutableList<Char>>) { repeat(amount) { stacks[to].add(stacks[from].removeLast()) } } fun execute2(stacks: List<MutableList<Char>>) { repeat(amount) { stacks[to].add(stacks[from].removeMiddleTop(amount - it)) } } } private fun parseStacks(input: List<String>): List<MutableList<Char>> { val stackRows = input.takeWhile { it.contains('[') } return (1..stackRows.last().length step 4).map { index -> stackRows .mapNotNull { it.getOrNull(index) } .filter { it.isUpperCase() } .reversed() .toMutableList() } } private fun parseMoves(input: List<String>): List<Move> { return input .dropWhile { !it.startsWith("move") } .map { row -> row.split(" ").let { parts -> Move(parts[1].toInt(), parts[3].toInt() - 1, parts[5].toInt() - 1) } } } private fun <E> MutableList<E>.removeMiddleTop(i: Int): E { return removeAt((size) - i) } private fun List<MutableList<Char>>.topToString(): String { return joinToString("", transform = { it.last().toString() }) } fun main() { fun part1(input: List<String>): String { val stacks = parseStacks(input) parseMoves(input) .forEach { it.execute1(stacks) } return stacks.topToString() } fun part2(input: List<String>): String { val stacks = parseStacks(input) parseMoves(input) .forEach { it.execute2(stacks) } return stacks.topToString() } // 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
2707e76f5abd96c9d59c782e7122427fc6fdaad1
1,806
advent-of-code-kotlin-1
Apache License 2.0
src/main/kotlin/com/github/davio/aoc/y2022/Day8.kt
Davio
317,510,947
false
{"Kotlin": 405939}
package com.github.davio.aoc.y2022 import com.github.davio.aoc.general.* import kotlin.system.measureTimeMillis fun main() { println(Day8.getResultPart1()) measureTimeMillis { println(Day8.getResultPart2()) }.call { println("Took $it ms") } } /** * See [Advent of Code 2022 Day 8](https://adventofcode.com/2022/day/8#part2]) */ object Day8 : Day() { fun getResultPart1(): Int { val grid = parseGrid() val visibleTrees = sortedSetOf<Point>() (0..grid[0].lastIndex).forEach { x -> visibleTrees.add(Point.of(x, 0)) visibleTrees.add(Point.of(x, grid[0].lastIndex)) } (0..grid.lastIndex).forEach { y -> visibleTrees.add(Point.of(0, y)) visibleTrees.add(Point.of(grid.lastIndex, y)) } (1 until grid.lastIndex).forEach { y -> (1 until grid[0].lastIndex).forEach { x -> val treeCoords = Point.of(x, y) if (!visibleTrees.contains(treeCoords) && isVisible(grid, treeCoords)) { visibleTrees.add(treeCoords) } } } return visibleTrees.size } private fun isVisible(grid: List<List<Int>>, point: Point): Boolean { val treeHeight = grid[point.y][point.x] return (0 until point.y).all { y -> // From the top grid[y][point.x] < treeHeight } || (grid.lastIndex downTo point.y + 1).all { y -> // From the bottom grid[y][point.x] < treeHeight } || (0 until point.x).all { x -> // From the left grid[point.y][x] < treeHeight } || (grid[0].lastIndex downTo point.x + 1).all { x -> // From the right grid[point.y][x] < treeHeight } } private fun getScenicScore(grid: List<List<Int>>, point: Point): Int { val treeHeight = grid[point.y][point.x] val viewingDistanceTop = (point.y - 1 downTo 0).takeUntil { y -> grid[y][point.x] >= treeHeight }.count() val viewingDistanceBottom = (point.y + 1..grid.lastIndex).takeUntil { y -> grid[y][point.x] >= treeHeight }.count() val viewingDistanceLeft = (point.x - 1 downTo 0).takeUntil { x -> grid[point.y][x] >= treeHeight }.count() val viewingDistanceRight = (point.x + 1..grid[0].lastIndex).takeUntil { x -> grid[point.y][x] >= treeHeight }.count() return viewingDistanceTop * viewingDistanceLeft * viewingDistanceBottom * viewingDistanceRight } fun getResultPart2(): Int { val grid = parseGrid() return (1 until grid.lastIndex).maxOf { y -> (1 until grid[0].lastIndex).maxOf { x -> getScenicScore(grid, Point.of(x, y)) } } } private fun parseGrid() = getInputAsSequence().map { parseTreeRow(it) }.fold(mutableListOf<List<Int>>()) { acc, row -> acc += row acc } private fun parseTreeRow(line: String) = line.toCharArray().map { it.digitToInt() }.toList() }
1
Kotlin
0
0
4fafd2b0a88f2f54aa478570301ed55f9649d8f3
2,999
advent-of-code
MIT License
src/main/kotlin/Day02.kt
dliszewski
573,836,961
false
{"Kotlin": 57757}
class Day02 { fun part1(input: List<String>): Int { return input.map { it.split(" ") } .map { (opponentCode, myCode) -> HandShape.fromOpponentCode(opponentCode) to HandShape.fromElfCode(myCode) } .sumOf { (opponentHandShape, myHandShape) -> HandScorer.score(opponentHandShape, myHandShape) } } fun part2(input: List<String>): Int { return input.map { it.split(" ") } .map { (opponentCode, command) -> HandShape.fromOpponentCode(opponentCode) to command } .sumOf { (opponentHandShape, command) -> HandScorer.score( opponentHandShape, HandShape.decodeHand(opponentHandShape, command) ) } } object HandScorer { fun score(opponentHand: HandShape, myHandShape: HandShape): Int { return myHandShape.score + resultScore(opponentHand, myHandShape) } private fun resultScore(opponentHand: HandShape, myHandShape: HandShape): Int { return when (opponentHand) { myHandShape -> 3 HandShape.defeats[myHandShape] -> 6 else -> 0 } } } enum class HandShape(val opponentCode: String, val elfCode: String, val score: Int) { ROCK("A", "X", 1), PAPER("B", "Y", 2), SCISSORS("C", "Z", 3); companion object { val defeats = mapOf( ROCK to SCISSORS, PAPER to ROCK, SCISSORS to PAPER ) fun fromOpponentCode(code: String) = values().first { it.opponentCode == code } fun fromElfCode(code: String) = values().first { it.elfCode == code } fun decodeHand(opponentHand: HandShape, command: String): HandShape { return when (command) { "X" -> defeats[opponentHand]!! "Y" -> opponentHand "Z" -> defeats.entries.first { it.value == opponentHand }.key else -> throw IllegalStateException() } } } } }
0
Kotlin
0
0
76d5eea8ff0c96392f49f450660220c07a264671
2,141
advent-of-code-2022
Apache License 2.0
src/year2022/day04/Day.kt
tiagoabrito
573,609,974
false
{"Kotlin": 73752}
package year2022.day04 import readInput private const val MIN_1 = 0 private const val MAX_1 = 1 private const val MIN_2 = 2 private const val MAX_2 = 3 fun main() { fun isInside(line: List<Int>) = ((line[MIN_1] <= line[MIN_2] && line[MAX_2] <= line[MAX_1]) || (line[MIN_2] <= line[MIN_1] && line[MAX_1] <= line[MAX_2])) fun isOverlap(line: List<Int>) = (line[MIN_2] <= line[MAX_1] && line[MIN_1] <= line[MIN_2]) || (line[MIN_1] <= line[MAX_2] && line[MIN_2] <= line[MIN_1]) || (line[MAX_1] >= line[MIN_2] && line[MIN_1] <= line[MIN_2]) || (line[MAX_2] >= line[MIN_1] && line[MIN_2] <= line[MIN_1]) fun part1(input: List<CharSequence>): Int { return input.map { isInside(it.split(",","-").map { it.toInt()})}.count { it } } fun part2(input: List<String>): Int { return input.map { isOverlap(it.split(",","-").map { it.toInt()})}.count { it } } // test if implementation meets criteria from the description, like: val testInput = readInput("year2022/day04/test") println(part1(testInput)) check(part1(testInput) == 2) { "expected 2 but was ${part1(testInput)}" } val input = readInput("year2022/day04/input") println(part1(input)) check(part2(testInput) == 4) { "expected 4 but was ${part1(testInput)}" } println(part2(input)) }
0
Kotlin
0
0
1f9becde3cbf5dcb345659a23cf9ff52718bbaf9
1,470
adventOfCode
Apache License 2.0
src/Day02.kt
josepatinob
571,756,490
false
{"Kotlin": 17374}
fun main() { fun part1(input: List<String>): Int { val firstRowMap = mapOf("A" to "rock", "B" to "paper", "C" to "scissors") val secondRowMap = mapOf("X" to "rock", "Y" to "paper", "Z" to "scissors") val winningMap = mapOf("scissors" to "rock", "rock" to "paper", "paper" to "scissors") val pointsMap = mapOf("win" to 6, "lose" to 0, "draw" to 3, "X" to 1, "Y" to 2, "Z" to 3) var totalScore = 0 for (i in input) { val handOne = i[0].toString() val handTwo = i[2].toString() if (firstRowMap[handOne] == secondRowMap[handTwo]) { totalScore += pointsMap["draw"]!! + pointsMap[handTwo]!! } else if (winningMap[firstRowMap[handOne]!!] == secondRowMap[handTwo]) { totalScore += pointsMap["win"]!! + pointsMap[handTwo]!! } else { totalScore += pointsMap[handTwo]!! } } return totalScore } fun part2(input: List<String>): Int { val outcomeMap = mapOf("X" to "lose", "Y" to "draw", "Z" to "win") val firstRowMap = mapOf("A" to "rock", "B" to "paper", "C" to "scissors") val secondRowMap = mapOf("X" to "rock", "Y" to "paper", "Z" to "scissors") val oppositeSecondRowMap = mapOf("rock" to "X", "paper" to "Y", "scissors" to "Z") val winningMap = mapOf("scissors" to "rock", "rock" to "paper", "paper" to "scissors") val oppositeWinningMap = mapOf("rock" to "scissors", "paper" to "rock", "scissors" to "paper") val pointsMap = mapOf("win" to 6, "lose" to 0, "draw" to 3, "X" to 1, "Y" to 2, "Z" to 3) var totalScore = 0 for (i in input) { val handOne = i[0].toString() val handTwo = i[2].toString() var realHandTwo = "" if (outcomeMap[handTwo] == "win") { realHandTwo = oppositeSecondRowMap[winningMap[firstRowMap[handOne]!!]!!]!! } else if (outcomeMap[handTwo] == "draw") { realHandTwo = oppositeSecondRowMap[firstRowMap[handOne]!!]!! } else { realHandTwo = oppositeSecondRowMap[oppositeWinningMap[firstRowMap[handOne]!!]!!]!! } if (firstRowMap[handOne] == secondRowMap[realHandTwo]) { totalScore += pointsMap["draw"]!! + pointsMap[realHandTwo]!! } else if (winningMap[firstRowMap[handOne]!!] == secondRowMap[realHandTwo]) { totalScore += pointsMap["win"]!! + pointsMap[realHandTwo]!! } else { totalScore += pointsMap[realHandTwo]!! } } return totalScore } // test if implementation meets criteria from the description, like: //val testInput = readInput("Day02Sample") //println(part1(testInput)) val input = readInput("Day02") //println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
d429a5fff7ddc3f533d0854e515c2ba4b0d461b0
2,920
aoc-kotlin-2022
Apache License 2.0
src/main/kotlin/days/day08.kt
josergdev
573,178,933
false
{"Kotlin": 20792}
package days import java.io.File fun <T> List<List<T>>.transpose(): List<List<T>> = when { this.first().isEmpty() -> listOf() else -> listOf(this.map { it.first() }) + this.map { it.drop(1) }.transpose() } fun day8part1() = File("input/08.txt").readLines() .mapIndexed { i, e1 -> e1.mapIndexed { j, e2 -> (i to j) to e2.digitToInt() }} .let { it to it.reversed().map { c -> c.reversed() } } .let { (mat, matRev) -> mat + matRev + mat.transpose() + matRev.transpose() } .map { it.fold(setOf<Pair<Pair<Int, Int>, Int>>()) { acc, c -> if (acc.isNotEmpty() && acc.maxOf { ac -> ac.second } >= c.second) acc else acc.plus(c) } } .flatten().toSet() .count() fun <T> List<T>.takeWhileInclusive(pred: (T) -> Boolean): List<T> { var shouldContinue = true return takeWhile { val result = shouldContinue shouldContinue = pred(it) result } } fun day8part2() = File("input/08.txt").readLines() .mapIndexed { i, e1 -> e1.mapIndexed { j, e2 -> (i to j) to e2.digitToInt() } } .let { it to it.reversed().map { c -> c.reversed() } } .let { (mat, matRev) -> mat + matRev + mat.transpose() + matRev.transpose() } .fold(mutableMapOf<Pair<Pair<Int, Int>, Int>, List<List<Pair<Pair<Int, Int>, Int>>>>()) { acc, p -> p.forEachIndexed { index, pair -> if (acc.containsKey(pair)) acc[pair] = acc[pair]!!.plus(listOf(p.subList(index + 1, p.size))) else acc[pair] = listOf(p.subList(index + 1, p.size)) } acc }.entries .map { it.key.second to it.value.map { lp -> lp.map { p -> p.second } } } .map { (element, neighbours) -> neighbours.map { it.takeWhileInclusive { tree -> tree < element }.count() } } .maxOf { it.reduce { acc, i -> acc * i } }
0
Kotlin
0
0
ea17b3f2a308618883caa7406295d80be2406260
1,880
aoc-2022
MIT License
src/year2022/Day07.kt
Maetthu24
572,844,320
false
{"Kotlin": 41016}
package year2022 fun main() { class Dir(val name: String, val path: List<String>, val files: MutableList<Pair<String, Int>> = mutableListOf(), val subDirs: MutableList<Dir> = mutableListOf()) { val totalSize: Int get() = files.sumOf { it.second } + subDirs.sumOf { it.totalSize } } var dirs = mutableListOf<Dir>() fun part1(input: List<String>): Int { dirs = mutableListOf() val currentPath = mutableListOf<String>() var currentDir: Dir? = null for (line in input) { val parts = line.split(" ") if (parts[0] == "$") { if(parts[1] == "cd") { when (parts[2]) { ".." -> currentPath.removeLast() else -> currentPath.add(parts[2]) } val p = currentPath.dropLast(1) currentDir = if (dirs.any { it.name == currentPath.last() && it.path == p }) { dirs.first { it.name == currentPath.last() && it.path == p } } else { val d = Dir(currentPath.last(), p) dirs.add(d) d } } } else { if (parts[0] == "dir") { val p = currentPath.toMutableList() val d = Dir(parts[1], p) if (!currentDir!!.subDirs.any { it.name == d.name }) { currentDir.subDirs.add(d) } if (!dirs.any { it.name == d.name && it.path == d.path }) { dirs.add(d) } } else { currentDir?.let { if (!it.files.any { it.first == parts[1] }) { it.files.add(Pair(parts[1], parts[0].toInt())) } } } } } return dirs.filter { it.totalSize <= 100000 }.sumOf { it.totalSize } } fun part2(): Int { val totalSpace = 70_000_000 val freeRequired = 30_000_000 val minNeeded = freeRequired - (totalSpace - dirs.first().totalSize) val dirSizes = dirs.map { it.totalSize }.sorted() return dirSizes.first { it >= minNeeded } } val day = "07" // Read inputs val testInput = readInput("Day${day}_test") val input = readInput("Day${day}") // Test & run part 1 val testResult = part1(testInput) val testExpected = 95437 check(testResult == testExpected) { "testResult should be $testExpected, but is $testResult" } // Test & run part 2 val testResult2 = part2() val testExpected2 = 24933642 check(testResult2 == testExpected2) { "testResult2 should be $testExpected2, but is $testResult2" } println(part1(input)) println(part2()) }
0
Kotlin
0
1
3b3b2984ab718899fbba591c14c991d76c34f28c
2,972
adventofcode-kotlin
Apache License 2.0
src/main/kotlin/y2023/day09/Day09.kt
TimWestmark
571,510,211
false
{"Kotlin": 97942, "Shell": 1067}
package y2023.day09 fun main() { AoCGenerics.printAndMeasureResults( part1 = { part1() }, part2 = { part2() } ) } fun input(): List<List<Int>> { return AoCGenerics.getInputLines("/y2023/day09/input.txt").map { line -> line.split(" ").map { it.toInt() } } } fun getSubSequence(sequence: List<Int>): MutableList<Int> { val diffs = mutableListOf<Int>() repeat(sequence.size-1) { diffs.add(sequence[it+1]-sequence[it]) } return diffs } fun getSubSequenceReversed(sequence: List<Int>): MutableList<Int> { var diffs = mutableListOf<Int>() repeat(sequence.size-1) { val diff = sequence[sequence.size-it-1] - sequence[sequence.size-it-2] diffs = (listOf(diff) + diffs).toMutableList() } return diffs } fun part1(): Int { val sequences = input() return sequences.sumOf { sequence -> val subsequences = mutableListOf(sequence.toMutableList()) var currentSubsequence = sequence.toMutableList() do { currentSubsequence = getSubSequence(currentSubsequence) subsequences.add(currentSubsequence) } while (currentSubsequence.any { it != 0 }) // start extrapolating val revSequences = subsequences.reversed() // We add the first zero to the last calculated sequence revSequences[0].add(0) revSequences.forEachIndexed{ index, subsequence -> if (index == 0) return@forEachIndexed subsequence.add(subsequence.last() + revSequences[index-1].last()) } return@sumOf revSequences.last().last() } } fun part2(): Int { val sequences = input() return sequences.sumOf { sequence -> val subsequences = mutableListOf(sequence.toMutableList()) var currentSubsequence = sequence.toMutableList() do { currentSubsequence = getSubSequenceReversed(currentSubsequence) subsequences.add(currentSubsequence) } while (currentSubsequence.any { it != 0 }) // start extrapolating val revSequences = subsequences.reversed().toMutableList() // We add the first zero to the last calculated sequence revSequences[0] = (mutableListOf(0) + revSequences[0]).toMutableList() revSequences.forEachIndexed{ index, subsequence -> if (index == 0) return@forEachIndexed revSequences[index] = (listOf(subsequence.first() - revSequences[index-1].first())).toMutableList() } return@sumOf revSequences.last().first() } }
0
Kotlin
0
0
23b3edf887e31bef5eed3f00c1826261b9a4bd30
2,575
AdventOfCode
MIT License
2018/src/five/GuardChallenge.kt
Mattias1
116,139,424
false
null
package five import parse import java.lang.Exception // Day 4 class GuardChallenge { fun longestAsleep(input: List<String>): Int { val sleepIntervals = buildSleepIntervals(input) val biggusDickus: GuardSleepIntervals = sleepIntervals.maxBy { it.totalSleepTime }!! val minute = biggusDickus.safestMinute() return biggusDickus.id * minute } fun popularMinute(input: List<String>): Int { val sleepIntervals = buildSleepIntervals(input) val biggusDickus = sleepIntervals.maxBy { it.safestMinuteValue() }!! val minute = biggusDickus.safestMinute() return biggusDickus.id * minute } private fun buildSleepIntervals(input: List<String>): List<GuardSleepIntervals> { val sleepIntervals = mutableListOf<GuardSleepIntervals>() var currentGuard: Int = -1 var startInterval: Int = -1 for (record in input.sorted()) { val parsed = parse(record, "\\[....-..-.. ..:{}\\] {} {}") val min = parsed[0].toInt() when (parsed[1]) { "Guard" -> { val id = parsed[2].substring(1).toInt() currentGuard = id if (sleepIntervals.none { it.id == id }) { sleepIntervals.add(GuardSleepIntervals(id)) } } "falls" -> { if (currentGuard == -1) { throw Exception("Aaaah!") } startInterval = min } "wakes" -> { if (currentGuard == -1 || startInterval == -1) { throw Exception("Aaaah!") } sleepIntervals.single { it.id == currentGuard }.addInterval(startInterval, min) startInterval = -1 } } } return sleepIntervals } } class GuardSleepIntervals { val id: Int private val intervals: MutableList<Pair<Int, Int>> var totalSleepTime: Int; private set constructor(id: Int) { this.id = id this.intervals = mutableListOf() this.totalSleepTime = 0 } fun addInterval(min: Int, max: Int) { this.intervals.add(Pair(min, max)) this.totalSleepTime += max - min } fun intervalCount(minute: Int): Int = intervals.count { minute in it.first until it.second } fun safestMinute(): Int = (0..59).maxBy { intervalCount(it) }!! fun safestMinuteValue(): Int = (0..59).map { intervalCount(it) }.max()!! }
0
Kotlin
0
0
6bcd889c6652681e243d493363eef1c2e57d35ef
2,718
advent-of-code
MIT License
src/day2/Day02.kt
rafagalan
573,145,902
false
{"Kotlin": 5674}
package day2 import readInput import kotlin.math.abs import kotlin.math.max interface Move { fun toScore(): Int } object Rock : Move { override fun toScore() = 0 } object Paper : Move { override fun toScore() = 1 } object Scissors : Move { override fun toScore() = 2 } fun String.toMove() = when(this) { "A", "X" -> Rock "B", "Y" -> Paper "C", "Z" -> Scissors else -> throw IllegalArgumentException() } fun String.toScore() = when(this) { "A", "X" -> 0 "B", "Y" -> 1 "C", "Z" -> 2 else -> throw IllegalArgumentException() } fun main() { fun matchScore(myMove: Move, opponentMove: Move): Int { // Draw if(opponentMove.toScore() == myMove.toScore()) return 4 + myMove.toScore() // Lost if((myMove.toScore() + 1) % 3 == opponentMove.toScore()) return 1 + myMove.toScore() // Won return 7 + myMove.toScore() } fun part1(input: List<String>) = input.sumOf { match -> match.split(" ").let { matchScore(it[1].toMove(), it[0].toMove()) } } fun part2(input: List<String>) = input.sumOf { match -> match.split(" ").let { when(it[1]) { "X" -> (it[0].toScore() + 2) % 3 + 1 "Y" -> it[0].toScore() + 4 "Z" -> (it[0].toScore() + 4 ) % 3 + 7 else -> throw IllegalArgumentException() } } } val testInput = readInput("day2/Day02_test") check(part1(testInput) == 15) val realInput = readInput("day2/Day02") println(part1(realInput)) val testInput2 = readInput("day2/Day02_test") check(part2(testInput2) == 12) val realInput2 = readInput("day2/Day02") println(part2(realInput2)) }
0
Kotlin
0
0
8e7d3f25fe52a4153479adb56c5924b50f6c0be9
1,758
AdventOfCode2022
Apache License 2.0
src/y2021/Day11.kt
Yg0R2
433,731,745
false
null
package y2021 fun main() { fun part1(input: List<String>): Int { val grid: Array<Array<Int>> = input.toGrid() var flashCounter = 0 for (step in 0 until 100) { grid.increaseEnergyLevel() while (grid.hasChargedOctopus()) { grid.flash() } flashCounter += grid.getFlashedCount() } return flashCounter } fun part2(input: List<String>): Int { val grid: Array<Array<Int>> = input.toGrid() val octopusCount = grid.sumOf { it.size } var stepCounter = 0 while (grid.getFlashedCount() != octopusCount) { grid.increaseEnergyLevel() while (grid.hasChargedOctopus()) { grid.flash() } stepCounter += 1 } return stepCounter } // test if implementation meets criteria from the description, like: val testInput = readInput("Day11_test") check(part1(testInput).also { println(it) } == 1656) check(part2(testInput).also { println(it) } == 195) val input = readInput("Day11") println(part1(input)) println(part2(input)) } private fun Array<Array<Int>>.flash() = this.forEachIndexed { x, row -> row.forEachIndexed { y, _ -> if (this[x][y] > 9) { flash(this, x, y) this[x][y] = 0 } } } private fun flash(grid: Array<Array<Int>>, x: Int, y: Int) { for (x1 in ((x - 1)..(x + 1))) { for (y1 in ((y - 1)..(y + 1))) { if (((x1 == x) && (y1 == y)) || (x1 < 0) || (x1 >= grid.size) || (y1 < 0) || (y1 >= grid[x].size)) { continue } if (grid[x1][y1] != 0) { grid[x1][y1] += 1 } } } } private fun Array<Array<Int>>.getFlashedCount(): Int = this .sumOf { row -> row.count { it == 0 } } private fun Array<Array<Int>>.hasChargedOctopus(): Boolean = this.firstOrNull { row -> row.firstOrNull { octopus -> octopus > 9 } != null } != null private fun Array<Array<Int>>.increaseEnergyLevel() = this.forEachIndexed { x, row -> row.forEachIndexed { y, _ -> this[x][y] += 1 } } private fun List<String>.toGrid() = this .map { it.split("") .toIntList() .toTypedArray() } .toTypedArray() private fun <T> Array<Array<T>>.runOnEach(block: (Int, Int, T) -> Unit) { this.forEachIndexed { x, row -> row.forEachIndexed { y, element -> block(x, y, element) } } }
0
Kotlin
0
0
d88df7529665b65617334d84b87762bd3ead1323
2,629
advent-of-code
Apache License 2.0
2023/src/day06/day06.kt
Bridouille
433,940,923
false
{"Kotlin": 171124, "Go": 37047}
package day06 import GREEN import RESET import printTimeMillis import readInput fun part1(input: List<String>): Int { val times = input.first().split(":")[1].split(" ").map { it.trim().toIntOrNull() }.filterNotNull() val distances = input[1].split(":")[1].split(" ").map { it.trim().toIntOrNull() }.filterNotNull() var sum = 1 for (i in times.indices) { var betterWays = 0 for (t in 1 until times[i]) { if (t * (times[i] - t) > distances[i]) { betterWays += 1 } } sum *= betterWays } return sum } fun part2(input: List<String>): Int { val time = input.first().split(":")[1].replace(" ", "").toLong() val dist = input[1].split(":")[1].replace(" ", "").toLong() var betterWays = 0 for (t in 1 until time) { if (t * (time - t) > dist) { betterWays += 1 } } return betterWays } fun main() { val testInput = readInput("day06_example.txt") printTimeMillis { print("part1 example = $GREEN" + part1(testInput) + RESET) } printTimeMillis { print("part2 example = $GREEN" + part2(testInput) + RESET) } val input = readInput("day06.txt") printTimeMillis { print("part1 input = $GREEN" + part1(input) + RESET) } // 608902 printTimeMillis { print("part2 input = $GREEN" + part2(input) + RESET) } // 46173809 }
0
Kotlin
0
2
8ccdcce24cecca6e1d90c500423607d411c9fee2
1,376
advent-of-code
Apache License 2.0
src/main/kotlin/io/trie/WordSearchInMatrix.kt
jffiorillo
138,075,067
false
{"Kotlin": 434399, "Java": 14529, "Shell": 465}
package io.trie // https://leetcode.com/explore/learn/card/trie/149/practical-application-ii/1056/ class WordSearchInMatrix { fun execute(board: Array<CharArray>, words: Array<String>): List<String> { val root = TrieNodeW.root().also { it.addWords(words) } val result = mutableListOf<String>() val wordsList = words.toList() board.indices.map { i -> if (!result.containsAll(wordsList)) { board[i].indices.map { j -> if (!result.containsAll(wordsList)) { find(board, i, j, root, result) } } } } return result } private fun find(board: Array<CharArray>, i: Int, j: Int, node: TrieNodeW, acc: MutableList<String>): Unit = when { i in board.indices && j in board.first().indices && board[i][j] != '#' && node.children.any { it.value == board[i][j] } -> { val childNode = node.children.first { it.value == board[i][j] } childNode.isWord?.let { word -> childNode.isWord = null acc.add(word) } val temp = board[i][j] board[i][j] = '#' find(board, i + 1, j, childNode, acc) find(board, i - 1, j, childNode, acc) find(board, i, j + 1, childNode, acc) find(board, i, j - 1, childNode, acc) board[i][j] = temp } else -> { } } private data class TrieNodeW( val value: Char?, var isWord: String? = null, val children: MutableList<TrieNodeW> = mutableListOf()) { fun getOrAdd(char: Char) = children.firstOrNull { it.value == char } ?: TrieNodeW(char).also { children.add(it) } fun addWords(words: Array<String>) = words.map { addWord(it) } fun addWord(word: String) = word.fold(this) { acc, char -> acc.getOrAdd(char) }.also { it.isWord = word } companion object { fun root() = TrieNodeW(null) } } } private data class Input(val board: Array<CharArray>, val words: List<String>, val output: Set<String>) fun main() { val wordSearchInMatrix = WordSearchInMatrix() listOf( Input(arrayOf( charArrayOf('o', 'a', 'a', 'n'), charArrayOf('e', 't', 'a', 'e'), charArrayOf('i', 'h', 'k', 'r'), charArrayOf('i', 'f', 'l', 'v') ), listOf("oath", "pea", "eat", "rain"), setOf("eat", "oath")), Input(arrayOf( charArrayOf('o', 'a'), charArrayOf('e', 't') ), listOf("tea", "oat", "ta", "teo", "oate"), setOf("oat", "ta", "teo", "oate")), Input(arrayOf( charArrayOf('b', 'b', 'a', 'a', 'b', 'a'), charArrayOf('b', 'b', 'a', 'b', 'a', 'a'), charArrayOf('b', 'b', 'b', 'b', 'b', 'b'), charArrayOf('a', 'a', 'a', 'b', 'a', 'a'), charArrayOf('a', 'b', 'a', 'a', 'b', 'b') ), listOf("abbbababaa"), setOf("abbbababaa") ) ).mapIndexed { index, (board, words, output) -> val result = wordSearchInMatrix.execute(board, words.toTypedArray()).toSet() val isValid = result == output val message = if (isValid) "Index $index result is valid" else "$index expected $output but got $result " println(message) } }
0
Kotlin
0
0
f093c2c19cd76c85fab87605ae4a3ea157325d43
3,096
coding
MIT License
src/Day02.kt
pavlo-dh
572,882,309
false
{"Kotlin": 39999}
fun main() { fun parseInput(input: List<String>) = input.map { line -> line.split(' ', limit = 2).map(String::first) } fun part1(input: List<String>): Int { fun shapeScore(shape: Char) = when (shape) { 'X' -> 1 'Y' -> 2 else -> 3 } fun roundScore(opponent: Char, player: Char) = when { opponent == player - 23 -> 3 (player == 'X' && opponent == 'C' || player == 'Y' && opponent == 'A' || player == 'Z' && opponent == 'B') -> 6 else -> 0 } val data = parseInput(input) return data.fold(0) { totalScore, (opponent, player) -> totalScore + shapeScore(player) + roundScore(opponent, player) } } fun part2(input: List<String>): Int { fun roundScore(outcome: Char) = when (outcome) { 'X' -> 0 'Y' -> 3 else -> 6 } fun shapeScore(opponent: Char, outcome: Char): Int { val shape = when (outcome) { 'Y' -> opponent 'X' -> when (opponent) { 'A' -> 'C' 'B' -> 'A' else -> 'B' } else -> when (opponent) { 'A' -> 'B' 'B' -> 'C' else -> 'A' } } return when (shape) { 'A' -> 1 'B' -> 2 else -> 3 } } val data = parseInput(input) val result = data.fold(0) { totalScore, (opponent, outcome) -> totalScore + roundScore(outcome) + shapeScore(opponent, outcome) } return result } // test if implementation meets criteria from the description, like: val testInput = readInput("Day02_test") check(part2(testInput) == 12) val input = readInput("Day02") println(part1(input)) println(part2(input)) }
0
Kotlin
0
2
c10b0e1ce2c7c04fbb1ad34cbada104e3b99c992
2,033
aoc-2022-in-kotlin
Apache License 2.0
src/Day07.kt
shoresea
576,381,520
false
{"Kotlin": 29960}
import java.util.* fun main() { fun getDirectories(root: Directory): List<Directory> { val directories = ArrayList<Directory>() val queue = Stack<Directory>() queue.add(root) while (queue.isNotEmpty()) { val current = queue.pop() directories.add(current) current.children.filterIsInstance<Directory>().let { queue.addAll(it) } } return directories } fun generateFilesystem(inputs: List<String>): Directory { val root = Directory("/", ArrayList(), null) var current: FileSystemNode = root for (input in inputs) { if (input.startsWith("$ cd ")) { current = current as Directory val dirName = input.substringAfter("$ cd ").trim() current = when (dirName) { "/" -> { root } ".." -> { current.parent!! } else -> { current.children.firstOrNull { it.name == dirName } ?: Directory(dirName, ArrayList(), current) .also { (current as Directory).children.add(it) } } } } else if (input.startsWith("$ ls")) { continue } else { if (input.startsWith("dir")) { Directory(input.substringAfter("dir ").trim(), ArrayList(), current) .also { (current as Directory).children.add(it) } } else { val props = input.split(" ").map { it.trim() } File(props[1], props[0].toInt()) .also { (current as Directory).children.add(it) } } } } return root } fun part1(inputs: List<String>): Int { val root = generateFilesystem(inputs) return getDirectories(root).map { it.size() }.filter { it <= 100000 }.sum() } fun part2(inputs: List<String>): Int { val root = generateFilesystem(inputs) val availableStorage = 70000000 - root.size() val requiredFreeStorage = 30000000 - availableStorage return getDirectories(root).map{ it.size() }.filter { it >= requiredFreeStorage }.min() } val input = readInput("Day07") part1(input).println() part2(input).println() } abstract class FileSystemNode(open val name: String) { abstract fun size(): Int } data class File(override val name: String, private val size: Int) : FileSystemNode(name) { override fun size(): Int = size } data class Directory(override val name: String, val children: ArrayList<FileSystemNode>, val parent: FileSystemNode?) : FileSystemNode(name) { override fun size(): Int = children.sumOf { it.size() } }
0
Kotlin
0
0
e5d21eac78fcd4f1c469faa2967a4fd9aa197b0e
2,909
AOC2022InKotlin
Apache License 2.0
src/main/kotlin/adventofcode2017/potasz/P07TowerOfDiscs.kt
potasz
113,064,245
false
null
package adventofcode2017.potasz import kotlin.math.abs object P07TowerOfDiscs { data class Disc(val name: String, var weight: Int = 0, var totalWeight: Int = 0, var children: List<Disc> = emptyList(), var parent: Disc? = null) { override fun toString(): String { return "Disc($name, w: $weight, tw: $totalWeight, p: ${parent?.name} -> [${children.map { it.name }.joinToString()}])" } } fun countWeights(node: Disc): Int { node.totalWeight = node.weight + node.children.sumBy { countWeights(it) } return node.totalWeight } fun traverse(node: Disc, level: Int, maxLevel: Int, f: (Disc, Int) -> Unit) { if (level <= maxLevel) { f(node, level) node.children.forEach { traverse(it, level + 1, maxLevel, f) } } } fun findUnbalanced(node: Disc) { val avg = node.children.sumBy { it.totalWeight } / node.children.size.toDouble() val unBalanced = node.children.maxBy { abs(it.totalWeight - avg) } if (unBalanced != null && unBalanced.totalWeight != avg.toInt()) { findUnbalanced(unBalanced) } else { val sibling = node.parent!!.children.find { it.name != node.name } val diff = node.totalWeight - sibling!!.totalWeight println("Unbalanced: $node") println(" Sibling total weight: ${sibling.totalWeight}. New weight: ${node.weight - diff}") } } fun findRoot(lines: List<String>): Disc { val discMap = mutableMapOf<String, Disc>() lines.forEach { line -> val m = pattern.matchEntire(line) ?: throw RuntimeException("Cannot parse line: $line") with (m.destructured) { val name = component1() val weight = component2().toInt() val children = if (component3().isEmpty()) mutableListOf() else component3().split(", ") val disc = discMap.getOrPut(name, { Disc(name) }) disc.weight = weight val childList = children.map { discMap.getOrPut(it, { Disc(it) }).apply { this.parent = disc } } disc.children = childList } } return discMap.values.find { it.parent == null } ?: throw RuntimeException("Cannot find root") } val pattern = """([a-z]+)\s+\((\d+)\)[->\s]*([a-z,\s]*)""".toRegex() @JvmStatic fun main(args: Array<String>) { val sample = readLines("sample07.txt") val input = readLines("input07.txt") listOf(sample, input).forEach { val root = findRoot(it) countWeights(root) traverse(root, 0, 1) { disc, i -> println(" " * i + disc) } findUnbalanced(root) println() } } }
0
Kotlin
0
1
f787d9deb1f313febff158a38466ee7ddcea10ab
2,803
adventofcode2017
Apache License 2.0
kotlin/src/katas/kotlin/leetcode/candy/Candy.kt
dkandalov
2,517,870
false
{"Roff": 9263219, "JavaScript": 1513061, "Kotlin": 836347, "Scala": 475843, "Java": 475579, "Groovy": 414833, "Haskell": 148306, "HTML": 112989, "Ruby": 87169, "Python": 35433, "Rust": 32693, "C": 31069, "Clojure": 23648, "Lua": 19599, "C#": 12576, "q": 11524, "Scheme": 10734, "CSS": 8639, "R": 7235, "Racket": 6875, "C++": 5059, "Swift": 4500, "Elixir": 2877, "SuperCollider": 2822, "CMake": 1967, "Idris": 1741, "CoffeeScript": 1510, "Factor": 1428, "Makefile": 1379, "Gherkin": 221}
package katas.kotlin.leetcode.candy import datsok.shouldEqual import org.junit.jupiter.api.Test // // https://leetcode.com/problems/candy ✅ // // There are N children standing in a line. Each child is assigned a rating value. // You are giving candies to these children subjected to the following requirements: // - Each child must have at least one candy. // - Children with a higher rating get more candies than their neighbors. // What is the minimum candies you must give? // // Example 1: // Input: [1,0,2] // Output: 5 // Explanation: You can allocate to the first, second and third child with 2, 1, 2 candies respectively. // // Example 2: // Input: [1,2,2] // Output: 4 // Explanation: You can allocate to the first, second and third child with 1, 2, 1 candies respectively. // The third child gets 1 candy because it satisfies the above two conditions. // // [0,8,5,3,0] // [1,4,3,2,1] // [1,4,3,2,1] // [0,3,5,8,0] // [1,2,3,4,1] // [0,3,5,8,4,2,1] // [1,2,3,4,3,2,1] // [0,8,5,3,0,8,5,3,0] // [1,4,3,2,1,4,3,2,1] fun candy(ratings: IntArray): Int = candyPerChild_(ratings).sum() private fun candyPerChild(ratings: IntArray): List<Int> = candyPerChild(Children(ratings.mapIndexed { index, rating -> Child(index, rating, 0) })) .map { it.candyAmount } private fun candyPerChild(children: Children): Children { children.forEach { child -> child.candyAmount = 1 } (children + children.reversed()).forEach { child -> children.neighboursOf(child).forEach { neighbour -> if (isUnfairFor(child, neighbour)) child.candyAmount = neighbour.candyAmount + 1 } } return children } private class Children(private val value: List<Child>) : Iterable<Child> by value { fun neighboursOf(child: Child) = listOfNotNull( (child.index - 1).let { if (it >= 0) value[it] else null }, (child.index + 1).let { if (it <= value.lastIndex) value[it] else null } ) } private fun isUnfairFor(child: Child, neighbour: Child) = child.rating > neighbour.rating && child.candyAmount <= neighbour.candyAmount private data class Child(val index: Int, val rating: Int, var candyAmount: Int) fun candyPerChild_(ratings: IntArray): List<Int> { val children = ratings.indices fun neighboursOf(child: Int) = listOf(child - 1, child + 1).filter { it in 0..children.last } val candies = MutableList(ratings.size) { 1 } (children + children.reversed()).forEach { child -> neighboursOf(child).forEach { neighbour -> if (ratings[child] > ratings[neighbour] && candies[child] <= candies[neighbour]) { candies[child] = candies[neighbour] + 1 } } } return candies } class Tests { @Test fun `some examples`() { candyPerChild_(ratings = intArrayOf()) shouldEqual emptyList() candyPerChild_(ratings = intArrayOf(0)) shouldEqual listOf(1) candyPerChild_(ratings = intArrayOf(1)) shouldEqual listOf(1) candyPerChild_(ratings = intArrayOf(1, 0, 2)) shouldEqual listOf(2, 1, 2) candyPerChild_(ratings = intArrayOf(1, 2, 2)) shouldEqual listOf(1, 2, 1) candyPerChild_(ratings = intArrayOf(0, 3, 5, 8, 0)) shouldEqual listOf(1, 2, 3, 4, 1) candyPerChild_(ratings = intArrayOf(0, 8, 5, 3, 0)) shouldEqual listOf(1, 4, 3, 2, 1) candyPerChild_(ratings = intArrayOf(0, 3, 5, 8, 4, 2, 10)) shouldEqual listOf(1, 2, 3, 4, 2, 1, 2) } }
7
Roff
3
5
0f169804fae2984b1a78fc25da2d7157a8c7a7be
3,465
katas
The Unlicense
src/main/kotlin/Day16.kt
pavittr
317,532,861
false
null
import java.io.File import java.nio.charset.Charset fun main() { val testDocs = File("test/day16").readText(Charset.defaultCharset()) val puzzles = File("puzzles/day16").readText(Charset.defaultCharset()) fun part1(input: String) { val ranges = input.split("\n\n")[0].split("\n").flatMap { policyLine -> policyLine.drop(policyLine.indexOf(":") + 1).trim().split(" ").filter { it != "or" }.flatMap { range -> range.split("-").let { thisRange -> thisRange[0].toInt().rangeTo(thisRange[1].toInt()).toList() } } }.distinct() println(ranges) val tickets = input.split("\n\n")[2].split("\n").drop(1) .flatMap { ticketLine -> ticketLine.split(",").map { it.toInt() }.filterNot { ranges.contains(it) } }.sum() println(tickets) } part1(testDocs) part1(puzzles) fun part2(input: String) { val allRangesCombined = input.split("\n\n")[0].split("\n").flatMap { policyLine -> policyLine.drop(policyLine.indexOf(":") + 1).trim().split(" ").filter { it != "or" }.flatMap { range -> range.split("-").let { thisRange -> thisRange[0].toInt().rangeTo(thisRange[1].toInt()).toList() } } }.distinct() val validTickets = input.split("\n\n")[2].split("\n").drop(1) .map { ticketLine -> ticketLine.split(",").map { it.toInt() } } .filter { singleTicket -> singleTicket.all { allRangesCombined.contains(it) } } val rangesByCategory = input.split("\n\n")[0].split("\n").map { policyLine -> policyLine.take(policyLine.indexOf(":")).trim() to policyLine.drop(policyLine.indexOf(":") + 1).trim() .split(" ").filter { it != "or" }.flatMap { range -> range.split("-").let { thisRange -> thisRange[0].toInt().rangeTo(thisRange[1].toInt()).toList() } } }.toMap() // the most obvious way to handle this is to search for elements with a single member, and add those to a mutable map, and then remove those elements from the next search and iterate until the map is full var fieldGroupedByRowId = validTickets.flatMap { it.mapIndexed { index, i -> Pair(index, i) } }.groupBy({ it.first }, { it.second }) .mapValues { valuesForField -> rangesByCategory.filter { catergoryRange -> catergoryRange.value.containsAll(valuesForField.value) }.map { it.key }.toMutableList() }.toMutableMap() fieldGroupedByRowId.forEach{ println(it) } var listOfFields = mutableMapOf<Int, String>() while (fieldGroupedByRowId.isNotEmpty()) { val singlefields = fieldGroupedByRowId.filter { it.value.size == 1 }.mapValues { it.value.first() } listOfFields.putAll(singlefields) singlefields.forEach { fieldGroupedByRowId.remove(it.key) } fieldGroupedByRowId.forEach { it.value.removeAll(singlefields.values) } } println("List of fields: $listOfFields") val departureIndexes = listOfFields.filter { it.value.contains("departure") } println(departureIndexes) val myTicket = input.split("\n\n")[1].split("\n").drop(1).first().split(",") .filterIndexed { index, s -> departureIndexes.containsKey(index) }.map { it.toLong() } .reduceOrNull { acc, s -> acc * s } println(myTicket) } part2(testDocs) part2( "class: 0-1 or 4-19\n" + "row: 0-5 or 8-19\n" + "seat: 0-13 or 16-19\n" + "\n" + "your ticket:\n" + "11,12,13\n" + "\n" + "nearby tickets:\n" + "3,9,18\n" + "15,1,5\n" + "5,14,9" ) part2(puzzles) }
0
Kotlin
0
0
3d8c83a7fa8f5a8d0f129c20038e80a829ed7d04
3,964
aoc2020
Apache License 2.0
src/Day04.kt
rickbijkerk
572,911,701
false
{"Kotlin": 31571}
fun main() { fun part1(input: List<String>): Int { val elves = input.filter { line -> val elfOne = line.split(",")[0].let { it.split("-")[0].toInt() to it.split("-")[1].toInt() } val elfTwo = line.split(",")[1].let { it.split("-")[0].toInt() to it.split("-")[1].toInt() } elfOne.first >= elfTwo.first && elfOne.second <= elfTwo.second || elfTwo.first >= elfOne.first && elfTwo.second <= elfOne.second } return elves.size } fun part2(input: List<String>): Int { val elves = input.filter { line -> val elfOne = line.split(",")[0].let { it.split("-")[0].toInt() to it.split("-")[1].toInt() } val elfTwo = line.split(",")[1].let { it.split("-")[0].toInt() to it.split("-")[1].toInt() } elfOne.first in elfTwo.first..elfTwo.second|| elfOne.second in elfTwo.first..elfTwo.second|| elfTwo.first in elfOne.first..elfOne.second|| elfTwo.second in elfOne.first..elfOne.second } return elves.size } val testInput = readInput("day04_test") // test part1 val resultPart1 = part1(testInput) val expectedPart1 = 2 //TODO Change me println("Part1\nresult: $resultPart1") println("expected:$expectedPart1 \n") check(resultPart1 == expectedPart1) //Check results part1 val input = readInput("day04") println("Part1 ${part1(input)}\n\n") // test part2 val resultPart2 = part2(testInput) val expectedPart2 = 4 //TODO Change me println("Part2\nresult: $resultPart2") println("expected:$expectedPart2 \n") check(resultPart2 == expectedPart2) //Check results part2 println("Part2 ${part2(input)}") }
0
Kotlin
0
0
817a6348486c8865dbe2f1acf5e87e9403ef42fe
1,732
aoc-2022
Apache License 2.0
src/Day02.kt
korsik
573,366,257
false
{"Kotlin": 5186}
fun main() { fun part1(input: List<String>): Int { fun calculateOutcome(line: String): Int { return when(line) { "A Z", "B X", "C Y" -> 0 "A X", "B Y", "C Z" -> 3 "C X", "A Y", "B Z" -> 6 else -> error("Wrong Input!") } } fun calculateSymbolScore(shape: Char): Int { return when(shape) { 'A', 'X' -> 1 'B', 'Y' -> 2 'C', 'Z' -> 3 else -> error("Wrong Input!") } } return input.sumOf { calculateOutcome(it) + calculateSymbolScore(it[2]) } } fun part2(input: List<String>): Int { fun calculateOutcome(outcome: Char): Int { return when(outcome) { 'X' -> 0 'Y' -> 3 'Z' -> 6 else -> error("Wrong Input!") } } // Loses to Wins to // A -> Rock Paper(B) Scissors(C) // B -> Paper Scissors(C) Rock(A) // C -> Scissor Rock(A) Paper(B) // X -> Lose // Y -> Draw // Z -> Win fun calculateSymbolScore(line: String): Int { return when(line) { "A Y", "B X", "C Z" -> 1 "A Z", "B Y", "C X" -> 2 "A X", "B Z", "C Y" -> 3 else -> error("Wrong Input!") } } return input.sumOf { calculateOutcome(it[2]) + calculateSymbolScore(it) } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day02_default") println(part2(testInput)) // check(part1(testInput) == 1) val input = readInput("Day02_test") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
1a576c51fc8233b1a2d64e44e9301c7f4f2b6b01
1,884
aoc-2022-in-kotlin
Apache License 2.0
2022/src/main/kotlin/com/github/akowal/aoc/Day11.kt
akowal
573,170,341
false
{"Kotlin": 36572}
package com.github.akowal.aoc import com.github.akowal.aoc.Day11.Op class Day11 { fun solvePart1(): Long { return monkeyBusiness(20, 3) } fun solvePart2(): Long { return monkeyBusiness(10000, 1) } private fun monkeyBusiness(rounds: Int, relief: Long): Long { val monkeys = load() val divCommonMul = monkeys.fold(1L) { c, m -> c * m.div } repeat(rounds) { monkeys.forEach { m -> while (m.items.isNotEmpty()) { m.inspected++ val item = m.items.removeFirst() val worryLevel = (m.op.calc(item) / relief) % divCommonMul if (worryLevel % m.div == 0L) { monkeys[m.throwIfTrue].items.add(worryLevel) } else { monkeys[m.throwIfFalse].items.add(worryLevel) } } } } return monkeys.map { it.inspected }.sortedDescending().take(2).reduce(Long::times) } private fun load() = sequence { inputScanner("day11").let { input -> while (input.hasNextLine()) { if (input.nextLine().isEmpty()) { continue } val startingItems = input.nextLine().removePrefix(" Starting items: ").split(", ").map { it.toLong() } val op = input.nextLine().removePrefix(" Operation: new = ").let { when { it == "old * old" -> Op { old -> old * old } it.startsWith("old + ") -> { val x = it.substringAfterLast(' ').toLong() Op { old -> Math.addExact(old, x) } } it.startsWith("old * ") -> { val x = it.substringAfterLast(' ').toLong() Op { old -> Math.multiplyExact(old, x) } } else -> error("xoxoxo") } } val div = input.nextLine().removePrefix(" Test: divisible by ").toLong() val throwIfTrue = input.nextLine().removePrefix(" If true: throw to monkey ").toInt() val throwIfFalse = input.nextLine().removePrefix(" If false: throw to monkey ").toInt() yield(Monkey(div, op, throwIfTrue, throwIfFalse, startingItems)) } } }.toList() private fun interface Op { fun calc(old: Long): Long } private class Monkey( val div: Long, val op: Op, val throwIfTrue: Int, val throwIfFalse: Int, items: List<Long>, ) { var inspected: Long = 0 val items: MutableList<Long> = items.toMutableList() } } fun main() { val solution = Day11() println(solution.solvePart1()) println(solution.solvePart2()) }
0
Kotlin
0
0
02e52625c1c8bd00f8251eb9427828fb5c439fb5
2,969
advent-of-kode
Creative Commons Zero v1.0 Universal
src/Day02.kt
SnyderConsulting
573,040,913
false
{"Kotlin": 46459}
sealed class Choice { abstract val points: Int companion object { fun parseChoice(value: String): Choice { return when (value) { "A", "X" -> Rock "B", "Y" -> Paper "C", "Z" -> Scissors else -> Rock } } fun calculateChoiceForResult(opponent: Choice, desiredResult: Result): Choice { return when(desiredResult) { Win -> { when(opponent) { Paper -> Scissors Rock -> Paper Scissors -> Rock } } Loss -> { when(opponent) { Paper -> Rock Rock -> Scissors Scissors -> Paper } } Draw -> opponent } } } } object Rock : Choice() { override val points: Int get() = 1 } object Paper : Choice() { override val points: Int get() = 2 } object Scissors : Choice() { override val points: Int get() = 3 } sealed class Result { abstract val points: Int } object Loss : Result() { override val points: Int get() = 0 } object Draw : Result() { override val points: Int get() = 3 } object Win : Result() { override val points: Int get() = 6 } data class Round(val opponent: Choice, val instruction: Choice) { fun getResult(): Result { return when { opponent == instruction -> Draw opponent == Rock && instruction == Scissors -> Loss opponent == Paper && instruction == Rock -> Loss opponent == Scissors && instruction == Paper -> Loss else -> Win } } companion object { fun parseResult(value: String): Result { return when(value) { "X" -> Loss "Y" -> Draw "Z" -> Win else -> Loss } } } } fun main() { fun part1(input: List<String>): Int { /** * A = Rock * B = Paper * C = Scissors * X = Rock (1) * Y = Paper (2) * Z = Scissors (3) * Loss = 0 * Draw = 3 * Win = 6 */ val rounds = input.map { line -> line.split(" ").let { (opponent, instruction) -> Round( opponent = Choice.parseChoice(opponent), instruction = Choice.parseChoice(instruction) ) } } return rounds.sumOf { round -> round.getResult().points + round.instruction.points } } fun part2(input: List<String>): Int { /** * A = Rock * B = Paper * C = Scissors * X = Loss * Y = Draw * Z = Win * Loss = 0 * Draw = 3 * Win = 6 */ val rounds = input.map { line -> line.split(" ").let { (opponent, desiredResult) -> Round( Choice.parseChoice(opponent), Choice.calculateChoiceForResult( opponent = Choice.parseChoice(opponent), desiredResult = Round.parseResult(desiredResult) ) ) } } return rounds.sumOf { round -> round.getResult().points + round.instruction.points } } val input = readInput("Day02") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
ee8806b1b4916fe0b3d576b37269c7e76712a921
3,699
Advent-Of-Code-2022
Apache License 2.0
src/Day13.kt
ricardorlg-yml
573,098,872
false
{"Kotlin": 38331}
private sealed interface Packet : Comparable<Packet> { fun add(packet: Packet) { throw UnsupportedOperationException() } companion object { fun parse(input: String): Packet { val stack = ArrayDeque<Packet>() var current: Packet? = null var continueOnIndex = -1 input.forEachIndexed { index, c -> if (index <= continueOnIndex) { continueOnIndex = -1 return@forEachIndexed } when (c) { '[' -> { val newPacket = ListPacket() stack.addLast(newPacket) current?.add(newPacket) current = newPacket } ']' -> { if (stack.size > 1) { stack.removeLast() current = stack.last() } } ',' -> return@forEachIndexed else -> { val n = input.substring(index) .takeWhile { it.isDigit() } //a packet number can be more than one digit continueOnIndex = index + n.length - 1 //we need to skip the number we just read, don't ignore last char because it could be an ']' current?.add(IntPacket(n.toInt())) } } } return stack.first()//the first packet is the root } } } private data class IntPacket(val value: Int) : Packet { fun toListPacket() = ListPacket(mutableListOf(this)) override fun compareTo(other: Packet) = when (other) { is IntPacket -> value compareTo other.value is ListPacket -> this.toListPacket() compareTo other } } private data class ListPacket(private val packets: MutableList<Packet> = mutableListOf()) : Packet { override fun add(packet: Packet) { packets.add(packet) } override fun compareTo(other: Packet) = when (other) { is IntPacket -> this compareTo other.toListPacket() is ListPacket -> packets .zip(other.packets, Packet::compareTo) .firstOrNull { it != 0 } ?: packets.size.compareTo(other.packets.size) } } class Day13Solver(private val data: List<String>) { private fun processData() = data .asSequence() .filter { it.isNotBlank() } .map { Packet.parse(it) } fun solvePart1(): Int { val packets = processData() return packets .chunked(2) .withIndex() .fold(0) { acc, (index, packets) -> val (leftPacket, rightPacket) = packets (acc + index + 1).takeIf { leftPacket < rightPacket } ?: acc } } fun solvePart2(): Int { val packets = processData() val firstDividerPacket = Packet.parse("[[2]]") val secondDividerPacket = Packet.parse("[[6]]") return (packets + firstDividerPacket + secondDividerPacket) .sorted() .withIndex() .fold(1) { acc, (index, packet) -> when (packet) { firstDividerPacket, secondDividerPacket -> acc * (index + 1) else -> acc } } } } fun main() { // val data = readInput("Day13_test") val data = readInput("Day13") val solver = Day13Solver(data) // check(solver.solvePart1() == 13) // check(solver.solvePart2() == 140) println(solver.solvePart1()) println(solver.solvePart2()) }
0
Kotlin
0
0
d7cd903485f41fe8c7023c015e4e606af9e10315
3,704
advent_code_2022
Apache License 2.0
src/main/kotlin/day5.kt
noamfree
433,962,392
false
{"Kotlin": 93533}
import kotlin.math.abs import kotlin.math.max private val testInput1 = """ 0,9 -> 5,9 8,0 -> 0,8 9,4 -> 3,4 2,2 -> 2,1 7,0 -> 7,4 6,4 -> 2,0 0,9 -> 2,9 3,4 -> 1,4 0,0 -> 8,8 5,5 -> 8,2 """.trimIndent() private fun tests() { val testLines = parseInput(testInput1) assertEquals(part1(testLines), 5) assertEquals(part2(testLines), 12) } fun main() { tests() // val input = testInput1 val input = readInputFile("input5") val lines = parseInput(input) println("part 1:") println(part1(lines)) // print the map as in the example // (0..height).forEach { r -> // (0..width).forEach { c -> // val size = sensors[r to c]!!.size // print(if (size == 0) '.' else size.toString()) // } // print("\n") // } println("part 2:") println(countPointsWithMoreThenOneLine(lines)) println("day5") } private fun part1(lines: List<Line>): Int { val axisAlignedLines = lines.filter { it.x1 == it.x2 || it.y1 == it.y2 } return countPointsWithMoreThenOneLine(axisAlignedLines) } private fun part2(lines: List<Line>): Int = countPointsWithMoreThenOneLine(lines) private fun countPointsWithMoreThenOneLine(lines: List<Line>): Int { val sensors: Map<Pair<Int, Int>, MutableList<Line>> = createEmptySensorMap(lines) lines.forEach { line -> line.points().forEach { point -> sensors[point]!!.add(line) } } return sensors.count { it.value.size > 1 } } private fun createEmptySensorMap(lines: List<Line>): Map<Pair<Int, Int>, MutableList<Line>> { val width = lines.maxOf { max(it.x1, it.x2) } val height = lines.maxOf { max(it.y1, it.y2) } return mutableMapOf<Pair<Int, Int>, MutableList<Line>>().apply { (0..height).forEach { r -> (0..width).forEach { c -> put(r to c, mutableListOf()) } } } } private fun Line.points(): List<Pair<Int, Int>> { return if (x1 == x2) range(y1, y2).map { it to x1 } else if (y1 == y2) range(x1, x2).map { y1 to it } else range(y1, y2).zip(range(x1, x2)) //.also { println(it) } } private fun range(a: Int, b: Int) = if (a < b) a..b else a downTo b private fun parseInput(string: String): List<Line> { return string.lines().map { val (x1, y1, x2, y2) = Regex("(\\d+),(\\d+) -> (\\d+),(\\d+)").find(it)!!.destructured Line(x1.toInt(), y1.toInt(), x2.toInt(), y2.toInt()) } } private data class Line( val x1: Int, val y1: Int, val x2: Int, val y2: Int ) { init { require( x1 == x2 || y1 == y2 || abs(x1 - x2) == abs(y1 - y2) ) } override fun toString(): String = "$x1,$y1 -> $x2,$y2" }
0
Kotlin
0
0
566cbb2ef2caaf77c349822f42153badc36565b7
2,784
AOC-2021
MIT License
src/main/kotlin/aoc/Day11.kt
dtsaryov
573,392,550
false
{"Kotlin": 28947}
package aoc import java.math.BigInteger import java.util.* private val operationRegex = Regex("\\s*Operation: new = (old|\\d+) ([+\\-*/]) (old|\\d+)") private const val ROUNDS = 10_000 fun main() { val input = readInput("day11.txt") ?: return val monkeys = parseMonkeys(input) println(sumOfTwoMostActiveMonkeyInspections(monkeys)) } fun sumOfTwoMostActiveMonkeyInspections(monkeys: List<Monkey>): Long { val lcm = monkeys.map { it.divider }.reduce(BigInteger::times) val dividers = monkeys.map { it.divider } for (round in 0 until ROUNDS) { for ((i, monkey) in monkeys.withIndex()) { while (monkey.items.isNotEmpty()) { val item = monkey.inspect()?.mod(lcm) ?: continue if (item.mod(dividers[i]) == BigInteger.ZERO) { monkeys[monkey.trueMonkey].take(item) } else { monkeys[monkey.falseMonkey].take(item) } } } } return monkeys.map { it.inspections } .sortedByDescending { it } .subList(0, 2) .reduce(Long::times) } fun parseMonkeys(input: List<String>): List<Monkey> { val monkeys = mutableListOf<Monkey>() for (i in input.indices) { val line = input[i] if (line.startsWith("Monkey ")) { monkeys += parseMonkey(input.subList(i + 1, i + 6)) } } return monkeys } fun parseMonkey(lines: List<String>): Monkey { val items = parseItems(lines[0]) val operation = parseOperation(lines[1]) val divider = lines[2].split(" ").last().toBigInteger() val trueMonkey = lines[3].split(" ").last().toInt() val falseMonkey = lines[4].split(" ").last().toInt() return Monkey(items, operation, divider, trueMonkey, falseMonkey) } private fun parseItems(items: String): Queue<BigInteger> { return items.substringAfter(":") .trim() .split(", ") .map { it.toBigInteger() } .let { LinkedList(it) } } private fun parseOperation(operation: String): (BigInteger) -> BigInteger { val (_, a, op, b) = operationRegex.matchEntire(operation) ?.groupValues ?: return { it } val operator = parseOp(op) val numA = a.toBigIntegerOrNull() val numB = b.toBigIntegerOrNull() return when { a == "old" && b == "old" -> { v -> operator.invoke(v, v) } a == "old" -> { v -> operator.invoke(v, numB!!) } b == "old" -> { v -> operator.invoke(numA!!, v) } else -> error("impossible branch") } } private fun parseOp(op: String): (BigInteger, BigInteger) -> BigInteger { return when (op) { "+" -> BigInteger::plus "-" -> BigInteger::minus "*" -> BigInteger::times "/" -> BigInteger::div else -> error("wrong operator") } } data class Monkey( val items: Queue<BigInteger>, val operation: (BigInteger) -> BigInteger, val divider: BigInteger, val trueMonkey: Int, val falseMonkey: Int ) { var inspections: Long = 0 private set fun inspect(): BigInteger? { return if (items.isEmpty()) { null } else { inspections++ operation.invoke(items.poll()) } } fun take(item: BigInteger) { items.add(item) } }
0
Kotlin
0
0
549f255f18b35e5f52ebcd030476993e31185ad3
3,306
aoc-2022
Apache License 2.0
src/main/kotlin/com/github/ferinagy/adventOfCode/aoc2023/2023-03.kt
ferinagy
432,170,488
false
{"Kotlin": 787586}
package com.github.ferinagy.adventOfCode.aoc2023 import com.github.ferinagy.adventOfCode.Coord2D import com.github.ferinagy.adventOfCode.println import com.github.ferinagy.adventOfCode.readInputLines fun main() { val input = readInputLines(2023, "03-input") val test1 = readInputLines(2023, "03-test1") println("Part1:") part1(test1).println() part1(input).println() println() println("Part2:") part2(test1).println() part2(input).println() } private fun part1(input: List<String>): Int { val numberRegex = """\d+""".toRegex() val symbolRegex = """[^\d.]""".toRegex() val symbols = mutableSetOf<Coord2D>() val numbers = mutableSetOf<Pair<Int, IntRange>>() input.forEachIndexed { index, line -> numberRegex.findAll(line).forEach { numbers += index to it.range } symbolRegex.findAll(line).forEach { symbols += Coord2D(it.range.first, index) } } val parts = numbers.filter { (row, range) -> symbols.any { it.x in range.first - 1 .. range.last + 1 && it.y in row - 1 .. row + 1 } } return parts.sumOf { it.toInt(input) } } private fun part2(input: List<String>): Int { val numberRegex = """\d+""".toRegex() val gearRegex = """\*""".toRegex() val numbers = mutableSetOf<Pair<Int, IntRange>>() val gears = mutableSetOf<Coord2D>() input.forEachIndexed { index, line -> numberRegex.findAll(line).forEach { numbers += index to it.range } gearRegex.findAll(line).forEach { gears += Coord2D(it.range.first, index) } } return gears.sumOf { gear -> val adjacent = numbers.filter { (row, range) -> gear.x in range.first - 1 .. range.last + 1 && gear.y in row - 1 .. row + 1 } if (adjacent.size == 2) adjacent[0].toInt(input) * adjacent[1].toInt(input) else 0 } } private fun Pair<Int, IntRange>.toInt(lines: List<String>): Int = lines[first].substring(second).toInt()
0
Kotlin
0
1
f4890c25841c78784b308db0c814d88cf2de384b
2,031
advent-of-code
MIT License
src/main/kotlin/days/Day9.kt
butnotstupid
571,247,661
false
{"Kotlin": 90768}
package days import kotlin.math.sign class Day9 : Day(9) { override fun partOne(): Any = calculateNextKnotVisits(inputList.map { it.split(" ") } .map { Configuration.fromCode(it[0]) to it[1].toInt() }).toSet().size override fun partTwo(): Any = generateSequence(inputList.map { it.split(" ") }.map { Configuration.fromCode(it[0]) to it[1].toInt() }) { generateNextKnotMoves(it) }.take(9).last().let { calculateNextKnotVisits(it) }.toSet().size private fun move(rope: Rope, dir: Configuration): Rope { val (newR, newC) = dir.let { rope.conf.dr + it.dr to rope.conf.dc + it.dc } return if (newR in -1..1 && newC in -1..1) { rope.copy(conf = Configuration.values().find { it.dr == newR && it.dc == newC }!!) } else { Rope( pos = rope.pos.first + newR.sign to rope.pos.second + newC.sign, conf = Configuration.fromDelta(newR - newR.sign to newC - newC.sign) ) } } private fun calculateNextKnotVisits(input: List<Pair<Configuration, Int>>): Sequence<Pair<Int, Int>> = sequence { var state = Rope(0 to 0, Configuration.CENTER) yield(state) input.forEach { (command, steps) -> repeat(steps) { state = move(state, command) yield(state) } } }.map { it.pos } private fun generateNextKnotMoves(input: List<Pair<Configuration, Int>>): List<Pair<Configuration, Int>> { return sequence { var state = Rope(0 to 0, Configuration.CENTER) input.forEach { (command, steps) -> repeat(steps) { val newState = move(state, command) val nextConf = Configuration.fromDelta(newState.pos.first - state.pos.first to newState.pos.second - state.pos.second) yield(nextConf to 1) state = newState } } }.toList() } /** * Tail is in the middle at position `pos`, head is in `conf` configuration * UL U UR * L C R * DL D DR */ data class Rope(val pos: Pair<Int, Int>, val conf: Configuration) enum class Configuration(val dr: Int, val dc: Int) { UP_LEFT(-1,-1), UP(-1,0), UP_RIGHT(-1, 1), LEFT(0, -1), CENTER(0,0), RIGHT(0, 1), DOWN_RIGHT(1,1), DOWN(1, 0), DOWN_LEFT(1, -1); companion object { fun fromDelta(delta: Pair<Int, Int>) = values().find { it.dr == delta.first && it.dc == delta.second }!! fun fromCode(code: String) = when (code) { "R" -> RIGHT "L" -> LEFT "U" -> UP "D" -> DOWN else -> throw IllegalArgumentException("Unknown move code $code") } } } }
0
Kotlin
0
0
4760289e11d322b341141c1cde34cfbc7d0ed59b
2,892
aoc-2022
Creative Commons Zero v1.0 Universal
kotlin/src/main/kotlin/year2023/Day11.kt
adrisalas
725,641,735
false
{"Kotlin": 130217, "Python": 1548}
package year2023 import kotlin.math.abs fun main() { val input = readInput("Day11") Day11.part1(input).println() Day11.part2(input).println() } object Day11 { fun part1(input: List<String>): Long { val expandedGalaxy = expandGalaxy(input) val galaxies = findGalaxies(expandedGalaxy) val distances = mutableListOf<Long>() for (i in galaxies.indices) { for (j in i + 1 until galaxies.size) { distances.add(galaxies[i].distanceTo(galaxies[j])) } } return distances.sum() } data class Galaxy(val row: Long, val column: Long) { fun distanceTo(other: Galaxy): Long { return abs(other.row - this.row) + abs(other.column - this.column) } } private fun findGalaxies(expandedGalaxy: List<String>): List<Galaxy> { val galaxies = mutableListOf<Galaxy>() var millionsOfRows = 0L expandedGalaxy.forEachIndexed { row, line -> if (expandedGalaxy[row].all { it == ' ' }) { millionsOfRows++ } var millionsOfColumns = 0L line.forEachIndexed { column, value -> if (expandedGalaxy.all { it[column] == ' ' }) { millionsOfColumns++ } if (value == '#') { galaxies.add( Galaxy( row.toLong() + (millionsOfRows * 999_999L), column.toLong() + (millionsOfColumns * 999_999L) ) ) } } } return galaxies } fun expandGalaxy(input: List<String>): List<String> { val expandedGalaxy = mutableListOf<String>() for (row in input) { expandedGalaxy.add(row) val emptyRow = row.all { it == '.' } if (emptyRow) { expandedGalaxy.add(row) } } for (column in (expandedGalaxy[0].length - 1) downTo 0) { val emptyColumn = expandedGalaxy.all { it[column] == '.' } if (!emptyColumn) { continue } for (row in 0 until expandedGalaxy.size) { val sb = StringBuilder(expandedGalaxy[row]) sb.insert(column, '.') expandedGalaxy[row] = sb.toString() } } return expandedGalaxy } fun part2(input: List<String>): Long { val expandedGalaxy = expandGalaxyLikeReallyReallyBig(input) val galaxies = findGalaxies(expandedGalaxy) val distances = mutableListOf<Long>() for (i in galaxies.indices) { for (j in i + 1 until galaxies.size) { distances.add(galaxies[i].distanceTo(galaxies[j])) } } return distances.sum() } // '.' <-- One distance // ' ' <-- One million distance fun expandGalaxyLikeReallyReallyBig(input: List<String>): List<String> { val expandedGalaxy = mutableListOf<String>() for (row in input) { val emptyRow = row.all { it == '.' } if (emptyRow) { expandedGalaxy.add(row.replace(".", " ")) } else { expandedGalaxy.add(row) } } for (column in (expandedGalaxy[0].length - 1) downTo 0) { val emptyColumn = expandedGalaxy.all { it[column] == '.' || it[column] == ' ' } if (!emptyColumn) { continue } for (row in 0 until expandedGalaxy.size) { val sb = StringBuilder(expandedGalaxy[row]) sb.replace(column, column + 1, " ") expandedGalaxy[row] = sb.toString() } } return expandedGalaxy } }
0
Kotlin
0
2
6733e3a270781ad0d0c383f7996be9f027c56c0e
3,858
advent-of-code
MIT License
src/Day02.kt
MisterTeatime
560,956,854
false
{"Kotlin": 37980}
fun main() { /* A, X = Rock B, Y = Paper C, Z = Scissors */ fun part1(input: List<String>): Int { val duelPoints = mapOf( "AX" to 3 + 1, //Rock, Rock, Draw "AY" to 6 + 2, //Rock, Paper, Win "AZ" to 0 + 3, //Rock, Scissors, Loss "BX" to 0 + 1, //Paper, Rock, Loss "BY" to 3 + 2, //Paper, Paper, Draw "BZ" to 6 + 3, //Paper, Scissors, Win "CX" to 6 + 1, //Scissors, Rock, Win "CY" to 0 + 2, //Scissors, Paper, Loss "CZ" to 3 + 3 //Scissors, Scissors, Draw ) return input .map { it.split(" ") } .sumOf { (elf, me) -> duelPoints[elf + me]!! } } fun part2(input: List<String>): Int { val duelPoints = mapOf( "AX" to 0 + 3, //Rock, Loss, Scissors "AY" to 3 + 1, //Rock, Draw, Rock "AZ" to 6 + 2, //Rock, Win, Paper "BX" to 0 + 1, //Paper, Loss, Rock "BY" to 3 + 2, //Paper, Draw, Paper "BZ" to 6 + 3, //Paper, Win, Scissors "CX" to 0 + 2, //Scissors, Loss, Paper "CY" to 3 + 3, //Scissors, Draw, Scissors "CZ" to 6 + 1 //Scissors, Win, Rock ) return input .map { it.split(" ") } .sumOf { (elf, outcome) -> duelPoints[elf + outcome]!! } } // 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
8ba0c36992921e1623d9b2ed3585c8eb8d88718e
1,672
AoC2022
Apache License 2.0
src/Day18.kt
l8nite
573,298,097
false
{"Kotlin": 105683}
class Droplet(val points: Set<Triple<Int,Int,Int>>) { val minZ = points.minOf { it.third } val maxZ = points.maxOf { it.third } val minY = points.minOf { it.second } val maxY = points.maxOf { it.second } val minX = points.minOf { it.first } val maxX = points.maxOf { it.first } val wormholes = mutableSetOf<Triple<Int,Int,Int>>() val holes = mutableSetOf<Triple<Int,Int,Int>>() init { for (z in minZ..maxZ) { for (y in minY..maxY) { for (x in minX..maxX) { val point = Triple(x, y, z) if (!points.contains(point)) { if (isEdge(point)) { wormholes.add(point) } else { holes.add(point) } } } } } } fun scanWormholes() { for (wormhole in wormholes.toList()) { explore(wormhole) } } fun explore(point: Triple<Int, Int, Int>) { val neighbors = neighbors(point) val holesConnected = neighbors.filter { !points.contains(it) && !wormholes.contains(it) }.toSet() wormholes.addAll(holesConnected) holes.removeAll(holesConnected) for (neighbor in holesConnected) { explore(neighbor) } } fun neighbors(point: Triple<Int, Int, Int>, filterEnclosed: Boolean = true): Set<Triple<Int,Int,Int>> { val (x,y,z) = point val neighbors = setOf( Triple(x - 1, y, z), Triple(x + 1, y, z), Triple(x, y - 1, z), Triple(x, y + 1, z), Triple(x, y, z - 1), Triple(x, y, z + 1), ) if (filterEnclosed) { return neighbors.filter { encloses(it) }.toSet() } return neighbors } fun encloses(point: Triple<Int,Int,Int>): Boolean { return point.first in minX..maxX && point.second in minY..maxY && point.third in minZ..maxZ } fun isEdge(point: Triple<Int,Int,Int>): Boolean { return point.first == minX || point.first == maxX || point.second == minY || point.second == maxY || point.third == minZ || point.third == maxZ } companion object { fun from(input: List<String>): Droplet { val points = mutableSetOf<Triple<Int, Int, Int>>() input.forEach { line -> val (x, y, z) = line.split(",").map(String::toInt) val point = Triple(x, y, z) points.add(point) } return Droplet(points) } } } fun main() { fun part1(input: List<String>): Int { val droplet = Droplet.from(input) val surface = droplet.points.sumOf { droplet.neighbors(it, false).filter { n -> !droplet.points.contains(n) }.size } return surface } fun part2(input: List<String>): Int { val droplet = Droplet.from(input) droplet.scanWormholes() val surfaceArea = droplet.points.sumOf { droplet.neighbors(it, false).filter { n -> !droplet.points.contains(n) }.size } val interiors = droplet.holes.sumOf { droplet.neighbors(it).filter { n -> droplet.points.contains(n) }.size } return surfaceArea - interiors } // test if implementation meets criteria from the description, like: val testInput = readInput("Day18_test") check(part1(testInput) == 64) println("Part 1 checked out ok!") check(part2(testInput) == 58) println("Part 2 checked out ok!") val input = readInput("Day18") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
f74331778fdd5a563ee43cf7fff042e69de72272
3,801
advent-of-code-2022
Apache License 2.0
src/main/kotlin/org/hydev/lcci/lcci_05.kt
VergeDX
334,298,924
false
null
import kotlin.math.max // https://leetcode-cn.com/problems/insert-into-bits-lcci/ fun insertBits(N: Int, M: Int, i: Int, j: Int): Int { // https://stackoverflow.com/questions/50173028/how-to-get-binary-representation-of-int-in-kotlin var rawNReversed = Integer.toBinaryString(N).reversed() val insertM = Integer.toBinaryString(M) if (rawNReversed.length <= insertM.length) return M val replaceLength = j - i + 1 // Maybe we should insert 0 to last. @see println(insertBits(1143207437, 1017033, 11, 31)). // Extreme case, j >= rawNReversed.length, means should += "0". if (j >= rawNReversed.length) rawNReversed += "0".repeat(j - rawNReversed.length + 1) val afterCleaned = rawNReversed.replaceRange(IntRange(i, j), "0".repeat(replaceLength)) val newLength = insertM.length val newRange = IntRange(i, i + newLength - 1) val afterReplaced = afterCleaned.replaceRange(newRange, insertM.reversed()) val resultString = afterReplaced.reversed() return Integer.parseInt(resultString, 2) } // https://leetcode-cn.com/problems/reverse-bits-lcci/ fun reverseBits(num: Int): Int { var binary = Integer.toBinaryString(num) while (binary.length < 32) binary += "0" val result = ArrayList<Int>() for (index in binary.indices) { val check = binary.replaceRange(IntRange(index, index), "1") check.split("0").map { it.length }.max()?.let { result += it } } return result.max()!! } // https://leetcode-cn.com/problems/closed-number-lcci/ fun findClosedNumbers(num: Int): IntArray { TODO() } // https://leetcode-cn.com/problems/convert-integer-lcci/ fun convertInteger(A: Int, B: Int): Int { var aBinary = Integer.toBinaryString(A) var bBinary = Integer.toBinaryString(B) // Fill width, maxLength can also be constant 32. val maxLength = max(aBinary.length, bBinary.length) while (aBinary.length < maxLength) aBinary = "0$aBinary" while (bBinary.length < maxLength) bBinary = "0$bBinary" var result = 0 for ((aChar, bChar) in aBinary zip bBinary) if (aChar != bChar) result++ return result } // https://leetcode-cn.com/problems/exchange-lcci/ fun exchangeBits(num: Int): Int { var binary = Integer.toBinaryString(num) if (binary.length % 2 != 0) binary = "0$binary" for (index in 0 until binary.length step 2) binary = binary.replaceRange(IntRange(index, index + 1), "${binary[index + 1]}${binary[index]}") return Integer.parseInt(binary, 2) } // https://leetcode-cn.com/problems/draw-line-lcci/ fun drawLine(length: Int, w: Int, x1: Int, x2: Int, y: Int): IntArray { // Cannot understand : ( TODO() } fun main() { // println(insertBits(1024, 19, 2, 6)) // println(insertBits(0, 31, 0, 4)) println(insertBits(1143207437, 1017033, 11, 31)) println(reverseBits(2147483647)) println(exchangeBits(1)) }
0
Kotlin
0
0
9a26ac2e24b0a0bdf4ec5c491523fe9721c6c406
2,898
LeetCode_Practice
MIT License
src/main/kotlin/RPS.kt
alebedev
573,733,821
false
{"Kotlin": 82424}
import java.lang.RuntimeException fun main() { RPS.solve() } private object RPS { // Day 2 fun solve() { val input = readInput() var result = 0 for (pair in input) { val myMove = when(pair.second) { Result.Draw -> pair.first Result.Win -> when(pair.first) { Move.Rock -> Move.Paper Move.Paper -> Move.Scissors Move.Scissors -> Move.Rock } Result.Lose -> when(pair.first) { Move.Rock -> Move.Scissors Move.Paper -> Move.Rock Move.Scissors -> Move.Paper } } val game = Pair(pair.first, myMove) result += getScore(game) } println("Total score: $result") } private fun readInput(): Iterable<Pair<Move, Result>> { val result = mutableListOf<Pair<Move, Result>>() val lines = generateSequence(::readLine) for (line in lines) { val parts = line.split(" ") val first = when (parts[0]) { "A" -> Move.Rock "B" -> Move.Paper "C" -> Move.Scissors else -> throw RuntimeException("Invalid first char") } val second = when (parts[1]) { "X" -> Result.Lose "Y" -> Result.Draw "Z" -> Result.Win else -> throw RuntimeException("Invalid second char") } result.add(Pair(first, second)) } return result } private fun getScore(game: Pair<Move, Move>): Int { val my = game.second val other = game.first var score = when (my) { Move.Rock -> 1 Move.Paper -> 2 Move.Scissors -> 3 } score += when { my == other -> 3 my == Move.Rock && other == Move.Scissors -> 6 my == Move.Paper && other == Move.Rock -> 6 my == Move.Scissors && other == Move.Paper -> 6 else -> 0 } return score } private enum class Move { Rock, Paper, Scissors } private enum class Result { Lose, Draw, Win } }
0
Kotlin
0
0
d6ba46bc414c6a55a1093f46a6f97510df399cd1
2,338
aoc2022
MIT License
src/Day04.kt
chbirmes
572,675,727
false
{"Kotlin": 32114}
fun main() { fun part1(input: List<String>): Int = input .map { it.toRangePair() } .count { it.first.contains(it.second) || it.second.contains(it.first) } fun part2(input: List<String>): Int = input .map { it.toRangePair() } .count { it.containsOverlap() } val testInput = readInput("Day04_test") check(part1(testInput) == 2) check(part2(testInput) == 4) val input = readInput("Day04") println(part1(input)) println(part2(input)) } private fun String.toRangePair() = split(',').map { range -> range.split('-') .map { it.toInt() } } .map { it[0]..it[1] } .let { Pair(it[0], it[1]) } private fun IntRange.contains(other: IntRange) = contains(other.first) && contains(other.last) private fun Pair<IntRange, IntRange>.containsOverlap() = first.contains(second.first) || first.contains(second.last) || second.contains(first)
0
Kotlin
0
0
db82954ee965238e19c9c917d5c278a274975f26
976
aoc-2022
Apache License 2.0
src/Day21.kt
Riari
574,587,661
false
{"Kotlin": 83546, "Python": 1054}
fun main() { class OperationMonkey(val leftId: String, val rightId: String, val operation: Char) fun processInput(input: List<String>): Pair<MutableMap<String, Long>, MutableMap<String, OperationMonkey>> { val yellers = mutableMapOf<String, Long>() val operators = mutableMapOf<String, OperationMonkey>() for (line in input) { val (id, value) = line.split(": ") val long = value.toLongOrNull() if (long != null) { yellers[id] = long continue } val parts = value.split(' ') operators[id] = OperationMonkey(parts[0], parts[2], parts[1].toCharArray()[0]) } return Pair(yellers, operators) } fun solve(yellers: MutableMap<String, Long>, operators: MutableMap<String, OperationMonkey>, isPart2: Boolean = false, recurse: Boolean = false): Long { while (operators.isNotEmpty()) { val iterator = operators.iterator() while (iterator.hasNext()) { val monkey = iterator.next() val left = yellers.getOrDefault(monkey.value.leftId, null) ?: continue val right = yellers.getOrDefault(monkey.value.rightId, null) ?: continue // For part two, when we find the monkey using the value given by humn, start a recursive search for the correct value // TODO: Optimise this properly. if (isPart2) { if (recurse) { val isHumanLeft = monkey.value.leftId == "humn" val isHumanRight = monkey.value.rightId == "humn" if (isHumanLeft || isHumanRight) { val yellersCopy = yellers.toMutableMap() val thresholds = mutableListOf(4096L * 4096L, 2048L * 2048L, 1024L * 1024L, 512L * 512L, 256L * 256L) var thresholdExceeded = false var value = 0L var result = 0L do { // There are some really dumb workarounds here to speed things up for actual input. // Likely not to work with other people's input. for (threshold in thresholds) { if (result < threshold) continue value += threshold / 2 thresholdExceeded = true break } yellersCopy["humn"] = value value += if (thresholdExceeded && result < 0) -1024L else 1 result = solve(yellersCopy.toMutableMap(), operators.toMutableMap(), true) } while (result != 0L) return value - 1 } } else if (monkey.key == "root") { return left - right } } val result = when (monkey.value.operation) { '+' -> left + right '-' -> left - right '*' -> left * right '/' -> left / right else -> 0L } yellers[monkey.key] = result iterator.remove() } } return yellers["root"]!!.toLong() } fun part1(monkeys: Pair<MutableMap<String, Long>, MutableMap<String, OperationMonkey>>): Long { return solve(monkeys.first.toMutableMap(), monkeys.second.toMutableMap()) } fun part2(monkeys: Pair<MutableMap<String, Long>, MutableMap<String, OperationMonkey>>): Long { return solve(monkeys.first.toMutableMap(), monkeys.second.toMutableMap(), true, true) } val testInput = processInput(readInput("Day21_test")) check(part1(testInput) == 152L) check(part2(testInput) == 301L) val input = processInput(readInput("Day21")) println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
8eecfb5c0c160e26f3ef0e277e48cb7fe86c903d
4,190
aoc-2022
Apache License 2.0
04/part_one.kt
ivanilos
433,620,308
false
{"Kotlin": 97993}
import java.io.File private const val SIZE = 5 fun readInput() : Pair<List<Int>, List<Board>> { val lines = File("input.txt") .readLines() .map { it.split("\n") } .filter{ it[0] != "" } val numbers = lines[0][0].split(",").map{ it.toInt() } val boards = mutableListOf<Board>() for (i in 1 until lines.size step SIZE) { boards.add(Board(lines.subList(i, i + SIZE))) } return Pair(numbers, boards) } class Board(inputBoard: List<List<String>>) { private val numbersPos = HashMap<Int, Pair<Int, Int>>() private val filledInRows = IntArray(SIZE){0} private val filledInCols = IntArray(SIZE){0} private val crossed = HashSet<Int>() private var boardSum = 0 private var crossedSum = 0 init { for ((rowIdx, row) in inputBoard.withIndex()) { val values = row[0].split(" ") .filter { it.isNotEmpty() } .map{ it.toInt() } for ((colIdx, num) in values.withIndex()) { numbersPos[num] = Pair(rowIdx, colIdx) boardSum += num } } } fun cross(num : Int) { if (num in numbersPos) { crossed.add(num) crossedSum += num val (rowIdx, colIdx) = numbersPos[num]!! filledInRows[rowIdx]++ filledInCols[colIdx]++ } } fun hasBingo() : Boolean { for (i in 0 until SIZE) { if (filledInRows[i] >= SIZE || filledInCols[i] >= SIZE) { return true } } return false } fun getScore(lastCrossedNumber : Int): Int { return (boardSum - crossedSum) * lastCrossedNumber } } fun solve(numbers : List<Int>, boards : List<Board>) : Int { for (num in numbers) { for (board in boards) { board.cross(num) if (board.hasBingo()) { return board.getScore(num) } } } throw Exception("No board won bingo") } fun main() { val (numbers, boards) = readInput() val ans = solve(numbers, boards) println(ans) }
0
Kotlin
0
3
a24b6f7e8968e513767dfd7e21b935f9fdfb6d72
2,153
advent-of-code-2021
MIT License
src/main/kotlin/_2019/Day10.kt
thebrightspark
227,161,060
false
{"Kotlin": 548420}
package _2019 import aocRun import between import kotlin.math.abs import kotlin.math.atan2 fun main() { aocRun(puzzleInput) { calcBestAsteroid(parseAsteroidGrid(it)) } aocRun(puzzleInput) { input -> val asteroidGrid = parseAsteroidGrid(input) val gunPos = calcBestAsteroid(asteroidGrid) println("Pos: $gunPos") var remaining = asteroidGrid.stream().mapToInt { line -> line.count { it } }.sum() - 1 var rotationNum = 1 var nextAsteroidNum = 1 lateinit var _200th: Pair<Int, Int> while (remaining > 0) { asteroidGrid.forEachIndexed { y, line -> val l = line.mapIndexed { x, b -> when { y == gunPos.second && x == gunPos.first -> "X" b -> "#" else -> "." } }.joinToString(separator = "") println(l) } println("$remaining remaining at start of rotation $rotationNum") getVisibleAsteroids(gunPos.first, gunPos.second, asteroidGrid).forEach { pos -> if (nextAsteroidNum == 200) _200th = pos println("${nextAsteroidNum++}\t- ${pos.first},${pos.second}") asteroidGrid[pos.second][pos.first] = false remaining-- } rotationNum++ } return@aocRun "200th: $_200th -> ${_200th.first * 100 + _200th.second}" } } private fun parseAsteroidGrid(input: String): MutableList<MutableList<Boolean>> = input.split("\n").mapTo(mutableListOf()) { line -> line.toCharArray().mapTo(mutableListOf()) { it == '#' } } private fun calcBestAsteroid(asteroidGrid: List<List<Boolean>>): Pair<Int, Int> { val asteroids = mutableMapOf<Pair<Int, Int>, Int>() asteroidGrid.forEachIndexed y1@{ y1, line1 -> line1.forEachIndexed x1@{ x1, isAsteroid1 -> if (!isAsteroid1) return@x1 var numCanSee = 0 asteroidGrid.forEachIndexed y2@{ y2, line2 -> line2.forEachIndexed x2@{ x2, isAsteroid2 -> if (isAsteroid2 && (x1 != x2 && y1 != y2) && canSee(x1, y1, x2, y2, asteroidGrid)) numCanSee++ } } asteroids[x1 to y1] = numCanSee } } /*println(asteroids) asteroidGrid.forEachIndexed { y, line -> println(line.mapIndexed { x, _ -> asteroids[x to y]?.toString() ?: "." }.joinToString(separator = " ")) }*/ return asteroids.maxByOrNull { it.value }!!.key } private fun getVisibleAsteroids(x1: Int, y1: Int, asteroidGrid: List<List<Boolean>>): List<Pair<Int, Int>> { val visible = mutableListOf<Triple<Int, Int, Double>>() asteroidGrid.forEachIndexed { y2, line -> line.forEachIndexed x@{ x2, isAsteroid -> if (isAsteroid && (x1 != x2 || y1 != y2) && canSee(x1, y1, x2, y2, asteroidGrid)) { val angle = Math.PI - atan2(x2.toDouble() - x1.toDouble(), y2.toDouble() - y1.toDouble()) visible += Triple(x2, y2, angle) } } } return visible.sortedBy { it.third }.map { it.first to it.second } } private fun canSee(x1: Int, y1: Int, x2: Int, y2: Int, asteroidGrid: List<List<Boolean>>): Boolean = when { x1 == x2 -> between(y1, y2).map { x1 to it }.none { asteroidGrid[it.second][it.first] } y1 == y2 -> between(x1, x2).map { it to y1 }.none { asteroidGrid[it.second][it.first] } else -> { val xDiff = x2 - x1 val yDiff = y2 - y1 val gcd = gcd(abs(xDiff), abs(yDiff)) val xVec = xDiff / gcd val yVec = yDiff / gcd var xPos = x1 + xVec var yPos = y1 + yVec var r = true while (xPos in between(x1, x2) && yPos in between(y1, y2)) { if (asteroidGrid[yPos][xPos]) { r = false break } xPos += xVec yPos += yVec } r } } private tailrec fun gcd(int1: Int, int2: Int): Int = if (int2 == 0) int1 else gcd(int2, int1 % int2) private val testInput1 = """ .#..##.###...####### ##.############..##. .#.######.########.# .###.#######.####.#. #####.##.#.##.###.## ..#####..#.######### #################### #.####....###.#.#.## ##.################# #####.##.###..####.. ..######..##.####### ####.##.####...##..# .#####..#.######.### ##...#.##########... #.##########.####### .####.#.###.###.#.## ....##.##.###..##### .#.#.###########.### #.#.#.#####.####.### ###.##.####.##.#..## """.trimIndent() private val testInput2 = """ .#....#####...#.. ##...##.#####..## ##...#...#.#####. ..#.....X...###.. ..#.#.....#....## """.trimIndent() private val puzzleInput = """ .............#..#.#......##........#..# .#...##....#........##.#......#......#. ..#.#.#...#...#...##.#...#............. .....##.................#.....##..#.#.# ......##...#.##......#..#.......#...... ......#.....#....#.#..#..##....#....... ...................##.#..#.....#.....#. #.....#.##.....#...##....#####....#.#.. ..#.#..........#..##.......#.#...#....# ...#.#..#...#......#..........###.#.... ##..##...#.#.......##....#.#..#...##... ..........#.#....#.#.#......#.....#.... ....#.........#..#..##..#.##........#.. ........#......###..............#.#.... ...##.#...#.#.#......#........#........ ......##.#.....#.#.....#..#.....#.#.... ..#....#.###..#...##.#..##............# ...##..#...#.##.#.#....#.#.....#...#..# ......#............#.##..#..#....##.... .#.#.......#..#...###...........#.#.##. ........##........#.#...#.#......##.... .#.#........#......#..........#....#... ...............#...#........##..#.#.... .#......#....#.......#..#......#....... .....#...#.#...#...#..###......#.##.... .#...#..##................##.#......... ..###...#.......#.##.#....#....#....#.# ...#..#.......###.............##.#..... #..##....###.......##........#..#...#.# .#......#...#...#.##......#..#......... #...#.....#......#..##.............#... ...###.........###.###.#.....###.#.#... #......#......#.#..#....#..#.....##.#.. .##....#.....#...#.##..#.#..##.......#. ..#........#.......##.##....#......#... ##............#....#.#.....#........... ........###.............##...#........# #.........#.....#..##.#.#.#..#....#.... ..............##.#.#.#...........#..... """.trimMargin()
0
Kotlin
0
0
ac62ce8aeaed065f8fbd11e30368bfe5d31b7033
6,346
AdventOfCode
Creative Commons Zero v1.0 Universal
2020/src/year2020/day10/Day10.kt
eburke56
436,742,568
false
{"Kotlin": 61133}
package year2020.day10 import util.readAllLinesAsInt private fun readInput(filename: String) = readAllLinesAsInt(filename).sorted().toMutableList().apply { add(0, 0) add(checkNotNull(maxOrNull()) + 3) } private fun findOnesAndThrees(filename: String) { val input = readInput(filename) input.mapIndexed { index, value -> if (index > 0) value - input[index - 1] else 0 }.apply { val ones = count { it == 1 } val threes = count { it == 3 } println(ones * threes) } } private fun traverse( map: Map<Int, List<Int>>, cache: MutableMap<Int, Long>, start: Int ): Long { if (cache.containsKey(start)) { return checkNotNull(cache[start]) } val list = checkNotNull(map[start]) return if (list.isNotEmpty()) { var sum = 0L list.forEach { sum += traverse(map, cache, it) } sum } else { 1 }.also { cache[start] = it } } private fun findPossibleArrangements(filename: String) { val input = readInput(filename) val map = mutableMapOf<Int, MutableList<Int>>() input.forEachIndexed { index, value -> val list = mutableListOf<Int>() map[index] = list for (i in index + 1 until input.size) { if (input[i] - value <= 3) { list.add(i) } else { break } } } val cache = mutableMapOf<Int, Long>() val combinations = traverse(map, cache, 0) println(combinations) } fun main() { findOnesAndThrees("test.txt") findOnesAndThrees("test2.txt") findOnesAndThrees("input.txt") findPossibleArrangements("test.txt") findPossibleArrangements("test2.txt") findPossibleArrangements("input.txt") }
0
Kotlin
0
0
24ae0848d3ede32c9c4d8a4bf643bf67325a718e
1,802
adventofcode
MIT License
src/Day03.kt
SimoneStefani
572,915,832
false
{"Kotlin": 33918}
fun main() { fun letterToPriority(letter: Char): Int = when (letter) { in 'A'..'Z' -> letter.code - 38 // ASCII code of "A" starts at 65 in 'a'..'z' -> letter.code - 96 // ASCII code of "a" starts at 97 else -> throw IllegalStateException("Invalid character!") } fun part1(input: List<String>): Int { return input.sumOf { line -> val (first, second) = line.splitInHalf() val commonLetters = first.toSet().intersect(second.toSet()) if (commonLetters.size != 1) throw IllegalStateException("Too many common characters!") letterToPriority(commonLetters.first()) } } fun part2(input: List<String>): Int { return input.chunked(3).sumOf { lines -> val commonLetters = lines[0].toSet().intersect(lines[1].toSet()).intersect(lines[2].toSet()) if (commonLetters.size != 1) throw IllegalStateException("Too many common characters!") letterToPriority(commonLetters.first()) } } val testInput = readInput("Day03_test") check(part1(testInput) == 157) check(part2(testInput) == 70) val input = readInput("Day03") println(part1(input)) println(part2(input)) } fun String.splitInHalf(): Pair<String, String> { val mid: Int = this.length / 2 return Pair(this.substring(0, mid), this.substring(mid)) }
0
Kotlin
0
0
b3244a6dfb8a1f0f4b47db2788cbb3d55426d018
1,385
aoc-2022
Apache License 2.0
src/poyea/aoc/mmxxii/day09/Day09.kt
poyea
572,895,010
false
{"Kotlin": 68491}
package poyea.aoc.mmxxii.day09 import poyea.aoc.utils.readInput import kotlin.math.abs import kotlin.math.sign data class Point(val x: Int, val y: Int) { fun moveTowards(other: Point) = this + Point((other.x - x).sign, (other.y - y).sign) fun isNear(other: Point) = abs(other.x - x) < 2 && abs(other.y - y) < 2 operator fun plus(other: Point) = Point(other.x + x, other.y + y) } fun part1(input: String): Int { val points = mutableSetOf<Point>() var head = Point(0, 0) var tail = Point(0, 0) input.split("\n").forEach { action -> val items = action.split(" ") val direction = items[0] val units = items[1].toInt() for (i in 1..units) { head += when (direction) { "U" -> Point(0, 1) "D" -> Point(0, -1) "L" -> Point(-1, 0) "R" -> Point(1, 0) else -> Point(0, 0) } if (!tail.isNear(head)) { tail = tail.moveTowards(head) } points.add(tail) } } return points.size } fun part2(input: String): Int { val knots = MutableList(10) { Point(0, 0) } val points = mutableSetOf<Point>() input.split("\n").forEach { action -> val items = action.split(" ") val direction = items[0] val units = items[1].toInt() for (i in 1..units) { knots[0] += when (direction) { "U" -> Point(0, 1) "D" -> Point(0, -1) "L" -> Point(-1, 0) "R" -> Point(1, 0) else -> Point(0, 0) } knots.indices.windowed(2) { (head, tail) -> if (!knots[tail].isNear(knots[head])) { knots[tail] = knots[tail].moveTowards(knots[head]) } } points.add(knots.last()) } } return points.size } fun main() { println(part1(readInput("Day09"))) println(part2(readInput("Day09"))) }
0
Kotlin
0
1
fd3c96e99e3e786d358d807368c2a4a6085edb2e
2,022
aoc-mmxxii
MIT License
src/y2023/Day15.kt
gaetjen
572,857,330
false
{"Kotlin": 325874, "Mermaid": 571}
package y2023 import util.readInput import util.timingStatistics object Day15 { private fun parse(input: List<String>): List<String> { return input.first().split(",") } fun part1(input: List<String>): Int { val parsed = parse(input) return parsed.sumOf { hash(it) } } fun hash(str: String): Int { return str.fold(0) { acc, c -> ((acc + c.code) * 17) % 256 } } data class Operation( val label: String, val focalLength: Int?, val opChar: Char, val box: Int ) private fun operations(input: List<String>): List<Operation> { return input.map { ins -> val (label, focalLengthStr) = ins.split('-', '=') val box = hash(label) if (ins.last() == '-') { Operation( label = label, focalLength = null, opChar = '-', box = box ) } else { Operation( label = label, focalLength = focalLengthStr.toInt(), opChar = '=', box = box ) } } } fun part2(input: List<String>): Long { val parsed = parse(input) val operations = operations(parsed) val boxes = List(256) { mutableMapOf<String, Int>() } operations.forEach { op -> if (op.opChar == '-') { boxes[op.box].remove(op.label) } else { boxes[op.box][op.label] = op.focalLength!! } } return focusingPower(boxes) } private fun focusingPower(boxes: List<Map<String, Int>>): Long { return boxes.withIndex().sumOf { (boxNumber, box) -> box.values.withIndex().sumOf { (idx, focalLength) -> (1L + boxNumber) * (idx + 1L) * focalLength } } } } fun main() { val testInput = """ rn=1,cm-,qp=3,cm=2,qp-,pc=4,ot=9,ab=5,pc-,pc=6,ot=7 """.trimIndent().split("\n") println("------Tests------") println(Day15.part1(testInput)) println(Day15.part2(testInput)) println("------Real------") val input = readInput(2023, 15) println("Part 1 result: ${Day15.part1(input)}") println("Part 2 result: ${Day15.part2(input)}") timingStatistics { Day15.part1(input) } timingStatistics { Day15.part2(input) } }
0
Kotlin
0
0
d0b9b5e16cf50025bd9c1ea1df02a308ac1cb66a
2,484
advent-of-code
Apache License 2.0
day23/src/main/kotlin/Main.kt
rstockbridge
159,586,951
false
null
import java.io.File fun main() { val nanobots = parseInput(readInputFile()) println("Part I: the solution is ${solvePartI(nanobots)}.") println("Part II: not solved; no general algorithm apparently available.") } fun readInputFile(): List<String> { return File(ClassLoader.getSystemResource("input.txt").file).readLines() } fun parseInput(input: List<String>): List<Nanobot> { val nanobotRegex = "pos=<(-?\\d+),(-?\\d+),(-?\\d+)>, r=(\\d+)".toRegex() return input .map { instruction -> val (x, y, z, signalStrength) = nanobotRegex.matchEntire(instruction)!!.destructured Nanobot.fromInput(x.toInt(), y.toInt(), z.toInt(), signalStrength.toInt()) } } fun solvePartI(nanobots: List<Nanobot>): Int { val nanobotWithLargestSignalRadius = nanobots.maxBy { nanobot -> nanobot.signalRadius }!! return nanobots .filter { nanobot -> nanobotWithLargestSignalRadius.signalRadius >= nanobotWithLargestSignalRadius.getManhattanDistance(nanobot) } .size } data class Nanobot(val position: Coordinate3d, val signalRadius: Int) { companion object { fun fromInput(x: Int, y: Int, z: Int, signalRadius: Int): Nanobot { return Nanobot(Coordinate3d(x, y, z), signalRadius) } } fun getManhattanDistance(other: Nanobot): Int { return this.position.getManhattanDistance(other.position) } } data class Coordinate3d(val x: Int, val y: Int, val z: Int) { fun getManhattanDistance(other: Coordinate3d): Int { return Math.abs(other.x - this.x) + Math.abs(other.y - this.y) + Math.abs(other.z - this.z) } }
0
Kotlin
0
0
c404f1c47c9dee266b2330ecae98471e19056549
1,671
AdventOfCode2018
MIT License
cz.wrent.advent/Day9.kt
Wrent
572,992,605
false
{"Kotlin": 206165}
package cz.wrent.advent fun main() { println(partOne(test)) val result = partOne(input) println("9a: $result") println(partTwo(test)) println(partTwo(test2)) val resultTwo = partTwo(input) println("9b: $resultTwo") } private fun partOne(input: String): Long { val commands = input.split("\n") .map { it.split(" ") } .map { it.get(0) to it.get(1).toInt() } val visited = mutableSetOf(0 to 0) var head = 0 to 0 var tail = 0 to 0 commands.forEach { command -> repeat(command.second) { head = head.moveHead(command.first) tail = tail.moveTail(head) visited.add(tail) } } return visited.size.toLong() } private fun partTwo(input: String): Long { val commands = input.split("\n") .map { it.split(" ") } .map { it.get(0) to it.get(1).toInt() } val visited = mutableSetOf(0 to 0) val knots = mutableListOf<Pair<Int, Int>>() repeat(10) { knots.add(0 to 0) } commands.forEach { command -> repeat(command.second) { knots[0] = knots.first().moveHead(command.first) for (i in 1..9) { knots[i] = knots[i].moveTail(knots[i - 1]) } visited.add(knots[9]) } } return visited.size.toLong()} private fun Pair<Int, Int>.moveHead(direction: String): Pair<Int, Int> { return when (direction) { "U" -> this.first to this.second + 1 "D" -> this.first to this.second - 1 "R" -> this.first + 1 to this.second "L" -> this.first - 1 to this.second else -> error("") } } private fun Pair<Int, Int>.toNeighboursAll(): Set<Pair<Int, Int>> { val set = mutableSetOf<Pair<Int, Int>>() for (i in this.first - 1..this.first + 1) { for (j in this.second - 1 .. this.second + 1) { set.add(i to j) } } return set } private fun Pair<Int, Int>.moveTail(head: Pair<Int, Int>): Pair<Int, Int> { if (head.toNeighboursAll().contains(this)) { return this } else if (this.first == head.first) { return this.first to if (this.second > head.second) this.second - 1 else this.second + 1 } else if (this.second == head.second) { return (if (this.first > head.first) this.first - 1 else this.first + 1) to this.second } else { return (if (this.first > head.first) this.first - 1 else this.first + 1) to if (this.second > head.second) this.second - 1 else this.second + 1 } } private const val test = """R 4 U 4 L 3 D 1 R 4 D 1 L 5 R 2""" private const val test2 = """R 5 U 8 L 8 D 3 R 17 D 10 L 25 U 20""" private const val input = """R 2 L 2 D 2 U 2 R 2 D 2 L 2 D 2 U 2 L 2 D 1 R 1 D 2 R 2 U 1 R 1 U 2 R 1 L 2 D 2 L 1 U 1 L 1 D 1 R 1 L 2 U 2 R 2 U 1 R 2 L 2 D 1 U 1 D 2 L 1 U 1 L 1 D 1 U 1 D 1 L 2 D 2 U 2 L 2 U 1 R 2 D 2 L 1 R 1 U 1 R 1 L 1 U 2 D 1 U 2 R 1 U 1 R 2 D 2 R 2 U 2 D 2 U 2 L 1 D 2 R 1 L 2 D 2 R 2 L 2 U 2 L 2 R 1 D 1 R 1 L 2 D 1 L 2 R 1 U 1 R 1 U 1 L 2 U 1 D 2 R 1 L 1 D 1 R 1 L 2 R 2 L 2 R 1 L 1 D 1 L 1 R 1 D 2 U 1 D 2 R 1 D 1 U 1 L 1 R 1 D 2 R 2 L 2 R 1 L 1 R 1 U 3 L 2 R 3 L 1 R 1 L 2 D 1 U 3 L 1 R 3 U 1 L 2 U 2 D 2 R 2 D 1 L 2 U 1 R 1 L 3 R 2 L 3 R 2 L 2 D 2 U 3 R 2 L 1 R 2 U 1 D 2 U 3 D 1 U 3 L 1 R 3 D 2 R 1 L 2 D 1 L 1 D 3 U 2 L 3 R 1 U 3 L 1 R 2 U 3 D 2 U 3 L 3 R 1 L 2 R 2 D 3 L 1 D 3 R 3 L 1 U 1 D 1 L 3 D 1 U 2 D 3 U 3 L 1 U 2 D 1 R 3 D 1 R 1 L 2 U 1 R 1 L 1 U 3 D 3 U 3 R 1 D 3 U 1 L 2 R 2 U 2 R 1 D 3 L 1 D 2 U 2 R 2 D 2 R 3 L 2 R 1 L 3 D 3 R 1 L 1 U 3 R 1 D 3 R 3 D 2 U 2 R 2 D 2 U 3 D 2 R 1 U 2 L 3 D 1 L 2 U 1 D 1 U 4 R 4 U 4 D 4 U 3 D 1 R 4 L 1 D 2 R 3 U 1 R 2 D 2 U 4 R 3 D 2 L 1 U 4 D 3 U 1 D 4 L 2 U 3 D 4 R 3 L 2 D 4 L 2 R 3 U 2 R 2 U 1 L 3 R 3 L 3 U 4 R 4 U 2 R 3 U 1 L 3 D 4 L 4 R 4 D 3 L 4 R 1 U 4 D 3 R 3 U 1 L 4 U 2 L 2 D 4 U 3 R 1 U 2 D 4 U 4 D 4 U 1 L 4 R 3 U 2 R 1 L 4 D 4 U 3 R 2 L 2 U 3 L 1 R 1 L 1 U 4 L 1 R 3 U 1 R 1 D 2 R 2 L 4 D 1 L 2 R 1 D 1 L 3 D 3 U 4 R 2 L 4 U 2 L 1 R 3 U 3 L 2 R 2 D 2 R 3 U 4 L 1 U 3 L 3 U 1 R 1 L 2 D 3 L 5 D 2 U 2 D 4 R 2 L 3 U 3 R 1 U 4 D 1 R 2 U 1 L 5 R 4 D 5 R 5 D 2 U 2 L 5 D 2 U 3 R 2 L 4 D 5 L 4 R 4 U 5 R 2 U 5 L 1 D 2 L 3 U 4 D 2 U 2 L 3 R 4 U 4 R 5 L 1 D 2 U 4 D 5 L 5 R 4 U 3 R 2 U 5 L 3 U 5 R 3 U 2 R 2 D 3 R 2 L 2 D 4 R 4 U 3 R 3 D 5 R 2 U 3 L 5 R 1 U 5 D 4 R 3 D 5 U 1 R 4 L 5 D 1 U 3 L 4 U 3 R 3 D 5 U 5 D 5 L 5 U 4 D 5 L 3 R 3 D 4 U 2 L 5 R 1 U 5 L 4 U 4 D 5 R 4 L 1 U 2 D 2 L 1 R 2 D 4 R 5 L 3 R 4 D 4 L 4 R 2 L 1 D 3 L 3 R 2 D 3 R 5 D 2 U 4 D 5 L 1 U 3 D 3 U 6 L 1 R 1 L 4 R 6 L 1 R 1 D 2 U 6 R 1 U 3 R 6 U 1 R 1 L 3 D 5 R 6 L 6 R 1 U 2 R 1 L 5 R 5 D 6 R 4 D 4 R 1 U 6 R 4 U 1 R 5 U 3 L 5 U 1 R 5 L 5 D 5 R 3 L 5 D 3 L 2 U 3 R 1 U 1 D 4 R 4 L 2 U 3 L 1 U 5 L 5 D 4 R 6 U 6 L 5 U 3 R 3 D 1 U 6 R 2 L 4 R 2 L 5 U 3 D 1 U 3 R 1 D 1 L 3 U 6 L 5 U 2 L 3 D 1 L 3 U 6 L 4 D 3 R 4 D 1 L 4 U 1 R 6 D 6 R 5 D 4 R 4 D 4 U 6 D 4 L 3 R 4 L 5 R 1 D 6 U 6 D 2 R 1 L 6 U 6 L 5 D 6 U 4 R 4 D 3 U 5 D 6 U 7 L 5 U 7 R 6 U 1 L 6 U 1 R 2 D 7 R 4 U 1 R 6 L 6 D 4 L 4 U 4 R 1 D 7 L 7 D 7 L 5 D 1 L 1 U 2 R 5 D 5 L 3 U 5 D 6 L 4 R 1 U 6 L 3 D 6 L 7 D 6 R 3 U 7 R 1 D 6 R 3 U 7 D 5 U 1 L 4 U 3 D 3 U 3 R 1 L 2 R 2 L 1 U 3 D 5 U 7 D 1 U 7 L 4 D 3 U 4 R 6 D 2 L 5 R 7 L 5 R 1 U 6 R 7 U 4 D 3 U 1 L 1 D 1 U 6 L 1 U 1 R 7 L 4 D 1 U 2 R 7 L 7 R 5 U 4 R 2 L 7 U 6 R 5 L 1 R 3 U 7 D 7 L 4 R 1 U 4 R 1 L 7 D 4 L 5 D 7 U 4 L 5 R 6 U 1 L 4 R 6 D 2 L 1 D 2 U 4 L 5 U 5 D 4 U 7 L 2 D 3 U 5 R 7 D 1 R 7 D 6 U 4 R 3 D 5 U 5 D 8 R 7 L 7 R 1 D 5 L 3 R 1 U 3 R 6 D 5 R 6 L 5 D 7 L 5 R 2 D 1 R 7 L 1 D 3 R 8 L 5 U 8 R 6 U 4 D 2 U 4 D 5 U 7 D 5 U 2 D 3 U 1 R 4 L 2 R 4 U 7 R 8 D 2 U 3 R 7 D 2 U 1 D 6 R 4 L 4 R 3 D 8 R 8 U 7 L 3 U 7 D 1 U 6 R 8 L 1 R 1 D 8 U 7 L 3 D 4 L 4 R 2 L 6 D 6 L 4 R 7 D 8 L 8 U 8 R 2 L 6 U 5 D 2 L 5 U 1 L 6 D 6 U 7 L 2 U 5 R 6 D 5 L 8 U 8 R 1 U 2 L 3 D 1 L 3 U 4 D 3 L 6 R 9 L 9 U 9 R 1 D 4 U 1 L 3 R 7 U 7 R 1 U 1 R 2 D 4 U 8 L 7 R 3 U 8 L 1 R 1 D 7 U 3 L 3 U 8 D 3 L 1 D 6 L 3 U 4 D 3 U 3 L 3 D 5 L 6 U 9 L 1 U 2 L 3 R 1 L 9 D 2 U 1 L 3 R 9 L 8 R 2 L 7 D 4 L 4 R 2 L 4 R 8 D 4 L 2 D 5 R 8 U 6 L 9 D 1 L 6 R 9 D 4 L 5 U 5 D 1 U 3 L 4 U 2 L 2 R 2 L 1 R 7 L 4 D 4 U 4 L 1 R 2 D 6 L 1 U 8 D 7 R 5 D 7 R 7 L 8 U 8 L 5 D 7 U 2 D 2 R 1 U 2 L 1 R 1 L 2 D 1 U 9 L 9 U 9 R 1 U 3 R 7 U 8 R 1 L 7 D 1 U 7 R 9 D 8 R 2 D 5 L 5 D 2 L 6 U 6 R 1 L 1 D 2 R 4 L 3 U 2 R 5 L 3 R 6 U 8 R 1 U 1 R 7 D 10 R 2 D 4 R 3 L 5 D 1 U 8 R 1 U 4 D 6 L 5 U 8 D 6 L 6 R 4 L 9 R 5 U 6 L 8 U 6 L 10 D 4 U 6 L 8 U 3 R 3 L 6 U 1 R 9 D 8 U 9 R 5 U 10 R 8 U 9 L 7 R 4 D 7 U 3 L 5 R 3 D 9 L 9 U 6 R 10 L 2 D 7 U 8 D 4 L 3 U 4 R 2 L 10 D 4 U 10 R 7 D 5 R 7 U 3 L 10 R 8 L 7 D 3 L 6 R 1 L 2 U 1 R 1 U 8 R 5 L 9 R 9 L 1 D 4 R 6 U 7 L 7 R 3 U 4 D 2 U 8 L 5 D 3 L 6 D 7 L 2 U 1 R 6 L 8 D 9 R 3 U 4 D 8 L 5 R 9 L 1 U 7 L 5 D 4 U 5 L 4 R 4 L 3 U 11 D 1 L 10 U 6 L 5 D 3 U 8 D 11 L 8 R 2 U 5 L 9 D 3 L 11 R 2 U 5 L 7 D 11 R 8 U 1 L 10 R 10 L 9 R 9 L 8 R 7 D 3 U 6 R 11 U 8 D 4 L 9 U 3 D 5 L 4 R 5 D 7 L 5 U 10 D 8 L 3 D 2 U 9 D 6 L 3 U 3 D 8 U 4 R 1 L 9 U 4 L 5 D 10 L 11 U 6 D 8 L 5 R 9 L 2 U 2 L 10 R 5 U 6 L 7 R 7 U 9 D 6 R 7 D 8 U 7 R 6 L 2 D 6 R 8 L 5 R 1 L 10 R 8 U 11 R 10 L 10 R 10 L 4 U 4 D 9 U 8 R 5 D 7 U 7 L 6 D 4 L 9 R 2 U 8 D 2 L 2 D 2 U 6 L 2 R 9 U 10 D 11 U 3 R 9 U 1 L 11 R 7 L 4 R 5 U 10 L 3 R 10 L 10 D 2 L 9 D 9 L 6 D 11 R 10 L 2 R 4 D 2 R 4 D 8 L 3 U 10 R 4 L 2 U 1 L 3 R 1 L 2 R 3 D 2 L 2 D 3 R 5 U 10 L 12 R 5 D 5 U 9 L 9 D 2 L 8 U 2 L 11 U 5 L 8 U 7 R 4 U 10 D 4 L 5 R 3 D 8 R 12 L 5 U 9 L 10 R 5 U 10 R 1 L 5 U 6 D 7 L 12 D 2 R 12 L 1 U 11 D 8 R 12 L 8 U 3 R 9 L 8 D 2 L 10 D 10 R 4 D 2 R 11 U 4 R 10 U 7 L 7 D 5 U 5 R 9 D 10 L 10 U 1 D 11 U 4 D 5 U 5 D 8 U 2 D 4 R 4 L 5 U 10 D 12 R 9 L 11 R 9 L 1 D 9 L 11 D 12 U 4 R 7 D 1 U 3 L 4 U 9 R 12 D 1 L 7 U 7 D 6 U 1 R 3 L 7 U 5 L 2 D 10 R 12 L 3 U 7 D 10 L 5 R 1 U 9 L 1 D 11 R 5 L 2 D 1 U 3 R 2 L 3 U 5 L 3 D 5 R 10 L 7 R 12 U 4 D 3 R 3 L 2 R 7 U 4 D 9 U 7 D 1 R 9 L 2 U 6 R 5 D 3 U 7 R 12 L 10 D 11 L 8 U 12 D 13 U 9 D 5 U 4 R 2 L 3 U 13 R 4 L 9 U 4 L 3 U 9 R 1 D 6 U 4 D 3 U 5 R 5 L 11 R 8 D 1 U 4 D 10 R 5 D 10 U 3 D 4 R 1 U 3 R 13 L 6 D 8 R 12 L 4 U 2 L 13 D 11 L 4 U 8 L 10 R 2 D 8 R 11 L 2 D 8 R 8 L 10 U 10 L 4 D 9 L 7 D 11 L 10 U 13 L 6 U 7 D 8 L 3 R 10 L 14 U 13 L 11 D 5 R 8 U 2 D 9 L 14 U 7 R 4 U 1 D 8 U 8 D 9 L 2 D 7 R 1 D 9 R 2 U 4 D 8 L 9 R 6 L 2 R 11 D 6 L 5 U 8 L 4 R 3 D 5 L 3 U 9 R 3 U 1 D 7 R 1 L 10 U 1 L 8 U 11 D 8 U 12 R 9 L 5 D 10 L 2 R 8 D 10 R 6 D 1 L 11 D 8 R 7 L 14 D 12 L 11 R 11 U 9 R 12 D 10 L 12 R 4 L 8 D 2 R 3 L 14 R 7 U 10 R 1 L 6 R 4 D 11 L 13 R 12 U 4 L 12 U 10 D 8 R 10 D 9 R 13 L 2 U 2 D 7 U 7 R 3 D 3 R 13 U 8 R 10 U 13 D 14 R 11 D 7 R 2 U 5 D 2 L 6 U 14 L 10 R 9 U 11 R 12 D 5 L 11 R 12 U 11 R 8 L 2 D 14 U 3 D 9 U 5 L 4 U 5 L 6 D 3 L 1 R 10 L 4 D 12 U 15 L 5 D 11 L 15 D 10 L 14 U 1 L 14 D 6 R 6 U 9 R 1 L 7 D 11 U 12 D 2 R 7 L 2 D 13 U 13 R 6 L 3 D 3 R 11 U 3 D 3 U 11 L 10 U 7 R 7 D 9 U 10 R 11 U 12 D 11 R 11 U 2 R 2 D 9 R 12 D 1 L 11 R 1 U 2 R 14 L 4 R 1 D 12 R 7 U 12 L 2 U 5 D 7 R 15 D 5 L 9 D 7 R 10 U 12 D 10 R 11 D 5 U 10 R 2 U 11 R 3 U 6 D 14 U 11 D 5 L 8 D 6 L 2 U 2 L 14 R 8 U 15 L 10 D 1 R 4 L 8 D 7 L 15 U 10 D 14 U 9 L 7 R 13 U 11 R 15 L 11 R 2 L 11 R 14 L 1 D 10 L 2 U 7 L 9 D 12 R 2 L 4 U 4 R 9 L 6 R 13 D 1 U 13 R 7 D 3 R 14 L 12 D 15 R 16 L 7 R 2 U 3 R 9 U 10 D 6 U 7 L 11 D 12 L 16 R 12 D 10 U 16 D 9 U 14 L 14 U 11 D 14 L 14 D 10 L 3 D 10 U 6 D 11 L 8 U 4 D 1 U 5 D 5 L 4 U 8 R 3 D 12 U 4 R 8 D 6 U 8 D 2 U 12 L 6 D 12 R 7 D 6 U 7 D 12 L 3 R 2 L 12 R 13 U 16 L 6 D 8 U 13 R 14 D 4 U 7 D 1 R 4 D 13 R 10 D 7 R 11 L 6 U 6 R 7 L 8 D 2 L 11 U 3 L 12 U 4 D 11 U 8 D 10 U 1 R 12 U 1 L 15 R 15 D 2 L 8 D 13 L 3 R 8 U 14 R 5 U 3 D 15 U 7 D 1 L 6 D 8 U 13 R 6 L 6 D 3 L 9 D 17 U 8 R 16 L 6 D 9 U 3 L 10 R 13 L 14 U 8 R 7 U 12 D 14 R 1 D 3 L 11 R 8 D 9 R 17 D 5 R 17 U 8 L 10 D 7 U 4 D 16 L 9 D 1 L 16 R 7 L 1 R 11 U 10 R 2 U 10 L 15 U 10 R 2 D 11 U 12 L 15 U 4 D 2 R 4 U 2 L 11 R 16 U 10 R 4 D 9 U 7 D 2 R 10 D 14 L 10 U 9 R 7 D 3 R 7 L 3 U 15 D 13 L 17 R 12 U 13 D 16 U 13 R 13 U 14 L 16 U 7 D 2 R 11 U 17 D 9 R 12 U 16 L 11 R 3 U 9 L 6 D 2 U 1 D 7 L 1 U 7 D 8 U 11 L 4 R 6 L 2 U 12 L 13 U 5 L 17 R 16 D 10 U 12 L 7 R 4 U 8 D 17 R 13 L 2 D 5 L 1 R 2 D 16 U 9 D 15 L 8 U 14 R 9 D 18 U 16 L 17 U 9 D 11 U 17 R 8 D 17 U 14 D 8 U 8 R 8 U 14 R 5 L 1 R 3 D 5 U 10 R 16 U 18 D 16 U 11 D 18 U 13 L 11 D 2 R 16 D 15 L 9 D 12 R 11 L 8 U 8 R 10 L 2 D 6 L 5 D 9 L 3 D 1 U 18 D 12 U 13 L 6 R 17 D 10 R 9 L 6 R 3 U 1 R 1 U 6 L 15 U 8 D 15 U 14 R 10 L 6 U 1 L 12 R 9 D 13 U 1 L 16 U 16 L 13 R 4 U 3 D 11 L 12 R 11 U 17 R 18 L 4 R 6 L 18 D 10 L 16 R 2 D 4 R 14 D 11 L 12 R 7 L 9 U 12 D 12 R 4 L 1 D 14 R 14 L 3 U 2 L 6 R 7 D 6 U 18 L 17 U 12 R 12 L 5 D 13 R 7 D 8 L 16 D 13 U 4 D 3 R 16 L 9 U 8 D 15 R 8 L 12 R 5 L 1 U 11 D 11 L 10 U 7 D 6 L 15 D 9 R 10 D 6 U 14 L 7 U 19 R 17 L 12 U 1 L 9 R 17 D 12 U 3 L 15 R 16 D 15 R 15 L 1 U 16 R 19 D 9 L 16 D 12 R 8 L 2 D 16 L 17 U 16 D 9 L 9 U 8 L 9 R 16 L 3 D 8 U 7 D 10 U 17 R 2 D 16 R 6 U 9 R 4 L 17 D 10 U 10 L 14 D 9 R 8 L 9 R 18 U 13 L 16 R 2 U 16 L 11 U 4 L 13 R 8 L 19 U 4 D 10 R 10 U 14 R 13 L 17 U 17 R 12 D 18 R 2 D 5 L 12 U 6 D 7 R 9 L 13 D 15 R 9 U 16 D 14 R 8 L 8 U 10 L 8 D 18 U 8 D 9 L 6 R 8 U 4 D 14 L 13 D 4 R 3 U 13 L 2"""
0
Kotlin
0
0
8230fce9a907343f11a2c042ebe0bf204775be3f
10,785
advent-of-code-2022
MIT License
src/day13/Day13.kt
ayukatawago
572,742,437
false
{"Kotlin": 58880}
package day13 import readInput fun main() { val testInput = readInput("day13/test") val packets = testInput.filter { it.isNotBlank() }.map { Packet.from(it) } part1(packets) part2(packets) } private fun part1(packets: List<Packet>) { val answer = packets.chunked(2).mapIndexed { index, pair -> if (pair.first() < pair.last()) index + 1 else 0 } println(answer.sum()) } private fun part2(packets: List<Packet>) { val packet2 = Packet.from("[[2]]") val packet6 = Packet.from("[[6]]") val sortedPackets = (packets + packet2 + packet6).sorted() val index2 = sortedPackets.indexOf(packet2) + 1 val index6 = sortedPackets.indexOf(packet6) + 1 println(index2 * index6) } sealed class Packet : Comparable<Packet> { class ListPacket(val values: List<Packet>) : Packet() { override fun compareTo(other: Packet): Int = when (other) { is ListPacket -> values.zip(other.values).map { (first, second) -> first.compareTo(second) }.firstOrNull { it != 0 } ?: values.size.compareTo(other.values.size) is IntPacket -> compareTo(other.toList()) } } data class IntPacket(val value: Int) : Packet() { fun toList(): Packet = ListPacket(listOf(this)) override fun compareTo(other: Packet): Int = when (other) { is ListPacket -> toList().compareTo(other) is IntPacket -> value.compareTo(other.value) } } companion object { fun from(input: String): Packet { val iterator = input.split("""((?<=[\[\],])|(?=[\[\],]))""".toRegex()) .filter { it.isNotBlank() } .filter { it != "," } .iterator() return from(iterator) } private fun from(iterator: Iterator<String>): Packet { val packet = mutableListOf<Packet>() while (iterator.hasNext()) { when (val value = iterator.next()) { "]" -> return ListPacket(packet) "[" -> packet.add(from(iterator)) else -> packet.add(IntPacket(value.toInt())) } } return ListPacket(packet) } } }
0
Kotlin
0
0
923f08f3de3cdd7baae3cb19b5e9cf3e46745b51
2,314
advent-of-code-2022
Apache License 2.0
src/Day04.kt
KliminV
573,758,839
false
{"Kotlin": 19586}
fun main() { fun part1(input: List<String>): Int { return input.asSequence().map { it.split(",", "-") } .flatten().map { it.toInt() }.chunked(4).map { (a, b, c, d) -> if (a == c) 1 else if (a < c) { if (b >= d) 1 else 0 } else { if (b <= d) 1 else 0 } }.sum() } fun part2(input: List<String>): Int { return input.asSequence().map { it.split(",", "-") } .flatten().map { it.toInt() }.chunked(4).map { (a, b, c, d) -> if ((b < c) || (a > d) ) 0 else 1 }.sum() } // 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
542991741cf37481515900894480304d52a989ae
1,001
AOC-2022-in-kotlin
Apache License 2.0
2021/src/day24/Solution.kt
vadimsemenov
437,677,116
false
{"Kotlin": 56211, "Rust": 37295}
package day24 import java.nio.file.Files import java.nio.file.Paths import java.util.TreeMap import kotlin.system.measureTimeMillis fun main() { fun Char.registerId() = code - 'w'.code val alu = longArrayOf(0, 0, 0, 0) var nextInput = -1 fun String.parseCommand(): Command { return if (startsWith("inp ")) { Command { alu[this[4].registerId()] = nextInput.toLong().also { check(it in 1..9) } } } else { val (cmd, a, b) = split(" ") check(a.length == 1) val register = a.first().registerId() val value = { if (b.first() in "wxyz") alu[b.first().registerId()] else b.toLong() } when (cmd) { "add" -> Command { alu[register] += value() } "mul" -> Command { alu[register] *= value() } "div" -> Command { alu[register] /= value() } "mod" -> Command { alu[register] %= value() } "eql" -> Command { alu[register] = if (alu[register] == value()) 1 else 0 } else -> error("Unknown command $cmd") } } } fun solve(input: Input, comparator: Comparator<Int>): Long { check(input.size % 14 == 0) val commands = input.map(String::parseCommand).chunked(input.size / 14) data class State(val digit: Int, val prevZ: Long) : Comparable<State> { override fun compareTo(other: State) = comparator.compare(this.digit, other.digit) } val mem = Array(15) { TreeMap<Long, State>() } mem[0][0] = State(0, Long.MIN_VALUE) val pow26 = generateSequence(1L) { it * 26 }.takeWhile { it < Int.MAX_VALUE }.toList() for (len in 1..14) { val threshold = pow26.getOrElse(15 - len) { Long.MAX_VALUE } for (digit in 1..9) { nextInput = digit for (z in mem[len - 1].keys) { if (z > threshold) break // We won't get Z=0 in the end if current Z is too big. alu.fill(0); alu['z'.registerId()] = z commands[len - 1].forEach { it.execute() } mem[len].merge(alu['z'.registerId()], State(digit, z), ::maxOf) } } } val (answer, _, _) = mem.foldRight(Triple(0L, 1L, 0L)) { map, (acc, pow10, z) -> val (digit, prevZ) = map[z]!! Triple(acc + digit * pow10, pow10 * 10, prevZ) } return answer } fun part1(input: Input): Long { return solve(input, Comparator.naturalOrder()) } fun part2(input: Input): Long { return solve(input, Comparator.reverseOrder()) } val millis = measureTimeMillis { println(part1(readInput("input.txt"))) println(part2(readInput("input.txt"))) } System.err.println("Done in $millis ms") } private fun interface Command { fun execute() } private fun readInput(s: String): Input { return Files.newBufferedReader(Paths.get("src/day24/$s")).readLines() } private typealias Input = List<String>
0
Kotlin
0
0
8f31d39d1a94c862f88278f22430e620b424bd68
2,776
advent-of-code
Apache License 2.0
src/Day02.kt
robotfooder
573,164,789
false
{"Kotlin": 25811}
import Shape.* import Result.* import java.lang.IllegalArgumentException enum class Shape(val points: Int) { ROCK(1), PAPER(2), SCISSORS(3) } enum class Result(val points: Int) { WIN(6), DRAW(3), LOOSE(0) } fun main() { fun mapToShape(shape: String): Shape { return when (shape) { "X", "A" -> ROCK "Y", "B" -> PAPER "Z", "C" -> SCISSORS else -> { throw IllegalArgumentException("Could not convert $shape to a shape") } } } fun mapToResult(result: String): Result { return when (result) { "X" -> LOOSE "Y" -> DRAW "Z" -> WIN else -> { throw IllegalArgumentException("Could not convert $result to a result") } } } fun calculateResult(theirHand: Shape, myHand: Shape): Result { if (theirHand == myHand) { return DRAW } return when (myHand) { ROCK -> if (theirHand == SCISSORS) WIN else LOOSE PAPER -> if (theirHand == ROCK) WIN else LOOSE SCISSORS -> if (theirHand == PAPER) WIN else LOOSE } } fun calculate(play: Pair<Shape, Shape>): Int { val (theirGesture, myGesture) = play val result = calculateResult(theirGesture, myGesture) return myGesture.points + result.points } fun getShapeToMatchResult(strategy: Pair<Shape, Result>): Pair<Shape, Shape> { val (theirShape, expectedResult) = strategy val myShape = Shape.values().find { calculateResult(theirShape, it) == expectedResult }!! return theirShape to myShape } fun part1(input: List<String>): Int { return input .map { it.split(" ") } .map { mapToShape(it[0]) to mapToShape(it[1]) } .sumOf { calculate(it) } } fun part2(input: List<String>): Int { return input .map { it.split(" ") } .map { mapToShape(it[0]) to mapToResult(it[1]) } .map { getShapeToMatchResult(it) } .sumOf { calculate(it) } } fun runTest(expected: Int, day: String, testFunction: (List<String>) -> Int) { val actual = testFunction(readInput("Day${day}_test")) check(expected == actual) { "Failing for day $day, ${testFunction}. " + "Expected $expected but got $actual" } } val day = "02" // test if implementation meets criteria from the description, like: runTest(15, day, ::part1) runTest(12, day, ::part2) val input = readInput("Day$day") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
9876a52ef9288353d64685f294a899a58b2de9b5
2,711
aoc2022
Apache License 2.0
src/main/kotlin/day15/solution.kt
bukajsytlos
433,979,778
false
{"Kotlin": 63913}
package day15 import java.io.File import java.util.* fun main() { val lines = File("src/main/kotlin/day15/input.txt").readLines() val mapSize = lines.size val riskLevelGrid: Array<IntArray> = Array(mapSize) { i -> lines[i].map { it.digitToInt() }.toIntArray() } val minimumRiskLevelGrid: Array<IntArray> = findMinimumRiskLevels(mapSize, riskLevelGrid) println(minimumRiskLevelGrid[mapSize - 1][mapSize - 1]) val riskLevelFullGrid: Array<IntArray> = Array(mapSize * 5) { y -> IntArray(mapSize * 5) { x -> (riskLevelGrid[y % mapSize][x % mapSize] + x / mapSize + y / mapSize - 1) % 9 + 1 } } val minimumRiskLevelFullGrid: Array<IntArray> = findMinimumRiskLevels(mapSize * 5, riskLevelFullGrid) println(minimumRiskLevelFullGrid[mapSize * 5 - 1][mapSize * 5 - 1]) } private fun findMinimumRiskLevels( mapSize: Int, riskLevelGrid: Array<IntArray> ): Array<IntArray> { val minimumRiskLevelGrid: Array<IntArray> = Array(mapSize) { IntArray(mapSize) { Int.MAX_VALUE } } val parents: MutableMap<Point, Point> = mutableMapOf() val unvisited: MutableSet<Point> = (0 until mapSize).flatMap { y -> (0 until mapSize).map { x -> Point(x, y) } }.toMutableSet() minimumRiskLevelGrid[0][0] = 0 val visiting: PriorityQueue<Pair<Point, Int>> = PriorityQueue { o1, o2 -> o1.second - o2.second } visiting.add(Point(0, 0) to 0) while (visiting.isNotEmpty()) { val (nextCandidate, parentRiskLevel) = visiting.poll() for (adjacent in nextCandidate.adjacents(mapSize)) { if (adjacent in unvisited) { val adjacentRiskLevel = riskLevelGrid[adjacent.y][adjacent.x] val adjacentMinimumRiskLevel = minimumRiskLevelGrid[adjacent.y][adjacent.x] if (adjacentRiskLevel + parentRiskLevel < adjacentMinimumRiskLevel) { minimumRiskLevelGrid[adjacent.y][adjacent.x] = adjacentRiskLevel + parentRiskLevel parents[adjacent] = nextCandidate visiting.offer(adjacent to adjacentRiskLevel + parentRiskLevel) } } } unvisited.remove(nextCandidate) } return minimumRiskLevelGrid } data class Point(val x: Int, val y: Int) fun Point.adjacents(size: Int): Set<Point> { val points = mutableSetOf<Point>() if (this.x > 0) points.add(Point(this.x - 1, this.y)) if (this.x < size) points.add(Point(this.x + 1, this.y)) if (this.y > 0) points.add(Point(this.x, this.y - 1)) if (this.y < size) points.add(Point(this.x, this.y + 1)) return points }
0
Kotlin
0
0
f47d092399c3e395381406b7a0048c0795d332b9
2,620
aoc-2021
MIT License
src/Day05.kt
SebastianHelzer
573,026,636
false
{"Kotlin": 27111}
fun main() { val day = "05" fun List<String>.toState(): List<String> { val numCols = last().split(" ").filterNot { it.isBlank() }.size val mutableList = MutableList(numCols) { "" } dropLast(1).forEach { it.chunked(4) .mapIndexed { index, s -> index to s[1] } .forEach { (i, v) -> if (v.isLetter()) mutableList[i] = v + mutableList[i] } } return mutableList } fun List<String>.toSteps(): List<Triple<Int, Int, Int>> { return map { val (a, b, c) = it.split(' ').mapNotNull { it.toIntOrNull() } Triple(a, b - 1, c - 1) } } fun parseInput(input: List<String>): Pair<List<String>, List<Triple<Int, Int, Int>>> { val blankIndex = input.indexOfFirst { it.isBlank() } val state = input.subList(0, blankIndex).toState() val steps = input.subList(blankIndex + 1, input.size).toSteps() return state to steps } fun List<String>.applySteps(steps: List<Triple<Int, Int, Int>>, withReversal: Boolean = true): List<String> { val mutableList = this.toMutableList() steps.forEach { (count, fromIndex, toIndex) -> val (moveable, leftover) = mutableList[fromIndex].let { it.takeLast(count) to it.take(it.length - count) } mutableList[fromIndex] = leftover mutableList[toIndex] += if(withReversal) moveable.reversed() else moveable } return mutableList } fun part1(input: List<String>): String { val (initialState, steps) = parseInput(input) val endState = initialState.applySteps(steps) return endState.map { it.last() }.joinToString("") } fun part2(input: List<String>): String { val (initialState, steps) = parseInput(input) val endState = initialState.applySteps(steps, false) return endState.map { it.last() }.joinToString("") } // test if implementation meets criteria from the description, like: val testInput = readInput("Day${day}_test") checkEquals("CMZ", part1(testInput)) checkEquals("MCD", part2(testInput)) val input = readInput("Day$day") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
e48757626eb2fb5286fa1c59960acd4582432700
2,240
advent-of-code-2022
Apache License 2.0
src/Day07.kt
strindberg
572,685,170
false
{"Kotlin": 15804}
sealed class File { abstract fun size(): Int } class TextFile(private val size: Int) : File() { override fun size(): Int = size } class Dir(private val parent: Dir?) : File() { private val children: MutableMap<String, File> = mutableMapOf() override fun size(): Int = children.values.sumOf { it.size() } fun parent() = parent!! fun childDir(name: String): Dir = children.getOrPut(name) { Dir(this) } as Dir fun childFile(name: String, size: String) { children[name] = TextFile(size.toInt()) } fun allDirs(): List<Dir> = children.values.filterIsInstance<Dir>().flatMap { it.allDirs() } + this } fun main() { fun parse(input: List<String>): Dir { val top = Dir(null) input.fold(top) { current, line -> if (line.startsWith("$")) { if (line.substring(2).startsWith("cd ")) { when (val dest = line.substring(5)) { "/" -> top ".." -> current.parent() else -> current.childDir(dest) } } else current } else { if (line.startsWith("dir ")) { current.childDir(line.substring(4)) } else { val info = line.split(" ") current.childFile(info[1], info[0]) } current } } return top } fun part1(input: List<String>): Int { val top = parse(input) return top.allDirs().filter { it.size() < 100000 }.sumOf { it.size() } } fun part2(input: List<String>): Int { val top = parse(input) val free = 70000000 - top.size() return top.allDirs().filter { free + it.size() > 30000000 }.minBy { it.size() }.size() } val input = readInput("Day07") val part1 = part1(input) println(part1) check(part1 == 1423358) val part2 = part2(input) println(part2) check(part2 == 545729) }
0
Kotlin
0
0
c5d26b5bdc320ca2aeb39eba8c776fcfc50ea6c8
2,030
aoc-2022
Apache License 2.0
src/main/kotlin/Day04.kt
brigham
573,127,412
false
{"Kotlin": 59675}
fun toRange(s: String): IntRange { val (start, end) = s.split(',') return (start.toInt())..(end.toInt()) } fun toRange(l: List<String>): IntRange { return (l[0].toInt())..(l[1].toInt()) } fun main() { fun parse(input: List<String>) = input.map { it.split(',') } .map { it[0] to it[1] } .map { pair -> pair.map { toRange(it) } } fun part1(input: List<String>): Int { return parse(input) .map { it.toList().contains(it.first.overlap(it.second)) } .count { it } } fun part2(input: List<String>): Int { return parse(input) .map { it.first.overlap(it.second) != null } .count { it } } // 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
b87ffc772e5bd9fd721d552913cf79c575062f19
970
advent-of-code-2022
Apache License 2.0
src/main/kotlin/g2101_2200/s2188_minimum_time_to_finish_the_race/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g2101_2200.s2188_minimum_time_to_finish_the_race // #Hard #Array #Dynamic_Programming #2023_06_26_Time_1220_ms_(100.00%)_Space_117_MB_(100.00%) class Solution { fun minimumFinishTime(tires: Array<IntArray>, changeTime: Int, numLaps: Int): Int { var minf = Int.MAX_VALUE // find the minimum of f, to deal with special case and stronger constraints later. for (tire in tires) { minf = Math.min(minf, tire[0]) } // if min-f >= changeTime, we can return early if (minf >= changeTime) { return minf * numLaps + changeTime * (numLaps - 1) } // shortest[i] record shortest time that one single tire is worth to go the i-th laps // worth to go means the i-th lap time is shorter than changeTime + f val shortest = IntArray(numLaps + 1) shortest.fill(Int.MAX_VALUE) var len = 0 // traverse all tires, and update the shortest[i] // this shortest time is available from [1, len] in the array // len is updated in the traverse for (tire in tires) { val f = tire[0] val r = tire[1] // index start from 1 to be consistent with numLaps var index = 1 var t = f var sum = t // use changeTime + minf here, which is a strong constraints than changeTime + f while (t <= changeTime + minf && index <= numLaps) { shortest[index] = Math.min(shortest[index], sum) t = t * r sum += t index++ } len = Math.max(len, index - 1) } for (i in 2..numLaps) { // for j > Math.min(i/2, len), it's simply recombination of the values of shortest // [1:len] // it's ok to go furthur for the loop, just repeat the Math.min computation for (j in 1..Math.min(i / 2, len)) { shortest[i] = Math.min(shortest[i], shortest[j] + shortest[i - j] + changeTime) } } return shortest[numLaps] } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
2,108
LeetCode-in-Kotlin
MIT License
codeforces/round576/d.kt
mikhail-dvorkin
93,438,157
false
{"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408}
package codeforces.round576 fun main() { val n = readInt() val f = Array(n) { readLn().map { if (it == '#') 1 else 0 } } val cum = Array(n + 1) { IntArray(n + 1) } for (i in 0 until n) { for (j in 0 until n) { cum[i + 1][j + 1] = cum[i][j + 1] + cum[i + 1][j] - cum[i][j] + f[i][j] } } val dp = Array(n + 1) { Array(n + 1) { Array(n + 1) { IntArray(n + 1) }}} for (i1 in n - 1 downTo 0) { for (i2 in i1 + 1..n) { for (j1 in n - 1 downTo 0) { for (j2 in j1 + 1..n) { if (sum(cum, i1, j1, i2, j2) == 0) continue var res = maxOf(i2 - i1, j2 - j1) for (i in i1 until i2) { if (sum(cum, i, j1, i + 1, j2) != 0) continue res = minOf(res, dp[i1][j1][i][j2] + dp[i + 1][j1][i2][j2]) } for (j in j1 until j2) { if (sum(cum, i1, j, i2, j + 1) != 0) continue res = minOf(res, dp[i1][j1][i2][j] + dp[i1][j + 1][i2][j2]) } dp[i1][j1][i2][j2] = res } } } } println(dp[0][0][n][n]) } private fun sum(cum: Array<IntArray>, i1: Int, j1: Int, i2: Int, j2: Int) = cum[i2][j2] - cum[i1][j2] - cum[i2][j1] + cum[i1][j1] private fun readLn() = readLine()!! private fun readInt() = readLn().toInt()
0
Java
1
9
30953122834fcaee817fe21fb108a374946f8c7c
1,174
competitions
The Unlicense
src/Day13.kt
Cryosleeper
572,977,188
false
{"Kotlin": 43613}
import kotlin.math.max fun main() { fun part1(input: List<String>): Int { val pairs = input.parse() val indexes = mutableListOf<Int>() pairs.forEachIndexed { pairIndex, pair -> if (pair.first precedes pair.second) indexes.add(pairIndex) } return indexes.sumOf { it+1 } } fun part2(input: List<String>): Int { val parsed = input.filter { it.isNotEmpty() }.toMutableList() parsed.add("[[2]]") parsed.add("[[6]]") val sorted = parsed.sortedWith { o1, o2 -> if (o1 precedes o2) -1 else 1 } println("Sorted list is: \n${sorted.joinToString("\n")}") return (sorted.indexOf("[[2]]")+1) * (sorted.indexOf("[[6]]")+1) } // test if implementation meets criteria from the description, like: val testInput = readInput("Day13_test") check(part1(testInput) == 13) check(part2(testInput) == 140) val input = readInput("Day13") println(part1(input)) println(part2(input)) } private fun List<String>.parse(): List<Pair<String, String>> { val result = mutableListOf<Pair<String, String>>() this.chunked(3) { result.add(it[0] to it[1]) } return result } private fun Char.isElevenBasedDigit() = this-'0' in 0..10 private infix fun String.precedes( that: String ): Boolean { fun MutableList<Char>.toStringFormat() = joinToString("").replace(":","10") var result = false println("Pair ${this} - \n ${that}") run pair@{ val firstCode = mutableListOf<Char>().also { it.addAll(this.replace("10",":").toList()) } val secondCode = mutableListOf<Char>().also { it.addAll(that.replace("10",":").toList()) } (0 until max(firstCode.size, secondCode.size)).forEach { index -> print("\tPosition $index: ${firstCode[index]}-${secondCode[index]}:") if (firstCode[index] == '[' && secondCode[index] == '[') { println("Starting arrays in both") } else if (firstCode[index] == ']' && secondCode[index] == ']') { println("Closing arrays in both") } else if (firstCode[index] == '[' && secondCode[index].isElevenBasedDigit()) { println("Left one starts an array, creating array in the right one") secondCode.add(index + 1, ']') secondCode.add(index, '[') println( "\t\tNow comparing ${firstCode.toStringFormat()} - \n" + "\t\t ${secondCode.toStringFormat()}" ) } else if (firstCode[index].isElevenBasedDigit() && secondCode[index] == '[') { println("Right one starts an array, creating array in the left one") firstCode.add(index + 1, ']') firstCode.add(index, '[') println( "\t\tNow comparing ${firstCode.toStringFormat()} - \n" + "\t\t ${secondCode.toStringFormat()}" ) } else if (firstCode[index] == ']' && secondCode[index] != ']') { println("Left one closes an array, sequence is correct") result = true return@pair } else if (firstCode[index] != ']' && secondCode[index] == ']') { println("Right one closes an array, sequence is wrong") return@pair } else if (firstCode[index].isElevenBasedDigit() && secondCode[index].isElevenBasedDigit()) { println("Comparing ${firstCode[index]} and ${secondCode[index]}") val first = firstCode[index] - '0' val second = secondCode[index] - '0' if (first < second) { println("\tCorrect sequence") result = true return@pair } else if (first > second) { println("\tWrong sequence") return@pair } else { println("\tSame digit, continuing") } } else { println("Skipping coma") } if (index == firstCode.size - 1) { println("\tLeft one is shorter, sequence is correct") result = true return@pair } else if (index == secondCode.size - 1) { println("\tRight one is shorter, sequence is wrong") return@pair } } } return result }
0
Kotlin
0
0
a638356cda864b9e1799d72fa07d3482a5f2128e
4,541
aoc-2022
Apache License 2.0
src/main/kotlin/Day13.kt
cbrentharris
712,962,396
false
{"Kotlin": 171464}
import kotlin.String import kotlin.collections.List object Day13 { private const val NORMAL_MULTIPLIER = 100 private const val TRANSPOSED_MULTIPLIER = 1 fun part1(input: List<String>): String { val grids = parseGrids(input) return grids.sumOf { grid -> // Transposed is actually columns val transposedGrid = transpose(grid) scoreExact(grid, NORMAL_MULTIPLIER) + scoreExact(transposedGrid, TRANSPOSED_MULTIPLIER) }.toString() } private fun scoreExact(grid: List<String>, multiplier: Int): Int { return findLinesOfExactness(grid).find { isMirror(it, grid) }?.let { // Normal is rows, so rows above val rowsAbove = it.first + 1 return rowsAbove * multiplier } ?: 0 } private fun isMirror(it: Pair<Int, Int>, grid: List<String>): Boolean { val (a, b) = it if (a < 0 || b >= grid.size) { return true } return grid[a] == grid[b] && isMirror(a - 1 to b + 1, grid) } /** * Return the rows in which there is a line of exactness */ private fun findLinesOfExactness(grid: List<String>): List<Pair<Int, Int>> { return grid.withIndex().zipWithNext().filter { (a, b) -> a.value == b.value } .map { (a, b) -> a.index to b.index } } fun transpose(grid: List<String>): List<String> { val transposedGrid = List(grid[0].length) { CharArray(grid.size) } for (i in grid.indices) { for (j in grid[0].indices) { transposedGrid[j][i] = grid[i][j] } } return transposedGrid.map { it.joinToString("") } } private fun parseGrids(input: List<String>): List<List<String>> { val emptyIndexes = listOf(-1) + input.withIndex().filter { (_, b) -> b.isBlank() }.map { (i, _) -> i } + listOf(input.size) return emptyIndexes.zipWithNext().map { (a, b) -> input.subList(a + 1, b) } } fun part2(input: List<String>): String { val grids = parseGrids(input) return grids.sumOf { grid -> // Transposed is actually columns val transposedGrid = transpose(grid) scoreSmudged(grid, NORMAL_MULTIPLIER) + scoreSmudged(transposedGrid, TRANSPOSED_MULTIPLIER) }.toString() } private fun scoreSmudged(grid: List<String>, multiplier: Int): Int { val rowsOfMaybeExactness = findLinesOfExactness(grid) + findLinesOffByOne(grid) return rowsOfMaybeExactness.find { isAlmostMirror(it, grid, 0) }?.let { // Normal is rows, so rows above val rowsAbove = it.first + 1 rowsAbove * multiplier } ?: 0 } private fun findLinesOffByOne(grid: List<String>): List<Pair<Int, Int>> { return grid.withIndex().zipWithNext().filter { (a, b) -> isOffByOne(a.value, b.value) } .map { (a, b) -> a.index to b.index } } private fun isAlmostMirror(it: Pair<Int, Int>, grid: List<String>, offByOneCount: Int): Boolean { if (offByOneCount > 1) { return false } val (a, b) = it if (a < 0 || b >= grid.size) { return offByOneCount == 1 } val offByOne = isOffByOne(grid[a], grid[b]) val offByMoreThanOne = !offByOne && grid[a] != grid[b] if (offByMoreThanOne) { return false } val newCount = if (offByOne) { offByOneCount + 1 } else { offByOneCount } return isAlmostMirror(a - 1 to b + 1, grid, newCount) } private fun isOffByOne(a: String, b: String): Boolean { return a.toCharArray().zip(b.toCharArray()) .count { (a, b) -> a != b } == 1 } }
0
Kotlin
0
1
f689f8bbbf1a63fecf66e5e03b382becac5d0025
3,784
kotlin-kringle
Apache License 2.0
src/Day09.kt
dmarmelo
573,485,455
false
{"Kotlin": 28178}
import kotlin.math.absoluteValue private typealias Rope = List<Point2D> private enum class Direction { UP, DOWN, LEFT, RIGHT } fun main() { fun String.toDirection() = when (this) { "U" -> Direction.UP "D" -> Direction.DOWN "L" -> Direction.LEFT "R" -> Direction.RIGHT else -> error("Unknown direction $this") } fun List<String>.parseInput() = flatMap { it.split(" ").let { (direction, steps) -> List(steps.toInt()) { direction.toDirection() } } } fun Point2D.move(direction: Direction) = when (direction) { Direction.UP -> copy(y = y + 1) Direction.DOWN -> copy(y = y - 1) Direction.LEFT -> copy(x = x - 1) Direction.RIGHT -> copy(x = x + 1) } infix fun Point2D.follow(other: Point2D): Point2D { val (diffX, diffY) = other - this return if (diffX.absoluteValue <= 1 && diffY.absoluteValue <= 1) this else copy( x = x + diffX.coerceIn(-1..1), y = y + diffY.coerceIn(-1..1) ) } infix fun Rope.move(direction: Direction): Rope { val head = first().move(direction) val tail = drop(1) return tail.fold(listOf(head)) { rope, position -> rope + (position follow rope.last()) } } fun List<Direction>.moveRope(rope: Rope) = runningFold(rope) { previousPosition, direction -> previousPosition move direction } fun List<Direction>.getTailPositions(rope: Rope) = moveRope(rope).map { it.last() }.toSet() fun part1(input: List<Direction>): Int { return input.getTailPositions(List(2) { Point2D(0, 0) }).size } fun part2(input: List<Direction>): Int { return input.getTailPositions(List(10) { Point2D(0, 0) }).size } // test if implementation meets criteria from the description, like: val testInput = readInput("Day09_test").parseInput() check(part1(testInput) == 13) check(part2(testInput) == 1) val input = readInput("Day09").parseInput() println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
5d3cbd227f950693b813d2a5dc3220463ea9f0e4
2,135
advent-of-code-2022
Apache License 2.0
src/main/kotlin/com/hj/leetcode/kotlin/problem542/Solution.kt
hj-core
534,054,064
false
{"Kotlin": 619841}
package com.hj.leetcode.kotlin.problem542 /** * LeetCode page: [542. 01 Matrix](https://leetcode.com/problems/01-matrix/); */ class Solution { /* Complexity: * Time O(MN) and Space O(MN) where M and N are the number of rows and columns in mat; */ fun updateMatrix(mat: Array<IntArray>): Array<IntArray> { val result = Array(mat.size) { row -> IntArray(mat[row].size) { Int.MAX_VALUE } } val queue = ArrayDeque<Cell>() // Base cases are all zero-cells searchZeroCells(mat) { zeroCell -> result[zeroCell.row][zeroCell.column] = 0 queue.addLast(zeroCell) } // Update the distance of each one-cell through relaxation while (queue.isNotEmpty()) { relaxFirst(queue, mat, result) } return result } private data class Cell(val row: Int, val column: Int) private inline fun searchZeroCells(mat: Array<IntArray>, onZeroCell: (zeroCell: Cell) -> Unit) { for (row in mat.indices) { for (column in mat[row].indices) { if (mat[row][column] == 0) { onZeroCell(Cell(row, column)) } } } } private fun relaxFirst( queue: ArrayDeque<Cell>, mat: Array<IntArray>, minDistances: Array<IntArray> // minimum distance to zero of each cell ) { val cell = queue.removeFirst() for (neighbour in cell.neighbours()) { if (neighbour.isOutside(mat)) { continue } if (minDistances.getValue(cell) + 1 < minDistances.getValue(neighbour)) { minDistances.setValue(neighbour, minDistances.getValue(cell) + 1) queue.addLast(neighbour) } } } private fun Cell.neighbours(): List<Cell> = listOf( Cell(row - 1, column), Cell(row + 1, column), Cell(row, column - 1), Cell(row, column + 1) ) private fun Cell.isOutside(mat: Array<IntArray>): Boolean { return row !in mat.indices || column !in mat[row].indices } private fun Array<IntArray>.getValue(cell: Cell): Int { return this[cell.row][cell.column] } private fun Array<IntArray>.setValue(cell: Cell, newValue: Int) { this[cell.row][cell.column] = newValue } }
1
Kotlin
0
1
14c033f2bf43d1c4148633a222c133d76986029c
2,382
hj-leetcode-kotlin
Apache License 2.0
src/main/kotlin/io/steinh/aoc/day04/Scratchcard.kt
daincredibleholg
726,426,347
false
{"Kotlin": 25396}
package io.steinh.aoc.day04 class Scratchcard { fun calculatePoints(lines: List<String>) = getMatchingNumbers(lines).sum() fun calculateNumberOfCardsWon(lines: List<String>): Int { val givenNumberOfCards = lines.size val numberOfCards = initCardStack(givenNumberOfCards) for (line in lines) { val firstSplit = line.split(":") val cardId = firstSplit[0].substringAfter("Card ").trim().toInt() println("Processing card #$cardId:") val instancesOfThisCard = numberOfCards[cardId] println("\texisting instances: $instancesOfThisCard") val numberOfMatches = extractWinningNumbers(firstSplit[1]).size println("\tno. matching numbers: $numberOfMatches") if (numberOfMatches == 0) { println("\tNo matches, continuing to next card. Done processing card #$cardId") continue } val start = cardId + 1 if (start <= givenNumberOfCards) { val end = if (cardId + numberOfMatches < givenNumberOfCards) cardId + numberOfMatches else givenNumberOfCards println("\tWill add $instancesOfThisCard instances to cards ##" + (start..end)) for (i in start..end) { numberOfCards[i] = numberOfCards[i]!! + instancesOfThisCard!! println("\t\tAdded $instancesOfThisCard to card #$i. This card has now ${numberOfCards[i]} " + "instances.") } } println("\tDone processing card $cardId\n") } return numberOfCards .map { it.value } .sum() } private fun initCardStack(givenNumberOfCards: Int): MutableMap<Int, Int> { val result = mutableMapOf<Int, Int>() for (i in 1..givenNumberOfCards) { result[i] = 1 } return result } private fun getMatchingNumbers(lines: List<String>) = buildList { for (line in lines) { val firstSplit = line.split(":") val intersection = extractWinningNumbers(firstSplit[1]) var result = 0 for (i in 1..intersection.size) { result = if (i == 1) 1 else result * 2 } add(result) } } private fun extractWinningNumbers(matchesAndGuesses: String): Set<Int> { val winnersAndGuesses = matchesAndGuesses.split("|") val winners = winnersAndGuesses[0].split(" ") .filter { it.isNotEmpty() } .map { it.toInt() } val guesses = winnersAndGuesses[1].split(" ") .filter { it.isNotEmpty() } .map { it.toInt() } val intersection = winners.intersect(guesses.toSet()) return intersection } } fun main() { val lines = {}.javaClass.classLoader?.getResource("day04/input.txt")?.readText()?.lines()!! val scratchcard = Scratchcard() val resultPart1 = scratchcard.calculatePoints(lines) val resultPart2 = scratchcard.calculateNumberOfCardsWon(lines) println("Result day 04, part I: $resultPart1") println("Result day 04, part II: $resultPart2") }
0
Kotlin
0
0
4aa7c684d0e337c257ae55a95b80f1cf388972a9
3,303
AdventOfCode2023
MIT License
src/year2022/day07/Solution.kt
LewsTherinTelescope
573,240,975
false
{"Kotlin": 33565}
package year2022.day07 import utils.runIt import java.util.LinkedList fun main() = runIt( testInput = """ $ cd / $ ls dir a 14848514 b.txt 8504156 c.dat dir d $ cd a $ ls dir e 29116 f 2557 g 62596 h.lst $ cd e $ ls 584 i $ cd .. $ cd .. $ cd d $ ls 4060174 j 8033020 d.log 5626152 d.ext 7214296 k """.trimIndent(), ::part1, testAnswerPart1 = 95437, ::part2, testAnswerPart2 = 24933642, ) fun part1(input: String) = ConsoleLog(input).parseFolderTree().second .filter { it.size < 100000 } .sumOf { it.size } fun part2(input: String) = ConsoleLog(input) .suggestFolderToClear(targetSize = 30000000, diskSize = 70000000)!! .size sealed interface FileLike { val name: String val parent: Folder? val size: Int } class File( override val name: String, override val parent: Folder?, override val size: Int, ) : FileLike class Folder( override val name: String, override val parent: Folder?, val children: MutableList<FileLike>, ) : FileLike { override val size: Int by lazy { children.sumOf { it.size } } } @JvmInline value class ConsoleLog(val text: String) /** returns root + flat set of all folders */ fun ConsoleLog.parseFolderTree(): Pair<Folder, List<Folder>> { val root = Folder("", parent = null, LinkedList()) val all = LinkedList<Folder>().apply { add(root) } // drop "cd /" because we always start from root text.lines().drop(1).fold(root) { oldCwd, line -> val parts = line.split(' ') val (first, second) = parts var cwd = oldCwd when (first) { "$" -> when (second) { "cd" -> cwd = when (val target = parts[2]) { ".." -> cwd.parent!! else -> cwd.children.first { it.name == target } as Folder } } "dir" -> { val newFolder = Folder(second, cwd, LinkedList()) cwd.children += newFolder all += newFolder } else -> { cwd.children += File(second, cwd, first.toInt()) } } return@fold cwd } return root to all } fun ConsoleLog.suggestFolderToClear( targetSize: Int, diskSize: Int, ) = parseFolderTree().let { (root, all) -> val freeDiskSize = diskSize - root.size val sizeToClear = targetSize - freeDiskSize all.filter { it.size > sizeToClear }.minByOrNull { it.size } }
0
Kotlin
0
0
ee18157a24765cb129f9fe3f2644994f61bb1365
2,225
advent-of-code-kotlin
Do What The F*ck You Want To Public License
src/Day05.kt
astrofyz
572,802,282
false
{"Kotlin": 124466}
import java.io.File fun main() { class MyStack { var crates = mutableListOf<Char>() } fun MyStack.remove(n: Int): MutableList<Char>{ val removedCrates = this.crates.subList(this.crates.size-n, this.crates.size) this.crates = this.crates.subList(0, this.crates.size-n) return removedCrates } fun MyStack.add(newCrates: MutableList<Char>) { this.crates.addAll(newCrates.asReversed()) } fun MyStack.add9001(newCrates: MutableList<Char>) { this.crates.addAll(newCrates) } fun parseInput(lines: String): Pair<List<MyStack>, List<String>> { val stuff = lines.split("\n\n")[0].split("\n").dropLast(1).reversed() val rules = lines.split("\n\n")[1].split("\n") val numberOfStacks = stuff[0].count { it.isLetter() } val stacks: List<MyStack> = List(numberOfStacks) { MyStack() } stuff.forEach{line -> line.chunked(4) .map{ it.filter { elem -> elem.isLetter() }} .mapIndexed{idx, it -> when(it.isEmpty()){ true -> 0 else -> stacks[idx].add(mutableListOf(it[0])) } } } return Pair(stacks, rules) } // fun List<MyStack>.printUpdated(){ // for (stack in this){ // println(stack.crates) // } // } fun part1(input: String): String { val (stacks, rules) = parseInput(input) rules.forEach{rule -> val numberOfStacks = rule.split(" ")[1].toInt() val moveFrom = rule.split(" ")[3].toInt() - 1 val moveTo = rule.split(" ")[5].toInt() - 1 stacks[moveTo].add(stacks[moveFrom].remove(numberOfStacks)) } return stacks.map { it.crates[it.crates.size-1] }.joinToString("") } fun part2(input: String): String { val (stacks, rules) = parseInput(input) rules.forEach {rule -> val numberOfStacks = rule.split(" ")[1].toInt() val moveFrom = rule.split(" ")[3].toInt() - 1 val moveTo = rule.split(" ")[5].toInt() - 1 stacks[moveTo].add9001(stacks[moveFrom].remove(numberOfStacks)) } return stacks.map { it.crates[it.crates.size-1] }.joinToString("") } // 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
a0bc190b391585ce3bb6fe2ba092fa1f437491a6
2,661
aoc22
Apache License 2.0
src/main/kotlin/day04_squid_bingo/SquidBingo.kt
barneyb
425,532,798
false
{"Kotlin": 238776, "Shell": 3825, "Java": 567}
package day04_squid_bingo /** * Our first non-homogenous input: the first line is the called balls while the * rest is a series of multi-line segments. We also have a bunch of parallel * compound states (the boards) to manage as we iterate through an "unrelated" * series of items (the balls). And, of course, the first "do spacial things" - * finding rows and cols - on the 2D plane. * * Part two requires iteratively narrowing collection, and also a nice fencepost * problem. Can't just identify the last board to win, you have to keep playing * until it has actually won. */ fun main() { util.solve(16716, ::partOne) util.solve(4880, ::partTwo) } private class Board(numbers: List<Int>) { private val board: IntArray init { assert(numbers.size == 25) board = numbers.toIntArray() } fun markDrawn(drawn: Int) { val idx = board.indexOf(drawn) if (idx < 0) return board[idx] = -1 } fun hasWon(): Boolean { for (r in 0 until 5) { if (((r * 5) until (r * 5 + 5)).all { board[it] < 0 }) return true } for (c in 0 until 5) { if ((c until 25 step 5).all { board[it] < 0 }) return true } return false } fun sumOfUnmarked() = board .asSequence() .filter { it >= 0 } .sum() } private val RE_SPACES = " +".toRegex() private fun String.toBallsAndBoards(): Pair<List<Int>, List<Board>> { val lines = lines() val balls = lines .first() .split(',') .map(String::toInt) val boards = lines .drop(1) .chunked(6) .map { board -> board .flatMap { line -> line .split(RE_SPACES) .filter(String::isNotBlank) .map(String::toInt) } } .map(::Board) return Pair(balls, boards) } fun partOne(input: String): Int { val (balls, boards) = input.toBallsAndBoards() balls.forEach { ball -> boards.forEach { board -> board.markDrawn(ball) if (board.hasWon()) { return ball * board.sumOfUnmarked() } } } throw IllegalStateException("No winning board found?!") } fun partTwo(input: String): Int { val (balls, allBoards) = input.toBallsAndBoards() balls.fold(allBoards) { boards, ball -> boards.forEach { it.markDrawn(ball) } if (boards.size == 1 && boards.first().hasWon()) { return ball * boards.first().sumOfUnmarked() } boards.filter { !it.hasWon() } } throw IllegalStateException("No winning board found?!") }
0
Kotlin
0
0
a8d52412772750c5e7d2e2e018f3a82354e8b1c3
2,802
aoc-2021
MIT License
src/day04/Day04.kt
martin3398
572,166,179
false
{"Kotlin": 76153}
package day04 import readInput typealias Day04InputType1 = List<Pair<Pair<Int, Int>, Pair<Int, Int>>> fun main() { fun fullyOverlaps(fst: Pair<Int, Int>, snd: Pair<Int, Int>): Boolean = (fst.first <= snd.first && fst.second >= snd.second) || (fst.first >= snd.first && fst.second <= snd.second) fun overlaps(fst: Pair<Int, Int>, snd: Pair<Int, Int>): Boolean = (fst.first >= snd.first && fst.first <= snd.second) || (fst.second >= snd.first && fst.second <= snd.second) || fullyOverlaps(fst, snd) fun part1(input: Day04InputType1): Int = input.map { if (fullyOverlaps(it.first, it.second)) 1 else 0 }.sum() fun part2(input: Day04InputType1): Int = input.map { if (overlaps(it.first, it.second)) 1 else 0 }.sum() fun preprocess(input: List<String>): Day04InputType1 = input.map { val split = it.split(",") val split0 = split[0].split("-") val split1 = split[1].split("-") Pair(Pair(split0[0].toInt(), split0[1].toInt()), Pair(split1[0].toInt(), split1[1].toInt())) } // test if implementation meets criteria from the description, like: val testInput = readInput(4, true) check(part1(preprocess(testInput)) == 2) val input = readInput(4) println(part1(preprocess(input))) check(part2(preprocess(testInput)) == 4) println(part2(preprocess(input))) }
0
Kotlin
0
0
4277dfc11212a997877329ac6df387c64be9529e
1,414
advent-of-code-2022
Apache License 2.0
src/main/kotlin/aoc2022/Day21.kt
w8mr
572,700,604
false
{"Kotlin": 140954}
package aoc2022 import aoc.parser.* class Day21() { enum class Operation(val text: String, val function: (Double, Double) -> Double){ PLUS("+", Double::plus), MINUS("-", Double::minus), TIMES("*", Double::times), DIV("/", Double::div) } sealed interface Monkey{ val name: String } data class NumberMonkey(override val name: String, val number: Double) : Monkey data class OperationMonkey(override val name: String, val monkey1: String, val operation: Operation, val monkey2: String) : Monkey val operation = byEnum(Operation::class, Operation::text) val numberMonkey = seq(word() followedBy ": ", number() map { it.toDouble()}, ::NumberMonkey) val operationMonkey = seq(word() followedBy ": ", word() followedBy " ", operation followedBy " ", word(), ::OperationMonkey) val monkey = numberMonkey or operationMonkey followedBy "\n" val parser = zeroOrMore(monkey)// map { it.associateBy(Monkey::name)} private fun solve( parsed: List<Monkey>, human: Double? = null ): MutableMap<String, NumberMonkey> { val (known, unknown) = parsed.partition { it is NumberMonkey } val knownMap = known.associateBy(Monkey::name).mapValues { it.value as NumberMonkey }.toMutableMap() if (human!=null) knownMap["humn"] = NumberMonkey("humn", human) val unknownMut = unknown.map { it as OperationMonkey }.toMutableList() while (unknownMut.isNotEmpty()) { val removable = mutableListOf<OperationMonkey>() unknownMut.forEach { monkey -> if ((monkey.monkey1 in knownMap) && (monkey.monkey2 in knownMap)) { val number1 = knownMap.getValue(monkey.monkey1).number val number2 = knownMap.getValue(monkey.monkey2).number val number = monkey.operation.function(number1, number2) removable.add(monkey) knownMap.put(monkey.name, NumberMonkey(monkey.name, number)) } } unknownMut.removeAll(removable) } // println(knownMap) return knownMap } fun part1(input: String): Long { val parsed = parser.parse(input) val knownMap = solve(parsed) return knownMap.getValue("root").number.toLong() } fun part2(input: String): Long { val parsed = parser.parse(input) val root = parsed.find { it.name == "root" }!! as OperationMonkey val monkeySearch = (root).monkey1 val searchKnownMap = solve(parsed) val search = searchKnownMap.getValue((root).monkey2).number // println(search) var low = 0.0 var high = searchKnownMap.getValue("humn").number fun test(test: Double) = solve(parsed, test).getValue(monkeySearch).number - search var diff = test(high) while(diff>=0) { // println("$diff $low $high") low = high high = high * 2 diff = test(high) } while(true) { // println("$diff $low $high") val mid = (low + high) / 2 diff = test(mid) when { diff > 0L -> low = mid diff < 0L -> high = mid else -> return mid.toLong() } } } } /* prrg=NumberMonkey(name=prrg, number=59078404922637) jntz=NumberMonkey(name=jntz, number=28379346560301) */
0
Kotlin
0
0
e9bd07770ccf8949f718a02db8d09daf5804273d
3,461
aoc-kotlin
Apache License 2.0
src/main/kotlin/day18/day18.kt
corneil
572,437,852
false
{"Kotlin": 93311, "Shell": 595}
package day18 import main.utils.filterUnique import main.utils.scanInts import utils.checkNumber import utils.readFile import utils.readLines import utils.separator import kotlin.math.round import kotlin.math.sqrt fun main() { val test = readLines( """2,2,2 1,2,2 3,2,2 2,1,2 2,3,2 2,2,1 2,2,3 2,2,4 2,2,6 1,2,5 3,2,5 2,1,5 2,3,5""" ) val input = readFile("day18") data class Coord3D(val x: Int, val y: Int, val z: Int) : Comparable<Coord3D> { val surrounds: Set<Coord3D> by lazy { setOf( copy(x = x - 1), copy(x = x + 1), copy(y = y - 1), copy(y = y + 1), copy(z = z - 1), copy(z = z + 1) ) } operator fun minus(other: Coord3D) = Coord3D(x - other.x, y - other.y, z - other.z) operator fun plus(other: Coord3D) = Coord3D(x + other.x, y + other.y, z + other.z) override fun compareTo(other: Coord3D): Int { val diff = this - other val square = (diff.x * diff.x) + (diff.y * diff.y) + (diff.z * diff.z) val sq = round(sqrt(square.toDouble())).toInt() return 0.compareTo(sq) } override fun toString(): String { return "Coord3D($x,$y,$z)" } } class Lava(val cubes: List<Coord3D>) { private val cubeSet = cubes.toSet() private val allXCaches = mutableMapOf<Pair<Int, Int>, List<Int>>() private val allYCaches = mutableMapOf<Pair<Int, Int>, List<Int>>() private val allZCaches = mutableMapOf<Pair<Int, Int>, List<Int>>() fun getAllX(y: Int, z: Int): List<Int> = allXCaches.getOrPut(Pair(y, z)) { cubes.filter { it.y == y && it.z == z }.map { it.x }.sorted() } fun getAllY(x: Int, z: Int): List<Int> = allYCaches.getOrPut(Pair(x, z)) { cubes.filter { it.x == x && it.z == z }.map { it.y }.sorted() } fun getAllZ(x: Int, y: Int): List<Int> = allZCaches.getOrPut(Pair(x, y)) { cubes.filter { it.x == x && it.y == y }.map { it.z }.sorted() } fun hasCube(loc: Coord3D) = cubeSet.contains(loc) fun isInside(loc: Coord3D): Boolean { if (hasCube(loc)) return true val allZ = getAllZ(loc.x, loc.y) if (allZ.isEmpty()) return false val allY = getAllY(loc.x, loc.z) if (allY.isEmpty()) return false val allX = getAllX(loc.y, loc.z) return allX.isNotEmpty() && loc.z in allZ.min()..allZ.max() && loc.x in allX.min()..allX.max() && loc.y in allY.min()..allY.max() } fun outSide(): List<Coord3D> { return cubes.flatMap { cube -> cube.surrounds.filter { !isInside(it) } }.filterUnique().toList() } val minX: Int = cubes.minOf { it.x } val minY: Int = cubes.minOf { it.y } val minZ: Int = cubes.minOf { it.z } val maxX: Int = cubes.maxOf { it.x } val maxY: Int = cubes.maxOf { it.y } val maxZ: Int = cubes.maxOf { it.z } val width: Int = maxX - minX val height: Int = maxY - minY val depth: Int = maxZ - minZ fun printCube(screen: Int = 0) { val columns = screen / width var col = 0 println("== Cube: Depth=$depth, Height=$height, Width=$width ==") for (z in minZ..maxZ) { println() println("---- Z = %02d --------".format(z)) col = 0 for (y in minY..maxY) { print("%02d ".format(y)) for (x in minX..maxX) { val loc = Coord3D(x, y, z) if (hasCube(loc)) { print('#') } else { if (isInside(loc)) { print('.') } else { print(' ') } } } print(' ') col++ if (col >= columns) { col = 0 println() } } } println() separator() } fun operateInside(operate: (Coord3D) -> Unit) { for (x in minX..maxX) { for (y in minY..maxY) { for (z in minZ..maxZ) { val loc = Coord3D(x, y, z) if (isInside(loc)) { operate(loc) } } } } } fun iterateInside(): Iterable<Coord3D> = (minX..maxX).flatMap { x -> (minY..maxY).flatMap { y -> (minZ..maxZ).mapNotNull { z -> val loc = Coord3D(x, y, z) if (isInside(loc)) loc else null } } } fun surfaceArea(): Int = cubes.sumOf { cube -> val surrounds = cube.surrounds surrounds.size - surrounds.count { hasCube(it) } } } fun scanLava(input: List<String>): List<Coord3D> = input.map { line -> val (x, y, z) = line.scanInts() Coord3D(x, y, z) } fun calcSolution1(input: List<String>): Int { return Lava(scanLava(input).toList()).surfaceArea() } fun createFilled(lavaCubes: List<Coord3D>): Lava { val lava = Lava(lavaCubes) val airPockets = mutableSetOf<Coord3D>() airPockets.addAll(lavaCubes) val lockedAir = lava.iterateInside().filter { loc -> !lava.hasCube(loc) && loc.surrounds.none { !lava.hasCube(it) && !lava.isInside(it) } } airPockets.addAll(lockedAir) println("Air Pockets = ${airPockets.size}") val filled = Lava(airPockets.toList()) println("Filled has ${filled.cubes.size} blocks") return filled } fun calcSolution2(input: List<String>): Int { val lava = createFilled(scanLava(input)) println("Total blocks = ${lava.cubes.size}") return lava.surfaceArea() } fun part1() { val testResult = calcSolution1(test) println("Part 1 Test Answer = $testResult") checkNumber(testResult, 64) val result = calcSolution1(input) println("Part 1 Answer = $result") checkNumber(result, 4242) } fun part2() { val testResult = calcSolution2(test) println("Part 2 Test Answer = $testResult") checkNumber(testResult, 58) val result = calcSolution2(input) println("Part 2 Answer = $result") checkNumber(result, 2428) } println("Day - 18") part1() part2() }
0
Kotlin
0
0
dd79aed1ecc65654cdaa9bc419d44043aee244b2
6,012
aoc-2022-in-kotlin
Apache License 2.0
2021/src/main/kotlin/day18.kt
madisp
434,510,913
false
{"Kotlin": 388138}
import utils.Parser import utils.Solution import utils.mapItems fun main() { Day18Func.run() } object Day18Func : Solution<List<Day18Func.Tree>>() { override val name = "day18" override val parser = Parser.lines.mapItems { Tree.from(it).first } override fun part1(input: List<Tree>): Int { val sum = input.reduce { acc, tree -> (acc + tree).reduce() } return sum.magnitude } override fun part2(input: List<Tree>): Int { return input.flatMap { a -> input.flatMap { b -> listOf((a + b).reduce(), (b + a).reduce()) } }.maxOf { it.magnitude } } sealed interface Tree { operator fun plus(other: Tree) = Branch(this, other) val magnitude: Int fun explode(depth: Int = 4): Pair<Tree, Pair<Int?, Int?>?> fun split(): Pair<Tree, Boolean> fun reduceOnce(): Pair<Tree, Boolean> fun reduce(): Tree { return generateSequence(this) { it.reduceOnce().takeIf { it.second }?.first } .last() } fun addFirstLeft(value: Int): Pair<Tree, Int?> fun addFirstRight(value: Int): Pair<Tree, Int?> companion object { fun from(string: String): Pair<Tree, Int> { if (string[0].isDigit()) { // find last digit val len = minOf( string.indexOf(',').takeIf { it > 0 } ?: Integer.MAX_VALUE, string.indexOf(']').takeIf { it > 0 } ?: Integer.MAX_VALUE, string.length ) return Node(string.substring(0, len).toInt()) to len } else if (string[0] != '[') { bad(string, 0) } val (left, leftSize) = from(string.substring(1)) if (string[1 + leftSize] != ',') { bad(string, 1+ leftSize) } val (right, rightSize) = from(string.substring(leftSize + 2)) return Branch(left, right) to leftSize + rightSize + 3 } private fun bad(string: String, col: Int) { throw IllegalArgumentException("Bad input at '${string.substring(col..minOf(col + 6, string.length))}'") } } } data class Node(val value: Int): Tree { override val magnitude = value override fun explode(depth: Int) = this to null override fun split(): Pair<Tree, Boolean> { return if (value >= 10) { Branch(Node(value / 2), Node((value + 1) / 2)) to true } else this to false } override fun addFirstLeft(value: Int): Pair<Tree, Int?> { return Node(this.value + value) to null } override fun addFirstRight(value: Int): Pair<Tree, Int?> { return Node(this.value + value) to null } override fun reduceOnce(): Pair<Tree, Boolean> { return this to false } override fun toString() = value.toString() } data class Branch(val left: Tree, val right: Tree): Tree { override val magnitude: Int get() = left.magnitude * 3 + right.magnitude * 2 override fun reduceOnce(): Pair<Tree, Boolean> { val (exploded, pair) = explode() if (pair != null) { return exploded to true } return split() } override fun explode(depth: Int): Pair<Tree, Pair<Int?, Int?>?> { if (depth == 0) { if (left !is Node || right !is Node) { throw IllegalStateException("Unexpected branch $this at this depth!") } return Node(0) to (left.value to right.value) } else { val (newLeft, leftPair) = left.explode(depth - 1) if (leftPair != null) { if (leftPair.second != null) { val (newRight, rightValue) = right.addFirstLeft(leftPair.second!!) return Branch(newLeft, newRight) to leftPair.copy(second = rightValue) } return Branch(newLeft, right) to leftPair } val (newRight, rightPair) = right.explode(depth - 1) if (rightPair != null) { if (rightPair.first != null) { val (newLeft, leftValue) = left.addFirstRight(rightPair.first!!) return Branch(newLeft, newRight) to rightPair.copy(first = leftValue) } return Branch(left, newRight) to rightPair } return this to null } } override fun split(): Pair<Tree, Boolean> { val (newLeft, leftDidSplit) = left.split() if (leftDidSplit) { return Branch(newLeft, right) to true } val (newRight, rightDidSplit) = right.split() return Branch(left, newRight) to rightDidSplit } override fun addFirstLeft(value: Int): Pair<Tree, Int?> { val added = left.addFirstLeft(value) return Branch(added.first, right) to added.second } override fun addFirstRight(value: Int): Pair<Tree, Int?> { val added = right.addFirstRight(value) return Branch(left, added.first) to added.second } override fun toString() = "[$left,$right]" } }
0
Kotlin
0
1
3f106415eeded3abd0fb60bed64fb77b4ab87d76
4,810
aoc_kotlin
MIT License
src/main/kotlin/day8.kt
gautemo
433,582,833
false
{"Kotlin": 91784}
import shared.getLines fun findNumbers(input: List<String>): Int{ var one = 0 var four = 0 var seven = 0 var eight = 0 for(line in input){ val output = line.split("|").last().trim().split(" ") one += output.count { it.length == 2 } four += output.count { it.length == 4 } seven += output.count { it.length == 3 } eight += output.count { it.length == 7 } } return one + four + seven + eight } fun findOutputSum(input: List<String>): Int{ var sum = 0 for (line in input){ val (patterns, output) = line.split("|").map { it.trim().split(" ") } sum += outputValue(patterns, output) } return sum } fun outputValue(patterns: List<String>, output: List<String>): Int{ val map = mutableMapOf( Pair('a', mutableListOf('a','b','c','d','e','f','g')), Pair('b', mutableListOf('a','b','c','d','e','f','g')), Pair('c', mutableListOf('a','b','c','d','e','f','g')), Pair('d', mutableListOf('a','b','c','d','e','f','g')), Pair('e', mutableListOf('a','b','c','d','e','f','g')), Pair('f', mutableListOf('a','b','c','d','e','f','g')), Pair('g', mutableListOf('a','b','c','d','e','f','g')), ) while(!map.values.all { it.size == 1 }){ val foundOne = map['c']!!.size <= 2 && map['f']!!.size <= 2 for(pattern in patterns){ when{ pattern.length == 2 -> { map['c']!!.removeIf { possibility -> pattern.none { it == possibility } } map['f']!!.removeIf { possibility -> pattern.none { it == possibility } } } pattern.length == 3 && foundOne -> { val a = pattern.filterNot { map['c']!!.contains(it) || map['f']!!.contains(it) } map['a']!!.removeIf { !a.contains(it) } } pattern.length == 4 && map['d']!!.size == 1 && foundOne -> { val b = pattern.filterNot { map['d']!!.contains(it) || map['c']!!.contains(it) || map['f']!!.contains(it) } map['b']!!.removeIf { !b.contains(it) } } pattern.length == 4 -> { map['b']!!.removeIf { possibility -> pattern.none { it == possibility } } map['c']!!.removeIf { possibility -> pattern.none { it == possibility } } map['d']!!.removeIf { possibility -> pattern.none { it == possibility } } map['f']!!.removeIf { possibility -> pattern.none { it == possibility } } } pattern.length == 5 && foundOne -> { if(map['a']!!.size == 1){ val dg = pattern.filterNot { map['a']!!.contains(it) || map['c']!!.contains(it) || map['f']!!.contains(it) } map['d']!!.removeIf { !dg.contains(it) } map['g']!!.removeIf { !dg.contains(it) } } if(map['b']!!.size == 1 && pattern.contains(map['b']!!.first())){ map['f']!!.removeIf { !pattern.contains(it) } } } } } for(option in map){ if(option.value.size == 1){ map.filter { it.key != option.key }.forEach { (_, value) -> value.removeIf { it == option.value.first() } } } } } return output.map { val a = it.contains(map['a']!!.first()) val b = it.contains(map['b']!!.first()) val c = it.contains(map['c']!!.first()) val d = it.contains(map['d']!!.first()) val e = it.contains(map['e']!!.first()) val f = it.contains(map['f']!!.first()) val g = it.contains(map['g']!!.first()) if(a && b && c && !d && e && f && g) return@map '0' if(!a && !b && c && !d && !e && f && !g) return@map '1' if(a && !b && c && d && e && !f && g) return@map '2' if(a && !b && c && d && !e && f && g) return@map '3' if(!a && b && c && d && !e && f && !g) return@map '4' if(a && b && !c && d && !e && f && g) return@map '5' if(a && b && !c && d && e && f && g) return@map '6' if(a && !b && c && !d && !e && f && !g) return@map '7' if(a && b && c && d && e && f && g) return@map '8' '9' }.joinToString("").toInt() } fun main(){ val input = getLines("day8.txt") val task1 = findNumbers(input) println(task1) val task2 = findOutputSum(input) println(task2) }
0
Kotlin
0
0
c50d872601ba52474fcf9451a78e3e1bcfa476f7
4,543
AdventOfCode2021
MIT License
advent-of-code2015/src/main/kotlin/day17/Advent17.kt
REDNBLACK
128,669,137
false
null
package day17 import combinations import parseInput import splitToLines /** --- Day 17: No Such Thing as Too Much --- The elves bought too much eggnog again - 150 liters this time. To fit it all into your refrigerator, you'll need to move it into smaller containers. You take an inventory of the capacities of the available containers. For example, suppose you have containers of size 20, 15, 10, 5, and 5 liters. If you need to store 25 liters, there are four ways to do it: 15 and 10 20 and 5 (the first 5) 20 and 5 (the second 5) 15, 5, and 5 Filling all containers entirely, how many different combinations of containers can exactly fit all 150 liters of eggnog? --- Part Two --- While playing with all the containers in the kitchen, another load of eggnog arrives! The shipping and receiving department is requesting as many containers as you can spare. Find the minimum number of containers that can exactly fit all 150 liters of eggnog. How many different ways can you fill that number of containers and still hold exactly 150 litres? In the example above, the minimum number of containers was two. There were three ways to use that many containers, and so the answer there would be 3. */ fun main(args: Array<String>) { val test = """ |5 |5 |10 |15 |20 """.trimMargin() val input = parseInput("day17-input.txt") println(findCombinations(test, 25)) println(findCombinations(input, 150)) } fun findCombinations(input: String, liters: Int): Map<String, Int?> { val containers = input.splitToLines().map(String::toInt) val ways = (1..containers.size) .map { i -> containers.combinations(i) .filter { it.sum() == liters } .count() } .filter { it != 0 } return mapOf("total" to ways.sum(), "minimal" to ways.dropLast(1).min()) }
0
Kotlin
0
0
e282d1f0fd0b973e4b701c8c2af1dbf4f4a149c7
1,965
courses
MIT License
src/Day13.kt
wgolyakov
572,463,468
false
null
import kotlin.math.max fun main() { var index = 0 fun parseList(input: String): List<Any> { if (input[index] != '[') error("Wrong input: $index") index++ val list = mutableListOf<Any>() while (index < input.length) { val c = input[index] if (c == '[') { list.add(parseList(input)) } else if (c == ']') { index++ return list } else if (c == ',') { index++ } else if (c.isDigit()) { var i = index + 1 while (input[i].isDigit()) i++ val num = input.substring(index, i).toInt() list.add(num) index = i } } return list } fun parseInput(input: List<String>): List<Pair<List<Any>, List<Any>>> { val pairs = mutableListOf<Pair<List<Any>, List<Any>>>() for (i in input.indices step 3) { index = 0 val list1 = parseList(input[i]) index = 0 val list2 = parseList(input[i + 1]) pairs.add(list1 to list2) } return pairs } class ListComparator: Comparator<List<Any>> { override fun compare(o1: List<Any>, o2: List<Any>): Int { for (i in 0 until max(o1.size, o2.size)) { if (i >= o1.size) return -1 if (i >= o2.size) return 1 val a1 = o1[i] val a2 = o2[i] if (a1 is Int) { if (a2 is Int) { if (a1 < a2) return -1 if (a1 > a2) return 1 } else { val c = compare(listOf(a1), a2 as List<Any>) if (c != 0) return c } } else { if (a2 is Int) { val c = compare(a1 as List<Any>, listOf(a2)) if (c != 0) return c } else { val c = compare(a1 as List<Any>, a2 as List<Any>) if (c != 0) return c } } } return 0 } } fun part1(input: List<String>): Int { val pairs = parseInput(input) val comparator = ListComparator() return pairs.withIndex() .filter { comparator.compare(it.value.first, it.value.second) <= 0 }.sumOf { it.index + 1 } } fun part2(input: List<String>): Int { val pairs = parseInput(input) val list = mutableListOf<List<Any>>() for (pair in pairs) { list.add(pair.first) list.add(pair.second) } val divider1 = listOf(listOf(2)) val divider2 = listOf(listOf(6)) list.add(divider1) list.add(divider2) list.sortWith(ListComparator()) return (list.indexOf(divider1) + 1) * (list.indexOf(divider2) + 1) } val testInput = readInput("Day13_test") check(part1(testInput) == 13) check(part2(testInput) == 140) val input = readInput("Day13") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
789a2a027ea57954301d7267a14e26e39bfbc3c7
2,432
advent-of-code-2022
Apache License 2.0
src/main/kotlin/com/colinodell/advent2023/Day23.kt
colinodell
726,073,391
false
{"Kotlin": 114923}
package com.colinodell.advent2023 class Day23(input: List<String>) { private val trails = input.toGrid() private val region = trails.region() private val start = trails.region().topLeft + Vector2(1, 0) private val end = trails.region().bottomRight - Vector2(1, 0) private fun getNeighborsConsideringSlopes(pos: Vector2): Collection<Vector2> { if (trails[pos] == 'v') return listOf(pos + Direction.SOUTH.vector()) if (trails[pos] == '^') return listOf(pos + Direction.NORTH.vector()) if (trails[pos] == '<') return listOf(pos + Direction.WEST.vector()) if (trails[pos] == '>') return listOf(pos + Direction.EAST.vector()) return pos.neighbors() } private fun isTrail(pos: Vector2) = pos in region && trails[pos] != '#' private fun isFork(pos: Vector2) = isTrail(pos) && pos.neighbors().count { isTrail(it) } > 2 private fun findForks() = buildSet { add(start) addAll(trails.keys.filter { isFork(it) }) add(end) } private fun findDistancesBetweenForks(forks: Set<Vector2>): Map<Vector2, Map<Vector2, Int>> { val ret = forks.associateWith { mutableMapOf<Vector2, Int>() } for (fork in forks) { var positions = setOf(fork) val visited = mutableSetOf(fork) var distance = 0 while (positions.isNotEmpty()) { distance++ positions = buildSet { positions.forEach { p -> p.neighbors().filter { isTrail(it) && it !in visited }.forEach { n -> visited.add(n) if (n in forks) { ret[fork]!![n] = distance } else { add(n) } } } } } } return ret } private fun <State> findLongestPathLength( start: State, reachedEnd: (State) -> Boolean, nextStates: (State) -> Map<State, Int>, visited: List<State> = emptyList(), distance: Int = 0, ): Int { if (reachedEnd(start)) { return distance } val next = nextStates(start) .filter { it.key !in visited } .map { pos -> findLongestPathLength(pos.key, reachedEnd, nextStates, visited + start, distance + pos.value) } .maxByOrNull { it } return next ?: 0 } fun solvePart1() = findLongestPathLength( start = start, reachedEnd = { it == end }, nextStates = { pos -> getNeighborsConsideringSlopes(pos).filter { isTrail(it) }.associateWith { 1 } }, ) fun solvePart2(): Int { val simplified = findDistancesBetweenForks(findForks()) return findLongestPathLength( start = start, reachedEnd = { it == end }, nextStates = { pos -> simplified[pos]!! }, ) } }
0
Kotlin
0
0
97e36330a24b30ef750b16f3887d30c92f3a0e83
3,031
advent-2023
MIT License
src/Day05.kt
mpylypovych
572,998,434
false
{"Kotlin": 6455}
fun main() { fun solve(input: List<String>, pred : (MutableList<ArrayDeque<Char>>, Int, Int, Int) -> Unit) : String { val numLine = input.indexOfFirst { it.contains('1') } val stacksCount = input[numLine].split(' ').last { it.isNotEmpty() }.toInt() // assuming the stacks count is single-digit val stacks = mutableListOf<ArrayDeque<Char>>() for(i in 0 until stacksCount) { stacks.add(ArrayDeque()) for (j in numLine - 1 downTo 0) { val c = input[j][1 + i * 4] if (c == ' ') break stacks[i].addLast(c) } } input.subList(numLine + 2, input.size).forEach { val command = it.split(' ') val amount = command[1].toInt() val from = command[3].toInt() - 1 val to = command[5].toInt() - 1 pred(stacks, amount, from, to) } return stacks.map { it.last() }.joinToString(separator = "") } fun part1(input: List<String>) = solve(input) {stacks, amount, from,to -> repeat(amount) { val c = stacks[from].removeLast() stacks[to].addLast(c) } } fun part2(input: List<String>) = solve(input) {stacks, amount, from,to -> stacks[to].addAll(stacks[from].subList(stacks[from].size - amount,stacks[from].size)) repeat(amount) {stacks[from].removeLast()} } 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
733b35c3f4eea777a5f666c804f3c92d0cc9854b
1,642
aoc-2022-in-kotlin
Apache License 2.0
src/main/kotlin/de/nosswald/aoc/days/Day08.kt
7rebux
722,943,964
false
{"Kotlin": 34890}
package de.nosswald.aoc.days import de.nosswald.aoc.Day // https://adventofcode.com/2023/day/8 object Day08 : Day<Long>(8, "<NAME>") { private enum class Direction { LEFT, RIGHT } private fun parseInput(input: List<String>): Pair<List<Direction>, Map<String, Pair<String, String>>> { val directions = input.first().map { if (it == 'L') Direction.LEFT else Direction.RIGHT } val entries = input.drop(2).map { line -> val instruction = line.split(" = ") val (left, right) = instruction .last() .split("(", ")", ", ") .filter(String::isNotBlank) return@map instruction.first() to Pair(left, right) }.toMap() return Pair(directions, entries) } private fun countSteps( from: String, until: (String) -> Boolean, network: Pair<List<Direction>, Map<String, Pair<String, String>>> ): Int { val (directions, entries) = network var current = from var steps = 0 while (!until(current)) { val next = entries[current]!! val dir = directions[steps % directions.size] current = if (dir == Direction.LEFT) next.first else next.second steps++ } return steps } override fun partOne(input: List<String>): Long { return countSteps( from = "AAA", until = { it == "ZZZ" }, parseInput(input) ).toLong() } override fun partTwo(input: List<String>): Long { val network = parseInput(input) return network.second .filter { it.key.last() == 'A' } .map { entry -> countSteps(entry.key, { it.last() == 'Z' }, network) } .map(Int::toBigInteger) .reduce { acc, steps -> acc * steps / acc.gcd(steps) } .toLong() } override val partOneTestExamples: Map<List<String>, Long> = mapOf( listOf( "RL", "", "AAA = (BBB, CCC)", "BBB = (DDD, EEE)", "CCC = (ZZZ, GGG)", "DDD = (DDD, DDD)", "EEE = (EEE, EEE)", "GGG = (GGG, GGG)", "ZZZ = (ZZZ, ZZZ)", ) to 2, listOf( "LLR", "", "AAA = (BBB, BBB)", "BBB = (AAA, ZZZ)", "ZZZ = (ZZZ, ZZZ)", ) to 6 ) override val partTwoTestExamples: Map<List<String>, Long> = mapOf( listOf( "LR", "", "11A = (11B, XXX)", "11B = (XXX, 11Z)", "11Z = (11B, XXX)", "22A = (22B, XXX)", "22B = (22C, 22C)", "22C = (22Z, 22Z)", "22Z = (22B, 22B)", "XXX = (XXX, XXX)", ) to 6 ) }
0
Kotlin
0
1
398fb9873cceecb2496c79c7adf792bb41ea85d7
2,839
advent-of-code-2023
MIT License
src/ad/kata/aoc2021/day12/Graph.kt
andrej-dyck
433,401,789
false
{"Kotlin": 161613}
package ad.kata.aoc2021.day12 import ad.kata.aoc2021.extensions.toMapMerging data class Graph<T>(private val edges: Map<T, Set<T>>) { fun distinctPaths(from: T, to: T, canRevisit: (T, Path<T>) -> Boolean = { _, _ -> false }) = findPaths(from, to, canRevisit = { n, p -> canRevisit(n, p) && n != from }) private fun findPaths( from: T, to: T, path: Path<T> = listOf(from), canRevisit: (T, Path<T>) -> Boolean ): Paths<T> { if (from == to) return setOf(path) val neighbors = adjacentNodesOf(from) - path.filterNot { canRevisit(it, path) }.toSet() return neighbors.flatMap { n -> findPaths(n, to, path + n, canRevisit) }.toHashSet() } private fun adjacentNodesOf(node: T) = edges[node] ?: emptySet() } typealias Edge<T> = Pair<T, T> typealias Path<T> = List<T> typealias Paths<T> = Set<Path<T>> fun <T> unidirectionalGraphOf(edges: List<Edge<T>>) = Graph((edges + edges.reversedEdges()).toMapMerging { it.toHashSet() }) private fun <T> List<Edge<T>>.reversedEdges() = map { (a, b) -> b to a } inline fun <T> unidirectionalGraphOf( edges: List<String>, delimiter: Char = '-', transform: (String) -> T ) = unidirectionalGraphOf( edges.flatMap { it.split(delimiter) .map(transform) .windowed(2) { (a, b) -> a to b } } )
0
Kotlin
0
0
28d374fee4178e5944cb51114c1804d0c55d1052
1,392
advent-of-code-2021
MIT License
src/Day21/Day21.kt
martin3398
436,014,815
false
{"Kotlin": 63436, "Python": 5921}
class Dice(private val sides: Int) { var counter: Int = 0 private set fun roll(): Int { var res = 0 for (i in 1..3) { res += counter % sides + 1 counter++ } return res } } data class Position(val pos0: Int, val score0: Int, val pos1: Int, val score1: Int) fun Position.add(player: Int, roll: Int): Position { return when (player) { 0 -> { val pos0New = (pos0 + roll - 1) % 10 + 1 Position(pos0New, score0 + pos0New, pos1, score1) } 1 -> { val pos1New = (pos0 + roll - 1) % 10 + 1 Position(pos0, score0, pos1New, score1 + pos1New) } else -> { throw IllegalArgumentException() } } } fun Position.swap() = Position(pos1, score1, pos0, score0) fun main() { fun preprocess(input: List<String>): List<Int> { return input.map { it.split(" ").last().toInt() } } fun part1(input: List<Int>): Int { val die = Dice(100) var player = 0 val pos = input.toMutableList() val score = mutableListOf(0, 0) while (score[1 - player] < 1000) { pos[player] = (pos[player] + die.roll() - 1) % 10 + 1 score[player] += pos[player] player = (player + 1) % 2 } return die.counter * score[player] } fun part2(input: List<Int>): Long { val intermediates = HashMap<Position, Array<Long>>() fun doStep(pos: Position): Array<Long> { intermediates[pos]?.also { return it } var res = arrayOf(0L, 0L) for (e0 in 1..3) for (e1 in 1..3) for (e2 in 1..3) { val diceCount = e0 + e1 + e2 val nextPos = pos.add(0, diceCount) if (nextPos.score0 >= 21) { res[0]++ } else { res = res.zip(doStep(nextPos.swap()).reversedArray()) { a, b -> a + b }.toTypedArray() } } intermediates[pos] = res return res } return doStep(Position(input[0], 0, input[1], 0)).maxOf { it } } val testInput = preprocess(readInput(21, true)) val input = preprocess(readInput(21)) check(part1(testInput) == 739785) println(part1(input)) check(part2(testInput) == 444356092776315L) println(part2(input)) }
0
Kotlin
0
0
085b1f2995e13233ade9cbde9cd506cafe64e1b5
2,409
advent-of-code-2021
Apache License 2.0
src/day05/Day05.kt
palpfiction
572,688,778
false
{"Kotlin": 38770}
package day05 import readInput import java.util.Stack typealias CrateStack = Stack<Char> typealias Arrangement = List<CrateStack> typealias Command = Triple<Int, Int, Int> inline fun <reified T> transpose(matrix: List<List<T>>): List<List<T>> { return List(matrix[0].size) { col -> List(matrix.size) { row -> matrix[row][col] } } } fun main() { val arrangementRegex = """.(.).\s?""".toRegex() val commandRegex = """move (\d*) from (\d*) to (\d*)""".toRegex() fun <T> List<T>.toStack(): Stack<T> { val stack = Stack<T>() this.forEach { stack.push(it) } return stack } fun parseLine(line: String): List<Char> { return arrangementRegex.findAll(line) .map { it.groupValues[1] } .map { it[0] } .toList() } fun parseStacks(input: List<String>): Arrangement { val arrangement = input.takeWhile { it.isNotEmpty() } .dropLast(1) .map { parseLine(it) } return transpose(arrangement) .map { it.filter { char -> char != ' ' } .asReversed() .toStack() } } fun parseCommands(input: List<String>): List<Command> = input .dropWhile { it.isNotEmpty() } .drop(1) .map { commandRegex.find(it)!!.groupValues } .map { (_, x, y, z) -> Command(x.toInt(), y.toInt(), z.toInt()) } fun Command.execute(stacks: Arrangement): Arrangement { repeat(this.first) { stacks[this.third - 1].push(stacks[this.second - 1].pop()) } return stacks } fun Command.execute9001(stacks: Arrangement): Arrangement { val crates = mutableListOf<Char>() repeat(this.first) { crates.add(stacks[this.second - 1].pop()) } crates.asReversed() .forEach { stacks[this.third - 1].push(it) } return stacks } fun part1(input: List<String>): String { val stacks = parseStacks(input) val commands = parseCommands(input) var currentArrangement = stacks for (command in commands) { currentArrangement = command.execute(currentArrangement) } return currentArrangement .map { it.last() } .joinToString("", "", "") } fun part2(input: List<String>): String { val stacks = parseStacks(input) val commands = parseCommands(input) var currentArrangement = stacks for (command in commands) { currentArrangement = command.execute9001(currentArrangement) } return currentArrangement .map { it.last() } .joinToString("", "", "") } val testInput = readInput("/day05/Day05_test") parseCommands(testInput) println(part1(testInput)) println(part2(testInput)) check(part1(testInput) == "CMZ") check(part2(testInput) == "MCD") val input = readInput("/day05/Day05") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
5b79ec5fa4116e496cd07f0c7cea7dabc8a371e7
3,117
advent-of-code
Apache License 2.0
src/year2022/day15/Day15.kt
kingdongus
573,014,376
false
{"Kotlin": 100767}
package year2022.day15 import Point2D import readInputFileByYearAndDay import readTestFileByYearAndDay import kotlin.math.abs data class Reading(val signal: Point2D, val closestBeacon: Point2D) { private fun reach(): Int = signal manhattanDistance closestBeacon private fun minReachableY(): Int = signal.y - reach() private fun maxReachableY(): Int = signal.y + reach() infix fun canReachY(toReach: Int): Boolean = if (this.signal.y > toReach) minReachableY() <= toReach else maxReachableY() >= toReach infix fun canReach(other: Point2D): Boolean = (this.signal manhattanDistance other) <= this.reach() infix fun intersectWithY(y: Int): List<Point2D> { if (!(this canReachY y)) return listOf() val dyToY = abs(signal.y - y) val offsetXMin = -(reach() - dyToY) val offsetXMax = reach() - dyToY return Point2D(signal.x + offsetXMin, y)..Point2D(signal.x + offsetXMax, y) } infix fun expandManhattanCircleBy(by: Int): List<Point2D> { val radius = (this.signal manhattanDistance this.closestBeacon) + by val result = mutableListOf<Point2D>() result.addAll( Point2D(this.signal.x, this.signal.y + radius)..Point2D( this.signal.x + radius, this.signal.y ) ) result.addAll( Point2D(this.signal.x + radius, this.signal.y)..Point2D( this.signal.x, this.signal.y - radius ) ) result.addAll( Point2D(this.signal.x, this.signal.y - radius)..Point2D( this.signal.x - radius, this.signal.y ) ) result.addAll( Point2D(this.signal.x - radius, this.signal.y)..Point2D( this.signal.x, this.signal.y + radius ) ) return result.distinct() } } fun main() { val regex = """Sensor at x=(-?\d*), y=(-?\d*): closest beacon is at x=(-?\d*), y=(-?\d*)""".toRegex() // this is much slower than the previous repeated String::split, but looks nicer fun parseReadings(input:List<String>):List<Reading> = input.asSequence() .map { regex.find(it) } .map { Reading( signal = Point2D(it!!.groupValues.get(1).toInt(), it!!.groupValues.get(2).toInt()), closestBeacon = Point2D(it!!.groupValues.get(3).toInt(), it!!.groupValues.get(4).toInt())) } .toList() fun part1(input: List<String>, y: Int): Int = parseReadings(input).let { val beaconsOnTargetDepth = it.map { it.closestBeacon }.filter { it.y == y } val readingsInReach = it.filter { reading -> reading canReachY y } readingsInReach.flatMap { it intersectWithY y } .distinct() .filterNot { beaconsOnTargetDepth.contains(it) } .size } fun part2(input: List<String>, searchSpace: Int): Long = parseReadings(input).let { for (reading in it) { for (candidate in reading.expandManhattanCircleBy(1)) { if (candidate.x < 0 || candidate.y < 0 || candidate.x > searchSpace || candidate.y > searchSpace) continue if (it.any { r -> r canReach candidate }) continue return (candidate.x.toLong() * 4000000) + candidate.y } } return -1 } val testInput = readTestFileByYearAndDay(2022, 15) check(part1(testInput, 10) == 26) check(part2(testInput, 20) == 56000011L) val input = readInputFileByYearAndDay(2022, 15) println(part1(input, 2_000_000)) println(part2(input, 4_000_000)) }
0
Kotlin
0
0
aa8da2591310beb4a0d2eef81ad2417ff0341384
3,731
advent-of-code-kotlin
Apache License 2.0
ceria/03/src/main/kotlin/Solution.kt
VisionistInc
317,503,410
false
null
import java.io.File; val tree :Char = '#' fun main(args : Array<String>) { val input = File(args.first()).readLines() println("Solution 1: ${solution1(input)}") println("Solution 2: ${solution2(input)}") } private fun solution1(input :List<String>) :Int { return checkSlope(findTrees(input, 3), input.size, 3, 1) } private fun solution2(input :List<String>) :Long { return checkSlope(findTrees(input, 1), input.size, 1, 1).toLong() * checkSlope(findTrees(input, 3), input.size, 3, 1).toLong() * checkSlope(findTrees(input, 5), input.size, 5, 1).toLong() * checkSlope(findTrees(input, 7), input.size, 7, 1).toLong() * checkSlope(findTrees(input, 1), input.size, 1, 2).toLong() } private fun findTrees(input :List<String>, xStep :Int) :List<Pair<Int, Int>> { val origPatternXCount = input.first().length val maxXNeeded = (input.size - 1) * xStep val numRepeatsNeeded = Math.ceil(maxXNeeded / origPatternXCount.toDouble()).toInt() val trees = mutableListOf<Pair<Int, Int>>() input.forEachIndexed { y, line -> val completeLine = line.repeat(numRepeatsNeeded) for (x in completeLine.indices) { if (completeLine[x] == tree) { trees.add(Pair(x, y)) } } } return trees } private fun checkSlope(trees :List<Pair<Int, Int>>, maxY :Int, xStep :Int, yStep :Int) :Int { var x = 0 var y = 0 var encounteredTreeCount = 0 while (y < maxY) { if (trees.contains(Pair(x, y))) { encounteredTreeCount++ } x += xStep y += yStep } return encounteredTreeCount }
0
Rust
0
0
002734670384aa02ca122086035f45dfb2ea9949
1,650
advent-of-code-2020
MIT License
day12/src/main/kotlin/com/lillicoder/adventofcode2023/day12/Day12.kt
lillicoder
731,776,788
false
{"Kotlin": 98872}
package com.lillicoder.adventofcode2023.day12 import kotlin.math.min fun main() { val day12 = Day12() val springs = SpringsParser().parse("input.txt") println("The number of valid arrangements for factor 1 is ${day12.part1(springs)}.") println("The number of valid arrangements for factor 5 is ${day12.part2(springs)}.") } class Day12 { fun part1(springs: List<Row>) = SpringPermutationCalculator().sumArrangements(springs) fun part2(springs: List<Row>) = SpringPermutationCalculator().sumArrangements(springs, 5) } /** * Represents a row of springs and their associated pattern of contiguous broken springs. */ class Row( val springs: String, val pattern: List<Int>, ) class SpringPermutationCalculator { private val damaged = '#' private val operational = '.' private val unknown = '?' private val cache = mutableMapOf<String, Long>() /** * Finds all valid arrangements of each of the given [Row] and sums them. * @param rows Rows to evaluate. * @param factor Fold factor. Defaults to 1. * @return Sum of valid arrangements. */ fun sumArrangements( rows: List<Row>, factor: Int = 1, ) = rows.sumOf { var expandedSprings = it.springs val expandedPattern = it.pattern.toMutableList() for (index in 1..<factor) { expandedSprings += "$unknown${it.springs}" expandedPattern += it.pattern } arrangements(expandedSprings, expandedPattern) } /** * Gets the number of valid arrangements for the given springs and their broken springs pattern. * @param springs Springs to evaluate. * @param pattern Pattern of contiguous blocks of broken springs. * @return Number of valid arrangements. */ private fun arrangements( springs: String, pattern: List<Int>, ): Long { val key = "$springs|${pattern.joinToString(",")}" return cache[key] ?: computeArrangements(springs, pattern).apply { cache[key] = this } } private fun computeArrangements( springs: String, pattern: List<Int>, ): Long { // Case 1 - no more patterns to check; spring must not have anything damaged as we've exhausted // available damaged gear blocks if (pattern.isEmpty()) return if (springs.contains(damaged)) 0L else 1L // Case 2 - not enough remaining springs; we need at least 1 space per pattern plus 1 in between each pattern val spaceNeeded = pattern.sum() + pattern.size - 1 if (springs.length < spaceNeeded) return 0 // Case 3 - starts with operational spring; we only want to evaluate unknown or damaged springs // just advance ahead to the next substring if (springs.startsWith(operational)) return arrangements(springs.drop(1), pattern) // Get the next block from the pattern val block = pattern.first() // Determine if we have any operational springs in this block val areAllNonOperational = springs.substring(0, block).contains(operational).not() // End of block is either next character or end of string, whichever comes first val end = min(block + 1, springs.length) var count = 0L // We have more springs available and we don't start val a = springs.length > block && springs[block] != damaged val b = springs.length <= block // Block is all # or ? AND is either the end of the springs OR is there are more spring blocks to come; // if so, drop this block and work the sub-problem if (areAllNonOperational && (a || b)) count += arrangements(springs.drop(end), pattern.drop(1)) // Block has an unknown string, work the sub-problem by dropping this spring if (springs.startsWith(unknown)) count += arrangements(springs.drop(1), pattern) return count } } class SpringsParser { fun parse(raw: List<String>) = raw.map { line -> val parts = line.split(" ") val springs = parts[0] val pattern = parts[1].split(",").map { it.toInt() } Row(springs, pattern) } /** * Parses the file with the given filename to a list of [Row]. * @param filename Filename. * @return Parsed spring rows. */ fun parse(filename: String) = parse(javaClass.classLoader.getResourceAsStream(filename)!!.reader().readLines()) }
0
Kotlin
0
0
390f804a3da7e9d2e5747ef29299a6ad42c8d877
4,454
advent-of-code-2023
Apache License 2.0
solutions/src/Day15.kt
khouari1
573,893,634
false
{"Kotlin": 132605, "HTML": 175}
import kotlin.math.abs typealias Coord = Pair<Int, Int> fun main() { fun part1(input: List<String>, targetLineY: Int): Int { // find sensors close to the target line val allBeaconCoords = getBeaconCoords(input) val intersectedCoords = mutableSetOf<Coord>() input.forEach { line -> val lineSplit = line.split(" ") val (sensorCoords, beaconCoords) = getCoords(lineSplit) val (sensorX, sensorY) = sensorCoords val (beaconX, beaconY) = beaconCoords val manhattanDistance = abs(sensorX - beaconX) + abs(sensorY - beaconY) if (sensorY < targetLineY) { // sensor is higher than the line val lowestYSensorReaches = sensorY + manhattanDistance val yDiff = lowestYSensorReaches - targetLineY if (yDiff >= 0) { // intersects line val xDiff = manhattanDistance - (targetLineY - sensorY) val newIntersectedCoords = getIntersectedCoords(xDiff, sensorX, targetLineY, allBeaconCoords) intersectedCoords.addAll(newIntersectedCoords) } } else if (sensorY > targetLineY) { // sensor is lower than the line val highestYSensorReaches = sensorY - manhattanDistance val yDiff = highestYSensorReaches - targetLineY if (yDiff <= 0) { // intersects line val xDiff = manhattanDistance - (sensorY - targetLineY) val newIntersectedCoords = getIntersectedCoords(xDiff, sensorX, targetLineY, allBeaconCoords) intersectedCoords.addAll(newIntersectedCoords) } } } return intersectedCoords.size } fun part2(input: List<String>, upperCoordLimit: Int): Long { val manhattanDistanceBySensorCoords = getManhattanDistanceBySensorCoords(input) var potential: Coord? = null outerloop@ for (y in 0..upperCoordLimit) { var xCount = 0 while (xCount <= upperCoordLimit) { val coord = xCount to y // is it within any sensor manhattan distances, if not then it's the distress beacon run sensorloop@{ manhattanDistanceBySensorCoords.forEach { (sensorCoords, maxManhattanDistance) -> val (sensorX, sensorY) = sensorCoords val manhattanDistance = abs(xCount - sensorX) + abs(y - sensorY) if (manhattanDistance > maxManhattanDistance) { // not within range of sensor if (potential == null) { potential = coord } } else { // within range of sensor potential = null // find out the manhattan distance diff and advance x coord by that amount val manhattanDistanceDiff = maxManhattanDistance - manhattanDistance xCount += manhattanDistanceDiff return@sensorloop } } } if (potential != null) { break@outerloop } xCount++ } } val (distressBeaconX, distressBeaconY) = potential!! return (distressBeaconX.toLong() * 4_000_000) + distressBeaconY } // test if implementation meets criteria from the description, like: val testInput = readInput("Day15_test") check(part1(testInput, 10) == 26) check(part2(testInput, 20) == 56_000_011L) val input = readInput("Day15") println(part1(input, 2_000_000)) println(part2(input, 4_000_000)) } private fun getCoords(lineSplit: List<String>): Pair<Pair<Int, Int>, Pair<Int, Int>> { val sensorX = lineSplit[2].substringAfter("=").substringBefore(",").toInt() val sensorY = lineSplit[3].substringAfter("=").substringBefore(":").toInt() val beaconX = lineSplit[8].substringAfter("=").substringBefore(",").toInt() val beaconY = lineSplit[9].substringAfter("=").toInt() return (sensorX to sensorY) to (beaconX to beaconY) } private fun getBeaconCoords(input: List<String>): Set<Pair<Int, Int>> = input.map { line -> val lineSplit = line.split(" ") val (_, beaconCoord) = getCoords(lineSplit) beaconCoord }.toSet() private fun getIntersectedCoords(xDiff: Int, sensorX: Int, targetLineY: Int, allBeaconCoords: Set<Coord>): Set<Coord> { val intersectedCoords = mutableSetOf<Coord>() for (i in xDiff downTo 0) { val coord = (sensorX - i) to targetLineY if (coord !in allBeaconCoords) { intersectedCoords.add(coord) } } // coords to the right for (i in 0..xDiff) { val coord = (sensorX + i) to targetLineY if (coord !in allBeaconCoords) { intersectedCoords.add(coord) } } // middle coord val coord = sensorX to targetLineY if (coord !in allBeaconCoords) { intersectedCoords.add(coord) } return intersectedCoords } private fun getManhattanDistanceBySensorCoords(input: List<String>) = input.associate { line -> val lineSplit = line.split(" ") val (sensorCoords, beaconCoords) = getCoords(lineSplit) val (sensorX, sensorY) = sensorCoords val (beaconX, beaconY) = beaconCoords val manhattanDistance = abs(sensorX - beaconX) + abs(sensorY - beaconY) sensorCoords to manhattanDistance }
0
Kotlin
0
1
b00ece4a569561eb7c3ca55edee2496505c0e465
5,711
advent-of-code-22
Apache License 2.0
src/Day04.kt
simonitor
572,972,937
false
{"Kotlin": 8461}
import kotlin.math.max import kotlin.math.min fun main() { // first val input = readInput("inputDay4") val ranges = input.map { it.split(",") } println(findNumberOfFullyContainedRanges(ranges)) // second println(findNumberOfOverlappingRanges(ranges)) } fun findNumberOfFullyContainedRanges(input: List<List<String>>): Int { return input.map { val (range, otherRange) = it fullyContains(range, otherRange) }.count { it } } fun findNumberOfOverlappingRanges(input: List<List<String>>): Int { return input.map { val (range, otherRange) = it overlap(range, otherRange) }.count { it } } fun fullyContains(range: String, otherRange: String): Boolean { val (lowerBound, upperBound) = range.getUpperLower() val (lowerBoundOther, upperBoundOther) = otherRange.getUpperLower() return ((lowerBound <= lowerBoundOther && upperBound >= upperBoundOther) || (lowerBound >= lowerBoundOther && upperBound <= upperBoundOther)) } fun overlap(range: String, otherRange: String): Boolean { val (lowerBound, upperBound) = range.getUpperLower() val (lowerBoundOther, upperBoundOther) = otherRange.getUpperLower() return max(lowerBound, upperBound) <= min(lowerBoundOther, upperBoundOther) } fun String.getUpperLower(): List<Int> { return this.split("-").map { it.toInt() } }
0
Kotlin
0
0
11d567712dd3aaf3c7dee424a3442d0d0344e1fa
1,359
AOC2022
Apache License 2.0
src/Day05.kt
robinpokorny
572,434,148
false
{"Kotlin": 38009}
typealias Stacks = List<ArrayDeque<Char>> typealias Steps = List<Triple<Int, Int, Int>> private fun parse(input: List<String>): Pair<Stacks, Steps> { val (rawStacks, rawSteps) = input .joinToString("\n") .split("\n\n") .map { it.lines() } val stacksPrepared = rawStacks .reversed() .map { it.filterIndexed { index, char -> index % 4 == 1 }.toList() } val stacks = stacksPrepared .first() .map { it.digitToInt() - 1 } .map { i -> stacksPrepared.mapNotNull { it.getOrNull(i) }.drop(1).filter { it != ' ' } } .map { ArrayDeque(it) } val re = """.* (\d+) .*(\d+).+(\d+).*""".toRegex() val steps = rawSteps .map { re.matchEntire(it)!!.groupValues.drop(1).map(String::toInt) } .map{ Triple(it[0], it[1] - 1, it[2] - 1) } return Pair(stacks, steps) } private fun part1(input: Pair<Stacks, Steps>): String { val (stacks, steps) = input return steps .fold(stacks){ s, (count, from, to) -> repeat(count) { s[to].addLast(s[from].removeLast()) } s } .map { it.last() } .joinToString("") } private fun part2(input: Pair<Stacks, Steps>): String { val (stacks, steps) = input return steps .fold(stacks){ s, (count, from, to) -> s[to].addAll(s[from].takeLast(count)) repeat(count) { s[from].removeLast() } s } .map { it.last() } .joinToString("") } fun main() { val input1 = parse(readDayInput(5)) val testInput1 = parse(rawTestInput) // PART 1 assertEquals(part1(testInput1), "CMZ") println("Part1: ${part1(input1)}") // We mutate the stacks so we need a new input val input2 = parse(readDayInput(5)) val testInput2 = parse(rawTestInput) // PART 2 assertEquals(part2(testInput2), "MCD") println("Part2: ${part2(input2)}") } private val rawTestInput = """ [D] [N] [C] [Z] [M] [P] 1 2 3 move 1 from 2 to 1 move 3 from 1 to 3 move 2 from 2 to 1 move 1 from 1 to 2 """.trimIndent().lines()
0
Kotlin
0
2
56a108aaf90b98030a7d7165d55d74d2aff22ecc
2,104
advent-of-code-2022
MIT License