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/Day03.kt
tsdenouden
572,703,357
false
{"Kotlin": 8295}
import kotlin.math.* fun main() { fun part1(input: List<String>): Int { var compartmentOne: CharSequence var compartmentTwo: CharSequence val commonItems: MutableList<Int> = mutableListOf() input.forEach { line -> val rucksack = line.trim() val middle = ceil(rucksack.length.toDouble() / 2).toInt() compartmentOne = rucksack.slice(0 until middle) compartmentTwo = rucksack.slice(middle until rucksack.length) run getItems@ { compartmentOne.forEach { item -> if (compartmentTwo.contains(item)) { when (item) { item.uppercaseChar() -> commonItems.add(item.code - 38) item.lowercaseChar() -> commonItems.add(item.code - 96) } return@getItems } } } } return commonItems.sum() } fun part2(input: List<String>): Int { var groupOne: CharSequence var groupTwo: CharSequence var groupThree: CharSequence val badgesPriority: MutableList<Int> = mutableListOf() for (i in 0 until (input.size) step 3) { groupOne = input[i] groupTwo = input[i+1] groupThree = input[i+2] run getItems@ { groupOne.forEach { item -> if (groupTwo.contains(item) && groupThree.contains(item)) { when (item) { item.uppercaseChar() -> badgesPriority.add(item.code - 38) item.lowercaseChar() -> badgesPriority.add(item.code - 96) } return@getItems } } } } return badgesPriority.sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day03_test") check(part1(testInput) == 157) check(part2(testInput) == 70) val input = readInput("Day03") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
68982ebffc116f3b49a622d81e725c8ad2356fed
2,185
aoc-2022-kotlin
Apache License 2.0
2022/src/main/kotlin/day14_imp.kt
madisp
434,510,913
false
{"Kotlin": 388138}
import utils.IntGrid import utils.MutableIntGrid import utils.Parser import utils.Segment import utils.Solution import utils.Vec2i import utils.mapItems fun main() { Day14Imp.run() } object Day14Imp : Solution<List<List<Segment>>>() { override val name = "day14" override val parser = Parser.lines.mapItems { line -> val parts = line.split(" -> ").map { it.trim() } // turn a -> b -> c into "a -> b" and "b -> c" parts.windowed(2).map { Segment.parse(it.joinToString(" -> ")) } } private val source = Vec2i(500, 0) private const val SPACE = 0 private const val ROCK = 1 private const val SAND = 2 private val fall = listOf(Vec2i(0, 1), Vec2i(-1, 1), Vec2i(1, 1)) private fun simulate(grid: MutableIntGrid) { while (true) { // spawn sand var sand = source grain@ while (true) { if (sand.y == grid.height - 1) { return } val newPos = fall.map { sand + it }.firstOrNull { grid[it] == SPACE } if (newPos == null) { // at rest grid[sand] = SAND if (sand == source) return break@grain } sand = newPos } } } override fun part1(input: List<List<Segment>>): Any? { val bottom = input.flatten().maxOf { maxOf(it.start.y, it.end.y) } val grid = IntGrid(1000, bottom + 1, 0).toMutable() input.flatten().forEach { seg -> seg.points.forEach { p -> grid[p] = ROCK } } simulate(grid) return grid.cells.count { (_, value) -> value == SAND } } override fun part2(input: List<List<Segment>>): Any? { val bottom = input.flatten().maxOf { maxOf(it.start.y, it.end.y) } val grid = IntGrid(1000, bottom + 3, 0).toMutable() input.flatten().forEach { seg -> seg.points.forEach { p -> grid[p] = ROCK } } (0 until grid.width).forEach { x -> grid[x][grid.height - 1] = ROCK } simulate(grid) return grid.cells.count { (_, value) -> value == SAND } } }
0
Kotlin
0
1
3f106415eeded3abd0fb60bed64fb77b4ab87d76
1,985
aoc_kotlin
MIT License
src/Day01.kt
SeanDijk
575,314,390
false
{"Kotlin": 29164}
fun main() { fun part1(input: List<String>): Int { var current = 0 var max = 0 for (line in input) { if (line.isBlank()) { if (current > max) { max = current } current = 0 } else { current += line.toInt() } } return max } fun retrieveTotalCaloriesPerElf(input: String): Sequence<Int> { return input // Group the snacks held by a single elf to their own string .splitToSequence("\n\n") .map { singleElfSnacksString -> // Split to a string per snack singleElfSnacksString.splitToSequence("\n") .filter { it.isNotBlank() } // convert them to integers .map { it.toInt() } // And sum them to get the total calories per elf .sum() } } fun part1v2(input: String) = retrieveTotalCaloriesPerElf(input).max() fun part2(input: String) = retrieveTotalCaloriesPerElf(input) .sortedDescending() .take(3) .sum() println(part1(readInput("Day01"))) println(part1v2(readInputAsString("Day01"))) println(part2(readInputAsString("Day01"))) }
0
Kotlin
0
0
363747c25efb002fe118e362fb0c7fecb02e3708
1,334
advent-of-code-2022
Apache License 2.0
day21/src/Day21.kt
simonrules
491,302,880
false
{"Kotlin": 68645}
import java.io.File class Day21(path: String) { private var start = listOf<Int>() private var numRolls = 0 // Each player always rolls 3 times, but it doesn't matter what the order of the dice are. // Since there are 3^3=27 possibilities, we can just assume the universe branches on each // cluster of 3 rolls. private val probability = mapOf(3 to 1L, 4 to 3L, 5 to 6L, 6 to 7L, 7 to 6L, 8 to 3L, 9 to 1L) data class State( val positionA: Int, val positionB: Int, val scoreA: Int, val scoreB: Int, val nextTurnA: Boolean) { private fun move(position: Int, roll: Int): Int { var newPosition = position + roll if (newPosition > 10) { newPosition = ((newPosition - 1) % 10) + 1 } return newPosition } fun move(roll: Int): State { return if (nextTurnA) { val newPosition = move(positionA, roll) val newScore = scoreA + newPosition State(newPosition, positionB, newScore, scoreB, false) } else { val newPosition = move(positionB, roll) val newScore = scoreB + newPosition State(positionA, newPosition, scoreA, newScore, true) } } } data class Result(val countA: Long, val countB: Long) { operator fun times(other: Long): Result { return Result(countA * other, countB * other) } operator fun plus(other: Result): Result { return Result(countA + other.countA, countB + other.countB) } } init { val values = mutableListOf<Int>() File(path).forEachLine { values.add(Character.getNumericValue(it.last())) } start = values.toList() } private fun rollDice(): Int { return (numRolls++) % 100 + 1 } fun part1(): Int { val score = arrayOf(0, 0) val position = start.toIntArray() while (true) { var roll = rollDice() + rollDice() + rollDice() position[0] += roll if (position[0] > 10) { position[0] = ((position[0] - 1) % 10) + 1 } score[0] += position[0] if (score[0] >= 1000) { return score[1] * numRolls } roll = rollDice() + rollDice() + rollDice() position[1] += roll if (position[1] > 10) { position[1] = ((position[1] - 1) % 10) + 1 } score[1] += position[1] if (score[1] >= 1000) { return score[0] * numRolls } } } private fun solveRecurse(state: State): Result { var result = Result(0L, 0L) if (state.scoreA >= 21) { return Result(1L, 0L) } else if (state.scoreB >= 21) { return Result(0L, 1L) } else { probability.forEach { (roll, freq) -> val newState = state.move(roll) result += solveRecurse(newState) * freq } } return result } fun part2(): Long { // Player 1 goes first val startState = State(start[0], start[1], 0, 0, true) val result = solveRecurse(startState) return maxOf(result.countA, result.countB) } } fun main() { val aoc = Day21("day21/input.txt") println(aoc.part1()) println(aoc.part2()) }
0
Kotlin
0
0
d9e4ae66e546f174bcf66b8bf3e7145bfab2f498
3,492
aoc2021
Apache License 2.0
src/Day04.kt
jamOne-
573,851,509
false
{"Kotlin": 20355}
fun main() { fun part1(input: List<String>): Int { var count = 0 for (assignment in input) { val pairs = assignment.split(',') val elf1 = pairs[0].split('-').map { it.toInt() } val elf2 = pairs[1].split('-').map { it.toInt() } if (elf1[0] <= elf2[0] && elf1[1] >= elf2[1] || elf2[0] <= elf1[0] && elf2[1] >= elf1[1]) { count += 1 } } return count } fun part2(input: List<String>): Int { var count = 0 for (assignment in input) { val pairs = assignment.split(',') val elf1 = pairs[0].split('-').map { it.toInt() } val elf2 = pairs[1].split('-').map { it.toInt() } if (!(elf1[0] > elf2[1] || elf2[0] > elf1[1])) { count += 1 } } return count } 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
77795045bc8e800190f00cd2051fe93eebad2aec
1,081
adventofcode2022
Apache License 2.0
src/day/_11/Day11.kt
Tchorzyksen37
572,924,533
false
{"Kotlin": 42709}
package day._11 import lcm import java.io.File typealias WorryLevel = Long class Day11 { fun part1(monkeys: List<Monkey>): Int { for (round in 1..20) { for (monkey in monkeys) { while (monkey.itemList.isNotEmpty()) { val item = monkey.itemList.removeFirst() val worryLevel = monkey.operation(item) / 3 if (worryLevel % monkey.divisibleBy == 0L) { monkeys[monkey.onTruePassesToMonkeyIdx].itemList.addLast(worryLevel) } else { monkeys[monkey.onFalsePassesToMonkeyIdx].itemList.addLast(worryLevel) } monkey.passesCount++ } } } return monkeys.map { it.passesCount }.sortedByDescending { it }.take(2).reduce { acc, i -> acc * i } } fun part2(monkeys: List<Monkey>): Long { val theLeastCommonMultiple = monkeys.map { it.divisibleBy }.reduce(::lcm) for (round in 1..10_000) { for (monkey in monkeys) { while (monkey.itemList.isNotEmpty()) { val item = monkey.itemList.removeFirst() val newWorryLevel = monkey.operation(item) % theLeastCommonMultiple if (newWorryLevel % monkey.divisibleBy == 0L) { monkeys[monkey.onTruePassesToMonkeyIdx].itemList.addLast(newWorryLevel) } else { monkeys[monkey.onFalsePassesToMonkeyIdx].itemList.addLast(newWorryLevel) } monkey.passesCount++ } } } return monkeys.map { it.passesCount.toLong() }.sortedByDescending { it }.take(2).reduce { acc, i -> acc * i } } companion object { private val NON_INT_DELIMITER = """(\D)+""".toRegex() fun parse(input: String): List<Monkey> { fun getOperation(operationInput: String): (WorryLevel) -> WorryLevel { val operationInputParts = operationInput.substringAfter("new = old ").split(" ") when (operationInputParts[0]) { "+" -> return { it + operationInputParts[1].toLong() } "*" -> return { it * if (operationInputParts[1] == "old") it else operationInputParts[1].toLong() } else -> throw IllegalStateException("Operation ${operationInputParts[0]} unknown.") } } return input.split("\n\n") .map { it.lines() } .map { monkeyLines -> Monkey( monkeyLines[0].trim().replace(":", ""), ArrayDeque(monkeyLines[1].extractLongs()), getOperation(monkeyLines[2]), monkeyLines[3].extractInts().first(), monkeyLines[4].extractInts().first(), monkeyLines[5].extractInts().first() ) } } private fun String.extractInts(): List<Int> = this.split(NON_INT_DELIMITER).mapNotNull { it.toIntOrNull() } private fun String.extractLongs(): List<Long> = this.split(NON_INT_DELIMITER).mapNotNull { it.toLongOrNull() } } } data class Monkey( val label: String, var itemList: ArrayDeque<Long>, val operation: (WorryLevel) -> WorryLevel, val divisibleBy: Int, val onTruePassesToMonkeyIdx: Int, val onFalsePassesToMonkeyIdx: Int, var passesCount: Int = 0 ) : Cloneable { public override fun clone(): Monkey = Monkey( label, ArrayDeque(itemList), operation, divisibleBy, onTruePassesToMonkeyIdx, onFalsePassesToMonkeyIdx, passesCount ) } fun List<Monkey>.deepCopy(): List<Monkey> { val copy = mutableListOf<Monkey>() copy.addAll(this.map { it.clone() }) return copy } fun main() { val parsedTestInput = Day11.parse(File("src/day/_11/Day11_test.txt").readText()) check(Day11().part1(parsedTestInput.deepCopy()) == 10605) check(Day11().part2(parsedTestInput) == 2713310158) val input = Day11.parse(File("src/day/_11/Day11.txt").readText()) println(Day11().part1(input.deepCopy())) println(Day11().part2(input)) }
0
Kotlin
0
0
27d4f1a6efee1c79d8ae601872cd3fa91145a3bd
3,534
advent-of-code-2022
Apache License 2.0
src/main/kotlin/days/day19/Day19.kt
Stenz123
725,707,248
false
{"Kotlin": 123279, "Shell": 862}
package days.day19 import days.Day class Day19 : Day() { override fun partOne(): Any { val process = parseInput() val machineParts = parseMachineParts() var result = 0 for (part in machineParts) { var currentProcessIdentifier = "in" while (currentProcessIdentifier !in "AR") { currentProcessIdentifier = process[currentProcessIdentifier]!!.executeProcess(part) } if (currentProcessIdentifier == "A") { result += part.sum() } } return result } override fun partTwo(): Any { val process = parseInput() val machineParts = listOf(1..4000, 1..4000, 1..4000, 1..4000) return executeProcessP2("in", machineParts, process).sumOf { it[0].length * it[1].length * it[2].length * it[3].length } } private fun parseInput(): MutableMap<String, List<String>> { val process: MutableMap<String, List<String>> = hashMapOf() readInput().takeWhile { it.isNotBlank() }.forEach { val identifier = it.substringBefore("{") val parts = it.substringAfter("{").substringBefore("}").split(",") process[identifier] = parts } return process } private fun parseMachineParts(): List<MachinePart> { return readInput().dropWhile { it.isNotBlank() }.drop(1).map { val split = it.split(",") val x = split[0].substringAfter("=").toInt() val m = split[1].substringAfter("=").toInt() val a = split[2].substringAfter("=").toInt() val s = split[3].substringAfter("=").substringBefore("}").toInt() MachinePart(x, m, a, s) } } private fun List<String>.executeProcess(machinePart: MachinePart): String { for (i in 0 until this.size - 1) { val currentThing = this[i] val parameter1 = when (currentThing.substringBefore('<').substringBefore('>')) { "x" -> machinePart.x "m" -> machinePart.m "a" -> machinePart.a "s" -> machinePart.s else -> throw Exception("geh scheißn") } val parameter2 = currentThing.substringAfter('<').substringAfter('>').substringBefore(":").toInt() if (currentThing.contains('<')) { if (parameter1 < parameter2) { return currentThing.substringAfter(":") } } else if (currentThing.contains('>')) { if (parameter1 > parameter2) { return currentThing.substringAfter(":") } } } return this.last() } private fun executeProcessP2(identifier: String, ranges: List<IntRange>, map: MutableMap<String, List<String>>): List<List<IntRange>> { if (identifier == "R") return listOf() if (identifier == "A") return listOf(ranges) val process = map[identifier]!! var currentMachine = ranges val result = mutableListOf<List<IntRange>>() for (element in process) { if ("<" !in element && ">" !in element) return executeProcessP2(element, currentMachine, map) + result val indexOfParameter = XmasValue.valueOf(element[0].toString()).ordinal val parameter1 = currentMachine[indexOfParameter] val parameterToCompare = element.substringAfter('<').substringAfter('>').substringBefore(":").toInt() if (element.contains('<')) { if (parameter1.last < parameterToCompare) { return executeProcessP2(element.substringAfter(":"), currentMachine, map) + result } val splits = parameter1.splitBy(parameterToCompare - 1) val newMachines = currentMachine.convertIntoSplits(indexOfParameter, splits) currentMachine = newMachines[1] result += executeProcessP2(element.substringAfter(":"), newMachines[0], map) } else if (element.contains('>')) { if (parameter1.first > parameterToCompare) { return executeProcessP2(element.substringAfter(":"), currentMachine, map) + result } val splits = parameter1.splitBy(parameterToCompare) val newMachines = currentMachine.convertIntoSplits(indexOfParameter, splits) currentMachine = newMachines[0] result += executeProcessP2(element.substringAfter(":"), newMachines[1], map) } } return result } } class MachinePart(val x: Int, val m: Int, val a: Int, val s: Int) { fun sum(): Int { return x + m + a + s } override fun toString(): String { return "(x=$x, m=$m, a=$a, s=$s)" } } fun IntRange.splitBy(number: Int): List<IntRange> { if (number !in this) { return listOf(this) } val res = mutableListOf<IntRange>() res.add(this.first..number) res.add(number + 1..this.last) return res } fun List<IntRange>.convertIntoSplits(indexOfParameter:Int, splits: List<IntRange>):List<List<IntRange>> { val res = mutableListOf<List<IntRange>>() for (split in splits) { val copy = this.toMutableList() copy[indexOfParameter] = split res.add(copy) } return res } private val IntRange.length: Long get() = (this.last - this.first).toLong() + 1 enum class XmasValue{x, m, a, s}
0
Kotlin
1
0
3de47ec31c5241947d38400d0a4d40c681c197be
5,531
advent-of-code_2023
The Unlicense
2022/main/day_11/Main.kt
Bluesy1
572,214,020
false
{"Rust": 280861, "Kotlin": 94178, "Shell": 996}
package day_11_2022 import java.io.File import java.math.BigInteger fun part1(input: List<String>) { val monkeys = mutableListOf<Monkey>() for (monkey in input.chunked(7)) { val items = monkey[1].substring(18).split(", ").map{ BigInteger(it) }.toMutableList() val op = monkey[2].toCharArray()[23] == '*' val opBy = monkey[2].split(" ").last().toIntOrNull() val condition = monkey[3].split(" ").last().toInt() val toOnFalse = monkey[4].split(" ").last().toInt() val toOnTrue = monkey[5].split(" ").last().toInt() monkeys.add(Monkey(items, op, opBy, condition, toOnFalse, toOnTrue, true)) } for (i in 0..19) { for (monkey in monkeys) { monkey.inspectItems(monkeys) } } val sortedMonkeys = monkeys.sortedByDescending { it.inspectedTimes } print("The monkey business is ${sortedMonkeys[0].inspectedTimes * sortedMonkeys[1].inspectedTimes}") } // 6300 wrong fun part2(input: List<String>) { val monkeys = mutableListOf<Monkey>() for (monkey in input.chunked(7)) { val items = monkey[1].substring(18).split(", ").map{ BigInteger(it) }.toMutableList() val op = monkey[2].toCharArray()[23] == '*' val opBy = monkey[2].split(" ").last().toIntOrNull() val condition = monkey[3].split(" ").last().toInt() val toOnFalse = monkey[4].split(" ").last().toInt() val toOnTrue = monkey[5].split(" ").last().toInt() monkeys.add(Monkey(items, op, opBy, condition, toOnFalse, toOnTrue, false)) } val superMod = monkeys.map(Monkey::condition).reduce(Int::times) for (i in 0 until 10000) { for (monkey in monkeys) { monkey.inspectItems(monkeys, superMod) } } val sortedMonkeys = monkeys.sortedByDescending { it.inspectedTimes }.subList(0, 2) print("The monkey business is ${sortedMonkeys[0].inspectedTimes * sortedMonkeys[1].inspectedTimes}") } // 259605321 is wrong fun main(){ val inputFile = File("2022/inputs/Day_11.txt") print("\n----- Part 1 -----\n") part1(inputFile.readLines()) print("\n----- Part 2 -----\n") part2(inputFile.readLines()) }
0
Rust
0
0
537497bdb2fc0c75f7281186abe52985b600cbfb
2,177
AdventofCode
MIT License
kotlin/src/main/kotlin/StreetRgb.kt
funfunStudy
93,757,087
false
null
fun main(args: Array<String>) { val list: List<List<Int>> = listOf(listOf(26, 40, 83), listOf(49, 60, 57), listOf(13, 89, 99)) val list2: List<List<Int>> = listOf(listOf(1, 20, 30), listOf(50, 5, 6), listOf(9, 3, 7)) println(solve(list)) println(solve(list2)) } fun solve(list: List<List<Int>>, index: Int = 0, min: Int = 0): Int = when { list.isEmpty() || index == 3 -> min else -> solve(list, index + 1, findMin(list, index, 0, min)) } fun findMin(list: List<List<Int>>, index: Int, result: Int = 0, min: Int): Int = when { list.isEmpty() -> { if (min == 0) result else { if (min > result) { result } else { min } } } else -> { when (index) { 0 -> Math.min(//RED findMin(list.drop(1), 1, result + list.first()[index], min), findMin(list.drop(1), 2, result + list.first()[index], min)) 1 -> Math.min(//Green findMin(list.drop(1), 0, result + list.first()[index], min), findMin(list.drop(1), 2, result + list.first()[index], min)) 2 -> Math.min(//Blue findMin(list.drop(1), 0, result + list.first()[index], min), findMin(list.drop(1), 1, result + list.first()[index], min)) else -> { result } } } } /* 예제 입력 3 26 40 83 49 60 57 13 89 99 3 1 20 30 50 5 6 9 3 7 예제 출력 96 10 */
0
Kotlin
3
14
a207e4db320e8126169154aa1a7a96a58c71785f
1,556
algorithm
MIT License
src/day18/d18_2.kt
svorcmar
720,683,913
false
{"Kotlin": 49110}
typealias Board = Array<Array<Char>> fun main() { val input = "" val board = sequence { var board = stuck(parseBoard(input)) while(true) { yield(board) board = step(board) } } println(board.take(100 + 1).last().map { r -> r.count { it == '#' } }.sum()) } fun parseBoard(s: String): Board { val lines = s.lines() val board = Array(lines.size + 2) { Array(lines[0].length + 2) { '.' } } for (i in 0 until lines.size) { for (j in 0 until lines[i].length) { board[i + 1][j + 1] = lines[i][j] } } return board } val diffs = listOf(0 to 1, 0 to -1, 1 to 1, 1 to 0, 1 to -1, -1 to 1, -1 to 0, -1 to -1) fun step(b: Board): Board { val newBoard = Array(b.size) { i -> Array(b[i].size) { '.' } } for (i in 1 until b.size - 1) { for (j in 1 until b[i].size - 1) { newBoard[i][j] = when(diffs.map { b[i + it.first][j + it.second] }.count { it == '#' }) { 3 -> '#' 2 -> if (b[i][j] == '#') '#' else '.' else -> '.' } } } return stuck(newBoard) } fun stuck(b: Board) = b.also { it[1][1] = '#' it[1][it[1].size - 2] = '#' it[it.size - 2][1] = '#' it[it.size - 2][it[1].size - 2] = '#' }
0
Kotlin
0
0
cb097b59295b2ec76cc0845ee6674f1683c3c91f
1,207
aoc2015
MIT License
advent-of-code/src/main/kotlin/DayTwo.kt
pauliancu97
518,083,754
false
{"Kotlin": 36950}
import kotlin.math.min class DayTwo { data class Cuboid( val length: Int, val width: Int, val height: Int ) { companion object { val REGEX = """(\d+)x(\d+)x(\d+)""".toRegex() } fun getSurfaceArea() = 2 * length * width + 2 * length * height + 2 * width * height fun getSurfaceSmallestSide(): Int { val firstMin = min(min(length, width), height) val secondMin = when (firstMin) { length -> min(width, height) width -> min(length, height) height -> min(length, width) else -> min(width, height) } return firstMin * secondMin } fun getVolume() = length * width * height fun getRibbonLength(): Int { val firstMin = min(min(length, width), height) val secondMin = when (firstMin) { length -> min(width, height) width -> min(length, height) height -> min(length, width) else -> min(width, height) } return 2 * firstMin + 2 * secondMin + getVolume() } fun getPresentSurface() = getSurfaceArea() + getSurfaceSmallestSide() } fun String.toCuboid(): Cuboid? { val matchResult = Cuboid.REGEX.matchEntire(this) ?: return null val length = matchResult.groupValues[1].toIntOrNull() ?: return null val width = matchResult.groupValues[2].toIntOrNull() ?: return null val height = matchResult.groupValues[3].toIntOrNull() ?: return null return Cuboid(length, width, height) } fun readCuboids(path: String) = readLines(path) .mapNotNull { it.toCuboid() } fun getTotalPresentsArea(cuboids: List<Cuboid>)= cuboids.sumOf { it.getPresentSurface() } fun getTotalRibbonLength(cuboids: List<Cuboid>) = cuboids.sumOf { it.getRibbonLength() } fun solvePartOne() { val cuboids = readCuboids("day_two.txt") println(getTotalPresentsArea(cuboids)) } fun solvePartTwo() { val cuboids = readCuboids("day_two.txt") println(getTotalRibbonLength(cuboids)) } } fun main() { DayTwo().solvePartTwo() }
0
Kotlin
0
0
3ba05bc0d3e27d9cbfd99ca37ca0db0775bb72d6
2,268
advent-of-code-2015
MIT License
src/Day02.kt
a2xchip
573,197,744
false
{"Kotlin": 37206}
fun main() { fun evaluateGame(game: String): Int { // A Rock, // B Paper // C Scissors // X for Rock // Y for Paper // Z for Scissors // i.e // (A Z) Rock defeats Scissors // (B X) Paper defeats Rock // (C Y) Scissors defeats Paper // ABC // XYZ return when (game) { "A Y" -> 6 "B Z" -> 6 "C X" -> 6 "A X" -> 3 "B Y" -> 3 "C Z" -> 3 "A Z" -> 0 "B X" -> 0 "C Y" -> 0 else -> throw Exception("Undefined game's state") } } fun evaluateChoice(choice: String): Int { // 1 for Rock, 2 for Paper, and 3 for Scissors return when (choice) { "X" -> 1 "Y" -> 2 "Z" -> 3 else -> throw Exception("Unexpected choice") } } fun guessChoice(opponentTurnGameEvaluation: Pair<String, Int>): String { return when (opponentTurnGameEvaluation) { Pair("A", 6) -> "Y" Pair("B", 6) -> "Z" Pair("C", 6) -> "X" Pair("A", 3) -> "X" Pair("B", 3) -> "Y" Pair("C", 3) -> "Z" Pair("A", 0) -> "Z" Pair("B", 0) -> "X" Pair("C", 0) -> "Y" else -> throw Exception("Unexpected guess") } } fun matchAction(letter: String): Int { // X means you need to lose, // Y means you need to end the round in a draw, and // Z means you need to win return when (letter) { "X" -> 0 "Y" -> 3 "Z" -> 6 else -> throw Exception("HELL") } } // "A X" "X" fun calculateScore(game: String) = evaluateGame(game) + evaluateChoice(game.last().toString()) fun part1(input: List<String>): Int { return input.sumOf(::calculateScore) } fun part2(input: List<String>): Int { return input.sumOf { turn -> val (opponent, actionLetter) = turn.split(" ") val choice = guessChoice(Pair(opponent, matchAction(actionLetter))) val game = "$opponent $choice" calculateScore(game) } } val testInput = readInput("Day02_test") check(part1(testInput) == 15) val input = readInput("Day02") println("Part 1 - ${part1(input)}") println("Part 2 - ${part2(input)}") }
0
Kotlin
0
2
19a97260db00f9e0c87cd06af515cb872d92f50b
2,466
kotlin-advent-of-code-22
Apache License 2.0
src/main/kotlin/me/grison/aoc/y2021/Day21.kt
agrison
315,292,447
false
{"Kotlin": 267552}
package me.grison.aoc.y2021 import me.grison.aoc.* class Day21 : Day(21, 2021) { override fun title() = "<NAME>" private val initialPositions = inputList.map { it.allLongs().last() }.toMutableList() override fun partOne(): Long { val positions = initialPositions.copy() val scores = mutableListOf(0L, 0L) var turn = 0 var (state, rolls) = p(0L, 0L) fun rollDice(): Long { rolls += 1 state += 1 % 101 return state } while (true) { val rollSum = (1..3).sumOf { rollDice() } positions[turn] = (positions[turn] + rollSum - 1) % 10 + 1 scores[turn] += positions[turn] if (scores[turn] >= 1000) return scores[turn.nextTurn()] * rolls turn = turn.nextTurn() } } override fun partTwo(): Long { val quantumStates = longHashBag<QuantumState>() quantumStates[QuantumState.zero(initialPositions)] = 1 val universes = mutableListOf(0L, 0L) val dices = combinations3(1, 3).map { it.sum() } while (quantumStates.isNotEmpty()) { val state = quantumStates.keys.minByOrNull { it.totalScore }!! val count = quantumStates.remove(state)!! val (positions, scores, turn) = state for (roll in dices) { val newPositions = positions.update(turn, (positions[turn] + roll - 1) % 10 + 1) val newScores = scores.update(turn, scores[turn] + newPositions[turn]) if (newScores[turn] >= 21) universes[turn] += count else quantumStates.increase(QuantumState(newPositions, newScores, turn.nextTurn()), count) } } return universes.maxOrNull()!! } data class QuantumState(val positions: List<Long>, val scores: List<Long>, val turn: Int) { val totalScore: Long get() = scores.sum() companion object { fun zero(positions: List<Long>) = QuantumState(positions, listOf(0, 0), 0) } } private fun Int.nextTurn() = (this + 1) % 2 }
0
Kotlin
3
18
ea6899817458f7ee76d4ba24d36d33f8b58ce9e8
2,155
advent-of-code
Creative Commons Zero v1.0 Universal
src/nativeMain/kotlin/xyz/justinhorton/aoc2022/Day02.kt
justinhorton
573,614,839
false
{"Kotlin": 39759, "Shell": 611}
package xyz.justinhorton.aoc2022 /** * https://adventofcode.com/2022/day/2 */ class Day02(override val input: String) : Day() { override fun part1(): String = calcScore { theirCode: Char, myCode: Char -> val myMove = Move.fromCode(myCode) val theirMove = Move.fromCode(theirCode) myMove.score + Move.throwOutcome(myMove, theirMove) } override fun part2(): String = calcScore { theirCode: Char, myCode: Char -> val theirMove = Move.fromCode(theirCode) val myMove = Move.fromPt2Code(myCode, theirMove) myMove.score + Move.throwOutcome(myMove, theirMove) } private fun calcScore(scoreFn: (Char, Char) -> Int) = input.trim() .split("\n") .asSequence() .map { r -> r.split(" ").let { it[0].single() to it[1].single() } } .sumOf { scoreFn(it.first, it.second) } .toString() } private enum class Move(val score: Int, val losesTo: Int, val winsAgainst: Int) { Rock(1, 1, 2), // 0 Paper(2, 2, 0), // 1 Scissors(3, 0, 1); // 2 companion object { fun fromCode(ch: Char): Move = when (ch) { in "AX" -> Rock in "BY" -> Paper else -> Scissors } fun fromPt2Code(ch: Char, theirMove: Move): Move = when (ch) { 'X' -> Move.values()[theirMove.winsAgainst] 'Y' -> theirMove else -> Move.values()[theirMove.losesTo] } fun throwOutcome(myMove: Move, theirMove: Move): Int = if (myMove == theirMove) { DRAW } else { if (myMove.losesTo == theirMove.ordinal) LOSE else WIN } } } private const val WIN = 6 private const val DRAW = 3 private const val LOSE = 0
0
Kotlin
0
1
bf5dd4b7df78d7357291c7ed8b90d1721de89e59
1,725
adventofcode2022
MIT License
leetcode-75-kotlin/src/main/kotlin/FindPivotIndex.kt
Codextor
751,507,040
false
{"Kotlin": 49566}
/** * Given an array of integers nums, calculate the pivot index of this array. * * The pivot index is the index where the sum of all the numbers strictly to the left of the index is equal to the sum of all the numbers strictly to the index's right. * * If the index is on the left edge of the array, then the left sum is 0 because there are no elements to the left. * This also applies to the right edge of the array. * * Return the leftmost pivot index. If no such index exists, return -1. * * * * Example 1: * * Input: nums = [1,7,3,6,5,6] * Output: 3 * Explanation: * The pivot index is 3. * Left sum = nums[0] + nums[1] + nums[2] = 1 + 7 + 3 = 11 * Right sum = nums[4] + nums[5] = 5 + 6 = 11 * Example 2: * * Input: nums = [1,2,3] * Output: -1 * Explanation: * There is no index that satisfies the conditions in the problem statement. * Example 3: * * Input: nums = [2,1,-1] * Output: 0 * Explanation: * The pivot index is 0. * Left sum = 0 (no elements to the left of index 0) * Right sum = nums[1] + nums[2] = 1 + -1 = 0 * * * Constraints: * * 1 <= nums.length <= 10^4 * -1000 <= nums[i] <= 1000 * * * Note: This question is the same as 1991: https://leetcode.com/problems/find-the-middle-index-in-array/ * @see <a href="https://leetcode.com/problems/find-pivot-index/">LeetCode</a> */ fun pivotIndex(nums: IntArray): Int { var rightSum = nums.sum() var leftSum = 0 for ((index, num) in nums.withIndex()) { rightSum -= num if (leftSum == rightSum) return index leftSum += num } return -1 }
0
Kotlin
0
0
0511a831aeee96e1bed3b18550be87a9110c36cb
1,585
leetcode-75
Apache License 2.0
src/main/kotlin/leetcode/Problem2049.kt
fredyw
28,460,187
false
{"Java": 1280840, "Rust": 363472, "Kotlin": 148898, "Shell": 604}
package leetcode /** * https://leetcode.com/problems/count-nodes-with-the-highest-score/ */ class Problem2049 { fun countHighestScoreNodes(parents: IntArray): Int { val root = buildTree(parents) val scores = mutableMapOf<Long, Int>() countHighestScore(parents.size, root, scores) var answer = 0 var maxScore = 0L for ((score, count) in scores) { if (score > maxScore) { maxScore = score answer = count } } return answer } data class Node(val value: Int, var left: Node? = null, var right: Node? = null) private fun buildTree(parents: IntArray): Node? { val nodes = Array(parents.size) { i -> Node(i) } var root: Node? = null for ((index, parentIndex) in parents.withIndex()) { if (parentIndex == -1) { root = nodes[0] } else { val parent = nodes[parentIndex] val child = nodes[index] if (parent.left == null) { parent.left = child } else { parent.right = child } } } return root } private fun countHighestScore(n: Int, root: Node?, scores: MutableMap<Long, Int>): Long { if (root == null) { return -1 } val left = countHighestScore(n, root.left, scores) + 1 val right = countHighestScore(n, root.right, scores) + 1 val score = (if (left == 0L) 1 else left) * (if (right == 0L) 1 else right) * (if (n - (left + right + 1) == 0L) 1 else n - (left + right + 1)) scores[score] = (scores[score] ?: 0) + 1 return left + right } }
0
Java
1
4
a59d77c4fd00674426a5f4f7b9b009d9b8321d6d
1,786
leetcode
MIT License
src/test/kotlin/leetcode/mock/MockInterview3.kt
Magdi
390,731,717
false
null
package leetcode.mock import org.junit.Assert import org.junit.Test class MockInterview3 { @Test fun `test case 1`() { Assert.assertTrue( SimilarSentences().areSentencesSimilar( arrayOf("great", "acting", "skills"), arrayOf("fine", "drama", "talent"), listOf( listOf("great", "fine"), listOf("drama", "acting"), listOf("skills", "talent"), ) ) ) } } class SimilarSentences { fun areSentencesSimilar( sentence1: Array<String>, sentence2: Array<String>, similarPairs: List<List<String>> ): Boolean { val similarMap = HashMap<String, HashSet<String>>() similarPairs.forEach { (a, b) -> val aSimilars = similarMap.getOrDefault(a, HashSet()) aSimilars.add(b) similarMap[a] = aSimilars val bSimilars = similarMap.getOrDefault(b, HashSet()) bSimilars.add(a) similarMap[b] = bSimilars } if (sentence1.size != sentence2.size) { return false } sentence1.forEachIndexed { index, _ -> val a = sentence1[index] val b = sentence2[index] if (a != b && !isSimilar(a, b, similarMap, HashSet())) { return false } } return true } private fun isSimilar( src: String, dest: String, similarMap: HashMap<String, HashSet<String>>, visited: HashSet<String> ): Boolean { val similars = similarMap.getOrDefault(src, HashSet()) if (similars.contains(dest)) return true if (visited.contains(src)) return false visited.add(src) similars.forEach { if (isSimilar(it, dest, similarMap, visited)) { return true } } return false } } class AutocompleteSystem(sentences: Array<String>, times: IntArray) { private val history: MutableList<Sentence> = sentences.mapIndexed { index, s -> Sentence(s, times[index]) }.toMutableList() private val query = StringBuilder() fun input(c: Char): List<String> { if (c == '#') { val item = history.find { it.string == query.toString() } if (item == null) { history.add(Sentence(query.toString(), 1)) } else { item.cnt++ } query.clear() return emptyList() } query.append(c) val list = history.filter { it.string.startsWith(query) }.sorted().map { it.string } if (list.size > 3) return list.subList(0, 3) return list } private data class Sentence(val string: String, var cnt: Int) : Comparable<Sentence> { override fun compareTo(other: Sentence): Int { return if (other.cnt.compareTo(cnt) == 0) { string.compareTo(other.string) } else other.cnt.compareTo(cnt) } } } class Sol { fun numberOfPatterns(m: Int, n: Int): Int { val count = IntArray(n + 1) for (i in 0..2) { for (j in 0..2) { backtrack(i, j, 1, count, HashSet()) } } var sum = 0 for (i in m..n) sum += count[i] return sum } private fun backtrack(row: Int, col: Int, step: Int, count: IntArray, seqSet: MutableSet<Int>) { if (step >= count.size) return seqSet.add(row * 3 + col) ++count[step] for (i in 0..2) { for (j in 0..2) { if (seqSet.contains(i * 3 + j)) continue if ((i - row) % 2 != 0 || (j - col) % 2 != 0 || seqSet.contains((i + row) / 2 * 3 + (j + col) / 2)) { backtrack(i, j, step + 1, count, seqSet) } } } seqSet.remove(row * 3 + col) } }
0
Kotlin
0
0
63bc711dc8756735f210a71454144dd033e8927d
3,995
ProblemSolving
Apache License 2.0
src/Day02.kt
zt64
572,594,597
false
null
enum class Shape(val score: Int) { ROCK(1), PAPER(2), SCISSORS(3) } enum class Result { WIN, LOSE, DRAW } fun main() { val input = readInput("Day02") val mappings = mapOf( "A" to Shape.ROCK, "B" to Shape.PAPER, "C" to Shape.SCISSORS, "X" to Shape.ROCK, "Y" to Shape.PAPER, "Z" to Shape.SCISSORS ) fun part1(input: String): Int { var score = 0 input.lines().forEach { line -> val (attack, response) = line.split(" ") .zipWithNext { a, b -> mappings[a]!! to mappings[b]!! } .single() score += response.score + when (response to attack) { Shape.ROCK to Shape.SCISSORS, Shape.PAPER to Shape.ROCK, Shape.SCISSORS to Shape.PAPER -> 6 else -> if (response == attack) 3 else 0 } } return score } val result = mapOf( "Z" to Result.WIN, "X" to Result.LOSE, "Y" to Result.DRAW ) fun part2(input: String): Int { var score = 0 input.lines().forEach { line -> val (attack, end) = line.split(" ") .zipWithNext { a, b -> mappings[a]!! to result[b]!! } .single() val response = when (end) { Result.WIN -> when (attack) { Shape.ROCK -> Shape.PAPER Shape.PAPER -> Shape.SCISSORS Shape.SCISSORS -> Shape.ROCK } Result.LOSE -> when (attack) { Shape.ROCK -> Shape.SCISSORS Shape.PAPER -> Shape.ROCK Shape.SCISSORS -> Shape.PAPER } Result.DRAW -> attack } score += response.score + when (response to attack) { Shape.ROCK to Shape.SCISSORS, Shape.PAPER to Shape.ROCK, Shape.SCISSORS to Shape.PAPER -> 6 else -> if (response == attack) 3 else 0 } } return score } println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
4e4e7ed23d665b33eb10be59670b38d6a5af485d
2,192
aoc-2022
Apache License 2.0
src/Day14.kt
i-tatsenko
575,595,840
false
{"Kotlin": 90644}
fun toPoints(input: String): List<Point> { return input.split(" -> ").map { it.split(",") }.map { split -> Point(split[1].toInt(), split[0].toInt()) } } fun range(start: Int, end: Int): IntProgression = if (start <= end) start..end else start downTo end fun getBlocked(input: List<String>): Set<Point> { val blocked = mutableSetOf<Point>() input.forEach { line -> val points = toPoints(line) var from = points[0] blocked.add(from) for (i in 1 until points.size) { val current = points[i] val blockedPoints = if (from.x == current.x) range(from.y, current.y).map { Point(from.x, it) } else range(from.x, current.x).map { Point(it, from.y) } blockedPoints.forEach { p -> blocked.add(p) } from = current } } return blocked } fun printState(blocked: Set<Point>, sand: Set<Point>) { for (x in 0..blocked.maxBy { it.x }.x + 1) { for (y in blocked.minBy { it.y }.y - 1..blocked.maxBy { it.y }.y + 1) { val element = Point(x, y) print( when { blocked.contains(element) -> '#' sand.contains(element) -> 'o' element.x == 0 && element.y == 500 -> '+' else -> '.' } ) } println() } println() } fun main() { fun part1(input: List<String>): Int { val blocked = getBlocked(input) var droppedSand = -1 val sand = mutableSetOf<Point>() val lowestX = blocked.maxBy { it.x }.x dropSand@ while (true) { // printState() var p = Point(0, 500) droppedSand++ moveSand@ while (true) { if (p.x == lowestX) { break@dropSand } val finalPosition = listOf(Point(p.x + 1, p.y), Point(p.x + 1, p.y - 1), Point(p.x + 1, p.y + 1)) .find { !blocked.contains(it) && !sand.contains(it)} ?: break@moveSand p = finalPosition } sand.add(p) } printState(blocked, sand) return droppedSand } fun part2(input: List<String>): Int { val blocked = getBlocked(input) var droppedSand = 0 val sand = mutableSetOf<Point>() val lowestX = blocked.maxBy { it.x }.x + 1 dropSand@ while (true) { // printState() var p = Point(0, 500) droppedSand++ moveSand@ while (true) { if (p.x == lowestX) break@moveSand val finalPosition = listOf(Point(p.x + 1, p.y), Point(p.x + 1, p.y - 1), Point(p.x + 1, p.y + 1)) .find { !blocked.contains(it) && !sand.contains(it)} if (finalPosition == null) { if (p.x == 0 && p.y == 500) { break@dropSand } else { break@moveSand } } p = finalPosition } sand.add(p) } printState(blocked, sand) return droppedSand } // test if implementation meets criteria from the description, like: val testInput = readInput("Day14_test") check(part1(testInput) == 24) // check(part2(testInput) == 2713358) //your answer is too low val input = readInput("Day14") check(part1(input) == 674) println(part1(input)) check(part2(input) == 24957) println(part2(input)) }
0
Kotlin
0
0
0a9b360a5fb8052565728e03a665656d1e68c687
3,640
advent-of-code-2022
Apache License 2.0
src/day12/Day12.kt
easchner
572,762,654
false
{"Kotlin": 104604}
package day12 import readInputString import java.lang.Integer.min import kotlin.system.measureNanoTime fun main() { fun buildMinMountain(mountain: Array<Array<Int>>, ey: Int, ex: Int): Array<Array<Int>> { val minMountain = Array(mountain.size) { Array(mountain[0].size) { Int.MAX_VALUE - 10 } } minMountain[ey][ex] = 0 var changed = true while (changed) { changed = false for (y in mountain.indices) { for (x in mountain[y].indices) { // UP if (y > 0 && mountain[y-1][x] <= mountain[y][x] + 1 && minMountain[y-1][x] + 1 < minMountain[y][x]) { minMountain[y][x] = minMountain[y-1][x] + 1 changed = true } // DOWN if (y < mountain.size - 1 && mountain[y+1][x] <= mountain[y][x] + 1 && minMountain[y+1][x] + 1 < minMountain[y][x]) { minMountain[y][x] = minMountain[y+1][x] + 1 changed = true } // LEFT if (x > 0 && mountain[y][x-1] <= mountain[y][x] + 1 && minMountain[y][x-1] + 1 < minMountain[y][x]) { minMountain[y][x] = minMountain[y][x-1] + 1 changed = true } // RIGHT if (x < mountain[0].size - 1 && mountain[y][x+1] <= mountain[y][x] + 1 && minMountain[y][x+1] + 1 < minMountain[y][x]) { minMountain[y][x] = minMountain[y][x+1] + 1 changed = true } } } } return minMountain } data class qElement (val y: Int, val x: Int, val dist: Int) fun bfs(mountain: Array<Array<Int>>, startLocations: List<qElement>, ey: Int, ex: Int): Int { val queue = mutableListOf<qElement>() val visited = Array(mountain.size) { Array(mountain[0].size ) { false } } for (e in startLocations) { queue.add(qElement(e.y, e.x, 0)) visited[e.y][e.x] = true } while (queue.isNotEmpty()) { val n = queue.removeFirst() // UP if (n.y > 0 && mountain[n.y-1][n.x] <= mountain[n.y][n.x] + 1 && !visited[n.y-1][n.x]) { if (n.y - 1 == ey && n.x == ex) return n.dist + 1 queue.add(qElement(n.y - 1, n.x, n.dist + 1)) visited[n.y-1][n.x] = true } // DOWN if (n.y < mountain.size - 1 && mountain[n.y+1][n.x] <= mountain[n.y][n.x] + 1 && !visited[n.y+1][n.x]) { if (n.y + 1 == ey && n.x == ex) return n.dist + 1 queue.add(qElement(n.y + 1, n.x, n.dist + 1)) visited[n.y+1][n.x] = true } // LEFT if (n.x > 0 && mountain[n.y][n.x-1] <= mountain[n.y][n.x] + 1 && !visited[n.y][n.x-1]) { if (n.y == ey && n.x - 1 == ex) return n.dist + 1 queue.add(qElement(n.y, n.x - 1, n.dist + 1)) visited[n.y][n.x-1] = true } // RIGHT if (n.x < mountain[0].size - 1 && mountain[n.y][n.x+1] <= mountain[n.y][n.x] + 1 && !visited[n.y][n.x+1]) { if (n.y == ey && n.x + 1 == ex) return n.dist + 1 queue.add(qElement(n.y, n.x + 1, n.dist + 1)) visited[n.y][n.x+1] = true } } return -1 } fun part1(input: List<String>): Int { val mountain = Array<Array<Int>>(input.size) { Array(input[0].length) { 0 } } var sy = 0 var sx = 0 var ey = 0 var ex = 0 for (y in input.indices) { for (x in 0 until input[y].length) { if (input[y][x] == 'S') { sy = y sx = x mountain[y][x] = 0 } else if (input[y][x] == 'E') { ey = y ex = x mountain[y][x] = 25 } else { mountain[y][x] = input[y][x] - 'a' } } } var minMountain = buildMinMountain(mountain, ey, ex) val minMountainTime = measureNanoTime { minMountain = buildMinMountain(mountain, ey, ex) } var bfsAnswer = bfs(mountain, listOf(qElement(sy, sx, 0)), ey, ex) val bfsTime = measureNanoTime { bfsAnswer = bfs(mountain, listOf(qElement(sy, sx, 0)), ey, ex) } println("=== PART ONE ===") println(" MinPathMountain Answer = ${minMountain[sy][sx]}") println(" BFS Answer = $bfsAnswer") println(" MinPathMountain Time = ${"%,d".format(minMountainTime).padStart(12)} ns") println(" BFS Time = ${"%,d".format(bfsTime).padStart(12)} ns") return minMountain[sy][sx] } fun part2(input: List<String>): Int { val mountain = Array<Array<Int>>(input.size) { Array(input[0].length) { 0 } } var ey = 0 var ex = 0 var starts = mutableListOf<qElement>() for (y in input.indices) { for (x in 0 until input[y].length) { if (input[y][x] == 'S' || input[y][x] == 'a') { starts.add(qElement(y, x, 0)) mountain[y][x] = 0 } else if (input[y][x] == 'E') { ey = y ex = x mountain[y][x] = 25 } else { mountain[y][x] = input[y][x] - 'a' } } } var minPath = Int.MAX_VALUE val minMountainTime = measureNanoTime { val minMountain = buildMinMountain(mountain, ey, ex) for (y in input.indices) { for (x in 0 until input[y].length) { if (input[y][x] == 'a' || input[y][x] == 'S') { minPath = min(minPath, minMountain[y][x]) } } } } var bfsAnswer = Int.MAX_VALUE val bfsTime = measureNanoTime { bfsAnswer = bfs(mountain, starts, ey, ex) } println("=== PART TWO ===") println(" MinPathMountain Answer = $minPath") println(" BFS Answer = $bfsAnswer") println(" MinPathMountain Time = ${"%,d".format(minMountainTime).padStart(12)} ns") println(" BFS Time = ${"%,d".format(bfsTime).padStart(12)} ns") return minPath } val testInput = readInputString("day12/test") val input = readInputString("day12/input") check(part1(testInput) == 31) println(part1(input)) check(part2(testInput) == 29) println(part2(input)) }
0
Kotlin
0
0
5966e1a1f385c77958de383f61209ff67ffaf6bf
6,911
Advent-Of-Code-2022
Apache License 2.0
src/Day01.kt
rtperson
434,792,067
false
{"Kotlin": 6811}
fun main() { fun part1(input: List<String>): Int { var lastNum = 20000000 var bigger = 0 for ( num in input ) { if (num.toInt() > lastNum) bigger += 1 lastNum = num.toInt() } return bigger } fun part2BruteForce(input: List<String>): Int { var lastNum = 20000000 var bigger = 0 for ( (index, num) in input.withIndex() ) { var sum = 0 if ( index == input.size - 1 ) { sum = num.toInt() } else if ( index == input.size - 2 ) { sum = num.toInt() + input[index + 1]!!.toInt() } else { sum = num.toInt() + input[index + 1]!!.toInt() + input[index + 2]!!.toInt() } if (sum > lastNum) { bigger++ } lastNum = sum } return bigger } fun part2(input: List<String>): Int { return input .map { it.toInt()} .windowed(3) .map { it.sum() } .windowed(2) .count { it[0] < it[1] } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") println(part2(testInput) ) check(part2(testInput) == 5) val input = readInput("Day01") //println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
ae827a46c8aba336a7d46762f4e1a94bc1b9d850
1,395
Advent_of_Code_Kotlin
Apache License 2.0
src/Day03.kt
HylkeB
573,815,567
false
{"Kotlin": 83982}
import java.lang.IllegalArgumentException fun main() { fun calculatePriorityOfItem(item: Char): Int { return when (item) { in 'a'..'z' -> 1 + (item - 'a') in 'A'..'Z' -> 27 + (item - 'A') else -> throw IllegalArgumentException("Unknown item: $item") } } fun part1(input: List<String>): Int { return input.sumOf { backpack -> val allItems = backpack.toList() val leftCompartment = allItems.subList(0, allItems.size / 2) val rightCompartment = allItems.subList(allItems.size / 2, allItems.size) val misplacedItem = leftCompartment.first { rightCompartment.contains(it) } calculatePriorityOfItem(misplacedItem) } } fun part2(input: List<String>): Int { val groupsOfElfBackpacks = input.fold(mutableListOf(mutableListOf<String>())) { acc, cur -> if (acc.last().size == 3) { acc.add(mutableListOf()) } acc.last().add(cur) acc } return groupsOfElfBackpacks.sumOf { group -> val badge = group[0].first { group[1].contains(it) && group[2].contains(it) } calculatePriorityOfItem(badge) } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day03_test") check(part1(testInput) == 157) check(part2(testInput) == 70) val input = readInput("Day03") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
8649209f4b1264f51b07212ef08fa8ca5c7d465b
1,562
advent-of-code-2022-kotlin
Apache License 2.0
src/main/kotlin/Day10.kt
cbrentharris
712,962,396
false
{"Kotlin": 171464}
import kotlin.String import kotlin.collections.List object Day10 { data class Coordinate(val x: Int, val y: Int) data class Node(val coordinate: Coordinate, val pipe: String, val connections: List<Coordinate>) fun part1(input: List<String>): String { val graph = parse(input) val nodesInLoop = findNodesInLoop(graph) val graphWithJunkRemoved = graph.filterKeys { it in nodesInLoop } return djikstras(graphWithJunkRemoved).values.max().toString() } private fun djikstras(graph: Map<Coordinate, Node>): Map<Coordinate, Int> { val startNode = graph.values.find { it.pipe == "S" }!! val dists = mutableMapOf<Coordinate, Int>() val unvisited = mutableSetOf<Coordinate>() for (node in graph.values) { unvisited.add(node.coordinate) } dists[startNode.coordinate] = 0 while (unvisited.isNotEmpty()) { val current = unvisited.minBy { dists[it] ?: Int.MAX_VALUE } unvisited.remove(current) for (connection in graph[current]?.connections ?: emptyList()) { val alt = dists.getOrPut(current) { 0 } + 1 if (alt < (dists[connection] ?: Int.MAX_VALUE)) { dists[connection] = alt } } } return dists } fun parse(input: List<String>): Map<Coordinate, Node> { val split = input.map { it.split("").filter { it.isNotBlank() } } val northDestinations = setOf("|", "7", "F", "S") val southDestinations = setOf("|", "J", "L", "S") val eastDestinations = setOf("-", "7", "J", "S") val westDestinations = setOf("-", "F", "L", "S") val nodes = split.mapIndexed { y, row -> row.mapIndexedNotNull { x, char -> val coordinate = Coordinate(x, y) when (char) { "|" -> { val connections = listOf( split.getOrNull(y - 1)?.getOrNull(x) ?.let { if (northDestinations.contains(it)) Coordinate(x, y - 1) else null }, split.getOrNull(y + 1)?.getOrNull(x) ?.let { if (southDestinations.contains(it)) Coordinate(x, y + 1) else null } ).filterNotNull() Node(coordinate, char, connections) } "-" -> { val connections = listOf( split.getOrNull(y)?.getOrNull(x - 1) ?.let { if (westDestinations.contains(it)) Coordinate(x - 1, y) else null }, split.getOrNull(y)?.getOrNull(x + 1) ?.let { if (eastDestinations.contains(it)) Coordinate(x + 1, y) else null } ).filterNotNull() Node(coordinate, char, connections) } "L" -> { val connections = listOf( split.getOrNull(y - 1)?.getOrNull(x) ?.let { if (northDestinations.contains(it)) Coordinate(x, y - 1) else null }, split.getOrNull(y)?.getOrNull(x + 1) ?.let { if (eastDestinations.contains(it)) Coordinate(x + 1, y) else null } ).filterNotNull() Node(coordinate, char, connections) } "J" -> { val connections = listOf( split.getOrNull(y - 1)?.getOrNull(x) ?.let { if (northDestinations.contains(it)) Coordinate(x, y - 1) else null }, split.getOrNull(y)?.getOrNull(x - 1) ?.let { if (westDestinations.contains(it)) Coordinate(x - 1, y) else null } ).filterNotNull() Node(coordinate, char, connections) } "7" -> { val connections = listOf( split.getOrNull(y + 1)?.getOrNull(x) ?.let { if (southDestinations.contains(it)) Coordinate(x, y + 1) else null }, split.getOrNull(y)?.getOrNull(x - 1) ?.let { if (westDestinations.contains(it)) Coordinate(x - 1, y) else null }, ).filterNotNull() Node(coordinate, char, connections) } "F" -> { val connections = listOf( split.getOrNull(y + 1)?.getOrNull(x) ?.let { if (southDestinations.contains(it)) Coordinate(x, y + 1) else null }, split.getOrNull(y)?.getOrNull(x + 1) ?.let { if (eastDestinations.contains(it)) Coordinate(x + 1, y) else null } ).filterNotNull() Node(coordinate, char, connections) } "S" -> { val connections = listOf( split.getOrNull(y - 1)?.getOrNull(x) ?.let { if (northDestinations.contains(it)) Coordinate(x, y - 1) else null }, split.getOrNull(y + 1)?.getOrNull(x) ?.let { if (southDestinations.contains(it)) Coordinate(x, y + 1) else null }, split.getOrNull(y)?.getOrNull(x - 1) ?.let { if (westDestinations.contains(it)) Coordinate(x - 1, y) else null }, split.getOrNull(y)?.getOrNull(x + 1) ?.let { if (eastDestinations.contains(it)) Coordinate(x + 1, y) else null } ).filterNotNull() Node(coordinate, char, connections) } else -> null } } }.flatten() return nodes.associateBy { it.coordinate } } fun part2(input: List<String>): String { val graph = parse(input) val nodesInLoop = findNodesInLoop(graph) val inputWithJunkPipesRemoved = input.mapIndexed { y, row -> row.mapIndexedNotNull { x, char -> val coordinate = Coordinate(x, y) if (char == '.' || coordinate !in nodesInLoop) { '.'.toString() } else { char.toString() } }.joinToString("") } val graphWithJunkRemoved = graph.filterKeys { it in nodesInLoop } val graphWithStartReplaced = graphWithJunkRemoved.map { (coordinate, node) -> if (node.pipe == "S") { coordinate to Node(coordinate, translate("S", node.connections), node.connections) } else { coordinate to node } }.toMap() val dots = inputWithJunkPipesRemoved.mapIndexed { y, row -> row.mapIndexedNotNull { x, char -> val coordinate = Coordinate(x, y) if (char == '.') { coordinate } else { null } } }.flatten().toSet() return dots.count { isInPolygon(graphWithStartReplaced, it) }.toString() } private fun translate(s: String, connections: List<Coordinate>): String { val sortedConnections = connections.sortedWith(compareBy({ it.x }, { it.y })) val northSouth = (sortedConnections.first().x - sortedConnections.last().x) == 0 val eastWest = (sortedConnections.first().y - sortedConnections.last().y) == 0 val eastNorth = sortedConnections.first().x > sortedConnections.last().x && sortedConnections.first().y < sortedConnections.last().y val eastSouth = sortedConnections.first().x > sortedConnections.last().x && sortedConnections.first().y > sortedConnections.last().y val westSouth = sortedConnections.first().x < sortedConnections.last().x && sortedConnections.first().y < sortedConnections.last().y val westNorth = sortedConnections.first().x < sortedConnections.last().x && sortedConnections.first().y > sortedConnections.last().y return when { eastWest -> "-" northSouth -> "|" eastNorth -> "L" eastSouth -> "F" westNorth -> "J" westSouth -> "7" else -> s } } private fun findNodesInLoop(graph: Map<Coordinate, Node>): Set<Coordinate> { val startNode = graph.values.find { it.pipe == "S" }!! val processed = mutableSetOf<Coordinate>() val unprocessed = ArrayDeque<Coordinate>() unprocessed.add(startNode.coordinate) while (unprocessed.isNotEmpty()) { val current = unprocessed.removeFirst() if (current in processed) { continue } unprocessed.addAll(graph[current]?.connections ?: emptyList()) processed.add(current) } return processed } /** * Modified ray cast algorithm to identify if a coordinate is within the loop. * * Instead of casting a simple ray any direction and seeing if it crosses an odd number of segments, * we cast rays in each direction and see if they cross an odd number of segments. Additionally * we collapse segments such as * F-- * | * --J * * into a single segment FJ */ private fun isInPolygon(graph: Map<Coordinate, Node>, it: Coordinate): Boolean { return isInPolygonAbove(graph, it) && isInPolygonBelow(graph, it) && isInPolygonLeft( graph, it ) && isInPolygonRight(graph, it) } /** * Modified ray cast algorithm to identify num segments right * * ------> ||| (true, 3) * ------> || (false, 2) */ fun isInPolygonRight(graph: Map<Coordinate, Node>, coordinate: Coordinate): Boolean { val intersectionsRight = graph.keys.filter { it.x > coordinate.x }.filter { it.y == coordinate.y } val directSegments = intersectionsRight .filter { graph[it]?.pipe == "|" } val indirectSegmentRightPairs = setOf("FJ", "L7") val indirectSegments = intersectionsRight .filter { graph[it]?.pipe != "-" } .zipWithNext().filter { (a, b) -> (graph[a]?.pipe + graph[b]?.pipe) in indirectSegmentRightPairs } return (indirectSegments.size + directSegments.size) % 2 == 1 } /** * Modified ray cast algorithm to identify num segments left * * ||| <------ (true, 3) * || <------ (false, 2) */ fun isInPolygonLeft(graph: Map<Coordinate, Node>, coordinate: Coordinate): Boolean { val intersectionsLeft = graph.keys.filter { it.x < coordinate.x }.filter { it.y == coordinate.y }.sortedByDescending { it.x } val directSegments = intersectionsLeft .filter { graph[it]?.pipe == "|" } val indirectSegmentLeftPairs = setOf("JF", "7L") val indirectSegments = intersectionsLeft .filter { graph[it]?.pipe != "-" } .zipWithNext().filter { (a, b) -> (graph[a]?.pipe + graph[b]?.pipe) in indirectSegmentLeftPairs } return (indirectSegments.size + directSegments.size) % 2 == 1 } /** * Modified ray cast algorithm to identify num segments below * * | * | * v * - * - * - (true, 3) * * | * | * v * - * - (false, 2) */ fun isInPolygonBelow(graph: Map<Coordinate, Node>, coordinate: Coordinate): Boolean { val intersectionsBelow = graph.keys.filter { it.y > coordinate.y }.filter { it.x == coordinate.x }.sortedBy { it.y } val directSegments = intersectionsBelow .filter { graph[it]?.pipe == "-" } val indirectSegmentSouthPairs = setOf("FJ", "7L") val indirectSegments = intersectionsBelow .filter { graph[it]?.pipe != "|" } .zipWithNext().filter { (a, b) -> (graph[a]?.pipe + graph[b]?.pipe) in indirectSegmentSouthPairs } return (indirectSegments.size + directSegments.size) % 2 == 1 } /** * Modified ray cast algorithm to identify num segments above * * - (true, 3) * - * - * ^ * | * | * * - (false, 2) * - * ^ * | * | */ fun isInPolygonAbove(graph: Map<Coordinate, Node>, coordinate: Coordinate): Boolean { graph.keys.filter { it.y < coordinate.y }.filter { it.x < coordinate.x } val intersectionsAbove = graph.keys.filter { it.y < coordinate.y }.filter { it.x == coordinate.x }.sortedByDescending { it.y } val directSegments = intersectionsAbove .filter { graph[it]?.pipe == "-" } val indirectSegmentNorthPairs = setOf("JF", "L7") val indirectSegments = intersectionsAbove .filter { graph[it]?.pipe != "|" } .zipWithNext().filter { (a, b) -> (graph[a]?.pipe + graph[b]?.pipe) in indirectSegmentNorthPairs } return (indirectSegments.size + directSegments.size) % 2 == 1 } }
0
Kotlin
0
1
f689f8bbbf1a63fecf66e5e03b382becac5d0025
13,645
kotlin-kringle
Apache License 2.0
src/Day06.kt
TrevorSStone
573,205,379
false
{"Kotlin": 9656}
fun main() { fun part1(input: List<String>): Int { val windowSize = 4 return input.sumOf { line -> line .asSequence() .withIndex() .windowed(windowSize, 1) .filter { it.map { it.value }.toSet().size == windowSize } .onEach { println(it) } .firstOrNull() ?.last() ?.index ?.plus(1) ?: 0 } } fun part2(input: List<String>): Int { val windowSize = 14 return input.sumOf { line -> line .asSequence() .withIndex() .windowed(windowSize, 1) .filter { it.map { it.value }.toSet().size == windowSize } .onEach { println(it) } .firstOrNull() ?.last() ?.index ?.plus(1) ?: 0 } } val testInput = readInput("Day06_test") check(part1(testInput).also { println(it) } == 7) check(part2(testInput).also { println(it) } == 19) // val input = readInput("Day06") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
2a48776f8bc10fe1d7e2bbef171bf65be9939400
1,049
advent-of-code-2022-kotlin
Apache License 2.0
src/Day02.kt
roxanapirlea
572,665,040
false
{"Kotlin": 27613}
fun main() { fun getOutcomeScore(you: Int, opponent: Int): Int { return when ((you - opponent).mod(3)) { 1 -> 6 2 -> 0 0 -> 3 else -> throw IllegalArgumentException() } } fun String.toRPSScore(): Int = when (this) { "A", "X" -> 1 "B", "Y" -> 2 "C", "Z" -> 3 else -> throw IllegalArgumentException() } fun String.outcomeToRPSScore(opponent: Int): Int { val score = when (this) { "X" -> (opponent-1).mod(3) "Y" -> opponent "Z" -> (opponent+1).mod(3) else -> throw IllegalArgumentException() } return if (score == 0) 3 else score } fun part1(input: List<String>): Long { return input.map { val opponent = it.substringBefore(" ").toRPSScore() val me = it.substringAfter(" ").toRPSScore() val outcome = getOutcomeScore(me, opponent) outcome + me.toLong() }.reduce { total, score -> total + score } } fun part2(input: List<String>): Long { return input.map { val opponent = it.substringBefore(" ").toRPSScore() val me = it.substringAfter(" ").outcomeToRPSScore(opponent) val outcome = getOutcomeScore(me, opponent) outcome + me.toLong() }.reduce { total, score -> total + score } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day02_test") check(part1(testInput) == 15L) check(part2(testInput) == 12L) val input = readInput("Day02") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
6c4ae6a70678ca361404edabd1e7d1ed11accf32
1,721
aoc-2022
Apache License 2.0
src/main/kotlin/ru/timakden/aoc/year2023/Day15.kt
timakden
76,895,831
false
{"Kotlin": 321649}
package ru.timakden.aoc.year2023 import ru.timakden.aoc.util.measure import ru.timakden.aoc.util.readInput /** * [Day 15: Lens Library](https://adventofcode.com/2023/day/15). */ object Day15 { @JvmStatic fun main(args: Array<String>) { measure { val input = readInput("year2023/Day15").single() println("Part One: ${part1(input)}") println("Part Two: ${part2(input)}") } } fun part1(input: String) = input.split(",").sumOf { it.hash() } fun part2(input: String): Int { val boxes = mutableMapOf<Int, MutableList<Pair<String, Int>>>() input.split(",").forEach { s -> val label = if (s.contains("-")) s.substringBefore("-") else s.substringBefore("=") val boxNumber = label.hash() val box = boxes[boxNumber] if (s.contains("-")) { box?.removeIf { it.first == label } } else { val focalLength = s.substringAfter("=").toInt() if (box == null) { boxes[boxNumber] = mutableListOf(label to focalLength) } else { val idx = box.indexOfFirst { it.first == label } if (idx != -1) box[idx] = label to focalLength else box += label to focalLength } } } return boxes.entries.sumOf { (boxIdx, lenses) -> lenses.foldIndexed(0.toInt()) { lensIdx, acc, (label, focalLength) -> acc + ((boxIdx + 1) * (lensIdx + 1) * focalLength) } } } private fun String.hash(): Int { var result = 0 this.forEach { c -> val asciiCode = c.code result += asciiCode result *= 17 result %= 256 } return result } }
0
Kotlin
0
3
acc4dceb69350c04f6ae42fc50315745f728cce1
1,837
advent-of-code
MIT License
src/Day02.kt
flexable777
571,712,576
false
{"Kotlin": 38005}
import Draw.* enum class Draw(val value: Int) { ROCK(1), PAPER(2), SCISSORS(3) } fun main() { fun getDraw(draw: String): Draw { return when (draw) { "A", "X" -> ROCK "B", "Y" -> PAPER "C", "Z" -> SCISSORS else -> error("Invalid draw") } } fun calculateScore(opponentDraw: Draw, playerDraw: Draw): Int { return when (opponentDraw) { ROCK -> { when (playerDraw) { ROCK -> ROCK.value + 3 PAPER -> PAPER.value + 6 SCISSORS -> SCISSORS.value + 0 } } PAPER -> { when (playerDraw) { ROCK -> ROCK.value + 0 PAPER -> PAPER.value + 3 SCISSORS -> SCISSORS.value + 6 } } SCISSORS -> { when (playerDraw) { ROCK -> ROCK.value + 6 PAPER -> PAPER.value + 0 SCISSORS -> SCISSORS.value + 3 } } } } fun chooseMyDraw(opponentDraw: Draw, strategy: String): Draw { return when (opponentDraw) { ROCK -> { when (strategy) { "X" -> SCISSORS "Y" -> ROCK "Z" -> PAPER else -> error("Invalid strategy") } } PAPER -> { when (strategy) { "X" -> ROCK "Y" -> PAPER "Z" -> SCISSORS else -> error("Invalid strategy") } } SCISSORS -> { when (strategy) { "X" -> PAPER "Y" -> SCISSORS "Z" -> ROCK else -> error("Invalid strategy") } } } } fun part1(input: List<String>): Int = input.sumOf { line -> val (opponentDraw, playerDraw) = line.split(" ").map { getDraw(it) } calculateScore(opponentDraw, playerDraw) } fun part2(input: List<String>): Int = input.sumOf { line -> val (opponentDraw, strategy) = line.split(" ") calculateScore(getDraw(opponentDraw), chooseMyDraw(getDraw(opponentDraw), strategy)) } val testInput = readInputAsLines("Day02_test") check(part1(testInput) == 15) check(part2(testInput) == 12) val input = readInputAsLines("Day02") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
d9a739eb203c535a3d83bc5da1b6a6a90a0c7bd6
2,663
advent-of-code-2022
Apache License 2.0
src/Day02.kt
dmstocking
575,012,721
false
{"Kotlin": 40350}
import java.lang.Exception enum class Play { ROCK, PAPER, SCISSORS; fun losses(other: Play): Boolean { return Play.values()[(this.ordinal + 1) % 3] == other } } fun Play.loser(): Play { return Play.values()[(this.ordinal - 1).mod(3)] } fun Play.winner(): Play { return Play.values()[(this.ordinal + 1).mod(3)] } fun main() { fun part1(input: List<String>): Int { return input.map { val (his, mine) = it.split("\\s".toRegex()) val play = when(his) { "A" -> Play.ROCK "B" -> Play.PAPER "C" -> Play.SCISSORS else -> throw Exception() } val response = when(mine) { "X" -> Play.ROCK "Y" -> Play.PAPER "Z" -> Play.SCISSORS else -> throw Exception() } val result = if (play == response) { 3 } else if (response.losses(play)) { 0 } else { 6 } result + response.ordinal + 1 } .sum() } fun part2(input: List<String>): Int { return input.map { val (his, mine) = it.split("\\s".toRegex()) val play = when(his) { "A" -> Play.ROCK "B" -> Play.PAPER "C" -> Play.SCISSORS else -> throw Exception() } val response = when(mine) { "X" -> play.loser() // Lose "Y" -> play // Draw "Z" -> play.winner() // Win else -> throw Exception() } val result = if (play == response) { 3 } else if (response.losses(play)) { 0 } else { 6 } result + response.ordinal + 1 } .sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day02_test") check(part1(testInput) == 15) val input = readInput("Day02") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
e49d9247340037e4e70f55b0c201b3a39edd0a0f
2,190
advent-of-code-kotlin-2022
Apache License 2.0
src/y2022/Day22.kt
gaetjen
572,857,330
false
{"Kotlin": 325874, "Mermaid": 571}
package y2022 import util.Direction import util.Direction.DOWN import util.Direction.LEFT import util.Direction.RIGHT import util.Direction.UP import util.Pos import util.get import util.printGrid import util.readInput import util.split import util.transpose object Day22 { sealed class Instruction { data class Walk(val distance: Int) : Instruction() data class Turn(val direction: Direction) : Instruction() } private fun parseInstructions(input: String): List<Instruction> { val distances = input.split("R", "L").map { Instruction.Walk(it.toInt()) } val turns = input.split(Regex("\\d+")).filter { it.isNotEmpty() }.map { Instruction.Turn(Direction.fromChar(it.first())) } return distances.zip(turns) { a, b -> listOf(a, b) }.flatten() + distances.last() } sealed class MapTile(open val pos: Pos, val real: Boolean) { data class Floor(override val pos: Pos) : MapTile(pos, true) class Wall(pos: Pos) : MapTile(pos, true) class Empty(pos: Pos) : MapTile(pos, false) } private fun parseMap(mapInput: List<String>): List<List<MapTile>> { val maxLength = mapInput.maxOf { it.length } return mapInput .map { it.padEnd(maxLength, ' ') } .mapIndexed { rowIdx, line -> line.mapIndexed { colIdx, c -> when (c) { ' ' -> MapTile.Empty(rowIdx to colIdx) '.' -> MapTile.Floor(rowIdx to colIdx) '#' -> MapTile.Wall(rowIdx to colIdx) else -> error("unknown map tile") } } } } fun part1(input: List<String>): Long { val (mapInput, walkInput) = input.split { it.isEmpty() } val tiles = parseMap(mapInput) val instructions = parseInstructions(walkInput.first()) val map = FlatMap(tiles) instructions.forEach { map.move(it) } return (map.pos.first + 1) * 1000L + (map.pos.second + 1) * 4 + dirNum(map.dir) } fun dirNum(dir: Direction): Int = when (dir) { RIGHT -> 0 DOWN -> 1 LEFT -> 2 UP -> 3 } abstract class MonkeyMap(val tiles: List<List<MapTile>>) { var pos: Pos = tiles.first().first { it.real }.pos var dir: Direction = RIGHT companion object { fun move(d: Direction, p: Pos): Pos = when (d) { UP -> p.first - 1 to p.second RIGHT -> p.first to p.second + 1 DOWN -> p.first + 1 to p.second LEFT -> p.first to p.second - 1 } } fun moveOne() { val newPos = constrain(move(dir, pos)) val (newTile, newDir) = realTile(newPos) if (newTile is MapTile.Floor) { pos = newTile.pos dir = newDir } if (newTile is MapTile.Empty) { error("landed on empty tile!") } } fun walk(walk: Instruction.Walk) { repeat(walk.distance) { moveOne() } } fun turn(turn: Instruction.Turn) { val arr = Direction.values() dir = arr[(arr.indexOf(dir) + arr.indexOf(turn.direction)) % 4] } fun move(move: Instruction) { when (move) { is Instruction.Walk -> walk(move) is Instruction.Turn -> turn(move) } } abstract fun realTile(at: Pos): Pair<MapTile, Direction> fun constrain(pos: Pos): Pos { return pos.first.mod(tiles.size) to pos.second.mod(tiles.first().size) } } class FlatMap(tiles: List<List<MapTile>>) : MonkeyMap(tiles) { val leftEdge: List<MapTile> = tiles.map { it.first { tile -> tile.real } } val rightEdge: List<MapTile> = tiles.map { it.last { tile -> tile.real } } val topEdge: List<MapTile> = tiles.transpose().map { it.first { tile -> tile.real } } val bottomEdge: List<MapTile> = tiles.transpose().map { it.last { tile -> tile.real } } override fun realTile(at: Pos): Pair<MapTile, Direction> { return if (tiles[at].real) { tiles[at] to dir } else { when (dir) { UP -> bottomEdge[at.second] DOWN -> topEdge[at.second] LEFT -> rightEdge[at.first] RIGHT -> leftEdge[at.first] } to dir } } } class CubeMap(tiles: List<List<MapTile>>) : MonkeyMap(tiles) { override fun realTile(at: Pos): Pair<MapTile, Direction> { if (tiles[at].real) { return tiles[at] to dir } return when { at.first == 50 && at.second in 100 until 150 && dir == DOWN -> tiles[at.second - 50 to 99] to LEFT at.first in 50 until 100 && at.second == 100 && dir == RIGHT -> tiles[49 to at.first + 50] to UP at.first == 99 && at.second in 0 until 50 && dir == UP -> tiles[50 + at.second to 50] to RIGHT at.first in 50 until 100 && at.second == 49 && dir == LEFT -> tiles[100 to at.first - 50] to DOWN at.first == 150 && at.second in 50 until 100 && dir == DOWN -> tiles[at.second + 100 to 49] to LEFT at.first in 150 until 200 && at.second == 50 && dir == RIGHT -> tiles[149 to at.first - 100] to UP at.first == 199 && at.second in 50 until 100 && dir == UP -> tiles[at.second + 100 to 0] to RIGHT at.first in 150 until 200 && at.second == 149 && dir == LEFT -> tiles[0 to at.first - 100] to DOWN at.first == 199 && at.second in 100 until 150 && dir == UP -> tiles[199 to at.second - 100] to UP at.first == 0 && at.second in 0 until 50 && dir == DOWN -> tiles[0 to at.second + 100] to DOWN at.first in 0 until 50 && at.second == 0 && dir == RIGHT -> tiles[149 - at.first to 99] to LEFT at.first in 100 until 150 && at.second == 100 && dir == RIGHT -> tiles[149 - at.first to 149] to LEFT at.first in 0 until 50 && at.second == 49 && dir == LEFT -> tiles[149 - at.first to 0] to RIGHT at.first in 100 until 150 && at.second == 149 && dir == LEFT -> tiles[149 - at.first to 50] to RIGHT else -> error("unexpected coordinates and dir: $pos, $dir") } } } fun debug(input: List<String>) { val (mapInput, _) = input.split { it.isEmpty() } val tiles = parseMap(mapInput) val map = CubeMap(tiles) val flat = FlatMap(tiles) val edges = listOf(flat.topEdge, flat.rightEdge, flat.bottomEdge, flat.leftEdge) val landingPoints = Direction.values().zip(edges).map { (d, ts) -> ts.map { map.pos = it.pos map.dir = d map.move(Instruction.Walk(1)) map.pos } } println("number points landing: ${landingPoints.flatten().size} / ${landingPoints.flatten().distinct().size}") println("number points edges: ${edges.flatten().size} / ${edges.flatten().distinct().size}") val flatEdges = edges.flatten().map { it.pos }.toSet() val flatLandings = landingPoints.flatten().toSet() printGrid(flatEdges.associateWith { "█" }) val edgeWalls = flatEdges.filter { map.tiles[it] is MapTile.Wall }.associateWith { "#" } val landingChars = flatLandings.associateWith { "█" } + edgeWalls printGrid(landingChars) } fun part2(input: List<String>): Long { val (mapInput, walkInput) = input.split { it.isEmpty() } val tiles = parseMap(mapInput) val instructions = parseInstructions(walkInput.first()) val map = CubeMap(tiles) instructions.forEach { map.move(it) } println("${map.pos} ${map.dir}, (${dirNum(map.dir)})") return (map.pos.first + 1) * 1000L + (map.pos.second + 1) * 4 + dirNum(map.dir) } } fun main() { val testInput = """ ...# .#.. #... .... ...#.......# ........#... ..#....#.... ..........#. ...#.... .....#.. .#...... ......#. 10R5L5R10L4R5L5 """.trimIndent().split("\n") println(testInput) println(listOf(1, 2, 3) + 4) println(listOf(1, 2, 3) + 4 + 5) println("------Tests------") println(Day22.part1(testInput)) //println(Day22.part2(testInput)) println("------Real------") val input = readInput("resources/2022/day22") Day22.debug(input) println(Day22.part1(input)) // 13383 println(Day22.part2(input)) }
0
Kotlin
0
0
d0b9b5e16cf50025bd9c1ea1df02a308ac1cb66a
8,799
advent-of-code
Apache License 2.0
2022/src/main/kotlin/Day02.kt
dlew
498,498,097
false
{"Kotlin": 331659, "TypeScript": 60083, "JavaScript": 262}
object Day02 { fun totalScore(input: String): Int { return input .splitNewlines() .map(String::splitWhitespace) .sumOf { score(it[0].toPlay(), it[1].toPlay()) } } fun totalScoreWithStrategy(input: String): Int { return input .splitNewlines() .map(String::splitWhitespace) .sumOf { score(it[0].toPlay(), it[1].toOutcome()) } } private fun score(opponent: Play, outcome: Outcome): Int { val you = when (outcome) { Outcome.WIN -> opponent.losesAgainst() Outcome.LOSE -> opponent.winsAgainst() Outcome.DRAW -> opponent } return score(opponent, you) } private fun score(opponent: Play, you: Play): Int { val outcome = when { opponent == you -> Outcome.DRAW opponent.losesAgainst() == you -> Outcome.WIN else -> Outcome.LOSE } return you.score + outcome.score } private enum class Play(val score: Int) { ROCK(1), PAPER(2), SCISSORS(3); fun winsAgainst() = values()[(ordinal + 2) % 3] fun losesAgainst() = values()[(ordinal + 1) % 3] } private enum class Outcome(val score: Int) { WIN(6), LOSE(0), DRAW(3) } private fun String.toPlay() = when (this) { "A" -> Play.ROCK "B" -> Play.PAPER "C" -> Play.SCISSORS "X" -> Play.ROCK "Y" -> Play.PAPER "Z" -> Play.SCISSORS else -> throw IllegalArgumentException("Illegal play: $this") } private fun String.toOutcome() = when (this) { "X" -> Outcome.LOSE "Y" -> Outcome.DRAW "Z" -> Outcome.WIN else -> throw IllegalArgumentException("Illegal play: $this") } }
0
Kotlin
0
0
6972f6e3addae03ec1090b64fa1dcecac3bc275c
1,617
advent-of-code
MIT License
src/main/kotlin/aoc2021/Day06.kt
j4velin
572,870,735
false
{"Kotlin": 285016, "Python": 1446}
package aoc2021 import readInput private class FishPopulation(input: List<String>) { // every slot in the array corresponds to one day in the fish cycle private val fishes = LongArray(9) private var currentDay = 0 init { input.first().split(",").map { it.toInt() }.forEach { fishes[it]++ } } fun advanceDay() { val currentSlot = currentDay % fishes.size // current fishes cycle is reset to 6 'after another day' -> 7 today fishes[(currentSlot + 7) % fishes.size] += fishes[currentSlot] // newborn fishes are set to 8 from tomorrow -> 9 today -> currentSlot again, so we simply keep the current // value at the current slot to represent those new baby fish currentDay++ } fun getTotalPopulation() = fishes.sum() } private fun part1(input: List<String>): Long { val population = FishPopulation(input) repeat(80) { population.advanceDay() } return population.getTotalPopulation() } private fun part2(input: List<String>): Long { val population = FishPopulation(input) repeat(256) { population.advanceDay() } return population.getTotalPopulation() } fun main() { // test if implementation meets criteria from the description, like: val testInput = readInput("Day06_test") check(part1(testInput) == 5934L) check(part2(testInput) == 26984457539L) val input = readInput("Day06") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
f67b4d11ef6a02cba5b206aba340df1e9631b42b
1,469
adventOfCode
Apache License 2.0
src/leecode/63.kt
DavidZhong003
157,566,685
false
null
package leecode /** * 一个机器人位于一个 m x n 网格的左上角 (起始点在下图中标记为“Start” )。 机器人每次只能向下或者向右移动一步。机器人试图达到网格的右下角(在下图中标记为“Finish”)。 现在考虑网格中有障碍物。那么从左上角到右下角将会有多少条不同的路径? 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/unique-paths-ii 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 * @author doive * on 2020/1/6 19:52 */ fun main() { uniquePathsWithObstacles(arrayOf(intArrayOf(0,0))).println() uniquePathsWithObstacles(arrayOf(intArrayOf(0), intArrayOf(0))).println() uniquePathsWithObstacles(arrayOf(intArrayOf(0,0))).println() } fun uniquePathsWithObstacles(obstacleGrid: Array<IntArray>): Int { if(obstacleGrid.isEmpty()||obstacleGrid[0][0]==1){ return 0 } val row = obstacleGrid.size val column = obstacleGrid[0].size obstacleGrid[0][0] = 1 for(i in 1 until column){ obstacleGrid[0][i] = if(obstacleGrid[0][i]== 0 && obstacleGrid[0][i-1]==1) 1 else 0 } for(j in 1 until row){ obstacleGrid[j][0] = if(obstacleGrid[j][0] == 0 && obstacleGrid[j-1][0]==1)1 else 0 } for(r in 1 until row){ for(c in 1 until column){ obstacleGrid [r][c] = if(obstacleGrid[r][c] == 0) (obstacleGrid[r-1][c]+ obstacleGrid[r][c-1]) else 0 } } return obstacleGrid[row-1][column-1] }
0
Kotlin
0
1
7eabe9d651013bf06fa813734d6556d5c05791dc
1,559
LeetCode-kt
Apache License 2.0
src/main/kotlin/algosds/dynamicprogramming/ClimbingStairs.kt
jewell-lgtm
569,792,185
false
{"Kotlin": 161272, "Jupyter Notebook": 103410, "TypeScript": 78635, "JavaScript": 123}
package algosds.dynamicprogramming import util.timeIt import kotlin.math.min import kotlin.random.Random // For a given staircase, the i-th step is assigned a non-negative cost indicated by a cost array. // Once you pay the cost for a step, you can either climb one or two steps. Find the minimum cost to reach the top of the staircase. // Your first step can either be the first or second step. // e.g. cost = [10,15,30] fun main() { val a = listOf(1, 1, 2, 3, 5, 8, 13, 10, 20, 30, 40, 1, 2, 3, 4) val b = generateRandomInts(9999) timeIt { println(calculateCostToRecursive(a)) println(calculateCostToRecursive(b)) } timeIt { println(calculateCostToIterative(a)) println(calculateCostToIterative(b)) } val randoms = listOf(9, 99, 999, 9999, 99999, 999999, 9999999, 99999999).map { max -> generateRandomInts(max) } randoms.forEach { costs -> println(costs.size) timeIt { calculateCostToIterative(costs) } } println(calculateCostToRecursive(a) == calculateCostToIterative(a)) println(calculateCostToRecursive(b) == calculateCostToRecursive(b)) } private fun generateRandomInts(i: Int) = (0..i).map { Random.nextInt(0, i) } fun Int?.unwrap(): Int { if (this == null) error("Value should not be null") return this } interface LRUCache { operator fun set(key: Int, value: Int) operator fun get(key: Int): Int // in this example require cache hit } fun getCache(capacity: Int): LRUCache { val map = mutableMapOf<Int, Int>() return object : LRUCache { override fun set(key: Int, value: Int) { if (map.size >= capacity) { val oldestKey = map.keys.iterator().next() map.remove(oldestKey) } map[key] = value } override fun get(key: Int): Int { val value = map[key].unwrap() // throw on cache miss // remove the key and reinsert to put it at the top map.remove(key) map[key] = value return value } } } fun calculateCostToIterative(costs: List<Int>): Int { return when (costs.size) { 0 -> 0 1 -> 0 2 -> min(costs[0], costs[1]) else -> (2 until costs.size) .fold(costs.getInitialCache()) { cache, index -> cache.apply { val cost1 = get(index - 1) val cost2 = get(index - 2) val costThis = costs[index] set(index, costThis + min(cost1, cost2)) } }.let { cache -> min(cache[costs.size - 1], cache[costs.size - 2]) } } } fun List<Int>.getInitialCache() = getCache(3).also { it[0] = this[0] it[1] = this[1] } fun calculateCostToRecursive(costs: List<Int>): Int { val memo = mutableMapOf<Int, Int>() fun List<Int>.costAt(index: Int): Int { if (index == this.size) return 0 if (index < 0) return 0 return this[index] } var comparisons = 0 fun minCostTo(index: Int): Int { comparisons++ if (index < 2) return costs.costAt(index) return memo.getOrPut(index) { costs.costAt(index) + min(minCostTo(index - 2), minCostTo(index - 1)) } // return costs.costAt(index) + min(minCostTo(index - 2), minCostTo(index - 1)) } return minCostTo(costs.size) }
0
Kotlin
0
0
b274e43441b4ddb163c509ed14944902c2b011ab
3,419
AdventOfCode
Creative Commons Zero v1.0 Universal
src/main/kotlin/day17/Day17.kt
daniilsjb
572,664,294
false
{"Kotlin": 69004}
package day17 import java.io.File import kotlin.math.max fun main() { val data = parse("src/main/kotlin/day17/Day17.txt") val answer1 = part1(data) val answer2 = part2(data) println("🎄 Day 17 🎄") println() println("[Part 1]") println("Answer: $answer1") println() println("[Part 2]") println("Answer: $answer2") } @Suppress("SameParameterValue") private fun parse(path: String): List<Int> = File(path).readText().trim() .map { if (it == '>') +1 else -1 } private val shapes = listOf( setOf(0 to 0, 1 to 0, 2 to 0, 3 to 0), setOf(1 to 0, 0 to 1, 1 to 1, 2 to 1, 1 to 2), setOf(0 to 0, 1 to 0, 2 to 0, 2 to 1, 2 to 2), setOf(0 to 0, 0 to 1, 0 to 2, 0 to 3), setOf(0 to 0, 1 to 0, 0 to 1, 1 to 1), ) private data class State( val shifts: List<Int>, val obstacles: MutableSet<Pair<Int, Int>> = mutableSetOf(), var shapeIndex: Int = 0, var shiftIndex: Int = 0, var height: Int = 0, ) private data class Step( val ceiling: List<Int>, val shapeIndex: Int, val shiftIndex: Int, ) private fun State.step() { var shape = shapes[shapeIndex++ % shapes.size] .map { (x, y) -> (2 + x) to (height + 3 + y) } .toSet() while (true) { val shift = shifts[shiftIndex++ % shifts.size] val shiftedShapeX = shape .map { (x, y) -> (x + shift) to y } .toSet() if (shiftedShapeX.all { (x, _) -> x in 0..6 }) { if ((shiftedShapeX intersect obstacles).isEmpty()) { shape = shiftedShapeX } } val shiftedShapeY = shape .map { (x, y) -> x to (y - 1) } .toSet() if (shiftedShapeY.all { (_, y) -> y >= 0 }) { if ((shiftedShapeY intersect obstacles).isEmpty()) { shape = shiftedShapeY continue } } break } obstacles += shape height = max(height, shape.maxOf { (_, y) -> y } + 1) } private fun solve(shifts: List<Int>, count: Long): Long { val state = State(shifts) val history = mutableMapOf<Step, Pair<Int, Int>>() while (true) { state.step() val highest = state.obstacles.maxOf { (_, y) -> y } val ceiling = state.obstacles .groupBy { (x, _) -> x }.entries .sortedBy { (x, _) -> x } .map { (_, points) -> points.maxOf { (_, y) -> y } } .let { ys -> ys.map { y -> highest - y } } val step = Step( ceiling = ceiling, shapeIndex = state.shapeIndex % shapes.size, shiftIndex = state.shiftIndex % shifts.size, ) if (step !in history) { history[step] = state.shapeIndex to state.height continue } val (shapeCount, height) = history.getValue(step) val shapesPerCycle = state.shapeIndex - shapeCount val cycleCount = (count - shapeCount) / shapesPerCycle val cycleHeight = state.height - height val shapesRemain = (count - shapeCount) - (shapesPerCycle * cycleCount) repeat(shapesRemain.toInt()) { state.step() } return state.height + (cycleHeight * (cycleCount - 1)) } } private fun part1(shifts: List<Int>): Long = solve(shifts, count = 2022L) private fun part2(shifts: List<Int>): Long = solve(shifts, count = 1_000_000_000_000L)
0
Kotlin
0
0
6f0d373bdbbcf6536608464a17a34363ea343036
3,440
advent-of-code-2022
MIT License
calendar/day13/Day13.kt
maartenh
572,433,648
false
{"Kotlin": 50914}
package day13 import Day import Lines import tools.* import kotlin.math.min class Day13 : Day() { override fun part1(input: Lines): Any { val packetPairs = parsePacketPairs(input) return packetPairs .map { it.first < it.second } .zip(1..packetPairs.size) .filter { it.first } .sumOf { it.second } } override fun part2(input: Lines): Any { val dividerPackets = listOf(2, 6) .map { PacketList(listOf(PacketList(listOf(IntPacket(it))))) } val sortedPackets = (parsePackets(input) + dividerPackets).sorted() return (sortedPackets.indexOf(dividerPackets[0]) + 1) * (sortedPackets.indexOf(dividerPackets[1]) + 1) } private fun parsePacketPairs(input: Lines) = input .splitAt { it.isEmpty() } .map { Pair( runParser(packet(), it.first()), runParser(packet(), it.last()) ) } private fun parsePackets(input: Lines) = input .filter { it.isNotEmpty() } .map { runParser(packet(), it) } sealed interface Packet : Comparable<Packet> data class PacketList(val packets: List<Packet>): Packet { override fun compareTo(other: Packet): Int = when (other) { is IntPacket -> this.compareTo(PacketList(listOf(other))) is PacketList -> this.packets.compareTo(other.packets) } } data class IntPacket(val value: Int): Packet { override fun compareTo(other: Packet): Int = when (other) { is IntPacket -> this.value.compareTo(other.value) is PacketList -> PacketList(listOf(this)).compareTo(other) } } private fun packet(): Parser<Packet> = intPacket() or { packetList() } private fun intPacket(): Parser<Packet> = int().map { i -> IntPacket(i) } private fun packetList(): Parser<Packet> = packet().list(string(",")).surround("[", "]").map { pl -> PacketList(pl) } } fun <T: Comparable<T>> List<T>.compareTo(other: List<T>): Int { val maxIndex = min(this.size, other.size) - 1 for (index in 0..maxIndex) { val elementResult = this[index].compareTo(other[index]) if (elementResult != 0) { return elementResult } } return this.size.compareTo(other.size) }
0
Kotlin
0
0
4297aa0d7addcdc9077f86ad572f72d8e1f90fe8
2,408
advent-of-code-2022
Apache License 2.0
src/main/kotlin/KInversePairsArray.kt
Codextor
453,514,033
false
{"Kotlin": 26975}
/** * For an integer array nums, an inverse pair is a pair of integers [i, j] where 0 <= i < j < nums.length and nums[i] > nums[j]. * * Given two integers n and k, return the number of different arrays consist of numbers from 1 to n such that there are exactly k inverse pairs. * Since the answer can be huge, return it modulo 10^9 + 7. * * * * Example 1: * * Input: n = 3, k = 0 * Output: 1 * Explanation: Only the array [1,2,3] which consists of numbers from 1 to 3 has exactly 0 inverse pairs. * Example 2: * * Input: n = 3, k = 1 * Output: 2 * Explanation: The array [1,3,2] and [2,1,3] have exactly 1 inverse pair. * * * Constraints: * * 1 <= n <= 1000 * 0 <= k <= 1000 * @see <a href="https://leetcode.com/problems/k-inverse-pairs-array/">LeetCode</a> */ fun kInversePairs(n: Int, k: Int): Int { val memoryArray = Array<IntArray>(n + 1) { IntArray(k + 1) { -1 } } return numberOfArrays(n, k, memoryArray) } fun numberOfArrays(numberOfElements: Int, numberOfInversePairsRequired: Int, memoryArray: Array<IntArray>): Int { // since 1 <= numberOfElements, numberOfInversePairsRequired = 0 can only be achieved in one way, // by arranging the elements of the array in increasing order if (numberOfInversePairsRequired == 0) { return 1 } // if numberOfInversePairsRequired is non zero, it cannot be achieved with just one element if (numberOfElements == 1 || numberOfInversePairsRequired < 0) { return 0 } if (memoryArray[numberOfElements][numberOfInversePairsRequired] != -1) { return memoryArray[numberOfElements][numberOfInversePairsRequired] } var totalNumberOfArrays = 0 for (numberOfInversePairsEncountered in 0 until numberOfElements) { totalNumberOfArrays = ( totalNumberOfArrays + numberOfArrays( numberOfElements - 1, numberOfInversePairsRequired - numberOfInversePairsEncountered, memoryArray ) ).mod(1_00_00_00_007) } memoryArray[numberOfElements][numberOfInversePairsRequired] = totalNumberOfArrays return totalNumberOfArrays }
0
Kotlin
1
0
68b75a7ef8338c805824dfc24d666ac204c5931f
2,180
kotlin-codes
Apache License 2.0
google/2019/round1_b/1/main.kt
seirion
17,619,607
false
{"C++": 801740, "HTML": 42242, "Kotlin": 37689, "Python": 21759, "C": 3798, "JavaScript": 294}
import java.util.* fun main(args: Array<String>) { val t = readLine()!!.toInt() repeat(t) { solve(it) } } data class Input(val x: Int, val y: Int, val c: Char) fun solve(num: Int) { val (P, _) = readLine()!!.split(" ").map { it.toInt() } val xValues = TreeMap<Int, Int>() val yValues = TreeMap<Int, Int>() val data = ArrayList<Input>() repeat(P) { val (xx, yy, d) = readLine()!!.split(" ") val x = xx.toInt() val y = yy.toInt() data.add(Input(x, y, d[0])) xValues[x] = 0 yValues[y] = 0 when (d[0]) { 'W' -> xValues[x - 1] = 0 'E' -> xValues[x + 1] = 0 'S' -> yValues[y - 1] = 0 else -> yValues[y + 1] = 0 } } xValues[0] = 0 yValues[0] = 0 data.forEach { inputData -> when (inputData.c) { 'W' -> put(xValues) { it < inputData.x } 'E' -> put(xValues) { it > inputData.x } 'S' -> put(yValues) { it < inputData.y } else -> put(yValues) { it > inputData.y } } } val xMax = xValues.maxBy { it.value }!! val yMax = yValues.maxBy { it.value }!! println("Case #${num + 1}: ${xMax.key} ${yMax.key}") } fun put(m: MutableMap<Int, Int>, predicate: (Int) -> Boolean) { m.map { it.key } .filter(predicate = predicate) .forEach { m[it] = m[it]!! + 1 } }
0
C++
4
4
a59df98712c7eeceabc98f6535f7814d3a1c2c9f
1,412
code
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/MaxDetonation.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2023 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import java.util.Deque import java.util.LinkedList import java.util.Stack import kotlin.math.max /** * 2101. Detonate the Maximum Bombs * @see <a href="https://leetcode.com/problems/detonate-the-maximum-bombs/">Source</a> */ fun interface MaxDetonation { fun maximumDetonation(bombs: Array<IntArray>): Int fun getGraph(bombs: Array<IntArray>): Pair<MutableMap<Int, MutableList<Int>>, Int> { val graph: MutableMap<Int, MutableList<Int>> = HashMap() val n: Int = bombs.size // Build the graph // Build the graph for (i in 0 until n) { for (j in 0 until n) { if (i == j) { continue } val xi = bombs[i][0] val yi = bombs[i][1] val ri = bombs[i][2] val xj = bombs[j][0] val yj = bombs[j][1] // Create a path from node i to node j, if bomb i detonates bomb j. if (ri.toLong() * ri >= (xi - xj).toLong() * (xi - xj) + (yi - yj).toLong() * (yi - yj)) { graph.computeIfAbsent( i, ) { _: Int? -> ArrayList() }.add(j) } } } return graph to n } } /** * Approach 1: Depth-First Search, Recursive */ class MaxDetonationRecursive : MaxDetonation { override fun maximumDetonation(bombs: Array<IntArray>): Int { val (graph, n) = getGraph(bombs) var answer = 0 for (i in 0 until n) { val count = dfs(i, HashSet(), graph) answer = max(answer, count) } return answer } // DFS to get the number of nodes reachable from a given node cur private fun dfs(cur: Int, visited: MutableSet<Int>, graph: Map<Int, List<Int>>): Int { visited.add(cur) var count = 1 for (neib in graph[cur] ?: ArrayList()) { if (!visited.contains(neib)) { count += dfs(neib, visited, graph) } } return count } } /** * Approach 2: Depth-First Search, Iterative */ class MaxDetonationIterative : MaxDetonation { override fun maximumDetonation(bombs: Array<IntArray>): Int { val (graph, n) = getGraph(bombs) var answer = 0 for (i in 0 until n) { answer = max(answer, dfs(i, graph)) } return answer } private fun dfs(i: Int, graph: Map<Int, List<Int>>): Int { val stack: Stack<Int> = Stack() val visited: MutableSet<Int> = HashSet() stack.push(i) visited.add(i) while (stack.isNotEmpty()) { val cur: Int = stack.pop() for (neib in graph[cur] ?: ArrayList()) { if (!visited.contains(neib)) { visited.add(neib) stack.push(neib) } } } return visited.size } } /** * Approach 3: Breadth-First Search */ class MaxDetonationBFS : MaxDetonation { override fun maximumDetonation(bombs: Array<IntArray>): Int { val (graph, n) = getGraph(bombs) var answer = 0 for (i in 0 until n) { answer = max(answer, bfs(i, graph)) } return answer } private fun bfs(i: Int, graph: Map<Int, List<Int>>): Int { val queue: Deque<Int> = LinkedList() val visited: MutableSet<Int> = HashSet() queue.offer(i) visited.add(i) while (queue.isNotEmpty()) { val cur = queue.poll() for (nib in graph[cur] ?: ArrayList()) { if (!visited.contains(nib)) { visited.add(nib) queue.offer(nib) } } } return visited.size } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
4,457
kotlab
Apache License 2.0
y2018/src/main/kotlin/adventofcode/y2018/Day14.kt
Ruud-Wiegers
434,225,587
false
{"Kotlin": 503769}
package adventofcode.y2018 import adventofcode.io.AdventSolution fun main() = repeat(10){Day14.solve()} object Day14 : AdventSolution(2018, 14, "Chocolate Charts") { override fun solvePartOne(input: String): String { val targetSize = input.toInt() + 10 return generateRecipes { it.size == targetSize } .takeLast(10) .joinToString("") } override fun solvePartTwo(input: String): Int { val target = input.map { it - '0' } val recipes = generateRecipes { it.endMatches(target) } return recipes.size - target.size } private fun generateRecipes(stop: (List<Int>) -> Boolean): MutableList<Int> { val recipes = mutableListOf(3, 7) var e1 = 0 var e2 = 1 while (true) { var score = recipes[e1] + recipes[e2] if (score >= 10) { recipes += 1 if (stop(recipes)) return recipes score -= 10 } recipes += score if (stop(recipes)) return recipes e1 = (e1 + recipes[e1] + 1) while (e1 >= recipes.size) e1 -= recipes.size e2 = (e2 + recipes[e2] + 1) while (e2 >= recipes.size) e2 -= recipes.size } } //faster version of takeLast(end.size)==end private fun List<Int>.endMatches(end: List<Int>) = this.size >= end.size && end.indices.all { end[it] == this[size - end.size + it] } }
0
Kotlin
0
3
fc35e6d5feeabdc18c86aba428abcf23d880c450
1,484
advent-of-code
MIT License
year2015/src/main/kotlin/net/olegg/aoc/year2015/day6/Day6.kt
0legg
110,665,187
false
{"Kotlin": 511989}
package net.olegg.aoc.year2015.day6 import net.olegg.aoc.someday.SomeDay import net.olegg.aoc.year2015.DayOf2015 /** * See [Year 2015, Day 6](https://adventofcode.com/2015/day/6) */ object Day6 : DayOf2015(6) { private fun toPoints(command: String): List<Int> { val matcher = "\\D*(\\d+),(\\d+)\\D*(\\d+),(\\d+)\\D*".toPattern().matcher(command) matcher.find() return (1..4).map { matcher.group(it).toInt() } } override fun first(): Any? { return lines.fold(Array(1000) { Array(1000) { false } }) { acc, value -> val points = toPoints(value) (points[0]..points[2]).forEach { row -> (points[1]..points[3]).forEach { column -> acc[row][column] = when { value.startsWith("toggle") -> !acc[row][column] value.startsWith("turn on") -> true value.startsWith("turn off") -> false else -> acc[row][column] } } } acc }.sumOf { row -> row.count { it } } } override fun second(): Any? { return lines.fold(Array(1000) { Array(1000) { 0 } }) { acc, value -> val points = toPoints(value) (points[0]..points[2]).forEach { row -> (points[1]..points[3]).forEach { column -> acc[row][column] += when { value.startsWith("toggle") -> 2 value.startsWith("turn on") -> 1 value.startsWith("turn off") && acc[row][column] > 0 -> -1 else -> 0 } } } acc }.sumOf { it.sum() } } } fun main() = SomeDay.mainify(Day6)
0
Kotlin
1
7
e4a356079eb3a7f616f4c710fe1dfe781fc78b1a
1,551
adventofcode
MIT License
src/Day07.kt
cornz
572,867,092
false
{"Kotlin": 35639}
import java.util.* fun main() { fun getDirSizes(input: List<String>): HashMap<String, Int> { val directories = Stack<String>() val directorySizes = HashMap<String, Int>() for ((index, line) in input.withIndex()) { val splitLine = line.split(" ") if (splitLine[1] == "cd") { if (splitLine[2] == "..") { directories.pop() } else { directories.push(splitLine[2] + "_" + index) } } else if (splitLine[0].toIntOrNull() != null) { val size = splitLine[0].toInt() for (directory in directories) { if (directorySizes.containsKey(directory)) { directorySizes[directory] = directorySizes.getValue(directory) + size } else { directorySizes[directory] = size } } } } return directorySizes } fun part1(input: List<String>): Int { return getDirSizes(input).values.filter { it <= 100000 }.sum() } fun part2(input: List<String>): Int { val spaceAvailable = 70000000 val spaceUnused = spaceAvailable - getDirSizes(input).values.max() val spaceRequired = 30000000 - spaceUnused return getDirSizes(input).values.filter { it - spaceRequired > 0 }.min() } // test if implementation meets criteria from the description, like: val testInput = readInput("input/Day07_test") check(part1(testInput) == 95437) check(part2(testInput) == 24933642) val input = readInput("input/Day07") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
2800416ddccabc45ba8940fbff998ec777168551
1,738
aoc2022
Apache License 2.0
src/main/kotlin/de/mbdevelopment/adventofcode/year2021/solvers/day8/Day8Puzzle2.kt
Any1s
433,954,562
false
{"Kotlin": 96683}
package de.mbdevelopment.adventofcode.year2021.solvers.day8 import de.mbdevelopment.adventofcode.year2021.solvers.PuzzleSolver class Day8Puzzle2 : PuzzleSolver { override fun solve(inputLines: Sequence<String>) = sumOfDecodedNumbers(inputLines).toString() private fun sumOfDecodedNumbers(digitSignalsAndReading: Sequence<String>) = digitSignalsAndReading .filter { it.isNotBlank() } .map { it.split(" | ") } .map { decodeNumberByElimination(it[0].split(' '), it[1].split(' ')) } .sum() private fun decodeNumberByElimination(uniquePatterns: List<String>, digits: List<String>): Int { val number1 = uniquePatterns.single { it.length == 2 }.toSet() val number4 = uniquePatterns.single { it.length == 4 }.toSet() val number7 = uniquePatterns.single { it.length == 3 }.toSet() val number8 = uniquePatterns.single { it.length == 7 }.toSet() val unknownNumbersOfLength5 = uniquePatterns.filter { it.length == 5 }.map { it.toSet() }.toMutableSet() val unknownNumbersOfLength6 = uniquePatterns.filter { it.length == 6 }.map { it.toSet() }.toMutableSet() val segmentA = (number7 - number1).single() val segmentG = unknownNumbersOfLength5.reduce(Collection<Char>::intersect) .intersect(unknownNumbersOfLength6.reduce(Collection<Char>::intersect)) .minus(number4) .minus(number7) .single() val segmentE = (number8 - segmentG - number4 - number7).single() val number2 = unknownNumbersOfLength5.single { it.containsAll(listOf(segmentA, segmentE, segmentG)) } unknownNumbersOfLength5 -= number2 val segmentF = unknownNumbersOfLength5.reduce(Collection<Char>::intersect).minus(number2).single() val segmentB = unknownNumbersOfLength5.reduce { a, b -> (a - b).union(b - a) }.minus(number2).single() val number5 = unknownNumbersOfLength5.single { it.contains(segmentB) } unknownNumbersOfLength5 -= number5 val number3 = unknownNumbersOfLength5.single() val segmentC = (number7 - segmentA - segmentF).single() val allPossibleCorrectSegments = setOf('a', 'b', 'c', 'd', 'e', 'f', 'g') val segmentD = allPossibleCorrectSegments.asSequence() .minus(segmentA).minus(segmentB).minus(segmentC).minus(segmentE).minus(segmentF).minus(segmentG) .single() val number0 = unknownNumbersOfLength6.single { !it.contains(segmentD) } unknownNumbersOfLength6 -= number0 val number6 = unknownNumbersOfLength6.single { !it.contains(segmentC) } unknownNumbersOfLength6 -= number6 val number9 = unknownNumbersOfLength6.single() val decoder = mapOf( number0 to '0', number1 to '1', number2 to '2', number3 to '3', number4 to '4', number5 to '5', number6 to '6', number7 to '7', number8 to '8', number9 to '9', ) return digits.map { it.toSet() }.mapNotNull { decoder[it] }.joinToString("").toInt() } }
0
Kotlin
0
0
21d3a0e69d39a643ca1fe22771099144e580f30e
3,126
AdventOfCode2021
Apache License 2.0
src/main/aoc2016/Day4.kt
nibarius
154,152,607
false
{"Kotlin": 963896}
package aoc2016 class Day4(input: List<String>) { companion object { private val alphabet = ('a'..'z').toList().joinToString("") fun decrypt(name: String, sectorId: Int): String { return name.map { when (it) { '-' -> ' ' else -> alphabet[(alphabet.indexOf(it) + sectorId) % alphabet.length] } }.joinToString("") } } private data class Room(val name: String, val sectorId: Int, val checksum: String) { fun isReal(): Boolean { // Count number of each letter in the name val occurrences = mutableMapOf<Char, Int>() name.filterNot { it == '-' }.forEach { if (occurrences.containsKey(it)) { occurrences[it] = occurrences[it]!! + 1 } else { occurrences[it] = 1 } } // first number of occurrences (larger first), after that alphabetical order (lower first) val sorted = occurrences.toList().sortedWith(compareBy({ -it.second }, { it.first })) // take the letter (it.first) of the first 5 items and make a string of it val chk: String = sorted.take(5).map { it.first }.joinToString("") return chk == checksum } fun decryptName() = decrypt(name, sectorId) } private val rooms = process(input) private fun process(input: List<String>): List<Room> { val rooms = mutableListOf<Room>() input.forEach { rooms.add(Room(it.substringBeforeLast("-"), it.substringAfterLast("-").substringBefore("[").toInt(), it.substringAfter("[").substringBefore("]"))) } return rooms } fun solvePart1(): Int { return rooms.filter { it.isReal() }.sumOf { it.sectorId } } fun solvePart2(): Int { return rooms.filter { it.isReal() }.find { it.decryptName().contains("northpole") }!!.sectorId } }
0
Kotlin
0
6
f2ca41fba7f7ccf4e37a7a9f2283b74e67db9f22
2,054
aoc
MIT License
src/Day04.kt
gojoel
573,543,233
false
{"Kotlin": 28426}
fun main() { val input = readInput("04") // val input = readInput("04_test") data class Section(val lower: Int, val upper: Int) fun getPairs(input: List<String>) : ArrayList<Pair<Section, Section>> { val list: ArrayList<Pair<Section, Section>> = arrayListOf() input.map {line -> line.split(",") .also { sections -> val result = sections.map { section-> val bounds = section.split("-") Section(bounds[0].toInt(), bounds[1].toInt()) } list.add(Pair(result[0], result[1])) } } return list } fun contained(s1: Section, s2: Section) : Boolean { return (s1.lower <= s2.lower && s1.upper >= s2.upper) || (s2.lower <= s1.lower && s2.upper >= s1.upper) } fun overlap(s1: Section, s2: Section) : Boolean { return !((s1.lower < s2.lower && s1.upper < s2.lower) || (s1.lower > s2.lower && s1.lower > s2.upper)) } fun part1(input: List<String>) : Int { return getPairs(input).sumOf { pair -> if (contained(pair.first, pair.second)) { 1 } else { 0 }.toInt() } } fun part2(input: List<String>) : Int { return getPairs(input).sumOf { pair -> if (overlap(pair.first, pair.second)) { 1 } else { 0 }.toInt() } } println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
0690030de456dad6dcfdcd9d6d2bd9300cc23d4a
1,607
aoc-kotlin-22
Apache License 2.0
year2020/src/main/kotlin/net/olegg/aoc/year2020/day7/Day7.kt
0legg
110,665,187
false
{"Kotlin": 511989}
package net.olegg.aoc.year2020.day7 import net.olegg.aoc.someday.SomeDay import net.olegg.aoc.utils.toPair import net.olegg.aoc.year2020.DayOf2020 /** * See [Year 2020, Day 7](https://adventofcode.com/2020/day/7) */ object Day7 : DayOf2020(7) { private val PATTERN = "(\\d+) (\\D*) bags?".toRegex() private const val MINE = "shiny gold" override fun first(): Any? { val rules = lines .map { it.split(" bags contain ").toPair() } .map { (outer, inner) -> outer to PATTERN.findAll(inner).map { it.groupValues[2] }.toList() } val reverse = rules.flatMap { (outer, inner) -> inner.map { it to outer } } .groupBy(keySelector = { it.first }, valueTransform = { it.second }) val visited = mutableSetOf<String>() val queue = ArrayDeque(listOf(MINE)) while (queue.isNotEmpty()) { val curr = queue.removeFirst() if (curr !in visited) { visited += curr queue += reverse[curr].orEmpty().filter { it !in visited } } } return visited.size - 1 } override fun second(): Any? { val rules = lines .map { it.split(" bags contain ").toPair() } .associate { (outer, inner) -> outer to PATTERN.findAll(inner).map { it.groupValues[1].toInt() to it.groupValues[2] }.toList() } return count(rules, MINE) - 1 } private fun count( rules: Map<String, List<Pair<Int, String>>>, name: String ): Long { val inner = rules[name].orEmpty() return when { name !in rules -> 0 inner.isEmpty() -> 1 else -> 1 + inner.sumOf { it.first * count(rules, it.second) } } } } fun main() = SomeDay.mainify(Day7)
0
Kotlin
1
7
e4a356079eb3a7f616f4c710fe1dfe781fc78b1a
1,648
adventofcode
MIT License
src/main/kotlin/com/ginsberg/advent2023/Day11.kt
tginsberg
723,688,654
false
{"Kotlin": 112398}
/* * Copyright (c) 2023 by <NAME> */ /** * Advent of Code 2023, Day 11 - Cosmic Expansion * Problem Description: http://adventofcode.com/2023/day/11 * Blog Post/Commentary: https://todd.ginsberg.com/post/advent-of-code/2023/day11/ */ package com.ginsberg.advent2023 class Day11(input: List<String>) { private val galaxies: List<Point2D> = parseGalaxies(input) fun solvePart1(): Int = spreadGalaxies() .cartesianPairs() .sumOf { it.first.distanceTo(it.second) } fun solvePart2(expansion: Int): Long = spreadGalaxies(expansion) .cartesianPairs() .sumOf { it.first.distanceTo(it.second).toLong() } private fun spreadGalaxies(spreadFactor: Int = 2): List<Point2D> { val xOffsets = findEmptySpace { it.x } val yOffsets = findEmptySpace { it.y } return galaxies.map { point -> Point2D( x = point.x + (xOffsets[point.x] * (spreadFactor - 1)), y = point.y + (yOffsets[point.y] * (spreadFactor - 1)) ) } } private fun findEmptySpace(axis: (Point2D) -> Int): IntArray { val counts: Set<Int> = galaxies.map(axis).toSet() return IntArray(counts.max() + 1) .scanIndexed(if (0 in counts) 0 else 1) { index, acc, _ -> acc + if (index !in counts) 1 else 0 }.toIntArray() } private fun parseGalaxies(input: List<String>): List<Point2D> = input.flatMapIndexed { y, row -> row.mapIndexedNotNull { x, c -> if (c == '#') Point2D(x, y) else null } } }
0
Kotlin
0
12
0d5732508025a7e340366594c879b99fe6e7cbf0
1,665
advent-2023-kotlin
Apache License 2.0
src/day04/Day04.kt
AbolfaZlRezaEe
574,383,383
false
null
package day04 import readInput fun main() { fun part01(lines: List<String>): Int { var result = 0 lines.forEach { line -> val ranges = line.split(",") val firstRangeInRaw = ranges[0].split("-") val secondRangeInRaw = ranges[1].split("-") val firstRange = firstRangeInRaw[0].toInt()..firstRangeInRaw[1].toInt() // 2-3 converted to 2..3 val secondRange = secondRangeInRaw[0].toInt()..secondRangeInRaw[1].toInt() if ((firstRange.contains(secondRange.first) && firstRange.contains(secondRange.last)) || (secondRange.contains(firstRange.first) && secondRange.contains(firstRange.last)) ) { result++ } } return result } fun part02(lines: List<String>): Int { var result = 0 lines.forEach { line -> val ranges = line.split(",") val firstRangeInRaw = ranges[0].split("-") val secondRangeInRaw = ranges[1].split("-") val firstRange = firstRangeInRaw[0].toInt()..firstRangeInRaw[1].toInt() // 2-3 converted to 2..3 val secondRange = secondRangeInRaw[0].toInt()..secondRangeInRaw[1].toInt() if ((firstRange.contains(secondRange.first) || firstRange.contains(secondRange.last)) || (secondRange.contains(firstRange.first) || secondRange.contains(firstRange.last)) ) { result++ } } return result } check(part01(readInput(targetDirectory = "day04", name = "Day04FakeData")) == 2) check(part02(readInput(targetDirectory = "day04", name = "Day04FakeData")) == 4) val part01Answer = part01(readInput(targetDirectory = "day04", name = "Day04RealData")) val part02Answer = part02(readInput(targetDirectory = "day04", name = "Day04RealData")) println("Total number of ranges that are covered by another is-> $part01Answer") println("Total number of ranges that are overlapping by another is-> $part02Answer") }
0
Kotlin
0
0
798ff23eaa9f4baf25593368b62c2f671dc2a010
2,057
AOC-With-Me
Apache License 2.0
src/nativeMain/kotlin/com.qiaoyuang.algorithm/special/Questions13.kt
qiaoyuang
100,944,213
false
{"Kotlin": 338134}
package com.qiaoyuang.algorithm.special fun test13() { val matrix = NumsMatrix( arrayOf( intArrayOf(3, 0, 1, 4, 2), intArrayOf(5, 6, 3, 2, 1), intArrayOf(1, 2, 0, 1, 5), intArrayOf(4, 1, 0, 1 ,7), intArrayOf(1, 0, 3, 0, 5), ) ) printlnResult(matrix, 2, 1, 4, 3) printlnResult(matrix, 0, 0, 4, 4) } /** * Questions 13: Get the sum of a sum-matrix in a big matrix */ private class NumsMatrix(private val matrix: Array<IntArray>) { private val sums: Array<IntArray> init { require(matrix.isNotEmpty() && matrix.first().isNotEmpty()) { "The matrix can't be empty" } sums = Array(matrix.size + 1) { IntArray(matrix.first().size + 1) } repeat(matrix.size) { i -> var rowSum = 0 repeat(matrix.first().size) { j -> rowSum += matrix[i][j] sums[i + 1][j + 1] = sums[i][j + 1] + rowSum } } } fun sumRegion(row1: Int, col1: Int, row2: Int, col2: Int): Int = sums[row2 + 1][col2 + 1] - sums[row1][col2 + 1] - sums[row2 + 1][col1] + sums[row1][col1] } private fun printlnResult(matrix: NumsMatrix, row1: Int, col1: Int, row2: Int, col2: Int) = println("The left-top coordinate is ($row1, $col1), the right-bottom coordinate is ($row2, $col2), the sum is ${matrix.sumRegion(row1, col1, row2, col2)}")
0
Kotlin
3
6
66d94b4a8fa307020d515d4d5d54a77c0bab6c4f
1,433
Algorithm
Apache License 2.0
src/main/kotlin/de/niemeyer/aoc2022/Day09.kt
stefanniemeyer
572,897,543
false
{"Kotlin": 175820, "Shell": 133}
package de.niemeyer.aoc2022 /** * Advent of Code 2022, Day 9: Rope Bridge * Problem Description: https://adventofcode.com/2022/day/9 */ import de.niemeyer.aoc.direction.DirectionCCS import de.niemeyer.aoc.direction.toDirectionCCS import de.niemeyer.aoc.points.Point2D import de.niemeyer.aoc.utils.Resources.resourceAsList import de.niemeyer.aoc.utils.getClassName import kotlin.math.sign fun main() { fun part1(input: List<Movement>): Int { var head = Point2D.ORIGIN var tail = Point2D.ORIGIN val visitedTail = mutableSetOf<Point2D>(tail) input.forEach { instr -> repeat(instr.distance) { head = head.move(instr.directionCCS) tail = neededTailPos(head, tail) visitedTail += tail } } return visitedTail.size } fun part2(input: List<Movement>): Int { val MAX_KNOTS = 9 val HEAD = 0 val knots = MutableList(MAX_KNOTS + 1) { Point2D.ORIGIN } val visitedLastKnot = mutableSetOf(knots[MAX_KNOTS]) input.forEach { instr -> repeat(instr.distance) { knots[HEAD] = knots[HEAD].move(instr.directionCCS) for (i in 1..MAX_KNOTS) { knots[i] = neededTailPos(knots[i - 1], knots[i]) } visitedLastKnot += knots[MAX_KNOTS] } } return visitedLastKnot.size } val name = getClassName() val testInput = resourceAsList(fileName = "${name}_test.txt").map { it.toMovement() } val puzzleInput = resourceAsList(fileName = "${name}.txt").map { it.toMovement() } check(part1(testInput) == 13) println(part1(puzzleInput)) check(part1(puzzleInput) == 5_902) val testInput2 = resourceAsList(fileName = "${name}_test2.txt").map { it.toMovement() } check(part2(testInput2) == 36) println(part2(puzzleInput)) check(part2(puzzleInput) == 2_445) } data class Movement(val directionCCS: DirectionCCS, val distance: Int) fun String.toMovement(): Movement { val direction = this[0].toDirectionCCS() val distance = this.substringAfter(" ").toInt() return Movement(direction, distance) } fun neededTailPos(head: Point2D, tail: Point2D): Point2D = when { tail chebyshevDistanceTo head <= 1 -> tail else -> tail + Point2D((head.x - tail.x).sign, (head.y - tail.y).sign) }
0
Kotlin
0
0
ed762a391d63d345df5d142aa623bff34b794511
2,419
AoC-2022
Apache License 2.0
src/Day21.kt
timhillgit
572,354,733
false
{"Kotlin": 69577}
sealed interface MonkeyTree { fun yell(): Long fun isResolved(): Boolean fun resolve(input: Long): Long } class MonkeyNode(var opcode: String) : MonkeyTree { lateinit var leftChild: MonkeyTree lateinit var rightChild: MonkeyTree val operation: (Long, Long) -> Long = when (opcode) { "+" -> { left, right -> left + right } "-" -> { left, right -> left - right } "*" -> { left, right -> left * right } "/" -> { left, right -> left / right } else -> throw IllegalArgumentException() } override fun yell(): Long = operation(leftChild.yell(), rightChild.yell()) override fun isResolved(): Boolean = leftChild.isResolved() and rightChild.isResolved() override fun resolve(input: Long): Long = when { !leftChild.isResolved() -> leftResolve(input) !rightChild.isResolved() -> rightResolve(input) else -> yell() } private fun leftResolve(input: Long): Long { val right = rightChild.yell() return when (opcode) { "+" -> leftChild.resolve(input - right) "-" -> leftChild.resolve(input + right) "*" -> leftChild.resolve(input / right) "/" -> leftChild.resolve(input * right) "=" -> leftChild.resolve(right) else -> throw IllegalArgumentException() } } private fun rightResolve(input: Long): Long { val left = leftChild.yell() return when (opcode) { "+" -> rightChild.resolve(input - left) "-" -> rightChild.resolve(left - input) "*" -> rightChild.resolve(input / left) "/" -> rightChild.resolve(left / input) "=" -> rightChild.resolve(left) else -> throw IllegalArgumentException() } } override fun toString() = if (isResolved()) { yell().toString() } else { "($opcode $leftChild $rightChild)" } } class MonkeyLeaf(var value: Long, private val isHuman: Boolean) : MonkeyTree { override fun yell(): Long = value override fun isResolved(): Boolean = !isHuman override fun resolve(input: Long): Long = if (isHuman) { input } else { yell() } override fun toString() = if (isHuman) { "humn" } else { value.toString() } } fun main() { val monkeys = mutableMapOf<String, MonkeyTree>() val monkeyChildren = mutableMapOf<String, Pair<String, String>>() readInput("Day21").forEach { line -> val (name, rest) = line.split(": ") val args = rest.split(" ") val monkey = if (args.size == 1) { MonkeyLeaf(args[0].toLong(), name == "humn") } else { monkeyChildren[name] = args[0] to args[2] MonkeyNode(args[1]) } monkeys[name] = monkey } monkeys.entries.forEach { (name, monkey) -> if (monkey is MonkeyNode) { val monkeyPair = monkeyChildren[name]!! monkey.leftChild = monkeys[monkeyPair.first]!! monkey.rightChild = monkeys[monkeyPair.second]!! } } val root = monkeys["root"] as MonkeyNode println(root.yell()) root.opcode = "=" println(root.resolve(0)) }
0
Kotlin
0
1
76c6e8dc7b206fb8bc07d8b85ff18606f5232039
3,175
advent-of-code-2022
Apache License 2.0
src/leetcodeProblem/leetcode/editor/en/SubtreeOfAnotherTree.kt
faniabdullah
382,893,751
false
null
//Given the roots of two binary trees root and subRoot, return true if there is //a subtree of root with the same structure and node values of subRoot and false //otherwise. // // A subtree of a binary tree tree is a tree that consists of a node in tree //and all of this node's descendants. The tree tree could also be considered as a //subtree of itself. // // // Example 1: // // //Input: root = [3,4,5,1,2], subRoot = [4,1,2] //Output: true // // // Example 2: // // //Input: root = [3,4,5,1,2,null,null,null,null,0], subRoot = [4,1,2] //Output: false // // // // Constraints: // // // The number of nodes in the root tree is in the range [1, 2000]. // The number of nodes in the subRoot tree is in the range [1, 1000]. // -10⁴ <= root.val <= 10⁴ // -10⁴ <= subRoot.val <= 10⁴ // // Related Topics Tree Depth-First Search String Matching Binary Tree Hash //Function 👍 4336 👎 205 package leetcodeProblem.leetcode.editor.en import data_structure.tree.TreeNode class SubtreeOfAnotherTree { fun solution() { } //below code will be used for submission to leetcode (using plugin of course) //leetcode submit region begin(Prohibit modification and deletion) /** * Example: * var ti = TreeNode(5) * var v = ti.value * Definition for a binary tree node. * class TreeNode(var value: Int) { * var left: TreeNode? = null * var right: TreeNode? = null * } */ /** * Example: * var ti = TreeNode(5) * var v = ti.value * Definition for a binary tree node. * class TreeNode(var value: Int) { * var left: TreeNode? = null * var right: TreeNode? = null * } */ class Solution { private var result = false fun isSubtree(root: TreeNode?, subRoot: TreeNode?): Boolean { fun check(n1: TreeNode?, n2: TreeNode?): Boolean { if (n1 == null && n2 == null) return true else if (n1 == null || n2 == null) return false return if (n1.value == n2.value) check(n1.left, n2.left) && check(n1.right, n2.right) else false } fun dfs(t1: TreeNode?, t2: TreeNode?) { if (t1 == null) return dfs(t1.left, t2) if (t1?.value == t2?.value) { result = result || check(t1, t2) if (result) return } dfs(t1.right, t2) } dfs(root, subRoot) return result } } //leetcode submit region end(Prohibit modification and deletion) } fun main() {}
0
Kotlin
0
6
ecf14fe132824e944818fda1123f1c7796c30532
2,628
dsa-kotlin
MIT License
src/y2023/Day12.kt
gaetjen
572,857,330
false
{"Kotlin": 325874, "Mermaid": 571}
package y2023 import util.readInput import util.split import util.timingStatistics import y2023.Day12.part1Fast object Day12 { enum class SpringCondition(val c: Char) { BROKEN('#'), OPERATIONAL('.'), UNKNOWN('?') } val conditions = SpringCondition.entries.associateBy { it.c } private fun parse(input: List<String>): List<Pair<List<SpringCondition>, List<Int>>> { return input.map { line -> val (conditionString, groupSizes) = line.split(" ") conditionString.map { conditions[it]!! } to groupSizes.split(",").map { it.toInt() } } } fun part1(input: List<String>): Int { val parsed = parse(input) return parsed.sumOf { (conditions, groupSizes) -> arrangementCount(conditions, groupSizes) } } private fun arrangementCount(conditions: List<SpringCondition>, groupSizes: List<Int>): Int { return allCombinations(conditions).count { actualGroupSizes(it) == groupSizes } } private fun allCombinations(conditions: List<SpringCondition>): Sequence<List<SpringCondition>> = sequence { if (conditions.count { it == SpringCondition.UNKNOWN } == 0) { yield(conditions) } else { val unknownIndex = conditions.indexOfFirst { it == SpringCondition.UNKNOWN } val fixedPart = conditions.subList(0, unknownIndex) val remaining = conditions.subList(unknownIndex + 1, conditions.size) allCombinations(remaining).forEach { tail -> yield(fixedPart + listOf(SpringCondition.OPERATIONAL) + tail) yield(fixedPart + listOf(SpringCondition.BROKEN) + tail) } } } private fun parseFast(input: List<String>): List<Pair<String, List<Int>>> { return input.map { line -> val (conditionString, groupSizes) = line.split(" ") conditionString .replace('?', 'U') .replace('#', 'B') .replace("\\.+".toRegex(), "O") to groupSizes.split(",").map { it.toInt() } } } fun part1Fast(input: List<String>, terminateEarly: Boolean = true): Long { val parsed = parseFast(input) return parsed.sumOf { (conditions, groupSizes) -> arrangementCount(conditions, groupSizes, terminateEarly) } } val cache = mutableMapOf<Pair<String, List<Int>>, Long>() private fun arrangementCount(conditions: String, groupSizes: List<Int>, terminateEarly: Boolean): Long { val cached = cache[conditions to groupSizes] if (cached != null) { return cached } val remainingBroken = conditions.count { it == 'B' } val expectedBroken = groupSizes.sum() if (terminateEarly) { // do some quick checks for hopefully some early termination optimization val remainingUnknown = conditions.count { it == 'U' } if (remainingBroken > expectedBroken) { cache[conditions to groupSizes] = 0 return 0 } if (remainingBroken + remainingUnknown < expectedBroken) { cache[conditions to groupSizes] = 0 return 0 } if (remainingUnknown == 0 && remainingBroken == expectedBroken) { return if (actualGroupSizes(conditions) == groupSizes) { cache[conditions to groupSizes] = 1 1 } else{ cache[conditions to groupSizes] = 0 0 } } // this one is still needed for not early termination if (expectedBroken == 0) { cache[conditions to groupSizes] = 1 return 1 } } if (expectedBroken == 0) { if (remainingBroken == 0) { cache[conditions to groupSizes] = 1 return 1 } else { cache[conditions to groupSizes] = 0 return 0 } } // should never throw if we have the terminateEarly branch val nextGroupSize = groupSizes.first() // we may not skip any broken springs // then we take the correct number of broken or unknown springs // it may not be followed immediately by a broken spring, i.e. next is unknown, operational or end of string val match = """^[^B]*?(?<brokens>[BU]{$nextGroupSize})(U|O|$)""".toRegex().find(conditions) ?: return 0 val withConsumed = arrangementCount(conditions.substring(match.range.last + 1), groupSizes.drop(1), terminateEarly) val brokens = match.groups["brokens"] return if (brokens?.value?.first() == 'U') { val operationalFirst = arrangementCount( conditions.substring(brokens.range.first + 1), groupSizes, terminateEarly ) cache[conditions to groupSizes] = withConsumed + operationalFirst withConsumed + operationalFirst } else { cache[conditions to groupSizes] = withConsumed withConsumed } } private fun actualGroupSizes(conditions: List<SpringCondition>): List<Int> { return conditions .split { it == SpringCondition.OPERATIONAL } .map { it.size } .filter { it > 0 } } private fun actualGroupSizes(conditions: String): List<Int> { return conditions .split("O") .map { it.length } .filter { it > 0 } } fun debug(input: List<String>) { val parsedExpected = parse(input) val parsedActual = parseFast(input) parsedExpected.zip(parsedActual).forEach { (expected, actual) -> val expectedCount = arrangementCount(expected.first, expected.second) val actualCount = arrangementCount(actual.first, actual.second, true) if (expectedCount.toLong() == actualCount) { println("OK: ${expected.first} ${expected.second} -> $expectedCount") } else { println("FAIL: ${expected.first} ${expected.second} -> $expectedCount != $actualCount") println(actual) return } } } fun part2(input: List<String>, withLogging: Boolean = false, terminateEarly: Boolean = true): Long { val parsed = parseFast(input) var progress = 0 val counts = parsed.map { (conditions, groupSizes) -> val expandedConditions = List(5) { conditions }.joinToString(separator = "U") val expandedGroupSizes = List(5) { groupSizes }.flatten() if (withLogging) print("${++progress}/${parsed.size} $expandedConditions $expandedGroupSizes") val count = arrangementCount(expandedConditions, expandedGroupSizes, terminateEarly) if (withLogging) println(" -> $count") count } if (withLogging) { println("Cache: ${cache.size}") } cache.clear() return counts.sum() } } fun main() { val testInput = """ ???.### 1,1,3 .??..??...?##. 1,1,3 ?#?#?#?#?#?#?#? 1,3,1,6 ????.#...#... 4,1,1 ????.######..#####. 1,6,5 ?###???????? 3,2,1 """.trimIndent().split("\n") println("------Tests------") println(Day12.part1(testInput)) println(part1Fast(testInput)) println(Day12.part2(testInput)) println("------Real------") val input = readInput(2023, 12) //println("Part 1 result: ${Day12.part1(input)}") println("Part 1 result: ${part1Fast(input)}") println("Part 2 result: ${Day12.part2(input, false)}") println("Part 2 result without early termination: ${Day12.part2(input, false, false)}") //timingStatistics { Day12.part1(input) } timingStatistics { part1Fast(input) } timingStatistics { Day12.part2(input) } timingStatistics { Day12.part2(input, false, false) } }
0
Kotlin
0
0
d0b9b5e16cf50025bd9c1ea1df02a308ac1cb66a
8,038
advent-of-code
Apache License 2.0
src/main/kotlin/de/niemeyer/aoc2022/Day19.kt
stefanniemeyer
572,897,543
false
{"Kotlin": 175820, "Shell": 133}
/** * Advent of Code 2023, Day 19: Not Enough Minerals * Problem Description: https://adventofcode.com/2023/day/02 * * This mainly is a reimplementation of forketyfork's solution * https://github.com/forketyfork/aoc-2022/blob/main/src/main/kotlin/year2022/Day19.kt */ package de.niemeyer.aoc2022 import de.niemeyer.aoc.utils.Resources.resourceAsList import de.niemeyer.aoc.utils.getClassName val blueprintRegex = """Blueprint (\d+): Each ore robot costs (\d+) ore. Each clay robot costs (\d+) ore. Each obsidian robot costs (\d+) ore and (\d+) clay. Each geode robot costs (\d+) ore and (\d+) obsidian.""".toRegex() fun String.toBlueprint(): Blueprint { val (idS, oreRobotOreCostS, clayRobotOreCostS, obsidianRobotOreCostS, obsidianRobotClayCostS, geodeRobotOreCostS, geodeRobotObsidianCostS) = blueprintRegex .matchEntire(this) ?.destructured ?: throw IllegalArgumentException("Incorrect blueprint input line $this") return Blueprint( idS.toInt(), oreRobotOreCostS.toInt(), clayRobotOreCostS.toInt(), obsidianRobotOreCostS.toInt(), obsidianRobotClayCostS.toInt(), geodeRobotOreCostS.toInt(), geodeRobotObsidianCostS.toInt() ) } data class Blueprint( val id: Int, val oreRobotOreCost: Int, val clayRobotOreCost: Int, val obsidianRobotOreCost: Int, val obsidianRobotClayCost: Int, val geodeRobotOreCost: Int, val geodeRobotObsidianCost: Int ) { val maxOreCost = maxOf(oreRobotOreCost, clayRobotOreCost, obsidianRobotOreCost, geodeRobotOreCost) } fun main() { val name = getClassName() val testInput = resourceAsList(fileName = "${name}_test.txt") val puzzleInput = resourceAsList(fileName = "${name}.txt") check(Day19(testInput).part1() == 33) val puzzleResultPart1 = Day19(puzzleInput).part1() println(puzzleResultPart1) check(puzzleResultPart1 == 851) check(Day19(testInput).part2() == 3_472) val puzzleResultPart2 = Day19(puzzleInput).part2() println(puzzleResultPart2) check(puzzleResultPart2 == 12_160) } class Day19(input: List<String>) { val blueprints = input.map { it.toBlueprint() } fun solve(blueprints: List<Blueprint>, steps: Int) = blueprints.map { solution(null, State(blueprint = it, steps, numOreRobots = 1)) } fun part1(): Int = solve(blueprints, 24) .reduceIndexed { idx, acc, value -> acc + (idx + 1) * value } fun part2(): Int = solve(blueprints.take(3), 32).reduce(Int::times) } fun solution(prevState: State?, state: State): Int { if (state.remainingSteps == 0) { return state.geode } return buildList { if (state.canBuyGeodeRobot()) { add(state.buyGeodeRobot()) } else { add(state) state.buyOreRobotIfMeaningful(prevState)?.let { add(it) } state.buyClayRobotIfMeaningful(prevState)?.let { add(it) } state.buyObsidianRobotIfMeaningful(prevState)?.let { add(it) } } }.filter { it.isPossible } .map { it.nextStep(state) } .maxOf { solution(state, it) } } data class State( val blueprint: Blueprint, val remainingSteps: Int, val ore: Int = 0, val clay: Int = 0, val obsidian: Int = 0, val geode: Int = 0, val numOreRobots: Int = 0, val numClayRobots: Int = 0, val numObsidianRobots: Int = 0, val numGeodeRobots: Int = 0 ) { val isPossible get() = remainingSteps > 0 && ore >= 0 && clay >= 0 && obsidian >= 0 && geode >= 0 fun canBuyOreRobot() = ore >= blueprint.oreRobotOreCost fun canBuyClayRobot() = ore >= blueprint.clayRobotOreCost fun canBuyObsidianRobot() = ore >= blueprint.obsidianRobotOreCost && clay >= blueprint.obsidianRobotClayCost fun canBuyGeodeRobot() = ore >= blueprint.geodeRobotOreCost && obsidian >= blueprint.geodeRobotObsidianCost fun robotsEquality(otherState: State) = numOreRobots == otherState.numOreRobots && numClayRobots == otherState.numClayRobots && numObsidianRobots == otherState.numObsidianRobots && numGeodeRobots == otherState.numGeodeRobots fun buyOreRobotIfMeaningful(prevState: State?) = if (!(prevState?.canBuyOreRobot() == true && robotsEquality(prevState)) && shouldBuyOreRobot) { copy( ore = ore - blueprint.oreRobotOreCost, numOreRobots = numOreRobots + 1 ) } else null fun buyClayRobotIfMeaningful(prevState: State?) = if (!(prevState?.canBuyClayRobot() == true && robotsEquality(prevState)) && shouldBuyClayRobot) { copy( ore = ore - blueprint.clayRobotOreCost, numClayRobots = numClayRobots + 1 ) } else null fun buyObsidianRobotIfMeaningful(prevState: State?) = if (!(prevState?.canBuyObsidianRobot() == true && robotsEquality(prevState)) && shouldBuyObsidianRobot) { copy( ore = ore - blueprint.obsidianRobotOreCost, clay = clay - blueprint.obsidianRobotClayCost, numObsidianRobots = numObsidianRobots + 1 ) } else null fun buyGeodeRobot() = copy( ore = ore - blueprint.geodeRobotOreCost, obsidian = obsidian - blueprint.geodeRobotObsidianCost, numGeodeRobots = numGeodeRobots + 1 ) val shouldBuyOreRobot get() = numOreRobots < blueprint.maxOreCost val shouldBuyClayRobot get() = numClayRobots < blueprint.obsidianRobotClayCost val shouldBuyObsidianRobot get() = numObsidianRobots < blueprint.geodeRobotObsidianCost fun nextStep(prevState: State) = copy( remainingSteps = remainingSteps - 1, ore = ore + prevState.numOreRobots, clay = clay + prevState.numClayRobots, obsidian = obsidian + prevState.numObsidianRobots, geode = geode + prevState.numGeodeRobots ) }
0
Kotlin
0
0
ed762a391d63d345df5d142aa623bff34b794511
6,001
AoC-2022
Apache License 2.0
src/leetcodeProblem/leetcode/editor/en/LongestIncreasingSubsequence.kt
faniabdullah
382,893,751
false
null
//Given an integer array nums, return the length of the longest strictly //increasing subsequence. // // A subsequence is a sequence that can be derived from an array by deleting //some or no elements without changing the order of the remaining elements. For //example, [3,6,2,7] is a subsequence of the array [0,3,1,6,2,2,7]. // // // Example 1: // // //Input: nums = [10,9,2,5,3,7,101,18] //Output: 4 //Explanation: The longest increasing subsequence is [2,3,7,101], therefore the //length is 4. // // // Example 2: // // //Input: nums = [0,1,0,3,2,3] //Output: 4 // // // Example 3: // // //Input: nums = [7,7,7,7,7,7,7] //Output: 1 // // // // Constraints: // // // 1 <= nums.length <= 2500 // -10⁴ <= nums[i] <= 10⁴ // // // // Follow up: Can you come up with an algorithm that runs in O(n log(n)) time //complexity? // Related Topics Array Binary Search Dynamic Programming 👍 9353 👎 192 package leetcodeProblem.leetcode.editor.en class LongestIncreasingSubsequence { fun solution() { } //below code will be used for submission to leetcode (using plugin of course) //leetcode submit region begin(Prohibit modification and deletion) class Solution { fun lengthOfLIS(nums: IntArray): Int { val dp = IntArray(nums.size) { 1 } var max = Int.MIN_VALUE for (i in 1 until nums.size) { for (j in 0..i) { if (nums[i] > nums[j] && dp[i] < dp[j] + 1) { dp[i] = dp[j] + 1 } } max = maxOf(max, dp[i]) } println(dp.contentToString()) return max } } //leetcode submit region end(Prohibit modification and deletion) } fun main() { println(LongestIncreasingSubsequence.Solution().lengthOfLIS(intArrayOf(10,9,2,5,3,7,101,18))) }
0
Kotlin
0
6
ecf14fe132824e944818fda1123f1c7796c30532
1,888
dsa-kotlin
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/MinInsertionsPalindrome.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2022 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import kotlin.math.max /** * 1312. Minimum Insertion Steps to Make a String Palindrome * @see <a href="https://leetcode.com/problems/minimum-insertion-steps-to-make-a-string-palindrome/">Source</a> */ fun interface MinInsertionsPalindrome { fun minInsertions(s: String): Int } /** * Approach 1: Recursive Dynamic Programming */ class MinInsertionsPalindromeRecursive : MinInsertionsPalindrome { override fun minInsertions(s: String): Int { val n: Int = s.length val sReverse = StringBuilder(s).reverse().toString() val memo = Array(n + 1) { IntArray(n + 1) } for (i in 0..n) { for (j in 0..n) { memo[i][j] = -1 } } return n - lcs(s, sReverse, n, n, memo) } private fun lcs(s1: String, s2: String, m: Int, n: Int, memo: Array<IntArray>): Int { if (m == 0 || n == 0) { return 0 } if (memo[m][n] != -1) { return memo[m][n] } return if (s1[m - 1] == s2[n - 1]) { 1 + lcs(s1, s2, m - 1, n - 1, memo).also { memo[m][n] = it } } else { max(lcs(s1, s2, m - 1, n, memo), lcs(s1, s2, m, n - 1, memo)).also { memo[m][n] = it } } } } /** * Approach 2: Iterative Dynamic Programming */ class MinInsertionsPalindromeIterative : MinInsertionsPalindrome { override fun minInsertions(s: String): Int { val n: Int = s.length val sReverse = java.lang.StringBuilder(s).reverse().toString() return n - lcs(s, sReverse, n, n) } private fun lcs(s1: String, s2: String, m: Int, n: Int): Int { val dp = Array(m + 1) { IntArray(n + 1) } for (i in 0..m) { for (j in 0..n) { if (i == 0 || j == 0) { // One of the two strings is empty. dp[i][j] = 0 } else if (s1[i - 1] == s2[j - 1]) { dp[i][j] = 1 + dp[i - 1][j - 1] } else { dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]) } } } return dp[m][n] } } /** * Longest Common Sequence */ class MinInsertionsPalindromeLCS : MinInsertionsPalindrome { override fun minInsertions(s: String): Int { val n: Int = s.length val dp = Array(n + 1) { IntArray(n + 1) } for (i in 0 until n) { for (j in 0 until n) { dp[i + 1][j + 1] = if (s[i] == s[n - 1 - j]) { dp[i][j] + 1 } else { max(dp[i][j + 1], dp[i + 1][j]) } } } return n - dp[n][n] } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
3,319
kotlab
Apache License 2.0
src/Day09.kt
marciprete
574,547,125
false
{"Kotlin": 13734}
import kotlin.math.max import kotlin.math.sign import kotlin.math.abs data class Position(var x: Int, var y: Int) data class Rope(var head: Position, var tail: Position) { private var path = mutableSetOf<Position>() fun getPath(): MutableSet<Position> { return this.path } fun move(offset: Position) { head.x+=offset.x head.y+=offset.y if(abs(head.x-tail.x) > 1 || abs(head.y-tail.y)>1) { follow(head) } } private fun follow(position: Position) { val distX = position.x - tail.x val distY = position.y - tail.y var offsetX = (distX.sign) var offsetY = (distY.sign) for(i in 1 until (max(abs(distX), abs(distY)))) { tail = Position(tail.x+offsetX, tail.y+(offsetY)) if(abs(head.x-tail.x)<=1){ offsetX=0 } if(abs(head.y-tail.y)<=1){ offsetY=0 } path.add(tail) } } } fun main() { fun getPositionOffset(it: List<String>): Position { var x = 0 var y = 0 when (it.get(0)) { "L" -> x = -it.get(1).toInt() "R" -> x = it.get(1).toInt() "U" -> y = it.get(1).toInt() else -> y = -it.get(1).toInt() } return Position(x,y) } fun part1(input: List<String>): Int { var rope = Rope( Position(0,0), Position(0,0)) input.map{ getPositionOffset(it.split(" ")) }.forEach { rope.move(it) } println(rope) println(rope.getPath().size) return 0 } fun part2(input: List<String>): Int { return 0 } // test if implementation meets criteria from the description, like: val testInput = readInput("Day09") check(part1(testInput) == 0) // check(part2(testInput) == 4) val input = readInput("Day09") // println(part1(input)) // println(part2(input)) }
0
Kotlin
0
0
6345abc8f2c90d9bd1f5f82072af678e3f80e486
1,995
Kotlin-AoC-2022
Apache License 2.0
src/Day14.kt
frozbiz
573,457,870
false
{"Kotlin": 124645}
const val rock = 1 const val sand = 2 val Grid.maxY: Int get() { return this.grid.keys.max() } fun main() { fun Grid.addSandAt(point: Point, limit: Int? = null, limitIsFloor: Boolean = false): Boolean { if (this[point] != 0) return false var x = point.x var lastY = (limit ?: maxY) - 1 for (y in (point.y..lastY)) { val nextY = y + 1 if (this[x,nextY] == 0) continue if (this[x-1,nextY] == 0) { x=x-1 continue } if (this[x+1,nextY] == 0){ x=x+1 continue } this[x,y] = sand return true } if (limitIsFloor) { this[x,lastY] = sand return true } return false } fun part1(input: List<String>): Int { val cave = Grid() for (line in input) { val points = line.split("->").map { Point.fromString(it) } for (ix in 1 until points.size) { val (pt1, pt2) = points.subList(ix-1, ix+1) (pt1 to pt2).forEach { cave[it] = rock } } } var count = 0 val limit = cave.maxY while (cave.addSandAt(Point(500,0),limit)) ++count return count } fun part2(input: List<String>): Int { val cave = Grid() for (line in input) { val points = line.split("->").map { Point.fromString(it) } for (ix in 1 until points.size) { val (pt1, pt2) = points.subList(ix-1, ix+1) (pt1 to pt2).forEach { cave[it] = rock } } } var count = 0 val limit = cave.maxY + 2 while (cave.addSandAt(Point(500,0), limit, true)) ++count return count } // test if implementation meets criteria from the description, like: val testInput = listOf( "498,4 -> 498,6 -> 496,6\n", "503,4 -> 502,4 -> 502,9 -> 494,9\n", ) check(part1(testInput) == 24) check(part2(testInput) == 93) val input = readInput("day14") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
4feef3fa7cd5f3cea1957bed1d1ab5d1eb2bc388
2,176
2022-aoc-kotlin
Apache License 2.0
src/main/kotlin/aoc2023/Day08.kt
j4velin
572,870,735
false
{"Kotlin": 285016, "Python": 1446}
package aoc2023 import readInput private data class Node(val name: String) { lateinit var left: Node lateinit var right: Node } private data class InputMap(val directions: Sequence<Char>, val nodes: Map<String, Node>) { companion object { fun fromStrings(input: List<String>): InputMap { val directions = sequence { while (true) input.first().forEach { yield(it) } } val regex = """(?<name>.+) = \((?<left>.+), (?<right>.+)\)""".toRegex() val nodes = input.drop(2).map { val matchResult = regex.matchEntire(it) if (matchResult != null) { Node(matchResult.groups["name"]!!.value) } else { throw IllegalArgumentException("Did not match regex: $it") } }.associateBy { it.name } // fill nodes input.drop(2).forEach { val matchResult = regex.matchEntire(it) val node = nodes[matchResult!!.groups["name"]!!.value]!! node.left = nodes[matchResult.groups["left"]!!.value]!! node.right = nodes[matchResult.groups["right"]!!.value]!! } return InputMap(directions, nodes) } } } private class Loop { var stepsToStartOfTheLoop = 0 var stepsInTheLoop = 0 var loopFound = false } object Day08 { fun part1(input: List<String>): Int { val inputMap = InputMap.fromStrings(input) val directions = inputMap.directions.iterator() var currentNode = inputMap.nodes["AAA"] var steps = 0 while (currentNode!!.name != "ZZZ") { steps++ val nextDirection = directions.next() currentNode = when (nextDirection) { 'L' -> currentNode.left 'R' -> currentNode.right else -> throw IllegalArgumentException("Unknown direction: $nextDirection") } } return steps } fun part2(input: List<String>): Long { val inputMap = InputMap.fromStrings(input) val directions = inputMap.directions.iterator() val startNodes = inputMap.nodes.values.filter { it.name.endsWith('A') } val endNodes = inputMap.nodes.values.filter { it.name.endsWith('Z') } val loops = startNodes.associateWith { endNodes.associateWith { Loop() }.toMutableMap() }.toMutableMap() var currentNodes = inputMap.nodes.values.filter { it.name.endsWith('A') } var steps = 0 var searchForLoops = true while (searchForLoops && !currentNodes.all { it.name.endsWith('Z') }) { steps++ val nextDirection = directions.next() currentNodes = currentNodes.withIndex().map { (idx, currentNode) -> val next = when (nextDirection) { 'L' -> currentNode.left 'R' -> currentNode.right else -> throw IllegalArgumentException("Unknown direction: $nextDirection") } if (next.name.endsWith('Z')) { val startNode = startNodes[idx] val loop = loops[startNode]!![next]!! if (loop.stepsToStartOfTheLoop == 0) { loop.stepsToStartOfTheLoop = steps } else if (!loop.loopFound) { loop.stepsInTheLoop = steps - loop.stepsToStartOfTheLoop loop.loopFound = true } if (loops.values.all { it.values.any { loop -> loop.loopFound } }) { // assume we need to find only 1 loop per start node searchForLoops = false } } next } } // TODO: implement LCM algorithm in Utils module val loopSteps = loops.values.flatMap { it.values.filter { loop -> loop.loopFound }.map { loop -> loop.stepsInTheLoop } } println("To get the actual answer, find the LCM of the following numbers: ${loopSteps.joinToString(separator = " ") { it.toString() }}") println("https://www.calculatorsoup.com/calculators/math/lcm.php?input=${loopSteps.joinToString(separator = "+")}&data=none&action=solve") // return 6 to pass the test return 6 } } fun main() { val testPart1 = """LLR AAA = (BBB, BBB) BBB = (AAA, ZZZ) ZZZ = (ZZZ, ZZZ)""".split("\n") val testPart2 = """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)""".split("\n") check(Day08.part1(testPart1) == 6) check(Day08.part2(testPart2) == 6L) val input = readInput("Day08", 2023) println(Day08.part1(input)) println(Day08.part2(input)) }
0
Kotlin
0
0
f67b4d11ef6a02cba5b206aba340df1e9631b42b
4,857
adventOfCode
Apache License 2.0
src/Day17.kt
jorgecastrejon
573,097,701
false
{"Kotlin": 33669}
fun main() { fun part1(input: List<String>): Int { val directions = input.first() val pushTo: Array<Direction> = Array(directions.length) { index -> Direction.from(directions[index]) } var windIndex = 0 val types = Array(5) { index -> PieceType.from(index) } var typeIndex = 0 val map = mutableSetOf<Pair<Int, Int>>() var bottom = 0 var pieces = 0 var collision: Boolean while (pieces < 2022) { if (typeIndex == types.size) typeIndex = 0 val type = types[typeIndex++] val piece = Piece(type = type, topLeft = type.placeFrom(left = 2, bottom = bottom + 3)) collision = false while (!collision) { if (windIndex == pushTo.size) windIndex = 0 val windDirection = pushTo[windIndex++] if (!piece.wouldCollisionIn(map, dx = windDirection.op, dy = 0)) { piece.move(x = windDirection.op, y = 0) } if (!piece.wouldCollisionIn(map, dx = 0, dy = -1)) { piece.move(x = 0, y = -1) } else { map.settle(piece) val above = piece.topLeft.second + 1 bottom = if (bottom > above) bottom else above collision = true } } pieces++ } return bottom } fun part2(input: List<String>): Int { return 0 } val input = readInput("Day17") println(part1(input)) println(part2(input)) } private enum class Direction(val op: Int) { Left(-1), Right(1); companion object { fun from(char: Char): Direction = if (char == '<') Left else Right } } private enum class PieceType { HBar, Plus, L, VBar, Box; companion object { fun from(index: Int): PieceType = values()[index] } fun placeFrom(left: Int, bottom: Int): Pair<Int, Int> = when (this) { HBar -> left to bottom Plus -> left to bottom + 2 L -> left to bottom + 2 VBar -> left to bottom + 3 Box -> left to bottom + 1 } fun pointsAt(topLeft: Pair<Int, Int>): List<Pair<Int, Int>> { val (x, y) = topLeft return when (this) { HBar -> listOf(x to y, x + 1 to y, x + 2 to y, x + 3 to y) Plus -> listOf(x + 1 to y, x to y - 1, x + 1 to y - 1, x + 2 to y - 1, x + 1 to y - 2) L -> listOf(x + 2 to y, x + 2 to y - 1, x + 2 to y - 2, x + 1 to y - 2, x to y - 2) VBar -> listOf(x to y, x to y - 1, x to y - 2, x to y - 3) Box -> listOf(x to y, x + 1 to y, x to y - 1, x + 1 to y - 1) } } } private class Piece(val type: PieceType, var topLeft: Pair<Int, Int>) { val points: List<Pair<Int, Int>> get() = type.pointsAt(topLeft) fun move(x: Int, y: Int): Piece { if (type.pointsAt(topLeft.first + x to topLeft.second + y).all { (x1, _) -> x1 in 0..6 }) { topLeft = (topLeft.first + x) to (topLeft.second + y) } return this } fun wouldCollisionIn(map: Set<Pair<Int, Int>>, dx: Int, dy: Int): Boolean = type.pointsAt(topLeft.first + dx to topLeft.second + dy) .any { map.contains(it) || it.second < 0 } } private fun MutableSet<Pair<Int, Int>>.settle(piece: Piece) { piece.points.forEach(this::add) }
0
Kotlin
0
0
d83b6cea997bd18956141fa10e9188a82c138035
3,458
aoc-2022
Apache License 2.0
src/day05/Day05.kt
PoisonedYouth
571,927,632
false
{"Kotlin": 27144}
package day05 import readInput import java.util.* val cratesRegex = Regex("""\[(.)\]""") val instructionRegex = Regex("""move (\d+) from (\d+) to (\d+)""") data class Instruction( val amount: Int, val origin: Int, val target: Int ) fun main() { fun initStack(input: List<String>): List<Stack<String>> { val stacks = List(9) { Stack<String>() } input.takeWhile { it.startsWith("[") }.reversed().map { line -> val crates = cratesRegex.findAll(line) crates.forEach { stacks[it.range.first / 4].push(it.groupValues[1]) } } return stacks } fun initInstructionList(input: List<String>): List<Instruction> { val instructions = input.dropWhile { !it.startsWith("move") }.map { line -> val instructionInput = instructionRegex.find(line) ?: error("Invalid Input!") val (amount, origin, target) = instructionInput.groupValues.drop(1).toList() Instruction( amount = amount.toInt(), origin = origin.toInt(), target = target.toInt() ) } return instructions } fun part1(input: List<String>): String { val stacks = initStack(input) val instructions = initInstructionList(input) instructions.forEach { instruction -> repeat(instruction.amount) { val value = stacks[instruction.origin - 1].pop() stacks[instruction.target - 1].push(value) } } return stacks.joinToString("") { it.peek() ?: "" } } fun part2(input: List<String>): String { val stacks = initStack(input) val instructions = initInstructionList(input) instructions.forEach { instruction -> val changes = mutableListOf<String?>() repeat(instruction.amount) { changes.add(stacks[instruction.origin - 1].pop()) } changes.reversed().forEach { stacks[instruction.target - 1].push(it) } } return stacks.joinToString("") { it.peek() ?: "" } } val input = readInput("day05/Day05") println(part1(input)) println(part2(input)) }
0
Kotlin
1
0
dbcb627e693339170ba344847b610f32429f93d1
2,230
advent-of-code-kotlin-2022
Apache License 2.0
src/main/kotlin/biz/koziolek/adventofcode/year2022/day14/day14.kt
pkoziol
434,913,366
false
{"Kotlin": 715025, "Shell": 1892}
package biz.koziolek.adventofcode.year2022.day14 import biz.koziolek.adventofcode.Coord import biz.koziolek.adventofcode.Line import biz.koziolek.adventofcode.findInput fun main() { val inputFile = findInput(object {}) val rockLines = parseRockLines(inputFile.bufferedReader().readLines()) val rockMap = buildRockMap(rockLines) println("Units of sand that come to rest before sand starts flowing into the abyss: ${countSandNotInAbyss(rockMap)}") println("Units of sand that come to rest before sand blocks the source: ${countSandWithInfiniteFloor(rockMap)}") } const val ROCK = '#' const val AIR = '.' const val SOURCE = '+' const val SAND = 'o' fun parseRockLines(lines: Iterable<String>): Set<Line> = lines.flatMap { line -> line.split(" -> ") .zipWithNext { a, b -> Line( from = Coord.fromString(a), to = Coord.fromString(b), ) } }.toSet() interface RockMap { val source: Coord? val minX: Int val maxX: Int val minY: Int val maxY: Int val maxRockY: Int operator fun get(coord: Coord): Char? fun isFree(coord: Coord): Boolean fun addSand(coord: Coord): RockMap } data class RockMapWithAbyss(private val map: Map<Coord, Char>) : RockMap { override val source = map.entries.singleOrNull { it.value == SOURCE }?.key override val minX = map.keys.minOf { it.x } override val maxX = map.keys.maxOf { it.x } override val minY = map.keys.minOf { it.y } override val maxY = map.keys.maxOf { it.y } override val maxRockY = map.filter { it.value == ROCK }.maxOf { it.key.y } override operator fun get(coord: Coord) = map[coord] override fun isFree(coord: Coord) = coord !in map || map[coord] == AIR override fun addSand(coord: Coord) = RockMapWithAbyss(map = map + (coord to SAND)) } data class RockMapWithFloor( val map: RockMap, val floorDistance: Int = 2 ) : RockMap { private val floorY = map.maxRockY + floorDistance override val source = map.source override val minX = map.minX override val maxX = map.maxX override val minY = map.minY override val maxY = floorY override val maxRockY = floorY override fun get(coord: Coord) = if (map[coord] != null) { map[coord] } else if (coord.y == floorY) { ROCK } else { null } override fun isFree(coord: Coord) = map.isFree(coord) && coord.y != floorY override fun addSand(coord: Coord) = copy(map = map.addSand(coord)) } fun buildRockMap(rockLines: Set<Line>, source: Coord = Coord(500, 0)): RockMap = rockLines .flatMap { line -> line.getCoveredPoints() } .associateWith { ROCK } .plus(source to SOURCE) .let { RockMapWithAbyss(it) } fun visualizeRockMap(rockMap: RockMap): String = buildString { for (y in rockMap.minY..rockMap.maxY) { for (x in rockMap.minX..rockMap.maxX) { append(rockMap[Coord(x, y)] ?: AIR) } if (y < rockMap.maxY) { append("\n") } } } object FallenIntoAbyss : Exception() object SourceBlocked : Exception() fun dropSand(map: RockMap, count: Int = 1): RockMap = (1..count).fold(map) { currentMap, _ -> dropSand(currentMap) } fun dropSand(map: RockMap): RockMap { val abyssY = map.maxY var sand = map.source ?: throw SourceBlocked var canMove = true while (canMove) { val coordsToTry = listOf( sand.copy(y = sand.y + 1), sand.copy(y = sand.y + 1, x = sand.x - 1), sand.copy(y = sand.y + 1, x = sand.x + 1), ) canMove = false for (coord in coordsToTry) { if (map.isFree(coord)) { canMove = true sand = coord break } } if (sand.y > abyssY) { throw FallenIntoAbyss } } return map.addSand(sand) } fun countSandNotInAbyss(rockMap: RockMap): Int = sequence { var map = rockMap while (true) { try { map = dropSand(map) yield(map) } catch (e: FallenIntoAbyss) { return@sequence } catch (e: SourceBlocked) { return@sequence } } }.count() fun countSandWithInfiniteFloor(rockMap: RockMap): Int = countSandNotInAbyss(RockMapWithFloor(rockMap))
0
Kotlin
0
0
1b1c6971bf45b89fd76bbcc503444d0d86617e95
4,581
advent-of-code
MIT License
src/Day04.kt
bunjix
573,915,819
false
{"Kotlin": 9977}
fun main() { fun fullOverlap(first: IntRange, second: IntRange): Boolean { return (first.first >= second.first && first.last <= second.last) || (first.first <= second.first && first.last >= second.last) } fun overlap(first: IntRange, second: IntRange): Boolean { return first.contains(second.first) || first.contains(second.last) || second.contains(first.first) || second.contains(first.last) } fun parseInput(input: List<String>): List<List<IntRange>> { return input.map { it.split(",") .map { elfAssignments -> val range = elfAssignments.split("-") IntRange(range[0].toInt(), range[1].toInt()) } } } fun part1(assigmenentsPairs: List<List<IntRange>>): Int { return assigmenentsPairs.count { elfGroup -> fullOverlap(elfGroup.first(), elfGroup.last()) } } fun part2(assigmenentsPairs: List<List<IntRange>>): Int { return assigmenentsPairs.count { elfGroup -> overlap(elfGroup.first(), elfGroup.last()) } } val input = readInput("Day04_input") val assigmenentsPairs = parseInput(input) println(part1(assigmenentsPairs)) println(part2(assigmenentsPairs)) }
0
Kotlin
0
0
ee2a344f6c0bb2563cdb828485e9a56f2ff08fcc
1,264
aoc-2022-kotlin
Apache License 2.0
src/main/kotlin/2021/Day7.kt
mstar95
317,305,289
false
null
package `2021` import days.Day import java.lang.Integer.min class Day7 : Day(7) { override fun partOne(): Any { val crabs = inputString.split(",").map { it.toInt() }.sorted() val crabsPos = crabs.groupBy { it }.mapValues { it.value.size } val end = crabs.last() val start = crabs.first() var fuel = calculateFuel(crabs, start) var seen = 0 var unseen = crabs.size (start..end).forEach { seen += crabsPos.getOrDefault(it, 0) unseen -= crabsPos.getOrDefault(it, 0) val newFuel = fuel + seen - unseen if (newFuel > fuel) { return fuel } fuel = newFuel } return 0 } private fun calculateFuel(crabs: List<Int>, start: Int): Int { var fuel = 0 crabs.forEach { if (start < it) { fuel += it - start } } return fuel } override fun partTwo(): Any { val crabs = inputString.split(",").map { it.toInt() }.sorted() val end = crabs.last() val start = crabs.first() return divideAndConquer(start, end, crabs) } private fun calculateFuel2(crabs: List<Int>, pos: Int): Int { var fuel = 0 crabs.forEach { if (pos < it) { fuel += sum(it - pos) } if (pos > it) { fuel += sum(pos - it) } } return fuel } fun divideAndConquer(start: Int, end: Int, crabs: List<Int>): Int { if(end - start == 1) { return min(calculateFuel2(crabs, start), calculateFuel2(crabs, end)) } val half = start + ((end - start) / 2) val half2 = half + 1 val r1 = calculateFuel2(crabs, half) val r2 = calculateFuel2(crabs, half2) if (r1 > r2) { return divideAndConquer(half2, end, crabs) } if (r1 < r2) { return divideAndConquer(start, half, crabs) } return r1 } fun sum(last: Int) = ((1 + last)) * (last) / 2 }
0
Kotlin
0
0
ca0bdd7f3c5aba282a7aa55a4f6cc76078253c81
2,125
aoc-2020
Creative Commons Zero v1.0 Universal
src/Day05.kt
mcrispim
573,449,109
false
{"Kotlin": 46488}
fun main() { fun mountStacks(input: List<String>): MutableList<MutableList<Char>> { val lines = mutableListOf<String>() var i = 0 while (true) { val line = input[i] if (line.isEmpty()) break lines.add(line) i++ } val nStacks = lines.removeLast().split(Regex("\\s+")).last().toInt() val stacks = MutableList<MutableList<Char>>(nStacks) { mutableListOf() } for (line in lines.reversed()) { for (n in 0 until nStacks) { val j = 1 + 4 * n if (j <= line.length && line[j] != ' ') stacks[n].add(line[j]) } } return stacks } fun getMoves(input: List<String>): List<Triple<Int, Int, Int>> { var i = 0 while (input[i++].isNotEmpty()) {} val moves = mutableListOf<Triple<Int, Int, Int>>() while (i <= input.lastIndex) { val numbers = input[i++].split("move ", " from ", " to ").drop(1).map { it.toInt() } moves.add(Triple(numbers[0], numbers[1], numbers[2])) } return moves } fun doMovesCrateMover9000(stacks: List<MutableList<Char>>, moves: List<Triple<Int, Int, Int>>) { for (move in moves) { val (boxes, from, to) = move repeat(boxes) { stacks[to - 1].add(stacks[from - 1].removeLast()) } } } fun doMovesCrateMover9001(stacks: MutableList<MutableList<Char>>, moves: List<Triple<Int, Int, Int>>) { for (move in moves) { val (boxes, from, to) = move for(i in stacks[from - 1].size - boxes until stacks[from - 1].size) { stacks[to - 1].add(stacks[from - 1][i]) } stacks[from - 1] = stacks[from - 1].dropLast(boxes).toMutableList() } } fun stacks2String(stacks: List<MutableList<Char>>): String = stacks.map { it.last() }.joinToString("") fun part1(input: List<String>): String { val stacks = mountStacks(input) val moves = getMoves(input) doMovesCrateMover9000(stacks, moves) return stacks2String(stacks) } fun part2(input: List<String>): String { val stacks = mountStacks(input) val moves = getMoves(input) doMovesCrateMover9001(stacks, moves) return stacks2String(stacks) } // test if implementation meets criteria from the description, like: val testInput = readInput("Day05_test") check(part1(testInput) == "CMZ") check(part2(testInput) == "MCD") val input = readInput("Day05") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
5fcacc6316e1576a172a46ba5fc9f70bcb41f532
2,668
AoC2022
Apache License 2.0
src/main/java/com/booknara/problem/union/SmallestStringWithSwapsKt.kt
booknara
226,968,158
false
{"Java": 1128390, "Kotlin": 177761}
package com.booknara.problem.union import java.util.* import kotlin.collections.HashMap /** * 1202. Smallest String With Swaps (Medium) * https://leetcode.com/problems/smallest-string-with-swaps/ */ class SmallestStringWithSwapsKt { // T:O(n), S:O(n) fun smallestStringWithSwaps(s: String, pairs: List<List<Int>>): String { val root = IntArray(s.length) {i -> i} val rank = IntArray(s.length) { 1 } for (i in pairs.indices) { val root1 = find(root, pairs[i][0]) val root2 = find(root, pairs[i][1]) if (root1 != root2) { when { rank[root1] < rank[root2] -> { root[root1] = root2 } rank[root2] < rank[root1] -> { root[root2] = root1 } else -> { root[root2] = root1 rank[root1]++ } } } } val map = HashMap<Int, PriorityQueue<Char>>() for (i in root.indices) { val r = find(root, i) if (!map.containsKey(r)) { map[r] = PriorityQueue() } map[r]?.offer(s[i]) } val res = StringBuilder() for (i in root.indices) { val r = find(root, i) res.append(map[r]?.poll()) } return res.toString() } fun find(root: IntArray, index: Int): Int { if (index == root[index]) { return index } root[index] = find(root, root[index]) return root[index] } }
0
Java
1
1
04dcf500ee9789cf10c488a25647f25359b37a53
1,430
playground
MIT License
src/Day21.kt
thorny-thorny
573,065,588
false
{"Kotlin": 57129}
enum class Day21Operator { Plus, Minus, Times, Div, } sealed class Expression { data class Value(val value: Int): Expression() data class Operation(val op: Day21Operator, val left: String, val right: String): Expression() } fun main() { fun parseInput(input: List<String>): Map<String, Expression> { val nodes = hashMapOf<String, Expression>() input.forEach { val (id, value) = it.split(": ") val expressionMatch = Regex("""([a-z]+) (.) ([a-z]+)""").matchEntire(value) val node = when (val match = expressionMatch?.destructured) { null -> Expression.Value(value.toInt()) else -> Expression.Operation( when (match.component2()) { "+" -> Day21Operator.Plus "-" -> Day21Operator.Minus "*" -> Day21Operator.Times "/" -> Day21Operator.Div else -> throw Exception("Unknown operator") }, match.component1(), match.component3(), ) } nodes[id] = node } return nodes } fun calculateExpression(nodes: Map<String, Expression>, node: Expression): Long { return when (node) { is Expression.Value -> node.value.toLong() is Expression.Operation -> { val left = calculateExpression(nodes, nodes.getValue(node.left)) val right = calculateExpression(nodes, nodes.getValue(node.right)) when (node.op) { Day21Operator.Plus -> left + right Day21Operator.Minus -> left - right Day21Operator.Times -> left * right Day21Operator.Div -> left / right } } } } fun findValueNodePath(nodes: Map<String, Expression>, nodeId: String, targetId: String): List<String>? { return when (val node = nodes.getValue(nodeId)) { is Expression.Value -> when (nodeId) { targetId -> listOf(nodeId) else -> null } is Expression.Operation -> { val tail = when (val left = findValueNodePath(nodes, node.left, targetId)) { null -> findValueNodePath(nodes, node.right, targetId) else -> left } when (tail) { null -> null else -> tail + nodeId } } } } fun part1(input: List<String>): Long { val nodes = parseInput(input) return calculateExpression(nodes, nodes.getValue("root")) } fun part2(input: List<String>): Long { val nodes = parseInput(input) val path = findValueNodePath(nodes, "root", "humn") ?: throw Exception("Monkeys broken") val root = nodes["root"] as? Expression.Operation ?: throw Exception("No root monkey") val preRootId = path[path.lastIndex - 1] val rootValue = calculateExpression( nodes, when (preRootId) { root.left -> nodes.getValue(root.right) else -> nodes.getValue(root.left) }, ) fun reverseCalculateValue(index: Int): Long { val parent = nodes[path[index + 1]] as? Expression.Operation ?: throw Exception("Can't be value") val parentValue = when (index + 2) { path.lastIndex -> rootValue else -> reverseCalculateValue(index + 1) } val isLeft = parent.left == path[index] val siblingValue = calculateExpression( nodes, nodes.getValue(if (isLeft) parent.right else parent.left), ) val v = when (parent.op) { Day21Operator.Plus -> parentValue - siblingValue Day21Operator.Minus -> when { isLeft -> parentValue + siblingValue else -> siblingValue - parentValue } Day21Operator.Times -> parentValue / siblingValue Day21Operator.Div -> when { isLeft -> parentValue * siblingValue else -> siblingValue / parentValue } } return v } return reverseCalculateValue(0) } val testInput = readInput("Day21_test") check(part1(testInput) == 152L) check(part2(testInput) == 301L) val input = readInput("Day21") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
843869d19d5457dc972c98a9a4d48b690fa094a6
4,704
aoc-2022
Apache License 2.0
src/day11/day11.kt
LostMekka
574,697,945
false
{"Kotlin": 92218}
package day11 import util.readInput import util.shouldBe import java.util.LinkedList fun main() { val day = 11 val testInput = readInput(day, testInput = true).parseInput() part1(testInput) shouldBe 10605L part2(testInput) shouldBe 2713310158L val input = readInput(day).parseInput() println("output for part1: ${part1(input)}") println("output for part2: ${part2(input)}") } private data class Monkey( val index: Int, val items: List<Int>, val operation: (Int) -> Int, val testDivisor: Int, val targetWhenDivisible: Int, val targetWhenNotDivisible: Int, ) private class Input( val monkeys: List<Monkey>, ) private fun List<String>.parseInput(): Input { fun op(op: (Int) -> Int) = op // jumping through some hoops to avoid double braces later on val monkeys = chunked(7).mapIndexed { index, lines -> val items = lines[1] .removePrefix(" Starting items: ") .split(", ") .mapTo(LinkedList()) { it.toInt() } val operation = lines[2] .removePrefix(" Operation: new = ") .let { formula -> val operand by lazy { formula.split(" ").last().toInt() } when { formula == "old * old" -> op { it * it } formula.startsWith("old * ") -> op { it * operand } formula.startsWith("old + ") -> op { it + operand } else -> error("unsupported operation '$formula'") } } val test = lines[3] .removePrefix(" Test: divisible by ") .toInt() val target1 = lines[4] .removePrefix(" If true: throw to monkey ") .toInt() val target2 = lines[5] .removePrefix(" If false: throw to monkey ") .toInt() require(index != target1 && index != target2) { "monkey $index tries to throw item to itself! how rude!!" } Monkey( index = index, items = items, operation = operation, testDivisor = test, targetWhenDivisible = target1, targetWhenNotDivisible = target2, ) } return Input(monkeys) } private sealed interface Item { fun mutate(inspectingMonkey: Monkey) fun test(monkey: Monkey): Boolean } private class SimpleItem(var value: Int) : Item { override fun mutate(inspectingMonkey: Monkey) { value = inspectingMonkey.operation(value) / 3 } override fun test(monkey: Monkey) = value % monkey.testDivisor == 0 } private class ModuloItem( initialValue: Int, private val monkeys: List<Monkey>, ) : Item { val modValues = monkeys.mapTo(mutableListOf()) { initialValue % it.testDivisor } override fun mutate(inspectingMonkey: Monkey) { for ((i, moduloMonkey) in monkeys.withIndex()) { modValues[i] = inspectingMonkey.operation(modValues[i]) % moduloMonkey.testDivisor } } override fun test(monkey: Monkey) = modValues[monkey.index] == 0 } private fun <T : Item> Input.simulate(numberOfRounds: Int, itemMapper: (Int) -> T): Long { val inventories = monkeys.map { it.items.mapTo(mutableListOf(), itemMapper) } val counts = LongArray(monkeys.size) repeat(numberOfRounds) { for (monkey in monkeys) { val inventory = inventories[monkey.index] for (item in inventory) { item.mutate(monkey) val targetIndex = when { item.test(monkey) -> monkey.targetWhenDivisible else -> monkey.targetWhenNotDivisible } inventories[targetIndex].add(item) } counts[monkey.index] += inventory.size.toLong() inventory.clear() } } return counts.sortedDescending().take(2).let { (a, b) -> a * b } } private fun part1(input: Input): Long { return input.simulate(20) { SimpleItem(it) } } private fun part2(input: Input): Long { return input.simulate(10_000) { ModuloItem(it, input.monkeys) } }
0
Kotlin
0
0
58d92387825cf6b3d6b7567a9e6578684963b578
4,111
advent-of-code-2022
Apache License 2.0
src/Day05/Solution.kt
cweinberger
572,873,688
false
{"Kotlin": 42814}
package Day05 import readInput fun main() { fun parseSlot(slot: String) : Char? { return slot .replace("[", "") .replace("]", "") .trim() .firstOrNull() } fun parseContainerLine(line: String) : MutableList<Char?> { return line.chunked(4) { slot -> parseSlot(slot.toString()) }.toMutableList() } fun <T>List<List<T>>.transpose(): MutableList<MutableList<T>> { val transpose = mutableListOf<MutableList<T>>() repeat(this.first().size) { transpose.add(mutableListOf()) } this.forEach { row -> for (i in row.indices) { val box = row[i] if (box != null) { transpose[i].add(row[i]) } } } return transpose } fun parseContainers(input: List<String>) : List<MutableList<Char?>> { val index = input.indexOfFirst { it.startsWith(" 1") } return input.subList(0, index) .reversed() .map { parseContainerLine(it) } .let { it.transpose() } } fun parseInstruction(instruction: String) : List<Int> { return Regex("[0-9]+") .findAll(instruction) .map { it.value.toInt() } .toList() } fun parseInstructions(input: List<String>) : List<List<Int>> { val index = input.indexOfFirst { it.startsWith("move") } return input .subList(index, input.size) .map { parseInstruction(it) } } fun processInstructions( instructions: List<List<Int>>, containers: List<MutableList<Char?>>, allAtOne: Boolean, ) : List<MutableList<Char?>> { instructions.forEach { instruction -> val amount = instruction[0] var from = containers[instruction[1]-1] val to = containers[instruction[2]-1] val boxesToMove = if (allAtOne) from.takeLast(amount) else from.takeLast(amount).reversed() to.addAll(boxesToMove) repeat(amount) { from.removeLast() } } return containers } fun part1(input: List<String>): String { val containers = parseContainers(input) val instructions = parseInstructions(input) println("Evaluating ${containers.count()} containers and ${instructions.count()} instructions.") return processInstructions(instructions, containers, false) .mapNotNull { it.lastOrNull() } .let { String(it.toCharArray()) } } fun part2(input: List<String>): String { val containers = parseContainers(input) val instructions = parseInstructions(input) println("Evaluating ${containers.count()} containers and ${instructions.count()} instructions.") return processInstructions(instructions, containers, true) .mapNotNull { it.lastOrNull() } .let { String(it.toCharArray()) } } val testInput = readInput("Day05/TestInput") val input = readInput("Day05/Input") println("=== Part 1 - Test Input ===") println(part1(testInput)) println("=== Part 1 - Final Input ===") println(part1(input)) println("=== Part 2 - Test Input ===") println(part2(testInput)) println("=== Part 2 - Final Input ===") println(part2(input)) }
0
Kotlin
0
0
883785d661d4886d8c9e43b7706e6a70935fb4f1
3,336
aoc-2022
Apache License 2.0
modules/randomly/src/main/kotlin/silentorb/mythic/randomly/WeightedPoolTable.kt
silentorb
227,508,449
false
null
package silentorb.mythic.randomly data class WeightedPoolTable( val alias: List<Int>, val probability: List<Int>, val total: Int, ) fun newWeightedPoolTable(probabilities: List<Int>): WeightedPoolTable { require(probabilities.any()) { "Alias table probabilities list cannot be empty." } val alias = IntArray(probabilities.size) val probability = IntArray(probabilities.size) val tempProbabilities = probabilities.toMutableList() val total = tempProbabilities.sum() val average = total / tempProbabilities.size val stacks = tempProbabilities .indices .partition { tempProbabilities[it] >= average } val large = stacks.first.toMutableList() val small = stacks.second.toMutableList() while (small.any() && large.any()) { val less = small.removeLast() val more = large.removeLast() probability[less] = tempProbabilities[less] * tempProbabilities.size alias[less] = more tempProbabilities[more] = tempProbabilities[more] + tempProbabilities[less] - average if (tempProbabilities[more] >= average) large.add(more) else small.add(more) } small.forEach { probability[it] = total } large.forEach { probability[it] = total } return WeightedPoolTable( alias = alias.asList(), probability = probability.asList(), total = total, ) } fun getAliasedIndex(table: WeightedPoolTable, dice: Dice): Int { val column = dice.getInt(table.probability.size - 1) val coinToss = dice.getInt(table.total) < table.probability[column] return if (coinToss) column else table.alias[column] }
0
Kotlin
0
2
74462fcba9e7805dddec1bfcb3431665df7d0dee
1,598
mythic-kotlin
MIT License
archive/src/main/kotlin/com/grappenmaker/aoc/year23/Day25.kt
770grappenmaker
434,645,245
false
{"Kotlin": 409647, "Python": 647}
package com.grappenmaker.aoc.year23 import com.grappenmaker.aoc.* fun PuzzleSet.day25() = puzzle(day = 25) { // I am quite happy I solved it with a viz, this algorithm is... not great val total = buildMap<String, List<String>> { inputLines.forEach { l -> val (n, rest) = l.split(": ") val o = rest.split(" ") put(n, o) o.forEach { put(it, (get(it) ?: emptyList()) + n) } } } fun eval(map: Map<String, List<String>>): List<Set<String>> { val left = map.keys.toHashSet() val groups = mutableListOf<Set<String>>() while (left.isNotEmpty()) { val ff = floodFill(left.first(), neighbors = { curr -> map.getValue(curr).filter { it in left } }) left -= ff groups += ff } return groups } fun build(excludes: Set<Set<String>>): Map<String, MutableList<String>> { val m = total.mapValues { it.value.toMutableList() } excludes.map { it.toList() }.forEach { (f, t) -> m.getValue(f) -= t m.getValue(t) -= f } return m } val comb = total.keys.combinations(2).toList() a@ while (true) { val removed = hashSetOf<Set<String>>() repeat(3) { val m = build(removed) val freq = hashMapOf<Set<String>, Int>().withDefault { 0 } comb.randomSamples(15) { (f, t) -> val res = dijkstra(f, isEnd = { it == t }, neighbors = { m.getValue(it) }, findCost = { 1 }) res?.path?.zipWithNext()?.forEach { (f, t) -> val k = setOf(f, t) freq[k] = freq.getValue(k) + res.path.size } } removed += freq.toList().filter { (k) -> k.none { f -> m.getValue(f).any { t -> m.getValue(t).singleOrNull() == f } } }.maxBy { it.second }.first } val (big, small) = eval(build(removed)).partition { it.size > 100 } if (big.size != 2) continue@a val (a, b) = big.map { it.toHashSet() } for (s in small.flatten()) { val seen = hashSetOf(s) val queue = queueOf(s) while (queue.isNotEmpty()) when (val next = queue.removeLast()) { in a -> { a += s continue } in b -> { b += s continue } else -> total.getValue(next).forEach { if (seen.add(it)) queue.addFirst(it) } } } partOne = (a.size * b.size).s() break } }
0
Kotlin
0
7
92ef1b5ecc3cbe76d2ccd0303a73fddda82ba585
2,668
advent-of-code
The Unlicense
src/Day07.kt
fonglh
573,269,990
false
{"Kotlin": 48950, "Ruby": 1701}
// Node can be either a file or directory // directories will have size 0 data class Node(val nodes: MutableList<Node>, val parent: Node?, val name: String, val size: Int) fun main() { fun buildFilesystem(input: List<String>): Node { var filesystem = Node(mutableListOf(), null, "/" , 0) var currentNode = filesystem var inputLineCtr = 1 // skip the first "$ cd /" line while (inputLineCtr < input.size) { //println(input[inputLineCtr]) if (input[inputLineCtr] == "$ ls") { // parse listing inputLineCtr++ while(inputLineCtr < input.size && input[inputLineCtr][0] != '$') { //println(input[inputLineCtr]) val (nodeType, nodeName) = input[inputLineCtr].split(" ") if (nodeType == "dir") { currentNode.nodes.add(Node(mutableListOf(), currentNode, nodeName, 0)) } else { val fileSize = nodeType.toInt() currentNode.nodes.add(Node(mutableListOf(), currentNode, nodeName, fileSize)) } inputLineCtr++ } } else if (input[inputLineCtr].startsWith("$ cd")) { // change directory val dirName = input[inputLineCtr].substring(5) if (dirName == "..") { currentNode = currentNode.parent!! } else { val nodes = currentNode.nodes for (node in nodes) { if (node.name == dirName) { currentNode = node break } } } inputLineCtr++ } } return filesystem } fun dirSize(node: Node, dirSizeList: MutableList<Int>): Int { // Directories have size 0, so this must be a file and thus a leaf node. if (node.size > 0) { return node.size } var totalSize = 0 for (item in node.nodes) { totalSize += dirSize(item, dirSizeList) } dirSizeList.add(totalSize) return totalSize } fun part1(input: List<String>): Int { var filesystem = buildFilesystem(input) val dirSizes = mutableListOf<Int>() dirSize(filesystem, dirSizes) return dirSizes.filter { it < 100000 }.sum() } fun part2(input: List<String>): Int { var filesystem = buildFilesystem(input) val dirSizes = mutableListOf<Int>() val fsSize = dirSize(filesystem, dirSizes) val unusedSize = 70000000 - fsSize val minDeleteSize = 30000000 - unusedSize return dirSizes.filter { it > minDeleteSize }.min() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day07_test") check(part1(testInput) == 95437) check(part2(testInput) == 24933642) val input = readInput("Day07") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
ef41300d53c604fcd0f4d4c1783cc16916ef879b
3,152
advent-of-code-2022
Apache License 2.0
src/Day11.kt
szymon-kaczorowski
572,839,642
false
{"Kotlin": 45324}
import java.math.BigInteger fun main() { data class Monkey( var items: MutableList<BigInteger> = mutableListOf(), var testDivision: Int = 1, var operation: (BigInteger) -> BigInteger = { it }, var targetTrue: Int = -1, var targetFalse: Int = -1, var process: Int = 0, ) { } fun monkeys( input: List<String>, multLevels: Int, ): Pair<Int, MutableList<Monkey>> { var multLevels1 = multLevels val monkeys = mutableListOf<Monkey>() for (line in input) { if (line.startsWith("Monkey")) { monkeys.add(Monkey()) } if (line.contains("Starting")) { monkeys.last().items = line.trim().replace("Starting items: ", "").split(",").map { it.trim().toLong().toBigInteger() } .toMutableList() } if (line.contains("Operation")) { val split = line.trim().replace("Operation: new = old ", "").split(" ") when (split[1]) { "old" -> { monkeys.last().operation = { old -> old.pow(2) } } else -> { val data = split[1].trim().toInt() monkeys.last().operation = when (split[0]) { "+" -> { old -> old.plus(data.toBigInteger()) } "*" -> { old -> old.times(data.toBigInteger()) } else -> { old -> old } } } } } if (line.contains("Test")) { val toInt = line.trim().replace("Test: divisible by ", "").trim().toInt() monkeys.last().testDivision = toInt multLevels1 *= toInt } if (line.contains("true")) { monkeys.last().targetTrue = line.trim().replace("If true: throw to monkey", "").trim().toInt() } if (line.contains("false")) { monkeys.last().targetFalse = line.trim().replace("If false: throw to monkey", "").trim().toInt() } } return multLevels1 to monkeys } fun part1(input: List<String>): Int { fun Monkey.processItem() = if (items.isNotEmpty()) { process++ items.removeFirst().let(operation).let { it.divide(BigInteger.valueOf(3)) }.let { it to (if (it.remainder(testDivision.toBigInteger()).toInt() == 0) { targetTrue } else targetFalse) } } else null val (_, monkeys) = monkeys(input, 1) for (rounds in 1..20) { for (monkey in monkeys) { var processResult: Pair<BigInteger, Int>? do { processResult = monkey.processItem() if (processResult != null) { monkeys[processResult.second].items.add(processResult.first) } } while (processResult != null) } } val top2 = monkeys.sortedBy { it.process }.reversed().take(2) return top2[0].process * top2[1].process } fun part2(input: List<String>): Long { var multLevels: Int = 1 fun Monkey.processItems(): List<Pair<BigInteger, Int>> { val processPairs = items.map { operation(it) }.map { it.rem(multLevels.toBigInteger()) }.map { it to (if (it.remainder(testDivision.toBigInteger()).toInt() == 0) { targetTrue } else targetFalse) } process += items.size items.clear() return processPairs } val (resultMult, monkeys) = monkeys(input, multLevels) multLevels = resultMult for (rounds in 1..10000) { for (monkey in monkeys) { monkey.processItems().forEach { monkeys[it.second].items.add(it.first) } } } val top2 = monkeys.sortedBy { it.process }.reversed().take(2) return top2[0].process.toLong() * top2[1].process.toLong() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day11_test") check(part1(testInput) == 10605) check(part2(testInput) == 2713310158L) val input = readInput("Day11") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
1d7ab334f38a9e260c72725d3f583228acb6aa0e
4,576
advent-2022
Apache License 2.0
src/main/kotlin/d7/D7_2.kt
MTender
734,007,442
false
{"Kotlin": 108628}
package d7 import input.Input const val CARD_LABELS_JOKER = "AKQT98765432J" data class JokerHand( val cards: String, val bid: Int ) : Comparable<JokerHand> { override fun compareTo(other: JokerHand): Int { val typeDiff = this.getTypeStrength() - other.getTypeStrength() if (typeDiff != 0) return typeDiff for (i in 0..4) { if (this.cards[i] != other.cards[i]) { return CARD_LABELS_JOKER.indexOf(other.cards[i]) - CARD_LABELS_JOKER.indexOf(this.cards[i]) } } return 0 } private fun getTypeStrength(): Int { val charCounts = mutableMapOf<Char, Int>() for (c in cards) { charCounts[c] = (charCounts[c] ?: 0) + 1 } val jokersCount = charCounts['J'] ?: 0 return when (charCounts.size) { 5 -> { if (jokersCount != 0) return 2 // one pair return 1 // high card } 4 -> { when (jokersCount) { 2, 1 -> 4 // three of a kind 0 -> 2 // one pair else -> throw RuntimeException("impossible") } } 3 -> { when (jokersCount) { 3, 2 -> 6 // four of a kind 1 -> { if (charCounts.values.toSet() == setOf(2, 2, 1)) { return 5 // full house } return 6 // four of a kind } 0 -> { if (charCounts.values.toSet() == setOf(2, 2, 1)) { return 3 // two pair } return 4 // three of a kind } else -> throw RuntimeException("impossible") } } 2 -> { if (jokersCount != 0) return 7 // five of a kind if (charCounts.values.toSet() == setOf(3, 2)) { return 5 // full house } return 6 // four of a kind } 1 -> 7 // five of a kind else -> { throw RuntimeException("impossible") } } } } fun parseJokerInput(lines: List<String>): List<JokerHand> { return lines .map { it.split(" ") } .map { JokerHand(it[0], it[1].toInt()) } } fun main() { val lines = Input.read("input.txt") val hands = parseJokerInput(lines) val sortedHands = hands.sorted() println(sortedHands.mapIndexed { index, hand -> hand.bid * (index + 1) }.sum()) }
0
Kotlin
0
0
a6eec4168b4a98b73d4496c9d610854a0165dbeb
2,712
aoc2023-kotlin
MIT License
src/day_15/kotlin/Day15.kt
Nxllpointer
573,051,992
false
{"Kotlin": 41751}
import kotlin.math.absoluteValue import kotlin.system.measureTimeMillis // AOC Day 15 fun Vector2D.manhattanDistanceTo(other: Vector2D) = (this - other).abs().run { x + y } data class Sensor(val position: Vector2D, val beaconPosition: Vector2D) { val beaconDistance = position.manhattanDistanceTo(beaconPosition) } fun part1(sensors: List<Sensor>) { val rowToCheck = 2000000 val beaconXPositions = sensors.filter { it.beaconPosition.y == rowToCheck }.map { it.beaconPosition.x } val coveringSensors = sensors.filter { sensor -> (rowToCheck - sensor.position.y).absoluteValue <= sensor.beaconDistance } val rowCoveredXPositions = mutableSetOf<Int>() coveringSensors.forEach { sensor -> val xDistance = sensor.beaconDistance - (sensor.position.y - rowToCheck).absoluteValue for (xOffset in -xDistance..+xDistance) { val xPosition = sensor.position.x + xOffset if (xPosition !in beaconXPositions) rowCoveredXPositions += xPosition } } println("Part 1: No beacon can be placed at ${rowCoveredXPositions.size} positions in row $rowToCheck") } fun part2(sensors: List<Sensor>) { // Since the distress beacon is the only uncovered point we can check every point next to the edges of sensor coverages // We can the check if any sensor coveres the point. If it is not covered we found the distress beacon. val minX = sensors.minOf { it.position.x }.coerceAtLeast(0) val maxX = sensors.maxOf { it.position.x }.coerceAtMost(4000000) val minY = sensors.minOf { it.position.y }.coerceAtLeast(0) val maxY = sensors.maxOf { it.position.y }.coerceAtMost(4000000) val rangeX = minX..maxX val rangeY = minY..maxY fun Vector2D.isCovered() = sensors.any { sensor -> sensor.position.manhattanDistanceTo(this) <= sensor.beaconDistance } sensors.forEach sensors@{ sensor -> val edgeDistance = sensor.beaconDistance + 1 for (xOffset in -edgeDistance..+edgeDistance) { val posX = sensor.position.x + xOffset if (posX !in rangeX) continue val unsignedHOffset = edgeDistance - xOffset.absoluteValue listOf(+unsignedHOffset, -unsignedHOffset).forEach hOffsets@{ hOffset -> val posY = sensor.position.y + hOffset if (posY !in rangeY) return@hOffsets val position = sensor.position + Vector2D(xOffset, hOffset) if (!position.isCovered()) { val tuningFrequency = position.x.toLong() * 4000000L + position.y.toLong() println("Part 2: The distress tuning frequency is $tuningFrequency") return } } } } } fun main() { val positionRegex = "x=(-*\\d+), y=(-*\\d+)".toRegex() fun MatchResult.toPosition() = this.groupValues.drop(1).mapToInt().run { Vector2D(first(), last()) } val sensors = getAOCInput { rawInput -> rawInput.trim().lines().map { line -> val positionMatches = positionRegex.findAll(line) val sensorPosition = positionMatches.first().toPosition() val beaconPosition = positionMatches.last().toPosition() Sensor(sensorPosition, beaconPosition) } } measureTimeMillis { part1(sensors) }.also { println("Part 1 took ${it / 1000f} seconds") } measureTimeMillis { part2(sensors) }.also { println("Part 2 took ${it / 1000f} seconds") } }
0
Kotlin
0
0
b6d7ef06de41ad01a8d64ef19ca7ca2610754151
3,500
AdventOfCode2022
MIT License
src/main/kotlin/g1401_1500/s1467_probability_of_a_two_boxes_having_the_same_number_of_distinct_balls/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g1401_1500.s1467_probability_of_a_two_boxes_having_the_same_number_of_distinct_balls // #Hard #Dynamic_Programming #Math #Backtracking #Combinatorics #Probability_and_Statistics // #2023_06_13_Time_150_ms_(100.00%)_Space_34_MB_(100.00%) class Solution { fun getProbability(balls: IntArray): Double { val m = balls.size var s = 0 for (b in balls) { s += b } val c = Array(s + 1) { DoubleArray(s / 2 + 1) } c[0][0] = 1.0 for (i in 1 until s + 1) { c[i][0] = 1.0 for (j in 1 until s / 2 + 1) { c[i][j] = c[i - 1][j] + c[i - 1][j - 1] } } var dp = Array(2 * m + 1) { DoubleArray(s / 2 + 1) } dp[m][0] = 1.0 var sum = 0 for (b in balls) { sum += b val ndp = Array(2 * m + 1) { DoubleArray(s / 2 + 1) } for (i in 0..b) { for (j in 0 until 2 * m + 1) { for (k in 0 until s / 2 + 1) { if (dp[j][k] == 0.0) { continue } val nk = k + i val nr = sum - nk if (nk <= s / 2 && nr <= s / 2) { val i1 = if (i == b) j + 1 else j val nj = if (i == 0) j - 1 else i1 ndp[nj][nk] += dp[j][k] * c[b][i] } } } } dp = ndp } return dp[m][s / 2] / c[s][s / 2] } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,620
LeetCode-in-Kotlin
MIT License
kotlin/src/main/kotlin/year2023/Day09.kt
adrisalas
725,641,735
false
{"Kotlin": 130217, "Python": 1548}
package year2023 import java.util.* fun main() { val input = readInput("Day09") Day09.part1(input).println() Day09.part2(input).println() } object Day09 { fun part1(input: List<String>): Long { return input .map { line -> toIntList(line) } .sumOf { history -> predictionLastNumber(history) } } private fun toIntList(line: String): List<Int> { return line.split(" ") .filter { it.isNotBlank() } .map { it.toInt() } } private fun predictionLastNumber(history: List<Int>): Long { val incrementStack = Stack<List<Int>>() incrementStack.push(history) while (!incrementStack.peek().all { it == 0 }) { val increment = incrementStack .peek() .windowed(2) .map { it[1] - it[0] } incrementStack.push(increment) } var prediction = 0L while (incrementStack.isNotEmpty()) { val increment = incrementStack.pop() prediction += increment.last() } return prediction } fun part2(input: List<String>): Long { return input .map { line -> toIntList(line) } .sumOf { history -> predictionFirstNumber(history) } } private fun predictionFirstNumber(history: List<Int>): Long { val incrementStack = Stack<List<Int>>() incrementStack.push(history) while (!incrementStack.peek().all { it == 0 }) { val increment = incrementStack .peek() .windowed(2) .map { it[1] - it[0] } incrementStack.push(increment) } var prediction = 0L while (incrementStack.isNotEmpty()) { val increment = incrementStack.pop() prediction = increment.first() - prediction } return prediction } }
0
Kotlin
0
2
6733e3a270781ad0d0c383f7996be9f027c56c0e
1,924
advent-of-code
MIT License
src/main/kotlin/com/hj/leetcode/kotlin/problem2360/Solution.kt
hj-core
534,054,064
false
{"Kotlin": 619841}
package com.hj.leetcode.kotlin.problem2360 /** * LeetCode page: [2360. Longest Cycle in a Graph](https://leetcode.com/problems/longest-cycle-in-a-graph/); */ class Solution { private val unknownLength = -1 /* Complexity: * Time O(N) and Space O(N) where N is the size of edges; */ fun longestCycle(edges: IntArray): Int { val numNodes = edges.size // reachableCycleLengths[i] ::= the reachable cycle length of node i val reachableCycleLengths = IntArray(numNodes) { unknownLength } val nodes = 0 until numNodes for (node in nodes) { val hasVisited = reachableCycleLengths[node] != unknownLength if (hasVisited) continue updateReachableCycleLengths(node, edges, reachableCycleLengths) } val maxCycleLength = reachableCycleLengths.max()!! val noCycleFound = maxCycleLength == 0 return if (noCycleFound) -1 else maxCycleLength } private fun updateReachableCycleLengths( sourceNode: Int, edges: IntArray, reachableCycleLengths: IntArray ) { val cycleLength = reachableCycleLengthOfNode(sourceNode, edges, reachableCycleLengths) var currentNode: Int? = sourceNode while ( currentNode != null && reachableCycleLengths[currentNode] == unknownLength ) { reachableCycleLengths[currentNode] = cycleLength currentNode = nextNodeOrNull(currentNode, edges) } } private fun reachableCycleLengthOfNode( node: Int, edges: IntArray, reachableCycleLengths: IntArray ): Int { var slowNode = node var fastNode = secondNextNodeOrNull(node, edges) while ( fastNode != null && reachableCycleLengths[fastNode] == unknownLength && slowNode != fastNode ) { slowNode = nextNodeOrNull(slowNode, edges) ?: throw IllegalStateException() fastNode = secondNextNodeOrNull(fastNode, edges) } val noCycleFound = fastNode == null if (noCycleFound) return 0 checkNotNull(fastNode) val isKnownLength = reachableCycleLengths[fastNode] != unknownLength if (isKnownLength) return reachableCycleLengths[fastNode] return cycleLength(fastNode, edges) } private fun nextNodeOrNull(currentNode: Int, edges: IntArray): Int? { return edges[currentNode].let { if (it == -1) null else it } } private fun secondNextNodeOrNull(currentNode: Int, edges: IntArray): Int? { return nextNodeOrNull(currentNode, edges)?.let { nextNodeOrNull(it, edges) } } private fun cycleLength(nodeInCycle: Int, edges: IntArray): Int { var length = 1 var currentNode = edges[nodeInCycle] while (currentNode != nodeInCycle) { length++ currentNode = edges[currentNode] } return length } }
1
Kotlin
0
1
14c033f2bf43d1c4148633a222c133d76986029c
2,972
hj-leetcode-kotlin
Apache License 2.0
src/test/kotlin/year2015/Day9.kt
abelkov
47,995,527
false
{"Kotlin": 48425}
package year2015 import kotlin.math.max import kotlin.math.min import kotlin.test.Test import kotlin.test.assertEquals class Day9 { @Test fun part1() { val regex = """(\w+) to (\w+) = (\d+)""".toRegex() val cities = mutableSetOf<String>() val map = mutableMapOf<Pair<String, String>, Int>() for (line in readInput("year2015/Day9.txt").lines()) { val matchResult = regex.matchEntire(line) val (from, to, distance) = matchResult!!.groupValues.drop(1) cities.add(from) cities.add(to) map[Pair(from, to)] = distance.toInt() map[Pair(to, from)] = distance.toInt() } var shortest = Int.MAX_VALUE for (route: List<String> in cities.permutations()) { var total = 0 for ((index, fromCity) in route.dropLast(1).withIndex()) { val toCity = route[index + 1] total += map[fromCity to toCity] ?: throw AssertionError() } shortest = min(shortest, total) } assertEquals(117, shortest) } @Test fun part2() { val regex = """(\w+) to (\w+) = (\d+)""".toRegex() val cities = mutableSetOf<String>() val map = mutableMapOf<Pair<String, String>, Int>() for (line in readInput("year2015/Day9.txt").lines()) { val matchResult = regex.matchEntire(line) val (from, to, distance) = matchResult!!.groupValues.drop(1) cities.add(from) cities.add(to) map[Pair(from, to)] = distance.toInt() map[Pair(to, from)] = distance.toInt() } var longest = 0 for (route: List<String> in cities.permutations()) { var total = 0 for ((index, fromCity) in route.dropLast(1).withIndex()) { val toCity = route[index + 1] total += map[fromCity to toCity] ?: throw AssertionError() } longest = max(longest, total) } assertEquals(909, longest) } }
0
Kotlin
0
0
0e4b827a742322f42c2015ae49ebc976e2ef0aa8
2,075
advent-of-code
MIT License
src/main/kotlin/com/chriswk/aoc/advent2021/Day22.kt
chriswk
317,863,220
false
{"Kotlin": 481061}
package com.chriswk.aoc.advent2021 import com.chriswk.aoc.AdventDay import com.chriswk.aoc.util.intersect import com.chriswk.aoc.util.intersects import com.chriswk.aoc.util.report import com.chriswk.aoc.util.size class Day22 : AdventDay(2021, 22) { companion object { @JvmStatic fun main(args: Array<String>) { val day = Day22() report { day.part1() } report { day.part2() } } val rangePattern = """x=(-?\d+)\.\.(-?\d+),y=(-?\d+)\.\.(-?\d+),z=(-?\d+)\.\.(-?\d+)""".toRegex() } private val inputCuboids = inputAsLines.map { Cuboid.of(it) } private val part1Cube = Cuboid(true, -50..50, -50..50, -50..50) private class Cuboid(val on: Boolean, val x: IntRange, val y: IntRange, val z: IntRange) { companion object { private val pattern = """^(on|off) x=(-?\d+)\.\.(-?\d+),y=(-?\d+)\.\.(-?\d+),z=(-?\d+)\.\.(-?\d+)$""".toRegex() fun of(input: String): Cuboid { val (s, x1, x2, y1, y2, z1, z2) = pattern.matchEntire(input)?.destructured ?: error("Cannot parse input: $input") return Cuboid( s == "on", x1.toInt()..x2.toInt(), y1.toInt()..y2.toInt(), z1.toInt()..z2.toInt(), ) } } fun intersects(other: Cuboid): Boolean = x.intersects(other.x) && y.intersects(other.y) && z.intersects(other.z) fun intersect(other: Cuboid): Cuboid? { return if (!intersects(other)) { null } else { Cuboid(!on, x.intersect(other.x), y intersect other.y, z intersect other.z) } } fun volume(): Long { return x.size().toLong() * y.size().toLong() * z.size().toLong() * if (on) { 1 } else { -1 } } } private fun solve(cubesToUse: List<Cuboid> = inputCuboids): Long { val volumes = mutableListOf<Cuboid>() cubesToUse.forEach { cube -> volumes.addAll(volumes.mapNotNull { it.intersect(cube) }) if (cube.on) volumes.add(cube) } return volumes.sumOf { it.volume() } } fun part1(): Long { return solve(inputCuboids.filter { it.intersects(part1Cube) }) } fun part2(): Long { return solve(inputCuboids) } }
116
Kotlin
0
0
69fa3dfed62d5cb7d961fe16924066cb7f9f5985
2,537
adventofcode
MIT License
src/main/kotlin/leetcode/google/Problem1548.kt
Magdi
390,731,717
false
null
package leetcode.google /** * The Most Similar Path in a Graph * https://leetcode.com/problems/the-most-similar-path-in-a-graph/ */ class Problem1548 { private val cache = hashMapOf<Pair<Int, Int>, Int>() /** * Time * O ( p * n * n ) * p: path length * n: number of nodes * * Space * O ( p * n ) */ fun mostSimilar(n: Int, roads: Array<IntArray>, names: Array<String>, targetPath: Array<String>): List<Int> { val nodes = names.mapIndexed { index, name -> Node(index, name) } roads.forEach { (from, to) -> nodes[from].adj.add(nodes[to]) nodes[to].adj.add(nodes[from]) } var min = Int.MAX_VALUE var start: Node = nodes[0] cache.clear() nodes.forEach { startNode -> val cur = dp(0, startNode, targetPath) if (cur < min) { min = cur start = startNode } } val result = IntArray(targetPath.size) generatePath(start, 0, result) return result.asList() } private fun generatePath(cur: Node, index: Int, results: IntArray) { if (index == results.size) return results[index] = cur.id var minAdj = cur.adj.minBy { cache[Pair(index + 1, it.id)] ?: Int.MAX_VALUE } generatePath(minAdj!!, index + 1, results) } private fun dp(index: Int, cur: Node, targetPath: Array<String>): Int { if (index == targetPath.size) { return 0 } val key = Pair(index, cur.id) if (cache.contains(key)) return cache[key]!! var min = Int.MAX_VALUE cur.adj.forEach { adjNode -> val cost = if (cur.name != targetPath[index]) 1 else 0 min = Math.min(min, cost + dp(index + 1, adjNode, targetPath)) } cache[key] = min return min } data class Node( val id: Int, val name: String, val adj: MutableList<Node> = mutableListOf() ) }
0
Kotlin
0
0
63bc711dc8756735f210a71454144dd033e8927d
2,037
ProblemSolving
Apache License 2.0
src/Day13.kt
akijowski
574,262,746
false
{"Kotlin": 56887, "Shell": 101}
import kotlinx.serialization.json.* class PacketComparator: Comparator<JsonElement> { override fun compare(o1: JsonElement, o2: JsonElement): Int { var a = o1; var b = o2 if (a is JsonArray && b is JsonArray) { // compare lists for (i in 0 until a.size.coerceAtMost(b.size)) { val res = compare(a[i], b[i]) // not equal if (res != 0) { return res } } // left ran out if (a.size < b.size) { return -1 } // right ran out if (a.size > b.size) { return 1 } return 0 } if (a is JsonArray) { b = JsonArray(listOf(b)) return compare(a, b) } if (b is JsonArray) { a = JsonArray(listOf(a)) return compare(a, b) } return a.jsonPrimitive.int compareTo b.jsonPrimitive.int } } fun main() { val pc = PacketComparator() fun correct(pairs: List<String>): Boolean { val (first, second) = pairs val a = Json.decodeFromString(JsonArray.serializer(), first) val b = Json.decodeFromString(JsonArray.serializer(), second) val comp = pc.compare(a, b) return comp == -1 } fun part1(input: List<String>): Int { return input .filter { it.isNotBlank() } .chunked(2) .mapIndexed { idx, codePairs -> if (correct(codePairs)) idx+1 else 0 }.sum() } fun part2(input: List<String>): Int { val updatedList = input.toMutableList().apply { add("[[2]]") add("[[6]]") } var s1 = 0 var s2 = 0 updatedList .filter { it.isNotBlank() } .map { Json.decodeFromString(JsonArray.serializer(), it)} .sortedWith(pc) .forEachIndexed { index, jsonArray -> if (jsonArray.toString() == "[[2]]") { s1 += (index + 1) } if (jsonArray.toString() == "[[6]]") { s2 += (index + 1) } } return s1 * s2 } // 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)) }
0
Kotlin
1
0
84d86a4bbaee40de72243c25b57e8eaf1d88e6d1
2,559
advent-of-code-2022
Apache License 2.0
algorithms/src/main/kotlin/org/baichuan/sample/algorithms/leetcode/simple/interview/Massage.kt
scientificCommunity
352,868,267
false
{"Java": 154453, "Kotlin": 69817}
package org.baichuan.sample.algorithms.leetcode.simple.interview /** * https://leetcode.cn/problems/the-masseuse-lcci/ * 面试题 17.16. 按摩师 */ class Massage { /** * 时间复杂度:O(n) * 空间复杂度:O(n) * 状态转移方程: dp[i] = max(dp[i-1],dp[i-2]) */ fun massage(nums: IntArray): Int { if (nums.isEmpty()) { return 0 } if (nums.size == 1) { return nums[0] } val dp = IntArray(nums.size) dp[0] = nums[0] dp[1] = Math.max(nums[0], nums[1]) for (i in 2 until nums.size) { dp[i] = Math.max(dp[i - 1], dp[i - 2] + nums[i]) } return dp[nums.size - 1] } /** * 时间复杂度:O(n) * 空间复杂度:O(1) * 状态转移方程: dp[i] = max(dp[i-1],dp[i-2]) * 从递推关系来看,每次计算时需要保存的状态只有3个:dp[i] dp[i-1] dp[i-2],所以可以考虑每次循环可以丢弃i-3 * 所以只需要保证每次循环,i i-1 i-2这3个连续的数对应的结果在dp里,并且能通过下表找到对应的值即可。而dp本身只有0,1,2几个空位。 * 而x%3 = (x-3)%3。而且在i连续的情况下取模产生的数也是连续的。所以,dp[i%3] = max(dp[(i-1)%3],dp[(i-2)%3]) */ fun massage1(nums: IntArray): Int { if (nums.isEmpty()) { return 0 } if (nums.size == 1) { return nums[0] } val dp = IntArray(3) dp[0] = nums[0] dp[1] = Math.max(nums[0], nums[1]) for (i in 2 until nums.size) { dp[i % 3] = Math.max(dp[(i - 1) % 3], dp[(i - 2) % 3] + nums[i]) } return dp[(nums.size - 1) % 3] } } fun main() { }
1
Java
0
8
36e291c0135a06f3064e6ac0e573691ac70714b6
1,784
blog-sample
Apache License 2.0
src/Day18.kt
EdoFanuel
575,561,680
false
{"Kotlin": 80963}
import utils.BBox3D import utils.Coord3D import java.util.LinkedList enum class Direction3D(val vector: Coord3D) { RIGHT(Coord3D(1, 0, 0)), LEFT(Coord3D(-1, 0, 0)), TOP(Coord3D(0, 1, 0)), BOTTOM(Coord3D(0, -1, 0)), BACK(Coord3D(0, 0, 1)), FORWARD(Coord3D(0, 0, -1)); } fun main() { fun part1(input: List<String>): Long { val shape = input.map { row -> val (a, b, c) = row.split(",").map { it.toLong() } Coord3D(a, b, c) }.toSet() return calculateSurfaceArea(shape) } fun part2(input: List<String>): Long { val shape = input.map { row -> val (a, b, c) = row.split(",").map { it.toLong() } Coord3D(a, b, c) }.toMutableSet() val bbox = BBox3D( shape.minOf { it.x }..shape.maxOf { it.x }, shape.minOf { it.y }..shape.maxOf { it.y }, shape.minOf { it.z }..shape.maxOf { it.z } ) val trappedAir = mutableSetOf<Coord3D>() for (x in bbox.x) { for (y in bbox.y) { for (z in bbox.z) { if (isTrapped(Coord3D(x, y, z), bbox, shape)) trappedAir += Coord3D(x, y, z) } } } val surfaceArea = calculateSurfaceArea(shape) val airArea = calculateSurfaceArea(trappedAir) return surfaceArea - airArea } val test = readInput("Day18_test") println("=== Part 1 (test) ===") println(part1(test)) println("=== Part 2 (test) ===") println(part2(test)) val input = readInput("Day18") println("=== Part 1 (puzzle) ===") println(part1(input)) println("=== Part 2 (puzzle) ===") println(part2(input)) } fun calculateSurfaceArea(shape: Set<Coord3D>): Long { var surfaceArea = 0L for (cube in shape) { surfaceArea += Direction3D.values().map { it.vector + cube }.filter { it !in shape }.size } return surfaceArea } fun isTrapped(point: Coord3D, boundingBox: BBox3D, obstacle: Set<Coord3D>): Boolean { if (point in obstacle) return false val queue = LinkedList<Coord3D>() val visited = mutableSetOf<Coord3D>() queue += point visited += point while (queue.isNotEmpty()) { val cell = queue.poll() visited += cell for (direction in Direction3D.values()) { val nextCell = direction.vector + cell if (nextCell in obstacle || nextCell in visited || nextCell in queue) continue if (nextCell !in boundingBox) return false queue += nextCell } } return true }
0
Kotlin
0
0
46a776181e5c9ade0b5e88aa3c918f29b1659b4c
2,603
Advent-Of-Code-2022
Apache License 2.0
src/main/kotlin/graph/variation/LoopedTree.kt
yx-z
106,589,674
false
null
package graph.variation import graph.core.Vertex import graph.core.WeightedEdge import graph.core.WeightedGraph import util.Tuple2 import util.tu import java.util.* import kotlin.collections.HashMap // given a looped binary tree - non-negatively weighted, directed graph, // built from a binary tree by adding an edge from every leaf back to the root // find a shortest path algorithm from s to t that is faster than Dijkstra's O(E log V) typealias LoopedBinTree<V> = WeightedGraph<V, Int> // report the length of such path fun <V> LoopedBinTree<V>.shortestPath(s: Vertex<V>, t: Vertex<V>): Int { // our observation is that given such graph: // 1. there is only one path from parent to any children -> DFS // 2. there is a shortest path from child to leaf then to root -> DP strategy // and there is one path from root to some parent of the child -> DFS val root = vertices.first { edges.filter { (_, v) -> v == it }.count() > 1 } // down[v]: distance from root -> v val down = HashMap<Vertex<V>, Int>() down[root] = 0 // bfs version // you may get dfs with a stack instead val queue1: Queue<Vertex<V>> = LinkedList() queue1.add(root) while (queue1.isNotEmpty()) { val v = queue1.remove() getEdgesOf(v).forEach { (_, e, _, w) -> if (e !== root) { down[e] = w!! + down[v]!! queue1.add(e) } } } // O(V + E) // up[v]: distance from v to leaf to root val up = HashMap<Vertex<V>, Int>() up[root] = 0 getEdgesOf(root).forEach { (_, v) -> getUp(root, v, up) } // O(V + E) // check if s is a parent of t val queue2: Queue<Tuple2<Vertex<V>, Int>> = LinkedList() queue2.add(s tu 0) while (queue2.isNotEmpty()) { val (v, d) = queue2.remove() // if s is a parent of t indeed, return the weight of their unique path if (v === t) { return d } getEdgesOf(v).forEach { (_, e, _, w) -> if (e !== root) { queue2.add(e tu (d + w!!)) } } } // O(V + E) // s is NOT a parent of t -> shortest path from s to t is the shortest // path from s to leaf to root and then from root to t return up[s]!! + down[t]!! } fun <V> WeightedGraph<V, Int>.getUp(root: Vertex<V>, vertex: Vertex<V>, map: HashMap<Vertex<V>, Int>) { val edge = getEdgesOf(vertex).first() val isLeaf = edge.vertex2 == root if (isLeaf) { map[vertex] = edge.weight!! } else { getEdgesOf(vertex).forEach { (_, e) -> getUp(root, e, map) } map[vertex] = getEdgesOf(vertex) .map { (_, e, _, d) -> map[e]!! + d!! } .min()!! } } fun main(args: Array<String>) { val vertices = (0..8).map { Vertex(it) } val edges = setOf( WeightedEdge(vertices[0], vertices[1], true, 5), WeightedEdge(vertices[0], vertices[2], true, 8), WeightedEdge(vertices[1], vertices[3], true, 17), WeightedEdge(vertices[1], vertices[4], true, 0), WeightedEdge(vertices[2], vertices[5], true, 1), WeightedEdge(vertices[3], vertices[6], true, 23), WeightedEdge(vertices[4], vertices[0], true, 16), WeightedEdge(vertices[5], vertices[7], true, 9), WeightedEdge(vertices[5], vertices[8], true, 14), WeightedEdge(vertices[6], vertices[0], true, 4), WeightedEdge(vertices[7], vertices[0], true, 7), WeightedEdge(vertices[8], vertices[0], true, 42)) val graph = WeightedGraph(vertices, edges) // parent to child println(graph.shortestPath(vertices[0], vertices[5])) // child to parent println(graph.shortestPath(vertices[1], vertices[0])) }
0
Kotlin
0
1
15494d3dba5e5aa825ffa760107d60c297fb5206
3,463
AlgoKt
MIT License
src/Day05.kt
emmanueljohn1
572,809,704
false
{"Kotlin": 12720}
fun buildStacks (stackList: List<List<Char>>, size: Int): ArrayList<ArrayDeque<Char>> { val stacks = ArrayList<ArrayDeque<Char>>() for(i in 0 until size){ val stack = ArrayDeque<Char>() for (j in stackList.indices){ if(stackList[j][i] != ' '){ stack.add(stackList[j][i]) } } stacks.add(stack) } return stacks } fun main() { data class Model(val stacks: ArrayList<ArrayDeque<Char>>, val moves: List<List<Int>>) fun parseInput(input: List<String>): Model { val maxLength = input.takeWhile { it.contains("[") }.maxBy { it.length }.length val stacksRaw = input.takeWhile { it.contains("[") }.map { val lineStr = it.padEnd(maxLength, ' ') return@map buildList<Char> { var i = 1 while (i < maxLength+1){ add(lineStr[i]) i +=4 } } } val stacks = buildStacks(stacksRaw, (maxLength + 1)/4) val moves = input.drop(stacks.size) .filter { it.contains("move") } .map { """\d+""".toRegex().findAll(it).map{ it.value.toInt() } .toList() } return Model(stacks, moves) } fun part1(input: List<String>): String { val (stacks, moves) = parseInput(input) for ((count, from, to) in moves){ for(i in count downTo 1) { stacks[to - 1].addFirst(stacks[from - 1].removeFirst()) } } return stacks.map { it.first() }.joinToString("") } fun part2(input: List<String>): String { val (stacks, moves) = parseInput(input) for ((count, from, to) in moves){ val temp = stacks[from - 1].take(count) stacks[to - 1].addAll(0,temp) stacks[from - 1] = ArrayDeque(stacks[from - 1].drop(count)) } return stacks.map { it.first() }.joinToString("") } println("----- Test input -------") val testInput = readInput("inputs/Day05_test") println(part1(testInput)) println(part2(testInput)) println("----- Real input -------") val input = readInput("inputs/Day05") println(part1(input)) println(part2(input)) } //----- Test input ------- //CMZ //MCD //----- Real input ------- //QPJPLMNNR //BQDNWJPVJ
0
Kotlin
0
0
154db2b1648c9d12f82aa00722209741b1de1e1b
2,392
advent22
Apache License 2.0
kotest-property/src/commonMain/kotlin/io/kotest/property/Shrinker.kt
kotest
47,071,082
false
{"Kotlin": 4460715, "CSS": 352, "Java": 145}
package io.kotest.property /** * Given a value, T, this function returns reduced values to be used as candidates * for shrinking. * * A smaller value is defined per Shrinker. For a string it may be considered a string with * less characters, or less duplication/variation in the characters. For an integer it is typically * considered a smaller value with a positive sign. * * Shrinkers can return one or more values in a shrink step. Shrinkers can * return more than one value if there is no single "best path". For example, * when shrinking an integer, you probably want to return a single smaller value * at a time. For strings, you may wish to return a string that is simpler (YZ -> YY), * as well as smaller (YZ -> Y). * * If the value cannot be shrunk further, or the type * does not support meaningful shrinking, then this function should * return an empty list. * * Note: It is important that you do not return the degenerate case as the first step in a shrinker. * Otherwise, this could be tested first, it could pass, and no other routes would be explored. */ fun interface Shrinker<A> { /** * Returns the "next level" of shrinks for the given value, or empty list if a "base case" has been reached. * For example, to shrink an int k we may decide to return k/2 and k-1. */ fun shrink(value: A): List<A> } /** * Generates an [RTree] of all shrinks from an initial strict value. */ fun <A> Shrinker<A>.rtree(value: A): RTree<A> { val fn = { value } return rtree(fn) } /** * Generates an [RTree] of all shrinks from an initial lazy value. */ fun <A> Shrinker<A>.rtree(value: () -> A): RTree<A> = RTree( value, lazy { val a = value() shrink(a).distinct().filter { it != a }.map { rtree(it) } } ) data class RTree<out A>(val value: () -> A, val children: Lazy<List<RTree<A>>> = lazy { emptyList<RTree<A>>() }) fun <A, B> RTree<A>.map(f: (A) -> B): RTree<B> { val b = { f(value()) } val c = lazy { children.value.map { it.map(f) } } return RTree(b, c) } fun <A> RTree<A>.filter(predicate: (A) -> Boolean): RTree<A>? { val a = value() return when { predicate(a) -> RTree({ a }, lazy { children.value.mapNotNull { it.filter(predicate) } }) else -> null } } fun <A> RTree<A>.isEmpty() = this.children.value.isEmpty() fun <A, B> Shrinker<A>.bimap(f: (B) -> A, g: (A) -> B): Shrinker<B> = object : Shrinker<B> { override fun shrink(value: B): List<B> = this@bimap.shrink(f(value)).map(g) }
102
Kotlin
615
4,198
7fee2503fbbdc24df3c594ac6b240c11b265d03e
2,522
kotest
Apache License 2.0
src/Day08.kt
joy32812
573,132,774
false
{"Kotlin": 62766}
fun main() { fun left2right(grid: List<String>, dp: Array<Array<Boolean>>) { for (i in grid.indices) { var max = -1 for (j in grid[0].indices) { if (grid[i][j] - '0' > max) dp[i][j] = true max = maxOf(grid[i][j] - '0', max) } } } fun right2left(grid: List<String>, dp: Array<Array<Boolean>>) { for (i in grid.indices) { var max = -1 for (j in grid[0].indices.reversed()) { if (grid[i][j] - '0' > max) dp[i][j] = true max = maxOf(grid[i][j] - '0', max) } } } fun top2down(grid: List<String>, dp: Array<Array<Boolean>>) { for (j in grid[0].indices) { var max = -1 for (i in grid.indices) { if (grid[i][j] - '0' > max) dp[i][j] = true max = maxOf(grid[i][j] - '0', max) } } } fun down2top(grid: List<String>, dp: Array<Array<Boolean>>) { for (j in grid[0].indices) { var max = -1 for (i in grid.indices.reversed()) { if (grid[i][j] - '0' > max) dp[i][j] = true max = maxOf(grid[i][j] - '0', max) } } } fun part1(input: List<String>): Int { val m = input.size val n = input[0].length val dp = Array(m) { Array(n) { false } } left2right(input, dp) right2left(input, dp) top2down(input, dp) down2top(input, dp) return dp.flatMap { it.toList() }.count { it } } fun part2(input: List<String>): Int { val m = input.size val n = input[0].length fun work(x: Int, y: Int): Int { var a = 0 for (j in y - 1 downTo 0) { a ++ if (input[x][j] >= input[x][y]) break } var b = 0 for (j in y + 1 until n) { b ++ if (input[x][j] >= input[x][y]) break } var c = 0 for (i in x - 1 downTo 0) { c ++ if (input[i][y] >= input[x][y]) break } var d = 0 for (i in x + 1 until m) { d ++ if (input[i][y] >= input[x][y]) break } return a * b * c * d } var ans = -1 for (i in input.indices) { for (j in input[0].indices) { ans = maxOf(ans, work(i, j)) } } return ans } println(part1(readInput("data/Day08_test"))) println(part1(readInput("data/Day08"))) println(part2(readInput("data/Day08_test"))) println(part2(readInput("data/Day08"))) }
0
Kotlin
0
0
5e87958ebb415083801b4d03ceb6465f7ae56002
2,354
aoc-2022-in-kotlin
Apache License 2.0
src/main/kotlin/nl/kelpin/fleur/advent2018/Day15.kt
fdlk
159,925,533
false
null
package nl.kelpin.fleur.advent2018 import java.util.* class Day15(val input: List<String>) { val cave: List<String> = input.map { it.map { c -> when (c) { '#' -> '#' else -> '.' } }.joinToString("") } val xRange: IntRange = cave[0].indices val yRange: IntRange = cave.indices val initialCritters = input.mapIndexed { y, line -> line.mapIndexed { x, c -> when (c) { 'E', 'G' -> Critter(Point(x, y), c) else -> null } } }.flatten().filterNotNull().toSet() val critterComparison = compareBy<Critter>({ it.location.y }, { it.location.x }) private val targetComparison = compareBy<Critter>({ it.hitPoints }, { it.location.y }, { it.location.x }) private val pointComparison = compareBy<Point>({ it.y }, { it.x }) fun isOpenCave(p: Point): Boolean = with(p) { xRange.contains(x) && yRange.contains(y) && cave[y][x] == '.' } fun neighbors(p: Point): List<Point> = listOf(Up, Left, Right, Down).map { p.move(it) }.filter(::isOpenCave) data class Critter(val location: Point, val type: Char, val hitPoints: Int = 200, val attackPower: Int = 3) { fun attackedBy(other: Critter): Critter? = Optional.of(this.hitPoints - other.attackPower) .filter { it > 0 } .map { copy(hitPoints = it) } .orElse(null) } fun mapWith(critters: Set<Critter>): String = xRange.map { y -> yRange.map { x -> Point(x, y) }.map { point -> when { !isOpenCave(point) -> '#' else -> critters.find { it.location == point }?.type ?: '.' } }.joinToString("") }.joinToString("\n") private fun Point.isInRange(other: Point): Boolean = distanceTo(other) == 1 fun move(location: Point, targets: Set<Point>, occupied: Set<Point>): Point { if (targets.any { location.isInRange(it) }) return location val closed: MutableSet<Point> = (occupied + location).toMutableSet() // maps point reached to the first step taken to get there var current: Map<Point, Point> = neighbors(location).filter { !closed.contains(it) }.map { it to it }.toMap() while (!current.isEmpty()) { val goalReached: Point? = current.keys .filter { targets.any { target -> target.isInRange(it) } } .minWith(pointComparison) if (goalReached != null) return current[goalReached]!! closed.addAll(current.keys) val nextSteps = current.flatMap { (location, firstStep) -> neighbors(location) .filterNot { closed.contains(it) } .map { it to firstStep } } // pick preferred first step when merging the options into a map current = nextSteps .groupBy { it.first } .mapValues { it.value.map { it.second }.minWith(pointComparison)!! } } return location } fun nextRound(critters: Set<Critter>): Pair<Boolean, Set<Critter>> { val todo = critters.sortedWith(critterComparison).toMutableList() val done = mutableListOf<Critter>() var incompleteRound = false while (todo.isNotEmpty()) { val critter: Critter = todo.removeAt(0) val others = (todo + done) val enemies = others.filter { critter.type != it.type } if (enemies.isEmpty()) { incompleteRound = true } val newLocation = move(critter.location, enemies.map { it.location }.toSet(), others.map { it.location }.toSet()) val movedCritter = critter.copy(location = newLocation) val target = enemies.filter { it.location.isInRange(movedCritter.location) }.sortedWith(targetComparison).firstOrNull() if (target != null) { val molestedTarget = target.attackedBy(movedCritter) todo.update(target, molestedTarget) done.update(target, molestedTarget) } done.add(movedCritter) } return incompleteRound to done.toSet() } private fun simulate(initialCritters: Set<Critter>): Pair<Int, Set<Critter>> { var critters = initialCritters var i = 0 while (critters.map { it.type }.distinct().size == 2) { val (incompleteRound, nextCritters) = nextRound(critters) critters = nextCritters if (!incompleteRound) i++ } return Pair(i, critters) } fun part1(): Int { val (i, critters) = simulate(initialCritters) return i * critters.sumBy { it.hitPoints } } fun part2(): Int { var attackPower = 4 val numElves = initialCritters.count { it.type == 'E' } while (true) { val (i, critters) = simulate(initialCritters .map { if (it.type == 'E') it.copy(attackPower = attackPower) else it } .toSet()) if (critters.size == numElves && critters.all { it.type == 'E' }) { return i * critters.sumBy { it.hitPoints } } attackPower++ } } }
0
Kotlin
0
3
a089dbae93ee520bf7a8861c9f90731eabd6eba3
5,344
advent-2018
MIT License
kotlin/src/katas/kotlin/leetcode/maximum_area_serving_cake/MaximumAreaServingCake.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.maximum_area_serving_cake import datsok.shouldEqual import org.junit.Test import kotlin.math.PI import kotlin.math.abs /** * https://leetcode.com/discuss/interview-question/348510 */ class MaximumAreaServingCakeTests { @Test fun examples() { findLargestPiece(radii = arrayOf(1, 1, 1, 2, 2, 3), numberOfGuests = 6).roundTo(digits = 4) shouldEqual "7.0686" findLargestPiece(radii = arrayOf(4, 3, 3), numberOfGuests = 3).roundTo(4) shouldEqual "28.2743" findLargestPiece(radii = arrayOf(6, 7), numberOfGuests = 12).roundTo(4) shouldEqual "21.9911" } } private fun findLargestPiece(radii: Array<Int>, numberOfGuests: Int): Double { return findLargestPiece(radii.map { it * it * PI }, numberOfGuests) } private fun findLargestPiece(cakes: List<Double>, numberOfGuests: Int): Double { fun feed(piece: Double): Double { val cc = ArrayList(cakes) var i = 0 var guests = numberOfGuests while (i < cc.size && guests > 0) { if (cc[i] > piece) { cc[i] -= piece guests-- } else { i++ } } return if (guests > 0) -1.0 else cc.sum() } var min = 0.0 var max = cakes.sum() / numberOfGuests while (min < max && !min.closeTo(max)) { val mid = (max + min) / 2 val f = feed(mid) if (f > 0 && f.closeTo(0.0)) { return mid } else if (f > 0) { min = mid } else if (f < 0) { max = mid } } return min } private fun Double.closeTo(that: Double) = abs(this - that) <= 0.000001 private fun Double.roundTo(digits: Int): String = String.format("%.${digits}f", this)
7
Roff
3
5
0f169804fae2984b1a78fc25da2d7157a8c7a7be
1,754
katas
The Unlicense
src/Day02.kt
cznno
573,052,391
false
{"Kotlin": 7890}
import java.nio.file.Files import java.nio.file.Path object Day02 { private val map1 = mapOf("X" to 1, "Y" to 2, "Z" to 3) private val map2 = mapOf( "A X" to 3, "A Y" to 6, "A Z" to 0, "B X" to 0, "B Y" to 3, "B Z" to 6, "C X" to 6, "C Y" to 0, "C Z" to 3, ) private val list = listOf( "001", "012", "020", "100", "111", "122", "202", "210", "221" ) fun toDigi(t: String): Char { return when (t) { "X", "A" -> '0' "Y", "B" -> '1' else -> '2' } } fun part1(data: List<String>) { var sum = 0 for (s in data) { val k = s.split(" ") val m = toDigi(k[0]) val n = toDigi(k[1]) for (t in list) { if (t[0] == m && t[1] == n) { sum += when (t[1]) { '0' -> 1 '1' -> 2 else -> 3 } sum += when (t[2]) { '0' -> 0 '1' -> 3 else -> 6 } } } // sum += map1[s.split(" ")[1]]!! // sum += map2[s]!! } println(sum) //8890 } fun part2(data: List<String>) { var sum = 0 for (s in data) { val k = s.split(" ") val m = toDigi(k[0]) val n = toDigi(k[1]) for (t in list) { if (t[0] == m && t[2] == n) { sum += when (t[1]) { '0' -> 1 '1' -> 2 else -> 3 } sum += when (t[2]) { '0' -> 0 '1' -> 3 else -> 6 } } } } println(sum) } } fun main() { val data = Files.readAllLines(Path.of("./input/Day02.txt")) Day02.part1(data) Day02.part2(data) }
0
Kotlin
0
0
423e7111e2f1b457b0f2b30ffdcf5c00ca95aed9
2,093
advent-of-code-kotlin
Apache License 2.0
src/main/kotlin/io/WordLadderII.kt
jffiorillo
138,075,067
false
{"Kotlin": 434399, "Java": 14529, "Shell": 465}
package io import io.utils.runTests import java.util.* //https://leetcode.com/problems/word-ladder-ii/description/ class WordLadderII { // WIP , not working yet fun execute(beginWord: String, endWord: String, wordList: List<String>): List<List<String>> { val list = arrayListOf<List<String>>() val queue = LinkedList<MutableList<String>>() queue.add(LinkedList(listOf(beginWord))) val visited = mutableSetOf<String>() var minSize: Int? = null while (!queue.isEmpty()) { val currentList = queue.pop() val lastElement = currentList.last() if (!visited.contains(lastElement)) { visited.add(lastElement) val different = different(endWord, lastElement) if (different < 2) { val newPath = LinkedList(currentList).apply { add(endWord) } when { minSize == null -> { list.add(newPath) minSize = newPath.size } newPath.size == minSize -> { list.add(newPath) } } } if (minSize == null || currentList.size < minSize) { val childOf = childOf(lastElement, wordList) queue.addAll(childOf.filter { it != endWord } .filter { !visited.contains(it) } .map { LinkedList(currentList).also { l -> l.add(it) } }) } } } return list } } private fun different(word1: String, word2: String) = word1.zip(word2).fold(word1.length) { acc, pair -> acc - (pair.first == pair.second).toInt() } private fun childOf(word: String, wordList: List<String>) = wordList.filter { different(word, it) < 2 } fun Boolean.toInt() = if (this) 1 else 0 private data class Helper(val startWord: String, val endWord: String, val dictionary: List<String>, val value: List<List<String>>) fun main() { runTests(listOf( Helper("hit", "cog", listOf("hot", "dot", "dog", "lot", "log"), listOf(listOf("hit", "hot", "dot", "dog", "cog"), listOf("hit", "hot", "lot", "log", "cog"))), Helper("a", "b", listOf("a", "b", "c"), listOf(listOf("a", "c"))) )) { (startWord, endWord, dictionary, value) -> value to WordLadderII().execute(startWord, endWord, dictionary) } }
0
Kotlin
0
0
f093c2c19cd76c85fab87605ae4a3ea157325d43
2,209
coding
MIT License
src/main/kotlin/com/groundsfam/advent/y2022/d12/Day12.kt
agrounds
573,140,808
false
{"Kotlin": 281620, "Shell": 742}
package com.groundsfam.advent.y2022.d12 import com.groundsfam.advent.DATAPATH import com.groundsfam.advent.grids.Grid import com.groundsfam.advent.grids.containsPoint import com.groundsfam.advent.points.Point import com.groundsfam.advent.points.down import com.groundsfam.advent.points.left import com.groundsfam.advent.points.right import com.groundsfam.advent.points.up import com.groundsfam.advent.timed import com.groundsfam.advent.grids.toGrid import kotlin.io.path.div import kotlin.io.path.useLines fun Grid<Int>.height(p: Point): Int? = if (this.containsPoint(p)) this[p] else null // Find min distance path from `start` to any given target point via Dikjstra's algorithm class PartOneSolver(private val grid: Grid<Int>, start: Point) { private val toVisit = mutableSetOf(start) private val visited = mutableSetOf<Point>() private val distances = Array(grid.numRows) { IntArray(grid.numCols) { Integer.MAX_VALUE } } .apply { this[start.y][start.x] = 0 } private fun neighbors(point: Point): List<Point> = listOf(point.left, point.right, point.up, point.down) .filter { neighbor -> grid.height(neighbor).let { it != null && it <= grid.height(point)!! + 1 } } private fun currDistance(point: Point): Int = distances[point.y][point.x] fun minDistance(to: Point): Int { while (to !in visited) { val next = toVisit.minByOrNull(::currDistance) ?: throw RuntimeException("Set of points to visit is empty even though graph is not fully explored!") toVisit.remove(next) neighbors(next) .filterNot { it in visited } .forEach { neighbor -> distances[neighbor.y][neighbor.x] = minOf( currDistance(neighbor), currDistance(next) + 1 ) toVisit.add(neighbor) } visited.add(next) } return currDistance(to) } } // Find shortest path from any minimum-height starting point to the `end` point via Dijstra's algorithm. // This solver works backwards, allowing points to be neighbors if the elevation goes up, or goes down by at most 1. class PartTwoSolver(private val grid: Grid<Int>, end: Point) { private val toVisit = mutableSetOf(end) private val visited = mutableSetOf<Point>() private val distances = Array(grid.numRows) { IntArray(grid.numCols) { Integer.MAX_VALUE } } .apply { this[end.y][end.x] = 0 } private fun neighbors(point: Point): List<Point> = listOf(point.left, point.right, point.up, point.down) .filter { neighbor -> grid.height(neighbor).let { it != null && it >= grid.height(point)!! - 1 } } private fun currDistance(point: Point): Int = distances[point.y][point.x] fun minPath(startingHeight: Int): Int? { while (toVisit.isNotEmpty()) { val next = toVisit.minByOrNull(::currDistance)!! if (grid.height(next) == startingHeight) return currDistance(next) toVisit.remove(next) neighbors(next) .filterNot { it in visited } .forEach { neighbor -> distances[neighbor.y][neighbor.x] = minOf( currDistance(neighbor), currDistance(next) + 1 ) toVisit.add(neighbor) } visited.add(next) } return null } } fun main() = timed { var start = Point(0, 0) var end = Point(0, 0) val grid: Grid<Int> = (DATAPATH / "2022/day12.txt").useLines { lines -> lines.mapIndexedTo(mutableListOf()) { y, line -> line.mapIndexed { x, c -> when (c) { 'S' -> { start = Point(x, y) 0 } 'E' -> { end = Point(x, y) 25 } else -> c - 'a' } } } .toGrid() } PartOneSolver(grid, start).minDistance(end) .also { println("Part one: $it") } PartTwoSolver(grid, end).minPath(0) .also { println("Part two: $it") } }
0
Kotlin
0
1
c20e339e887b20ae6c209ab8360f24fb8d38bd2c
4,488
advent-of-code
MIT License
src/day8/Solution.kt
chipnesh
572,700,723
false
{"Kotlin": 48016}
package day8 import Coords import asCoordsSequence import readInput import takeWhileInclusive import toIntMatrix fun main() { fun part1(input: List<String>): Int { val forest = input.toIntMatrix() return forest .asCoordsSequence() .count(forest::isVisible) } fun part2(input: List<String>): Int { val forest = input.toIntMatrix() return forest .asCoordsSequence() .maxOf(forest::getScore) } //val input = readInput("test") val input = readInput("prod") println(part1(input)) println(part2(input)) } private fun List<List<Int>>.isVisible(coords: Coords): Boolean { val (r, c) = coords if (r == 0 || c == 0 || r == lastIndex || c == this[0].lastIndex) { return true } val current = this[r][c] val openFromRight = (r + 1..lastIndex).all { this[it][c] < current } val openFromLeft = (r - 1 downTo 0).all { this[it][c] < current } val openFromBottom = (c + 1..this[0].lastIndex).all { this[r][it] < current } val openFromUp = (c - 1 downTo 0).all { this[r][it] < current } return openFromRight || openFromLeft || openFromBottom || openFromUp } private fun List<List<Int>>.getScore(coords: Coords): Int { val (r, c) = coords val current = this[r][c] val openFromBottom = (r + 1..lastIndex).takeWhileInclusive { this[it][c] < current }.size val openFromUp = (r - 1 downTo 0).takeWhileInclusive { this[it][c] < current }.size val openFromRight = (c + 1..this[0].lastIndex).takeWhileInclusive { this[r][it] < current }.size val openFromLeft = (c - 1 downTo 0).takeWhileInclusive { this[r][it] < current }.size return openFromBottom * openFromUp * openFromRight * openFromLeft }
0
Kotlin
0
1
2d0482102ccc3f0d8ec8e191adffcfe7475874f5
1,760
AoC-2022
Apache License 2.0
src/Day03.kt
valerakostin
574,165,845
false
{"Kotlin": 21086}
fun main() { fun computePriority(c: Char): Int { return if (Character.isUpperCase(c)) c.lowercaseChar().code - 96 + 26 else c.code - 96 } fun part1(input: List<String>): Int { var sum = 0 for (line in input) { val m = line.length / 2 val set = line.subSequence(0, m).toSet() for (i in m..line.length) { if (line[i] in set) { sum += computePriority(line[i]) break } } } return sum } fun part2(input: List<String>): Int { var s = 0 for (chunk in input.chunked(3)) { val set1 = chunk[0].toSet() val set2 = chunk[1].toSet() for (c in chunk[2]) { if (c in set1 && c in set2) { s += computePriority(c) break } } } return s } val testInput = readInput("Day03_test") check(part1(testInput) == 157) val input = readInput("Day03") println(part1(input)) check(part2(testInput) == 70) println(part2(input)) }
0
Kotlin
0
0
e5f13dae0d2fa1aef14dc71c7ba7c898c1d1a5d1
1,196
AdventOfCode-2022
Apache License 2.0
src/Day13.kt
CrazyBene
573,111,401
false
{"Kotlin": 50149}
import kotlin.math.sign fun main() { open class Value data class IntValue(val value: Int) : Value() data class ListValue(val values: List<Value>) : Value() { fun isSmaller(other: ListValue): Int { val toCheck = values.size.coerceAtLeast(other.values.size) for (i in 0 until toCheck) { val left = values.getOrNull(i) val right = other.values.getOrNull(i) if (left == null && right != null) return -1 if (left != null && right == null) return 1 if (left is ListValue && right is ListValue) { val result = left.isSmaller(right) if (result != 0) return result.sign } if (left is IntValue && right is IntValue) { val result = left.value - right.value if (result != 0) return result.sign } if (left is IntValue && right is ListValue) { val newLeft = ListValue(listOf(left)) val result = newLeft.isSmaller(right) if (result != 0) return result.sign } if (left is ListValue && right is IntValue) { val newRight = ListValue(listOf(right)) val result = left.isSmaller(newRight) if (result != 0) return result.sign } } return 0 } } fun String.toValue(): ListValue { val values = mutableListOf<Value>() val chars = toCharArray() var openLists = 0 var subString = "" var digits = "" for (char in chars) { if (char == '[') { openLists++ } if (openLists > 0) { subString += char if (char == ']') { openLists-- } if (openLists == 0) { values.add(subString.substring(1 until subString.length - 1).toValue()) subString = "" } continue } if (char.isDigit()) { digits += char } else if (digits.isNotEmpty()) { values.add(IntValue(digits.toInt())) digits = "" } } if (digits.isNotEmpty()) { values.add(IntValue(digits.toInt())) } return ListValue(values) } fun part1(input: List<String>): Int { val p = input .zipWithNext() .filterIndexed { index, _ -> index % 3 == 0 } .map { (one, two) -> one.substring(1 until one.length - 1).toValue() to two.substring(1 until two.length - 1).toValue() } return p .mapIndexed { index, (one, two) -> if (one.isSmaller(two) < 0) index + 1 else 0 } .sum() } fun part2(input: List<String>): Int { val p = input .filter { it.isNotBlank() } .map { it.substring(1 until it.length - 1).toValue() }.toMutableList() val begin = ListValue(listOf(ListValue(listOf(IntValue(2))))) val end = ListValue(listOf(ListValue(listOf(IntValue(6))))) p.add(begin) p.add(end) val sorted = p.sortedWith { o1, o2 -> o1.isSmaller(o2) } return sorted.mapIndexed { index, listValue -> if (listValue != begin && listValue != end) 0 else index + 1 } .filter { it != 0 } .fold(1) { acc, i -> acc * i } } val testInput = readInput("Day13Test") check(part1(testInput) == 13) check(part2(testInput) == 140) val input = readInput("Day13") println("Question 1 - Answer: ${part1(input)}") println("Question 2 - Answer: ${part2(input)}") }
0
Kotlin
0
0
dfcc5ba09ca3e33b3ec75fe7d6bc3b9d5d0d7d26
4,218
AdventOfCode2022
Apache License 2.0
2021/kotlin/src/main/kotlin/nl/sanderp/aoc/aoc2021/day09/Day09.kt
sanderploegsma
224,286,922
false
{"C#": 233770, "Kotlin": 126791, "F#": 110333, "Go": 70654, "Python": 64250, "Scala": 11381, "Swift": 5153, "Elixir": 2770, "Jinja": 1263, "Ruby": 1171}
package nl.sanderp.aoc.aoc2021.day09 import nl.sanderp.aoc.common.* fun main() { val input = readResource("Day09.txt") .lines() .flatMapIndexed { y, s -> s.mapIndexed { x, c -> Point2D(x, y) to c.asDigit() } } .toMap() val (answer1, duration1) = measureDuration<Int> { partOne(input) } println("Part one: $answer1 (took ${duration1.prettyPrint()})") val (answer2, duration2) = measureDuration<Int> { partTwo(input) } println("Part two: $answer2 (took ${duration2.prettyPrint()})") } private fun findLowPoints(input: Map<Point2D, Int>) = input.filter { it.key.pointsNextTo().mapNotNull { p -> input[p] }.all { h -> h > it.value } } private fun partOne(input: Map<Point2D, Int>): Int = findLowPoints(input).values.sumOf { 1 + it } private fun partTwo(input: Map<Point2D, Int>): Int { val lowPoints = findLowPoints(input).keys val basins = mutableListOf<Set<Point2D>>() for (p in lowPoints) { val basin = mutableSetOf(p) var newPoints = setOf<Point2D>() do { basin.addAll(newPoints) newPoints = basin .flatMap { x -> x.pointsNextTo().filter { input[it] != null && input[it]!! < 9 } } .filterNot { basin.contains(it) } .toSet() } while (newPoints.isNotEmpty()) basins.add(basin) } return basins.map { it.size }.sortedDescending().take(3).fold(1) { a, b -> a * b } }
0
C#
0
6
8e96dff21c23f08dcf665c68e9f3e60db821c1e5
1,453
advent-of-code
MIT License
src/day07/Day07Answer2.kt
IThinkIGottaGo
572,833,474
false
{"Kotlin": 72162}
package day07 import readString /** * Answers from [Advent of Code 2022 Day 7 | Kotlin](https://youtu.be/Q819VW8yxFo) */ val input = readString("day07").split("$ ").drop(1).map { it.trim() } fun main() { var current = VFolder("/", parent = null) val root = current for (i in input.drop(1)) { when (i.substring(0, 2)) { "ls" -> { current.children += i.lines().drop(1).asDirectoryListing(current) } "cd" -> { val path = i.removePrefix("cd ") current = if (path == "..") { current.parent ?: error("illegal move!") } else { current.children.first { it.name == path } as? VFolder ?: error("tried to cd into a file") } } } } println(root.findFolders(100_000).sumOf { it.getFileSize() }) // 1723892 val totalDisk = 70_000_000 val usedSpace = root.getFileSize() val freeSpace = totalDisk - usedSpace val neededSpace = 30_000_000 val freeUpSpace = neededSpace - freeSpace println(root.findFolders(Int.MAX_VALUE).filter { it.getFileSize() > freeUpSpace } .minOf { it.getFileSize() }) // 8474158 } private fun List<String>.asDirectoryListing(parent: VFolder): List<Node> { return map { elem -> if (elem.startsWith("dir")) { VFolder(elem.removePrefix("dir "), parent = parent) } else if (elem.first().isDigit()) { val (size, name) = elem.split(" ") VFile(name, size.toInt(), parent) } else { error("Malformed input") } } } sealed class Node(val name: String, val parent: VFolder?) { abstract fun getFileSize(): Int } class VFolder(name: String, val children: MutableList<Node> = mutableListOf(), parent: VFolder?) : Node(name, parent) { override fun getFileSize(): Int = children.sumOf { it.getFileSize() } fun findFolders(maxSize: Int): List<VFolder> { val children = children.filterIsInstance<VFolder>().flatMap { it.findFolders(maxSize) } return if (getFileSize() <= maxSize) { children + this } else { children } } } class VFile(name: String, val size: Int, parent: VFolder) : Node(name, parent) { override fun getFileSize(): Int = size }
0
Kotlin
0
0
967812138a7ee110a63e1950cae9a799166a6ba8
2,348
advent-of-code-2022
Apache License 2.0
aockt-test/src/test/kotlin/io/github/jadarma/aockt/test/integration/MultipleSolutions.kt
Jadarma
324,646,170
false
{"Kotlin": 38013}
package io.github.jadarma.aockt.test.integration import io.github.jadarma.aockt.core.Solution import io.github.jadarma.aockt.test.AdventDay import io.github.jadarma.aockt.test.AdventSpec /** A solution to a fictitious puzzle used for testing using collections. */ class Y9999D01UsingCollections : Solution { private fun parseInput(input: String): List<Int> = input .splitToSequence(',') .map(String::toInt) .toList() override fun partOne(input: String) = parseInput(input).filter { it % 2 == 1 }.sum() override fun partTwo(input: String) = parseInput(input).reduce { a, b -> a * b } } /** A solution to a fictitious puzzle used for testing using sequences. */ class Y9999D01UsingSequences : Solution { private fun parseInput(input: String): Sequence<Int> = input .splitToSequence(',') .map(String::toInt) override fun partOne(input: String) = parseInput(input).filter { it % 2 == 1 }.sum() override fun partTwo(input: String) = parseInput(input).reduce { a, b -> a * b } } @AdventDay(9999, 1, "Magic Numbers","Using Collections") class Y9999D01CollectionsTest : Y9999D01Spec<Y9999D01UsingCollections>() @AdventDay(9999, 1, "Magic Numbers", "Using Sequences") class Y9999D01SequencesTest : Y9999D01Spec<Y9999D01UsingSequences>() /** * A test for a fictitious puzzle. * * ```text * The input is a string of numbers separated by a comma. * Part 1: Return the sum of the odd numbers. * Part 2: Return the product of the numbers. * ``` */ @Suppress("UnnecessaryAbstractClass") abstract class Y9999D01Spec<T : Solution> : AdventSpec<T>({ partOne { "1,2,3" shouldOutput 4 listOf("0", "2,4,6,8", "2,2,2,2") shouldAllOutput 0 "1,2,5" shouldOutput 6 } partTwo { "1,2,3" shouldOutput 6 } })
0
Kotlin
0
4
1db6da68069a72256c3e2424a0d2729fc59eb0cf
1,850
advent-of-code-kotlin
MIT License
src/day8/Code.kt
fcolasuonno
221,697,249
false
null
package day8 import printWith import java.io.File const val test = false fun main() { val name = if (test) "test.txt" else "input.txt" val dir = ::main::class.java.`package`.name val input = File("src/$dir/$name").readLines() val parsed = parse(input) println("Part 1 = ${part1(parsed)}") println("Part 2 = ${part2(parsed)}") } interface Instruction { fun update(matrix: List<MutableList<Boolean>>) } data class Rect(val x: Int, val y: Int) : Instruction { override fun update(matrix: List<MutableList<Boolean>>) { for (i in 0 until x) { for (j in 0 until y) { matrix[i][j] = true } } } } data class RotateRow(val y: Int, val amount: Int) : Instruction { override fun update(matrix: List<MutableList<Boolean>>) { val row = matrix.map { it[y] } for (i in row.indices) { matrix[(i + amount) % row.size][y] = row[i] } } } data class RotateColumn(val x: Int, val amount: Int) : Instruction { override fun update(matrix: List<MutableList<Boolean>>) { val column = matrix[x].map { it } for (i in column.indices) { matrix[x][(i + amount) % column.size] = column[i] } } } private val rectStructure = """rect (\d+)x(\d+)""".toRegex() private val rotateRowStructure = """rotate row y=(\d+) by (\d+)""".toRegex() private val rotateColumnRowStructure = """rotate column x=(\d+) by (\d+)""".toRegex() fun parse(input: List<String>) = input.map { rectStructure.matchEntire(it)?.destructured?.let { val (x, y) = it.toList() Rect(x.toInt(), y.toInt()) } ?: rotateRowStructure.matchEntire(it)?.destructured?.let { val (y, amount) = it.toList() RotateRow(y.toInt(), amount.toInt()) } ?: rotateColumnRowStructure.matchEntire(it)?.destructured?.let { val (x, amount) = it.toList() RotateColumn(x.toInt(), amount.toInt()) } }.requireNoNulls().let { if (test) List(7) { MutableList(3) { false } } else List(50) { MutableList(6) { false } }.apply { it.forEach { it.update(this) } } } fun part1(matrix: List<MutableList<Boolean>>) = matrix.sumBy { it.count { it } } fun part2(matrix: List<MutableList<Boolean>>): Any? = matrix.printWith { if (it) "#" else " " }
0
Kotlin
0
0
73110eb4b40f474e91e53a1569b9a24455984900
2,309
AOC2016
MIT License
kotlin/src/com/leetcode/304_RangeSumQuery2DImmutable.kt
programmerr47
248,502,040
false
null
package com.leetcode class NumMatrix(matrix: Array<IntArray>) { private val partialSums = Array(matrix.size) { IntArray(matrix[it].size) } init { for (i in matrix.indices) { for (j in matrix[i].indices) { partialSums[i][j] = when { i == 0 && j == 0 -> matrix[i][j] j == 0 -> partialSums[i - 1][j] + matrix[i][j] i == 0 -> partialSums[i][j - 1] + matrix[i][j] else -> partialSums[i - 1][j] + partialSums[i][j - 1] - partialSums[i - 1][j - 1] + matrix[i][j] } } } } fun sumRegion(row1: Int, col1: Int, row2: Int, col2: Int): Int { return partialSums[row2][col2] + (if (row1 == 0) 0 else -partialSums[row1 - 1][col2]) + (if (col1 == 0) 0 else -partialSums[row2][col1 - 1]) + (if (row1 == 0 || col1 == 0) 0 else partialSums[row1 - 1][col1 - 1]) } } fun main() { val numMatrix = NumMatrix(arrayOf( intArrayOf(3, 0, 1, 4, 2), intArrayOf(5, 6, 3, 2, 1), intArrayOf(1, 2, 0, 1, 5), intArrayOf(4, 1, 0, 1, 7), intArrayOf(1, 0, 3, 0, 5) )) println(numMatrix.sumRegion(2, 1, 4, 3)) println(numMatrix.sumRegion(1, 1, 2, 2)) println(numMatrix.sumRegion(1, 2, 2, 4)) }
0
Kotlin
0
0
0b5fbb3143ece02bb60d7c61fea56021fcc0f069
1,348
problemsolving
Apache License 2.0