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/Day10.kt
kmes055
577,555,032
false
{"Kotlin": 35314}
fun main() { fun parseSignals(input: List<String>): Map<Int, Int> { val registers = mutableMapOf<Int, Int>() var cycle = 0 var register = 1 input.forEach { line -> cycle += 1 if (line == "noop") { registers[cycle] = register return@forEach } val amount = line.split(' ')[1].toInt() registers[cycle] = register cycle += 1 registers[cycle] = register register += amount } return registers } fun part1(input: List<String>): Int { val registers = parseSignals(input) return (20..220 step 40).sumOf { c -> val value = registers[c] ?: 0 value * c } } fun part2(input: List<String>): Int { val registers = parseSignals(input) (1 .. 240).map { val pos = ((it - 1) % 40) + 1 val register = registers[it] ?: 0 val c = if (pos in (register .. register + 2)) '#' else '.' println("cur: $it, $pos, $register: $c") c }.windowed(40, 40) .forEach { it.joinToString("").println() } return input.size } val testInput = readInput("Day10_test") part2(testInput) checkEquals(part1(testInput), 13140) val input = readInput("Day10") part1(input).println() checkEquals(part1(input), 14060) part2(input).println() }
0
Kotlin
0
0
84c2107fd70305353d953e9d8ba86a1a3d12fe49
1,480
advent-of-code-kotlin
Apache License 2.0
kotlin/src/test/kotlin/nl/dirkgroot/adventofcode/year2022/Day22Test.kt
dirkgroot
724,049,902
false
{"Kotlin": 203339, "Rust": 123129, "Clojure": 78288}
package nl.dirkgroot.adventofcode.year2022 import io.kotest.core.spec.style.StringSpec import io.kotest.matchers.shouldBe import nl.dirkgroot.adventofcode.util.input import nl.dirkgroot.adventofcode.util.invokedWith private fun solution1(input: String) = parse(input).let { (map, path) -> val height = map.size val width = map[0].size val position = walk(map, path) { pos -> val (dr, dc) = pos.facing.toDelta() Position((pos.r + dr + height) % height, (pos.c + dc + width) % width, pos.facing) } position.password } private fun solution2(mapping: Map<Position, Position>) = { input: String -> parse(input).let { (map, path) -> val position = walk(map, path) { pos -> val (dr, dc) = pos.facing.toDelta() val result = Position(pos.r + dr, pos.c + dc, pos.facing) mapping[result] ?: result } position.password } } private fun parse(input: String) = input.split("\n\n").let { (map, path) -> val mapLines = map.lines() val mapWidth = mapLines.maxOf { it.length } val parsedMap = mapLines .map { line -> CharArray(mapWidth) { x -> line.getOrElse(x) { ' ' } } } .toTypedArray<CharArray>() val parsedPath = "\\d+|[RL]".toRegex().findAll(path) .map { it.value } .map { if (it[0].isDigit()) Instruction.Move(it.toInt()) else Instruction.Turn(it) } parsedMap to parsedPath } private fun walk(map: Array<CharArray>, path: Sequence<Instruction>, next: (Position) -> Position): Position { var position = Position(0, map[0].indexOfFirst { it != ' ' }, Facing.R) path.forEach { instr -> when (instr) { is Instruction.Move -> { position = generateSequence(position) { pos -> next(pos) } .filter { (r, c, _) -> map[r][c] != ' ' } .take(instr.steps + 1) .takeWhile { (r, c, _) -> map[r][c] != '#' } .last() } is Instruction.Turn -> { position = position.copy( facing = when (instr.direction) { "R" -> position.facing.rotateRight() "L" -> position.facing.rotateLeft() else -> throw IllegalStateException() } ) } } } return position } private sealed interface Instruction { data class Move(val steps: Int) : Instruction data class Turn(val direction: String) : Instruction } private enum class Facing(val value: Int) { R(0) { override fun rotateLeft() = U override fun rotateRight() = D }, D(1) { override fun rotateLeft() = R override fun rotateRight() = L }, L(2) { override fun rotateLeft() = D override fun rotateRight() = U }, U(3) { override fun rotateLeft() = L override fun rotateRight() = R }; abstract fun rotateLeft(): Facing abstract fun rotateRight(): Facing fun toDelta() = when (this) { R -> 0 to 1 D -> 1 to 0 L -> 0 to -1 U -> -1 to 0 } } private data class Position(val r: Int, val c: Int, val facing: Facing = Facing.U) { operator fun rangeTo(other: Position): Iterable<Position> { val rRange = if (other.r < r) r downTo other.r else r..other.r val cRange = if (other.c < c) c downTo other.c else c..other.c return rRange.flatMap { row -> cRange.map { col -> Position(row, col, facing) } } } val password get() = (r + 1) * 1000 + (c + 1) * 4 + facing.value } // |00-03|04-07|08-11|12-15| // ------+-----+-----+-----+-----+ // 00-03 | - | - | T | - | // ------+-----+-----+-----+-----+ // 04-07 | B | L | F | - | // ------+-----+-----+-----+-----+ // 08-11 | - | - | D | R | // ------+-----+-----+-----+-----+ private val exampleMapping = generateMapping(-1, -1, 8, 11, Facing.U, 4, 4, 3, 0, Facing.D) + generateMapping(0, 3, 7, 7, Facing.L, 4, 4, 4, 7, Facing.D) + generateMapping(0, 3, 12, 12, Facing.R, 11, 8, 15, 15, Facing.L) + generateMapping(3, 3, 0, 3, Facing.U, 0, 0, 11, 8, Facing.D) + generateMapping(3, 3, 4, 7, Facing.U, 0, 3, 8, 8, Facing.R) + generateMapping(4, 7, -1, -1, Facing.L, 11, 11, 15, 12, Facing.U) + generateMapping(4, 7, 12, 12, Facing.R, 8, 8, 15, 12, Facing.D) + generateMapping(7, 7, 12, 15, Facing.U, 7, 4, 11, 11, Facing.L) + generateMapping(8, 8, 0, 3, Facing.D, 11, 11, 11, 8, Facing.U) + generateMapping(8, 8, 4, 7, Facing.D, 8, 8, 8, 11, Facing.R) + generateMapping(8, 11, 7, 7, Facing.L, 7, 7, 7, 4, Facing.U) + generateMapping(8, 11, 16, 16, Facing.R, 3, 0, 7, 7, Facing.L) + generateMapping(12, 12, 8, 11, Facing.D, 7, 7, 3, 0, Facing.U) + generateMapping(12, 12, 12, 15, Facing.D, 7, 4, 11, 11, Facing.L) // |000-049|050-099|100-149| // ----------+-------+--B-L--+--B-D--+ // 000-049 | - LL| T | R |DR // ----------+-------+-------+-------+ // 050-099 |FL - LT| F |RD - FR| // ----------+-------+-------+-------+ // 100-149 TL| L | D |RR - | // ----------+-------+-------+-------+ // 150-199 TU| B |DD - BR| - | // ----------+--R-U--+-------+-------+ private val inputMapping = /* TT->BL */ generateMapping(-1, -1, 50, 99, Facing.U, 150, 199, 0, 0, Facing.R) + /* RT->BD */ generateMapping(-1, -1, 100, 149, Facing.U, 199, 199, 0, 49, Facing.U) + /* TL->LL */ generateMapping(0, 49, 49, 49, Facing.L, 149, 100, 0, 0, Facing.R) + /* RR->DR */ generateMapping(0, 49, 150, 150, Facing.R, 149, 100, 99, 99, Facing.L) + /* RD->FR */ generateMapping(50, 50, 100, 149, Facing.D, 50, 99, 99, 99, Facing.L) + /* FL->LT */ generateMapping(50, 99, 49, 49, Facing.L, 100, 100, 0, 49, Facing.D) + /* FR->RD */ generateMapping(50, 99, 100, 100, Facing.R, 49, 49, 100, 149, Facing.U) + /* LT->FL */ generateMapping(99, 99, 0, 49, Facing.U, 50, 99, 50, 50, Facing.R) + /* LL->TL */ generateMapping(100, 149, -1, -1, Facing.L, 49, 0, 50, 50, Facing.R) + /* DR->RR */ generateMapping(100, 149, 100, 100, Facing.R, 49, 0, 149, 149, Facing.L) + /* DD->BR */ generateMapping(150, 150, 50, 99, Facing.D, 150, 199, 49, 49, Facing.L) + /* BL->TU */ generateMapping(150, 199, -1, -1, Facing.L, 0, 0, 50, 99, Facing.D) + /* BR->DD */ generateMapping(150, 199, 50, 50, Facing.R, 149, 149, 50, 99, Facing.U) + /* BD->RU */ generateMapping(200, 200, 0, 49, Facing.D, 0, 0, 100, 149, Facing.D) private fun generateMapping( fr1: Int, fr2: Int, fc1: Int, fc2: Int, ff: Facing, tr1: Int, tr2: Int, tc1: Int, tc2: Int, tf: Facing ) = (Position(fr1, fc1, ff)..Position(fr2, fc2) zip Position(tr1, tc1, tf)..Position(tr2, tc2)).toMap() //===============================================================================================\\ private const val YEAR = 2022 private const val DAY = 22 class Day22Test : StringSpec({ "example part 1" { ::solution1 invokedWith exampleInput shouldBe 6032 } "part 1 solution" { ::solution1 invokedWith input(YEAR, DAY) shouldBe 88226 } "example part 2" { solution2(exampleMapping) invokedWith exampleInput shouldBe 5031 } "part 2 solution" { solution2(inputMapping) invokedWith input(YEAR, DAY) shouldBe 57305 } }) private val exampleInput = """ ...# .#.. #... .... ...#.......# ........#... ..#....#.... ..........#. ...#.... .....#.. .#...... ......#. 10R5L5R10L4R5L5 """.trimIndent()
1
Kotlin
0
0
ced913cd74378a856813973a45dd10fdd3570011
7,814
adventofcode
MIT License
src/day03/Day03.kt
andreas-eberle
573,039,929
false
{"Kotlin": 90908}
package day03 import readInput fun main() { fun calculatePart1Score(input: List<String>): Int { return input.asSequence() .map { it.substring(0, it.length / 2) to it.substring(it.length / 2) } .map { it.first.toCharArray().toSet() to it.second.toCharArray().toSet() } .map { it.first.intersect(it.second) } .map { it.first() } .map { it.toPriority() } .sum() } fun calculatePart2Score(input: List<String>): Int { return input.asSequence() .map { it.toCharArray().toSet() } .withIndex() .groupBy({ it.index / 3 }) { it.value } .values.asSequence() .map { it[0] intersect it[1] intersect it[2] } .map { it.first() } .map { it.toPriority() } .sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("/day03/Day03_test") val input = readInput("/day03/Day03") val part1TestPoints = calculatePart1Score(testInput) val part1Points = calculatePart1Score(input) println("Part1 test points: $part1TestPoints") println("Part1 points: $part1Points") check(part1TestPoints == 157) val part2TestPoints = calculatePart2Score(testInput) val part2Points = calculatePart2Score(input) println("Part2 test points: $part2TestPoints") println("Part2 points: $part2Points") check(part2TestPoints == 70) } fun Char.toPriority(): Int = when (this) { in 'a'..'z' -> this - 'a' + 1 in 'A'..'Z' -> this - 'A' + 27 else -> error("Invalid char: $this") }
0
Kotlin
0
0
e42802d7721ad25d60c4f73d438b5b0d0176f120
1,649
advent-of-code-22-kotlin
Apache License 2.0
src/Day10.kt
mcdimus
572,064,601
false
{"Kotlin": 32343}
import util.readInput fun main() { fun part1(input: List<String>): Int { var registerValue = 1 return input.joinToString(separator = " ") .split(" ") .mapIndexed { index, s -> (index + 1 to registerValue).also { if (s != "noop" && s != "addx") { registerValue += s.toInt() } } }.sumOf { (cycle, registerValue) -> if ((cycle - 20) % 40 == 0) cycle * registerValue else 0 } } fun part2(input: List<String>): Int { var registerValue = 1 var currentSpritePosition = 1 val grid = input.joinToString(separator = " ") .split(" ") .mapIndexed { index, s -> var value = ' ' if (index % 40 in (currentSpritePosition - 1)..(currentSpritePosition + 1)) { value = '#' } if (s != "noop" && s != "addx") { registerValue += s.toInt() currentSpritePosition = registerValue } value } grid.forEachIndexed { index, c -> print(c) if ((index + 1) % 40 == 0) println() } return grid.count { it == '#' } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day10_test") check(part1(testInput) == 13140) check(part2(testInput) == 124) val input = readInput("Day10") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
dfa9cfda6626b0ee65014db73a388748b2319ed1
1,593
aoc-2022
Apache License 2.0
src/main/kotlin/com/dvdmunckhof/aoc/event2022/Day19.kt
dvdmunckhof
318,829,531
false
{"Kotlin": 195848, "PowerShell": 1266}
package com.dvdmunckhof.aoc.event2022 import kotlin.math.max class Day19(input: List<String>) { private val blueprints = input.map { line -> val numberRegex = Regex("-?\\d+") val numbers = numberRegex.findAll(line).map { it.groupValues.first().toInt() }.toList() Blueprint( numbers[0], listOf( Product(ProductType.GEODE, Inventory(geode = 1), Inventory(ore = numbers[5], obsidian = numbers[6])), Product(ProductType.OBSIDIAN, Inventory(obsidian = 1), Inventory(ore = numbers[3], clay = numbers[4])), Product(ProductType.CLAY, Inventory(clay = 1), Inventory(ore = numbers[2])), Product(ProductType.ORE, Inventory(ore = 1), Inventory(ore = numbers[1])), ), ) } fun solvePart1(): Int { return blueprints.fold(0) { acc, blueprint -> acc + blueprint.index * blueprint.calculateBestResult(24) } } fun solvePart2(): Int { return blueprints.take(3).fold(1) { acc, blueprint -> acc * blueprint.calculateBestResult(32) } } private data class Blueprint( val index: Int, val products: List<Product>, ) { fun calculateBestResult(time: Int): Int { val initialState = State(Inventory(ore = 1), Inventory()) val simulator = Simulator(this) simulator.simulate(initialState, initialState, time) return simulator.bestResult } } private data class State( val robots: Inventory, val materials: Inventory, ) { operator fun plus(product: Product): State { return State(this.robots + product.output, this.materials - product.materials) } fun canAfford(product: Product): Boolean { return this.materials.ore >= product.materials.ore && this.materials.clay >= product.materials.clay && this.materials.obsidian >= product.materials.obsidian && this.materials.geode >= product.materials.geode } } private data class Product( val type: ProductType, val output: Inventory, val materials: Inventory, ) private data class Inventory( val ore: Int = 0, val clay: Int = 0, val obsidian: Int = 0, val geode: Int = 0, ) { operator fun plus(other: Inventory) = Inventory( this.ore + other.ore, this.clay + other.clay, this.obsidian + other.obsidian, this.geode + other.geode, ) operator fun minus(other: Inventory) = Inventory( this.ore - other.ore, this.clay - other.clay, this.obsidian - other.obsidian, this.geode - other.geode, ) operator fun get(type: ProductType) = when(type) { ProductType.ORE -> this.ore ProductType.CLAY -> this.clay ProductType.OBSIDIAN -> this.obsidian ProductType.GEODE -> this.geode } } private class Simulator(val blueprint: Blueprint) { private val maxMaterials = ProductType.values() .map { type -> blueprint.products.maxOf { it.materials[type] } } var bestResult = 0 private set fun simulate(previousState: State, state: State, timeRemaining: Int) { if (timeRemaining == 0) { this.bestResult = max(this.bestResult, state.materials.geode) return } if (this.bestResult >= bestPossibleResult(state, timeRemaining)) { return } val nextState = state.copy(materials = state.materials + state.robots) for (product in blueprint.products) { if (!state.canAfford(product) || hasMaxRobots(product.type, state)) { continue } if (previousState.canAfford(product) && state.robots == previousState.robots) { continue } simulate(state, nextState + product, timeRemaining - 1) if (product.type == ProductType.GEODE) { return } } simulate(state, nextState, timeRemaining - 1) } private fun hasMaxRobots(type: ProductType, state: State): Boolean { return type != ProductType.GEODE && this.maxMaterials[type] <= state.robots[type] } private fun bestPossibleResult(state: State, timeRemaining: Int): Int { val averageRobots = state.robots.geode + 1 + ((timeRemaining - 1) / 2.0) val geodes = state.materials.geode + averageRobots * timeRemaining return geodes.toInt() } private operator fun <T> List<T>.get(type: ProductType) = this[type.ordinal] } private enum class ProductType { ORE, CLAY, OBSIDIAN, GEODE, } }
0
Kotlin
0
0
025090211886c8520faa44b33460015b96578159
4,995
advent-of-code
Apache License 2.0
src/Day03.kt
Qdelix
574,590,362
false
null
fun main() { fun part1(input: List<String>): Int { var string = "" input.forEach { line -> val firstCompartment = line.substring(0, line.length / 2) val secondCompartment = line.substring(line.length / 2, line.length) string += firstCompartment.first { letter -> secondCompartment.any { secondLetter -> letter == secondLetter } } } var sum = 0 ('a'..'z').forEachIndexed { index, c -> sum += string.count { it == c } * (index + 1) } ('A'..'Z').forEachIndexed { index, c -> sum += string.count { it == c } * (index + 27) } return sum } fun part2(input: List<String>): Int { var string = "" input.windowed(3, 3).forEach { window -> val mappedWindow = window.map { it.toList().distinct() } string += mappedWindow.first().first { letter -> mappedWindow[1].any { l -> l == letter } && mappedWindow[2].any { l -> l == letter } } } var sum = 0 ('a'..'z').forEachIndexed { index, c -> sum += string.count { it == c } * (index + 1) } ('A'..'Z').forEachIndexed { index, c -> sum += string.count { it == c } * (index + 27) } return sum } val input = readInput("Day03") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
8e5c599d5071d9363c8f33b800b008875eb0b5f5
1,445
aoc22
Apache License 2.0
aoc-2023/src/main/kotlin/aoc/aoc11.kts
triathematician
576,590,518
false
{"Kotlin": 615974}
import aoc.AocParser.Companion.parselines import aoc.* import aoc.util.* import java.lang.Math.abs val testInput = """ ...#...... .......#.. #......... .......... ......#... .#........ .........# .......... .......#.. #...#..... """.parselines class Universe(lines: List<String>) { val colsToExpand = lines[0].indices.filter { i -> lines.all { it[i] == '.' } } val rowsToExpand = lines.indices.filter { i -> lines[i].all { it == '.' } } val grid = lines.let { lines -> val colsToExpand = lines[0].indices.filter { i -> lines.all { it[i] == '.' } } lines.flatMap { val expanded = it.expand(colsToExpand) if ("#" in it) { listOf(expanded) } else { listOf(expanded, expanded) } } } val galaxies = grid.findCoords2 { it == '#' }.flatMap { it.value } val oGrid = lines val oGalaxies = oGrid.findCoords2 { it == '#' }.flatMap { it.value } init { println("-".repeat(40)) oGrid.forEach { println(it) } println("-".repeat(40)) grid.forEach { println(it) } println("-".repeat(40)) } fun String.expand(cols: List<Int>) = substring(0, cols.first()) + cols.mapIndexed { i, col -> ".." + substring(col + 1, cols.getOrNull(i + 1) ?: length) }.joinToString("") fun countShortestPaths(): Int { var sum = 0 galaxies.indices.forEach { g1 -> val gal1 = galaxies[g1] galaxies.indices.forEach { g2 -> val gal2 = galaxies[g2] if (g2 > g1) { sum += abs(gal1.x - gal2.x) + abs(gal1.y - gal2.y) } } } return sum } fun countShortestPaths2(expandNum: Int): Long { var sum = 0L oGalaxies.indices.forEach { g1 -> val gal1 = oGalaxies[g1] oGalaxies.indices.forEach { g2 -> if (g2 > g1) { val gal2 = oGalaxies[g2] val minx = minOf(gal1.x, gal2.x) val maxx = maxOf(gal1.x, gal2.x) sum += maxx - minx sum += (minx+1..maxx-1).count { it in colsToExpand } * (expandNum - 1) val miny = minOf(gal1.y, gal2.y) val maxy = maxOf(gal1.y, gal2.y) sum += maxy - miny sum += (miny+1..maxy-1).count { it in rowsToExpand } * (expandNum - 1) } } } return sum } } // part 1 fun List<String>.part1() = Universe(this).countShortestPaths() // part 2 fun List<String>.part2() = Universe(this).countShortestPaths2( if (size < 20) 100 else 1000000 ) // calculate answers val day = 11 val input = getDayInput(day, 2023) val testResult = testInput.part1() val testResult2 = testInput.part2() val answer1 = input.part1().also { it.print } val answer2 = input.part2().also { it.print } // print results AocRunner(day, test = { "$testResult, $testResult2" }, part1 = { answer1 }, part2 = { answer2 } ).run()
0
Kotlin
0
0
7b1b1542c4bdcd4329289c06763ce50db7a75a2d
3,169
advent-of-code
Apache License 2.0
src/Day02.kt
sebastian-heeschen
572,932,813
false
{"Kotlin": 17461}
fun main() { fun draws(input: List<String>) = input.flatMap { line -> line.split(" ") .map { it.first() } .zipWithNext() } fun resultCalculation( input: List<String>, drawsByStrategicGuide: (Pair<Char, Char>) -> Pair<Shape, Shape> ) = draws(input) .map(drawsByStrategicGuide) .fold(0) { points, (opponent, own) -> val result = own.result(opponent) points + result + own.points } fun part1(input: List<String>): Int = resultCalculation(input) { (opponent, own) -> Shape.from(opponent) to Shape.from(own) } fun part2(input: List<String>): Int = resultCalculation(input) { (opponentDraw, result) -> val opponent = Shape.from(opponentDraw) val own = when (result) { 'X' -> opponent.superior() 'Y' -> opponent 'Z' -> opponent.inferior() else -> error("not applicable") } opponent to own } // test if implementation meets criteria from the description, like: val testInput = readInput("Day02_test") check(part1(testInput) == 15) check(part2(testInput) == 12) val input = readInput("Day02") println(part1(input)) println(part2(input)) } enum class Shape(val points: Int) { Rock(1), Paper(2), Scissor(3); fun superior(): Shape = when (this) { Rock -> Scissor Paper -> Rock Scissor -> Paper } fun inferior(): Shape = when (this) { Rock -> Paper Paper -> Scissor Scissor -> Rock } fun result(other: Shape) = when { this.superior() == other -> 6 other.superior() == this -> 0 other == this -> 3 else -> error("not possible") } companion object { fun from(letter: Char) = when (letter) { 'A', 'X' -> Rock 'B', 'Y' -> Paper 'C', 'Z' -> Scissor else -> error("not applicable") } } }
0
Kotlin
0
0
4432581c8d9c27852ac217921896d19781f98947
2,006
advent-of-code-2022
Apache License 2.0
src/Day02.kt
trosendo
572,903,458
false
{"Kotlin": 26100}
private enum class RockPaperScissor( val points: Int, val winsOver: Char, val loosesOver: Char, val drawsOver: Char, ) { ROCK(1, 'C', 'B', 'A'), PAPER(2, 'A', 'C', 'B'), SCISSOR(3, 'B', 'A', 'C') } private enum class RockPaperScissorOutcome( val points: Int ) { WIN(6), DRAW(3), LOST(0) } fun main() { fun Char.translateToRockPaperScissor() = when(this) { 'A' -> RockPaperScissor.ROCK 'B' -> RockPaperScissor.PAPER else -> RockPaperScissor.SCISSOR } fun Char.translateToRockPaperScissorOutcome() = when(this) { 'X' -> RockPaperScissorOutcome.LOST 'Y' -> RockPaperScissorOutcome.DRAW else -> RockPaperScissorOutcome.WIN } fun RockPaperScissor.playAgainst(opponentMove: RockPaperScissor) = this.points + when(opponentMove) { this.drawsOver.translateToRockPaperScissor() -> RockPaperScissorOutcome.DRAW.points this.winsOver.translateToRockPaperScissor() -> RockPaperScissorOutcome.WIN.points this.loosesOver.translateToRockPaperScissor() -> RockPaperScissorOutcome.LOST.points else -> 0 } fun RockPaperScissor.getShapeForOutcome(outcome: RockPaperScissorOutcome) = when(outcome) { RockPaperScissorOutcome.WIN -> this.loosesOver.translateToRockPaperScissor() RockPaperScissorOutcome.DRAW -> this.drawsOver.translateToRockPaperScissor() RockPaperScissorOutcome.LOST -> this.winsOver.translateToRockPaperScissor() } fun part1(input: List<String>): Int { val (_, myResult) = input.map { val play = it.split(" ") play[0][0].translateToRockPaperScissor() to Char(play[1][0].code - 23).translateToRockPaperScissor() }.fold(0 to 0) { (opponentResult, myResult), (opponentMove, myMove) -> opponentResult + opponentMove.playAgainst(myMove) to myResult + myMove.playAgainst(opponentMove) } return myResult } fun part2(input: List<String>): Int { val (_, myResult) = input.map { val play = it.split(" ") play[0][0].translateToRockPaperScissor() to play[1][0].translateToRockPaperScissorOutcome() }.fold(0 to 0) { (opponentResult, myResult), (opponentMove, outcome) -> val myMove = opponentMove.getShapeForOutcome(outcome) opponentResult + opponentMove.playAgainst(myMove) to myResult + myMove.playAgainst(opponentMove) } return myResult } // test if implementation meets criteria from the description, like: val testInput = readInputAsList("Day02_test") check(part1(testInput) == 15) check(part2(testInput) == 12) val input = readInputAsList("Day02") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
ea66a6f6179dc131a73f884c10acf3eef8e66a43
2,910
AoC-2022
Apache License 2.0
src/main/kotlin/ru/timakden/aoc/year2022/Day09.kt
timakden
76,895,831
false
{"Kotlin": 321649}
package ru.timakden.aoc.year2022 import ru.timakden.aoc.util.Point import ru.timakden.aoc.util.measure import ru.timakden.aoc.util.readInput import ru.timakden.aoc.year2022.Day09.Direction.* import ru.timakden.aoc.year2022.Day09.Direction.Companion.toDirection import kotlin.math.absoluteValue /** * [Day 9: Rope Bridge](https://adventofcode.com/2022/day/9). */ object Day09 { @JvmStatic fun main(args: Array<String>) { measure { val input = readInput("year2022/Day09") println("Part One: ${part1(input)}") println("Part Two: ${part2(input)}") } } fun part1(input: List<String>) = performMotions(MutableList(2) { Point(0, 0) }, input) fun part2(input: List<String>) = performMotions(MutableList(10) { Point(0, 0) }, input) private fun performMotions(rope: MutableList<Point>, input: List<String>): Int { val visitedPositions = mutableSetOf<Point>().apply { add(Point(0, 0)) } input.forEach { instruction -> val (direction, steps) = instruction.split(' ').let { it.first().toDirection() to it.last().toInt() } repeat(steps) { rope[0] = moveHead(direction, rope.first()) (1..rope.lastIndex).forEach { i -> if (needMoveTail(rope[i], rope[i - 1])) { rope[i] = moveTail(rope[i], rope[i - 1]) if (i == rope.lastIndex) visitedPositions += rope[i] } } } } return visitedPositions.count() } private fun moveHead(direction: Direction, position: Point) = when (direction) { DOWN -> Point(position.x, position.y - 1) LEFT -> Point(position.x - 1, position.y) RIGHT -> Point(position.x + 1, position.y) UP -> Point(position.x, position.y + 1) } private fun needMoveTail(tail: Point, head: Point) = (tail.x - head.x).absoluteValue > 1 || (tail.y - head.y).absoluteValue > 1 private fun moveTail(tail: Point, head: Point): Point { val x = when { tail.x == head.x -> tail.x tail.x < head.x -> tail.x + 1 else -> tail.x - 1 } val y = when { tail.y == head.y -> tail.y tail.y < head.y -> tail.y + 1 else -> tail.y - 1 } return Point(x, y) } private enum class Direction { DOWN, LEFT, RIGHT, UP; companion object { fun String.toDirection() = when (this) { "D" -> DOWN "L" -> LEFT "R" -> RIGHT "U" -> UP else -> error("Unsupported direction") } } } }
0
Kotlin
0
3
acc4dceb69350c04f6ae42fc50315745f728cce1
2,741
advent-of-code
MIT License
src/main/kotlin/year2022/day-15.kt
ppichler94
653,105,004
false
{"Kotlin": 182859}
package year2022 import lib.aoc.Day import lib.aoc.Part import lib.math.Vector import kotlin.math.abs import kotlin.math.max fun main() { Day(15, 2022, PartA15(), PartB15()).run() } open class PartA15 : Part() { data class Sensor(val position: Vector, val closestBeacon: Vector) { private val beaconRadius = abs(position.x - closestBeacon.x) + abs(position.y - closestBeacon.y) fun coverageAtLevel(yLevel: Int): Pair<Int, Int>? { val coverage = beaconRadius - abs(position.y - yLevel) if (coverage > 0) { return Pair(position.x - coverage, position.x + coverage) } return null } companion object { fun ofText(text: String): Sensor { val matcher = """Sensor at x=(.*), y=(.*): closest beacon is at x=(.*), y=(.*)""".toRegex().matchEntire(text) val (sensorX, sensorY, beaconX, beaconY) = matcher!!.destructured return Sensor(Vector.at(sensorX.toInt(), sensorY.toInt()), Vector.at(beaconX.toInt(), beaconY.toInt())) } } } internal lateinit var sensors: List<Sensor> internal var isExample: Boolean = false override fun parse(text: String) { sensors = text.split("\n").map(Sensor::ofText) isExample = sensors.size <= 14 } override fun compute(): String { val yLevel = if (isExample) 20 else 2_000_000 val coverages = sensors.mapNotNull { it.coverageAtLevel(yLevel) } return countCoveredPositions(coverages).toString() } private fun countCoveredPositions(coverages: List<Pair<Int, Int>>): Int { val covered = mutableSetOf<Int>() coverages.forEach { (start, end) -> covered.addAll(start until end) } return covered.size } override val exampleAnswer: String get() = "26" } class PartB15 : PartA15() { override fun compute(): String { val maxPosition = if (isExample) 20 else 4_000_000 (0 until maxPosition).forEach { yLevel -> val coverages = sensors.mapNotNull { it.coverageAtLevel(yLevel) } val mergedCoverages = mergeCoverages(coverages) mergedCoverages.forEach { (start, end) -> if (start > 0) { return (yLevel.toBigInteger() + (start - 1).toBigInteger() * 4_000_000.toBigInteger()).toString() } if (end < maxPosition) { return (yLevel.toBigInteger() + (end + 1).toBigInteger() * 4_000_000.toBigInteger()).toString() } } } return "no solution found" } private fun mergeCoverages(coverages: List<Pair<Int, Int>>): List<Pair<Int, Int>> { if (coverages.size <= 1) { return coverages } val sortedCoverages = coverages.sortedBy { it.first } val result = mutableListOf(sortedCoverages.first()) sortedCoverages.drop(1).forEach { if (it.first <= result.last().second) { result[result.size - 1] = Pair(result.last().first, max(result.last().second, it.second)) } else { result.add(it) } } return result.toList() } override val exampleAnswer: String get() = "56000011" }
0
Kotlin
0
0
49dc6eb7aa2a68c45c716587427353567d7ea313
3,432
Advent-Of-Code-Kotlin
MIT License
src/Day04.kt
schoi80
726,076,340
false
{"Kotlin": 83778}
import kotlin.math.pow fun main() { val input = readInput("Day04") fun String.splitNumbers(): Pair<Set<String>, Set<String>> { return split(":")[1].split("|").map { it.trim().split("\\s+".toRegex()).toSet() }.let { it[0] to it[1] } } fun String.matchCount(): Int { val (winningNumbers, myNumbers) = splitNumbers() return myNumbers.count { winningNumbers.contains(it) } } fun String.score(): Int { return matchCount().let { if (it >= 1) 2.0.pow(it - 1).toInt() else 0 } } fun part1(input: List<String>): Int { return input.sumOf { it.score() } } fun part2(input: List<String>): Int { val copies = mutableMapOf<Int, Int>() input.forEachIndexed { i, line -> copies[i] = copies[i] ?: 1 val count = line.matchCount() if (count > 0) { (1..count).forEach { val gameCard = it + i copies[gameCard] = copies[i]!! + (copies[gameCard] ?: 1) } } } return copies.values.sum() } input[0].splitNumbers().println() part1(input).println() part2(input).println() }
0
Kotlin
0
0
ee9fb20d0ed2471496185b6f5f2ee665803b7393
1,316
aoc-2023
Apache License 2.0
src/Day09.kt
roxanapirlea
572,665,040
false
{"Kotlin": 27613}
import kotlin.math.abs private data class Point(val x: Int, val y: Int) private data class Move(val steps: Int, val dir: String) private data class Rope(val h: Point, val t: Point) fun main() { fun getMoves(input: List<String>) = input.map { line -> val (d, s) = line.split(" ") Move(s.toInt(), d) } fun Point.move(dir: String): Point = when (dir) { "R" -> copy(x = x + 1) "L" -> copy(x = x - 1) "U" -> copy(y = y + 1) "D" -> copy(y = y - 1) else -> throw IllegalArgumentException() } fun Point.moveAfter(head: Point): Point { val newTail = if (abs(head.x - x) <= 1 && abs(head.y - y) <= 1) this else if (head.x - x == 0) { if (head.y - y == 2) copy(y = y + 1) else copy(y = y - 1) } else if (head.y - y == 0) { if (head.x - x == 2) copy(x = x + 1) else copy(x = x - 1) } else { if (head.x - x > 0 && head.y - y > 0) copy(x = x + 1, y = y + 1) else if (head.x - x < 0 && head.y - y < 0) copy(x = x - 1, y = y - 1) else if (head.x - x > 0 && head.y - y < 0) copy(x = x + 1, y = y - 1) else copy(x = x - 1, y = y + 1) } return newTail } fun move(rope: Rope, dir: String): Rope { val newHead = rope.h.move(dir) val newTail = rope.t.moveAfter(newHead) return Rope(newHead, newTail) } fun part1(input: List<String>): Int { val coveredPos = mutableSetOf<Point>() var rope = Rope(Point(0, 0), Point(0, 0)) coveredPos.add(rope.t) getMoves(input).forEach { move -> repeat(move.steps) { rope = move(rope, move.dir) coveredPos.add(rope.t) } } return coveredPos.size } fun part2(input: List<String>): Int { val coveredPos = mutableSetOf<Point>() val bigRope = MutableList(10) { Point(0, 0) } coveredPos.add(bigRope.last()) getMoves(input).forEach { move -> repeat(move.steps) { bigRope[0] = bigRope[0].move(move.dir) for (i in 1 until bigRope.size) { bigRope[i] = bigRope[i].moveAfter(bigRope[i-1]) } coveredPos.add(bigRope.last()) } } return coveredPos.size } // test if implementation meets criteria from the description, like: val testInput = readInput("Day09_test") check(part1(testInput) == 13) check(part2(testInput) == 1) val testInput2 = readInput("Day09_test2") check(part2(testInput2) == 36) val input = readInput("Day09") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
6c4ae6a70678ca361404edabd1e7d1ed11accf32
2,904
aoc-2022
Apache License 2.0
src/day24/result.kt
davidcurrie
437,645,413
false
{"Kotlin": 37294}
import java.io.File fun main() { val programs = File("src/day24/input.txt").readText().split("inp w\n").drop(1) .map { it.split("\n").dropLast(1).map { it.split(" ") } } val variables = programs.map { Variables(it[3][2].toInt(), it[4][2].toInt(), it[14][2].toInt()) } val solutions = solve(variables) println(solutions.maxOf { it }) println(solutions.minOf { it }) } data class Variables(val zDiv: Int, val xAdd: Int, val yAdd: Int) { fun execute(input: Int, zReg: Int): Int { val x = if (((zReg % 26) + xAdd) != input) 1 else 0 return ((zReg / zDiv) * ((25 * x) + 1)) + ((input + yAdd) * x) } } fun solve(variablesList: List<Variables>): List<String> { var validZOutputs = setOf(0) val validZsByIndex = variablesList.reversed().map { variables -> (1..9).associateWith { input -> (0..10000000).filter { z -> variables.execute(input, z) in validZOutputs }.toSet() }.also { validZs -> validZOutputs = validZs.values.flatten().toSet() } }.reversed() fun findModelNumbers(index: Int, z: Int): List<String> { val inputs = validZsByIndex[index].entries.filter { z in it.value }.map { it.key } return if (index == 13) inputs.map { it.toString() } else inputs.flatMap { input -> val nextZ = variablesList[index].execute(input, z) findModelNumbers(index + 1, nextZ).map { input.toString() + it } } } return findModelNumbers(0, 0) }
0
Kotlin
0
0
dd37372420dc4b80066efd7250dd3711bc677f4c
1,500
advent-of-code-2021
MIT License
src/main/kotlin/g1601_1700/s1632_rank_transform_of_a_matrix/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g1601_1700.s1632_rank_transform_of_a_matrix // #Hard #Array #Greedy #Matrix #Graph #Union_Find #Topological_Sort // #2023_06_17_Time_807_ms_(100.00%)_Space_96.5_MB_(100.00%) import java.util.Arrays class Solution { fun matrixRankTransform(matrix: Array<IntArray>): Array<IntArray> { val rowCount = matrix.size val colCount = matrix[0].size val nums = LongArray(rowCount * colCount) var numsIdx = 0 val rows = IntArray(rowCount) val cols = IntArray(colCount) for (r in rowCount - 1 downTo 0) { for (c in colCount - 1 downTo 0) { nums[numsIdx++] = matrix[r][c].toLong() shl 32 or (r.toLong() shl 16) or c.toLong() } } nums.sort() var nIdx = 0 while (nIdx < numsIdx) { val num = nums[nIdx] and -0x100000000L var endIdx = nIdx + 1 while (endIdx < numsIdx && nums[endIdx] and -0x100000000L == num) { endIdx++ } doGroup(matrix, nums, nIdx, endIdx, rows, cols) nIdx = endIdx } return matrix } private fun doGroup( matrix: Array<IntArray>, nums: LongArray, startIdx: Int, endIdx: Int, rows: IntArray, cols: IntArray ) { if (startIdx + 1 == endIdx) { val r = nums[startIdx].toInt() shr 16 and 0xFFFF val c = nums[startIdx].toInt() and 0xFFFF cols[c] = rows[r].coerceAtLeast(cols[c]) + 1 rows[r] = cols[c] matrix[r][c] = rows[r] } else { val rowCount = matrix.size val ufind = IntArray(rowCount + matrix[0].size) Arrays.fill(ufind, -1) for (nIdx in startIdx until endIdx) { val r = nums[nIdx].toInt() shr 16 and 0xFFFF val c = nums[nIdx].toInt() and 0xFFFF val pr = getIdx(ufind, r) val pc = getIdx(ufind, rowCount + c) if (pr != pc) { ufind[pr] = ufind[pr].coerceAtMost(ufind[pc]) .coerceAtMost( -rows[r] .coerceAtLeast(cols[c]) - 1 ) ufind[pc] = pr } } for (nIdx in startIdx until endIdx) { val r = nums[nIdx].toInt() shr 16 and 0xFFFF val c = nums[nIdx].toInt() and 0xFFFF cols[c] = -ufind[getIdx(ufind, r)] rows[r] = cols[c] matrix[r][c] = rows[r] } } } private fun getIdx(ufind: IntArray, idx: Int): Int { return if (ufind[idx] < 0) { idx } else { ufind[idx] = getIdx(ufind, ufind[idx]) ufind[idx] } } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
2,872
LeetCode-in-Kotlin
MIT License
solutions/aockt/y2023/Y2023D06.kt
Jadarma
624,153,848
false
{"Kotlin": 435090}
package aockt.y2023 import aockt.util.parse import io.github.jadarma.aockt.core.Solution object Y2023D06 : Solution { /** A race record, detailing the [time] it took and the total [distance] travelled. */ private data class RaceRecord(val time: Long, val distance: Long) /** * A race simulation result. * @property time The total time spent on the race. * @property waitTime How much time was spent holding the boat's button. * @property distance The total distance traveled by the boat in the [time] frame. */ private data class RaceResult(val time: Long, val waitTime: Long, val distance: Long) /** Simulate all possible race outcomes that would beat this record, depending on how much to hold the button. */ private fun RaceRecord.simulateBetterStrategies(): Sequence<RaceResult> = sequence { for (waitTime in 0..time) { val raceTime = time - waitTime val raceDistance = raceTime * waitTime if (raceDistance > distance) yield(RaceResult(time, waitTime, raceDistance)) } } /** * Parses the [input], returning the list containing boat race records, depending on how you squint. * @param input The puzzle input. * @param noticeKerning Whether to treat the input as one big number or not. */ private fun parseInput(input: String, noticeKerning: Boolean): List<RaceRecord> = parse { fun String.parseMany() = split(' ').map(String::trim).filter(String::isNotBlank).map(String::toLong) fun String.parseOne() = split(' ').joinToString(separator = "", transform = String::trim).toLong().let(::listOf) val parser = if (noticeKerning) String::parseOne else String::parseMany val (timeLine, distanceLine) = input.split('\n', limit = 2) val times = timeLine.substringAfter("Time:").run(parser) val distances = distanceLine.substringAfter("Distance:").run(parser) require(times.size == distances.size) { "Some records are incomplete." } times.zip(distances, ::RaceRecord) } /** Given some records, finds in how many ways can each of it be beaten, and returns the product of those values.*/ private fun List<RaceRecord>.solve() = map { it.simulateBetterStrategies().count() }.fold(1L, Long::times) override fun partOne(input: String) = parseInput(input, noticeKerning = false).solve() override fun partTwo(input: String) = parseInput(input, noticeKerning = true).solve() }
0
Kotlin
0
3
19773317d665dcb29c84e44fa1b35a6f6122a5fa
2,489
advent-of-code-kotlin-solutions
The Unlicense
src/Day05.kt
jpereyrol
573,074,843
false
{"Kotlin": 9016}
import java.util.* fun main() { fun part1(input: List<String>): Int { val (moves, stacks) = input.filterNot { it == "" }.partition { it.contains("move") } // stacks val numStacks = stacks.last().last().toString().toInt() val stackValues = stacks.dropLast(1).reversed() val currentStacks = readListByColumn(stackValues, numStacks) //moves val regex = Regex("(\\d+)") val updatedMoves = moves.map { move -> regex.findAll(move).map { it.value.toInt() }.toList() } //operation updatedMoves.forEach { (move, from, to) -> for (i in 0 until move) { currentStacks[to - 1].push(currentStacks[from - 1].pop()) } } currentStacks.forEach { println(it) } val topValues = currentStacks.map { it.peek() }.joinToString(separator = "") println(topValues) return input.size } fun part2(input: List<String>): Int { val (moves, stacks) = input.filterNot { it == "" }.partition { it.contains("move") } // stacks val numStacks = stacks.last().last().toString().toInt() val stackValues = stacks.dropLast(1).reversed() val currentStacks = readListByColumn(stackValues, numStacks) //moves val regex = Regex("(\\d+)") val updatedMoves = moves.map { move -> regex.findAll(move).map { it.value.toInt() }.toList() } //operation updatedMoves.forEach { (move, from, to) -> currentStacks[to - 1].addAll(currentStacks[from - 1].takeLast(move)) for (i in 0 until move) { currentStacks[from - 1].pop() } } currentStacks.forEach { println(it) } val topValues = currentStacks.map { it.peek() }.joinToString(separator = "") println(topValues) return input.size } val input = readInput("Day05") println(part1(input)) println(part2(input)) } fun readListByColumn(list: List<String>, numStacks: Int): MutableList<Stack<Char?>> { val stacks = MutableList(numStacks) { Stack<Char?>() } val maxLength = list.map { it.length }.max() ?: 0 for (i in 0 until maxLength) { if ((i - 1) % 4 == 0) { // println("i = $i") for (str in list) { if (i < str.length) { if (str[i] != ' ') { stacks[(i - 1) / 4].push(str[i]) } } } } } return stacks }
0
Kotlin
0
0
e17165afe973392a0cbbac227eb31d215bc8e07c
2,624
advent-of-code
Apache License 2.0
src/day19/Day19.kt
dkoval
572,138,985
false
{"Kotlin": 86889}
package day19 import readInput import java.util.* import kotlin.system.measureTimeMillis private const val DAY_ID = "19" private data class Blueprint( val id: Int, val costs: List<List<Int>> ) fun main() { fun parseInput(input: List<String>): List<Blueprint> { val regex = """ |Blueprint (\d+): | Each ore robot costs (\d+) ore. | Each clay robot costs (\d+) ore. | Each obsidian robot costs (\d+) ore and (\d+) clay. | Each geode robot costs (\d+) ore and (\d+) obsidian. """.trimMargin().replace("\n", "").toRegex() return input.map { line -> val groups = regex.find(line)!!.groupValues Blueprint( groups[1].toInt(), listOf( // 0 - ore robot listOf(groups[2].toInt(), 0, 0, 0), // 1 - clay robot listOf(groups[3].toInt(), 0, 0, 0), // 2 - obsidian robot listOf(groups[4].toInt(), groups[5].toInt(), 0, 0), // 3 - geode robot listOf(groups[6].toInt(), 0, groups[7].toInt(), 0) ) ) } } fun solve(blueprint: Blueprint, time: Int): Int { data class State( val time: Int, val minerals: List<Int>, val robots: List<Int> ) val maxCanSpend = (0..3).map { i -> blueprint.costs.maxOf { costs -> costs[i] } } // ~ BFS to explore all possible states val q: Queue<State> = ArrayDeque() val seen = mutableSetOf<State>() fun enqueue(item: State) { if (item !in seen) { q.offer(item) seen += item } } infix fun Int.divRoundUp(y: Int): Int = (this - 1) / y + 1 var best = 0 enqueue(State(time, listOf(0, 0, 0, 0), listOf(1, 0, 0, 0))) while (!q.isEmpty()) { val curr = q.poll() // what is the number of geodes we can get from this state in curr.time remaining time? val numGeodesCanGet = curr.minerals[3] + curr.robots[3] * curr.time best = maxOf(best, numGeodesCanGet) if (curr.time == 0) { continue } for (x in 0..3) { // Do we already have enough x-collecting robots? if (x != 3 && curr.robots[x] >= maxCanSpend[x]) { continue } // What are the minerals required to build an x-collecting robot? val costs = blueprint.costs[x].withIndex().filter { (_, cost) -> cost > 0 } val canBuild = costs.all { (i, _) -> curr.robots[i] > 0 } if (!canBuild) { continue } // How much time does it take to build a new robot? // - 1 unit of time to assembly a robot // - plus time spent on collecting the required minerals val spentTime = 1 + costs.maxOf { (i, cost) -> if (curr.minerals[i] >= cost) 0 else (cost - curr.minerals[i]) divRoundUp curr.robots[i] } // Proceed to the next state val nextTime = curr.time - spentTime // remaining time if (nextTime <= 0) { continue } val nextMinerals = (0..3).map { i -> // Optimization to get part 2 working: // it's pointless to collect more minerals of a certain type i than we actually need // for building new robots collecting remaining types of minerals val ans = curr.minerals[i] - blueprint.costs[x][i] + curr.robots[i] * spentTime if (i < 3) minOf(ans, maxCanSpend[i] * nextTime) else ans } val nextRobots = curr.robots.mapIndexed { i, count -> if (i == x) count + 1 else count } enqueue(State(nextTime, nextMinerals, nextRobots)) } } return best } fun part1(input: List<String>): Int { val time = 24 val blueprints = parseInput(input) return blueprints.sumOf { blueprint -> blueprint.id * solve(blueprint, time) } } fun part2(input: List<String>): Long { val time = 32 val blueprints = parseInput(input) return blueprints.asSequence() .take(3) .fold(1L) { acc, blueprint -> acc * solve(blueprint, time) } } // test if implementation meets criteria from the description, like: val testInput = readInput("day${DAY_ID}/Day${DAY_ID}_test") check(part1(testInput) == 33) val input = readInput("day${DAY_ID}/Day${DAY_ID}") measureTimeMillis { println(part1(input)) // answer = 1725 }.also { println("Part 1 took $it ms") } measureTimeMillis { println(part2(input)) // answer = 15510 }.also { println("Part 2 took $it ms") } }
0
Kotlin
1
0
791dd54a4e23f937d5fc16d46d85577d91b1507a
5,096
aoc-2022-in-kotlin
Apache License 2.0
src/day03/Day03.kt
Regiva
573,089,637
false
{"Kotlin": 29453}
package day03 import readLines fun main() { val id = "03" fun readRucksacks(fileName: String): Sequence<Pair<String, String>> { return readLines(fileName) .asSequence() .map { it.substring(0, it.length / 2) to it.substring(it.length / 2, it.length) } } fun Char.priority() = if (isLowerCase()) code - 'a'.code + 1 else code - 'A'.code + 27 // Time — O(N * M), Memory — O(N) where M is a rucksack's compartment length fun part1(input: Sequence<Pair<String, String>>): Int { var count = 0 input.forEach { pair -> pair.first.toSet().intersect(pair.second.toSet()).forEach { count += it.priority() } } return count } // Time — O(N * M), Memory — O(N) fun part2(input: Sequence<Pair<String, String>>): Int { return input.map { it.first + it.second } .chunked(3) .map { it.map(String::toSet).reduce(Set<Char>::intersect).single() } .sumOf { it.priority() } } val testInput = readRucksacks("day$id/Day${id}_test") println(part1(testInput)) check(part1(testInput) == 157) check(part2(testInput) == 70) val input = readRucksacks("day$id/Day$id") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
2d9de95ee18916327f28a3565e68999c061ba810
1,316
advent-of-code-2022
Apache License 2.0
year2022/src/cz/veleto/aoc/year2022/Day07.kt
haluzpav
573,073,312
false
{"Kotlin": 164348}
package cz.veleto.aoc.year2022 import cz.veleto.aoc.core.AocDay class Day07(config: Config) : AocDay(config) { override fun part1(): String { val graph = parseIntoGraph() calculateDirSizes(graph) val atMost100kDirs = findAtMost100kDirs(graph) return atMost100kDirs.sumOf { it.childrenSize!! }.toString() } override fun part2(): String { val maxSpace = 70000000 val minNeeded = 30000000 val graph = parseIntoGraph() calculateDirSizes(graph) val nowAvailable = maxSpace - graph.childrenSize!! val toDeleteAtLeast = minNeeded - nowAvailable check(toDeleteAtLeast > 0) val deletionCandidates = findAtLeastDirs(graph, toDeleteAtLeast) return deletionCandidates.minOf { it.childrenSize!! }.toString() } private fun parseIntoGraph(): Node.Directory { check(cachedInput[0] == """$ cd /""") val root = Node.Directory("/") parseChildren(root, indexToContinueFrom = 1) return root } private fun parseChildren(directory: Node.Directory, indexToContinueFrom: Int): Int { check(cachedInput[indexToContinueFrom] == """$ ls""") var i = indexToContinueFrom + 1 while (i < cachedInput.size) { val line = cachedInput[i] when { line == """$ cd ..""" -> return (i - indexToContinueFrom + 1) line.startsWith("""$ cd""") -> { val childName = line.split(" ").also { check(it.size == 3) }[2] directory.children .filterIsInstance<Node.Directory>() .find { it.name == childName }!! .let { i += parseChildren(it, indexToContinueFrom = i + 1) } } line.startsWith("""dir""") -> { directory.children += Node.Directory( name = line.split(" ").also { check(it.size == 2) }[1], ) } else -> { val (size, name) = line.split(" ").also { check(it.size == 2) } directory.children += Node.File( name = name, size = size.toLong(), ) } } i++ } return (i - indexToContinueFrom + 1) } private fun calculateDirSizes(graph: Node.Directory): Long = graph.children.sumOf { when (it) { is Node.Directory -> calculateDirSizes(it) is Node.File -> it.size } }.also { graph.childrenSize = it } private fun findAtMost100kDirs(graph: Node.Directory): List<Node.Directory> = listOfNotNull(graph.takeIf { it.childrenSize!! <= 100_000 }) + graph.children .filterIsInstance<Node.Directory>() .flatMap { findAtMost100kDirs(it) } private fun findAtLeastDirs(graph: Node.Directory, minSize: Long): List<Node.Directory> = graph.takeIf { it.childrenSize!! >= minSize }?.let { bigEnoughGraph -> listOf(bigEnoughGraph) + bigEnoughGraph.children .filterIsInstance<Node.Directory>() .flatMap { findAtLeastDirs(it, minSize) } } ?: emptyList() private sealed interface Node { data class Directory( val name: String, val children: MutableList<Node> = mutableListOf(), var childrenSize: Long? = null, ) : Node data class File( val name: String, val size: Long, ) : Node } }
0
Kotlin
0
1
32003edb726f7736f881edc263a85a404be6a5f0
3,613
advent-of-pavel
Apache License 2.0
src/main/kotlin/g2701_2800/s2719_count_of_integers/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g2701_2800.s2719_count_of_integers // #Hard #String #Dynamic_Programming #Math #2023_08_02_Time_208_ms_(100.00%)_Space_38_MB_(68.42%) import java.util.Arrays class Solution { private lateinit var dp: Array<Array<Array<IntArray>>> private fun countStrings(i: Int, tight1: Boolean, tight2: Boolean, sum: Int, num1: String, num2: String): Int { if (sum < 0) return 0 if (i == num2.length) return 1 if (dp[i][if (tight1) 1 else 0][if (tight2) 1 else 0][sum] != -1) return dp[i][if (tight1) 1 else 0][if (tight2) 1 else 0][sum] val lo = if (tight1) num1[i].code - '0'.code else 0 val hi = if (tight2) num2[i].code - '0'.code else 9 var count = 0 for (idx in lo..hi) { count = ( count % MOD + countStrings( i + 1, tight1 and (idx == lo), tight2 and (idx == hi), sum - idx, num1, num2 ) % MOD ) % MOD } return count.also { dp[i][if (tight1) 1 else 0][if (tight2) 1 else 0][sum] = it } } fun count(num1: String, num2: String, minSum: Int, maxSum: Int): Int { val maxLength = num2.length val minLength = num1.length val leadingZeroes = maxLength - minLength val num1extended: String = "0".repeat(leadingZeroes) + num1 dp = Array(maxLength) { Array(2) { Array(2) { IntArray(401) } } } for (dim1 in dp) { for (dim2 in dim1) { for (dim3 in dim2) { Arrays.fill(dim3, -1) } } } val total = countStrings(0, true, true, maxSum, num1extended, num2) val unnecessary = countStrings(0, true, true, minSum - 1, num1extended, num2) var ans = (total - unnecessary) % MOD if (ans < 0) { ans += MOD } return ans } companion object { private const val MOD = 1e9.toInt() + 7 } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
2,081
LeetCode-in-Kotlin
MIT License
src/main/kotlin/dev/bogwalk/batch9/Problem93.kt
bog-walk
381,459,475
false
null
package dev.bogwalk.batch9 import dev.bogwalk.util.combinatorics.combinations import dev.bogwalk.util.custom.Fraction import kotlin.math.abs import kotlin.math.roundToInt /** * Problem 93: Arithmetic Expressions * * https://projecteuler.net/problem=93 * * Goal: Distinct positive integer outcomes can be achieved from expressions created using a set * of M distinct digits, each used exactly once with any of the operators +, -, *, /, as well as * parentheses. Find the largest possible integer N, such that [1, N] is expressible. If 1 is * not even a possible outcome, return 0. * * Constraints: 1 <= M <= 5 * * e.g.: M = 2 -> {2, 8} * outcomes = {8/2, 8-2, 2+8, 2*8} = {4, 6, 10, 16} * output = 0 * * M = 2 -> {1, 2} * outcomes = {1+2, 2-1, 1*2 or 2/1} = {3, 1, 2} * output = 3 */ class ArithmeticExpressions { /** * Recursive solution repeatedly reduces the number of digits in the set by evaluating all * possible expressions between different combinations of 2 digits in the set. The digits are * treated as Doubles from the beginning so that, once only 1 digit remains in the set, any * floating-point values can be handled to ensure no expressible outcomes are missed. * * Note that non-commutative operations have to be performed twice to account for the * alternative ordered combinations. * * N.B. Cache size was initially calculated using the product of the M largest digits: * * listOf(5, 6, 7, 8, 9).takeLast(m).reduce { acc, d -> acc * d }) * * Exhaustive search showed that this was excessive as, while these maximum values are * achievable, the longest streaks barely make it a fraction of the way: * 1 digit -> 1 * 2 digits -> 3 * 3 digits -> 10 * 4 digits -> 51 * 5 digits -> 192 * * @param [digits] List of unique digits sorted in ascending order. */ fun highestStreak(digits: List<Int>): Int { val maxCache = 200 val expressed = BooleanArray(maxCache) // value 1 at index 0 fun evaluateExpression(digits: List<Double>) { if (digits.size == 1) { val final = digits.single() val finalAsInt = final.roundToInt() if (abs(final - finalAsInt) <= 0.00001 && finalAsInt in 1..maxCache) { expressed[finalAsInt - 1] = true } } else { for (i in 0 until digits.lastIndex) { for (j in i+1..digits.lastIndex) { val newDigits = digits.toMutableList() val y = newDigits.removeAt(j) val x = newDigits.removeAt(i) // commutative operators newDigits.add(x + y) val lastI = newDigits.lastIndex evaluateExpression(newDigits) newDigits[lastI] = x * y evaluateExpression(newDigits) // non-commutative operators newDigits[lastI] = x - y evaluateExpression(newDigits) newDigits[lastI] = y - x evaluateExpression(newDigits) if (y != 0.0) { newDigits[lastI] = x / y evaluateExpression(newDigits) } if (x != 0.0) { newDigits[lastI] = y / x evaluateExpression(newDigits) } } } } } evaluateExpression(digits.map(Int::toDouble)) // index of first false means end of streak comes at previous index return expressed.indexOfFirst { !it } } /** * Identical to the previous solution except that digits are treated as custom class, * Fraction, (rational numbers) to avoid any floating-point issues. * * @param [digits] List of unique digits sorted in ascending order. */ fun highestStreakWithFractions(digits: List<Int>): Int { val maxCache = 200 val expressed = BooleanArray(maxCache) fun evaluateExpression(digits: List<Fraction>) { if (digits.size == 1) { val final = digits.single() if (final.denominator == 1 && final.numerator in 1..maxCache) { expressed[final.numerator - 1] = true } } else { for (i in 0 until digits.lastIndex) { for (j in i+1..digits.lastIndex) { val newDigits = digits.toMutableList() val y = newDigits.removeAt(j) val x = newDigits.removeAt(i) newDigits.add(x + y) val lastI = newDigits.lastIndex evaluateExpression(newDigits) newDigits[lastI] = x * y evaluateExpression(newDigits) newDigits[lastI] = x - y evaluateExpression(newDigits) newDigits[lastI] = y - x evaluateExpression(newDigits) if (y != Fraction()) { newDigits[lastI] = x / y evaluateExpression(newDigits) } if (x != Fraction()) { newDigits[lastI] = y / x evaluateExpression(newDigits) } } } } } evaluateExpression(digits.map { Fraction(it) }) return expressed.indexOfFirst { !it } } /** * Project Euler specific implementation that returns a String representation of the set of * digits that can express the longest streak of positive integers. * * Note that, including the digit 0 would have resulted in 210 4-digit combinations instead of * 126. It was left out because exhaustive search showed that [1, 2] was the longest streak * achievable by a 4-digit set that includes 0. */ fun longestStreakSet(m: Int = 4): String { var longestStreak = 0 to "" for (digitCombo in combinations(1..9, m)) { val highest = highestStreak(digitCombo) if (highest > longestStreak.first) { longestStreak = highest to digitCombo.joinToString("") } } return longestStreak.second } }
0
Kotlin
0
0
62b33367e3d1e15f7ea872d151c3512f8c606ce7
6,735
project-euler-kotlin
MIT License
src/main/kotlin/aoc2023/Day19.kt
Ceridan
725,711,266
false
{"Kotlin": 110767, "Shell": 1955}
package aoc2023 import kotlin.IllegalStateException import kotlin.math.min import kotlin.math.max class Day19 { fun part1(input: String): Int { val (workflows, parts) = parseInput(input) var totalSum = 0 for (part in parts) { var result = "in" while (result !in setOf("A", "R")) { result = workflows[result]!!.checkPart(part) } if (result == "A") { totalSum += part.sum() } } return totalSum } fun part2(input: String): Long { val (workflows, _) = parseInput(input) return dfs(workflows, "in") } private fun dfs( workflows: Map<String, Workflow>, currentWorkflow: String, accepted: XmasRange = XmasRange(1..4000, 1..4000, 1..4000, 1..4000), ): Long { var combinations = 0L var currAccepted = accepted for (rule in workflows[currentWorkflow]!!.compactRules()) { if (currAccepted.isEmptyCombinations()) return combinations val newAccepted = currAccepted.updateRange(rule.param, rule.toRange()) if (rule.result == "A") { combinations += newAccepted.calculateCombinations() } else if (rule.result != "R") { combinations += dfs(workflows, rule.result, newAccepted) } currAccepted = currAccepted.updateRange(rule.param, rule.inverse().toRange()) } return combinations } private fun parseInput(input: String): Pair<Map<String, Workflow>, List<XmasPart>> { val workflows = mutableMapOf<String, Workflow>() val parts = mutableListOf<XmasPart>() val lines = input.split('\n').filter { it.isNotEmpty() } val partRegex = "^\\{x=(\\d+),m=(\\d+),a=(\\d+),s=(\\d+)}$".toRegex() val workflowRegex = "^([a-z]+)\\{(.+)}$".toRegex() for (line in lines) { val partMatch = partRegex.find(line) if (partMatch != null) { val (x, m, a, s) = partMatch.destructured parts.add(XmasPart(x = x.toInt(), m = m.toInt(), a = a.toInt(), s = s.toInt())) continue } val (name, rawRules) = workflowRegex.find(line)!!.destructured val rules = rawRules.split(',').map { val condRules = it.split(':') if (condRules.size == 1) { Rule('x', '>', 0, condRules[0]) } else { val param = condRules[0].take(1)[0] val op = condRules[0].drop(1).take(1)[0] val value = condRules[0].drop(2).toInt() val result = condRules[1] Rule(param, op, value, result) } } workflows[name] = Workflow(name, rules) } return workflows to parts } data class Workflow(val name: String, private val rules: List<Rule>) { private val fnRules = mutableListOf<(XmasPart) -> String>() init { fnRules.addAll(rules.map { convertToFn(it) }) } fun checkPart(part: XmasPart): String { for (fnCond in fnRules) { val result = fnCond(part) if (result != "C") return result } throw IllegalStateException("No conditions are applicable. Workflow: $name, XmasPart: $part") } fun compactRules(): List<Rule> { val terminalCondition = rules.last() val compactedConditions = rules.asReversed().dropWhile { it.result == terminalCondition.result } .toMutableList() compactedConditions.reverse() compactedConditions.add(terminalCondition) return compactedConditions } private fun convertToFn(rule: Rule): (XmasPart) -> String { return when (val paramOpPair = "${rule.param}${rule.op}") { "x<" -> { xmas: XmasPart -> if (xmas.x < rule.value) rule.result else "C" } "x>" -> { xmas: XmasPart -> if (xmas.x > rule.value) rule.result else "C" } "m<" -> { xmas: XmasPart -> if (xmas.m < rule.value) rule.result else "C" } "m>" -> { xmas: XmasPart -> if (xmas.m > rule.value) rule.result else "C" } "a<" -> { xmas: XmasPart -> if (xmas.a < rule.value) rule.result else "C" } "a>" -> { xmas: XmasPart -> if (xmas.a > rule.value) rule.result else "C" } "s<" -> { xmas: XmasPart -> if (xmas.s < rule.value) rule.result else "C" } "s>" -> { xmas: XmasPart -> if (xmas.s > rule.value) rule.result else "C" } else -> throw IllegalArgumentException("Unknown operation: $paramOpPair") } } } data class Rule(val param: Char, val op: Char, val value: Int, val result: String) { fun toRange(): IntRange = if (op == '>') IntRange(value + 1, 4000) else IntRange(1, value - 1) fun inverse(): Rule { val invertedOp = if (op == '>') '<' else '>' val invertedValue = if (op == '>') value + 1 else value - 1 return Rule(param, invertedOp, invertedValue, result) } } data class XmasRange(val x: IntRange, val m: IntRange, val a: IntRange, val s: IntRange) { fun updateRange(ch: Char, range: IntRange): XmasRange = when (ch) { 'x' -> copy(x = x.rangeIntersect(range)) 'm' -> copy(m = m.rangeIntersect(range)) 'a' -> copy(a = a.rangeIntersect(range)) 's' -> copy(s = s.rangeIntersect(range)) else -> throw IllegalArgumentException("Unknown category $ch") } fun isEmptyCombinations(): Boolean = listOf(x, m, a, s).any { it.last == 0 } fun calculateCombinations(): Long = listOf(x, m, a, s).map { it.last - it.first + 1 }.fold(1L) { acc, size -> acc * size } private fun IntRange.rangeIntersect(other: IntRange): IntRange { if (this.first > other.last || this.last < other.first) { return IntRange(1, 0) } return IntRange(max(this.first, other.first), min(this.last, other.last)) } } data class XmasPart(val x: Int, val m: Int, val a: Int, val s: Int) { fun sum(): Int = x + m + a + s } } fun main() { val day19 = Day19() val input = readInputAsString("day19.txt") println("19, part 1: ${day19.part1(input)}") println("19, part 2: ${day19.part2(input)}") }
0
Kotlin
0
0
18b97d650f4a90219bd6a81a8cf4d445d56ea9e8
6,593
advent-of-code-2023
MIT License
src/Day01.kt
pinkpinkkjn
578,428,998
false
{"Kotlin": 2404}
fun main() { // fun part1(input: List<String>): Int { // return input.size // } fun part1(input: String): Int { val data = input.split("\n\n").map { elf -> elf.lines().map { it.toInt() } } return data.maxOf { it.sum() } } fun part1v2(input: String): Int { val data = input.split("\n\n").map { elf -> elf.lines().map { it.toInt() }.sum() } return data.max() } fun part1v3(input: String): Int { val data = input.split("\n\n").map { elf -> elf.lines().sumOf { it.toInt() } } return data.max() } fun part2(input: String): Int { val data = input.split("\n\n").map { elf -> elf.lines().map { it.toInt() } } return data.map { it.sum() }.sortedDescending().take(3).sum() } // test if implementation meets criteria from the description, like: val testInput = readInputText("Day01_test") check(part1(testInput) == 24000) check(part2(testInput) == 45000) val input = readInputText("Day01") // part1(input).println() // part1v3(input).println() part2(input).println() }
0
Kotlin
0
0
e1d3021e2963e8da9187da64a0a1be91da3747e5
1,183
advent-of-code-kotlin
Apache License 2.0
src/main/kotlin/day16/Day16.kt
Arch-vile
317,641,541
false
null
package day16 import readFile import utils.intersect import utils.transpose data class Field(val name: String, val range1: IntRange, val range2: IntRange) { fun accepts(number: Int): Boolean { return range1.contains(number) || range2.contains(number) } } fun main(args: Array<String>) { val fields = listOf( Field("departure location", 34..269, 286..964), Field("departure station", 27..584, 609..973), Field("departure platform", 49..135, 155..974), Field("departure track", 36..248, 255..954), Field("departure date", 50..373, 381..974), Field("departure time", 49..454, 472..967), Field("arrival location", 33..900, 925..968), Field("arrival station", 46..699, 706..965), Field("arrival platform", 42..656, 666..967), Field("arrival track", 49..408, 425..950), Field("class", 30..626, 651..957), Field("duration", 43..109, 127..964), Field("price", 33..778, 795..952), Field("route", 37..296, 315..966), Field("row", 28..318, 342..965), Field("seat", 33..189, 208..959), Field("train", 49..536, 552..968), Field("type", 46..749, 772..949), Field("wagon", 29..386, 401..954), Field("zone", 34..344, 368..954), ) val input = readFile("./src/main/resources/day16Input.txt") .drop(25) .map { it.split(",") } .map { it.map { it.toInt() } } // For each number collect all fields that match it var numbersToFields = input .map { numbers -> numbers.map { number -> fields .filter { it.accepts(number) } } } // Part 1 println(numbersToFields .mapIndexed { lineIndex, line -> line.mapIndexedNotNull { fieldIndex, fields -> if (fields.isEmpty()) { input[lineIndex][fieldIndex] } else null } }.map { it.sum() } .sum() ) println("--------------------------") // Part 2 // Remove invalid tickets var validTickets = numbersToFields .filter { ticket -> ticket.filter { it.isEmpty() }.count() == 0 } val fieldMatches = transpose(validTickets) val phase3 = fieldMatches .mapIndexed { index, list -> Pair(index, intersect(list)) } // Add a dummy element for the window to work on first element in next step .plus(Pair(-1, listOf())) .sortedBy { it.second.size } val fieldsInOrder = phase3 .windowed(2, 1) .map { Pair(it[1].first, it[1].second.subtract(it[0].second)) } .sortedBy { it.first } .map { it.second } .map { it.toList()[0].name } val myTicket = listOf(109, 101, 79, 127, 71, 59, 67, 61, 173, 157, 163, 103, 83, 97, 73, 167, 53, 107, 89, 131).map { it.toLong() } val answer = fieldsInOrder.zip(myTicket) .map { it } .filter { it.first.startsWith("departure") } .map { it.second } .reduce { acc, number -> acc * number } println(answer) }
0
Kotlin
0
0
12070ef9156b25f725820fc327c2e768af1167c0
2,851
adventOfCode2020
Apache License 2.0
src/main/kotlin/ru/timakden/aoc/year2015/Day07.kt
timakden
76,895,831
false
{"Kotlin": 321649}
package ru.timakden.aoc.year2015 import ru.timakden.aoc.util.isLetter import ru.timakden.aoc.util.isNumber import ru.timakden.aoc.util.measure import ru.timakden.aoc.util.readInput /** * [Day 7: Some Assembly Required](https://adventofcode.com/2015/day/7). */ object Day07 { @JvmStatic fun main(args: Array<String>) { measure { val input = readInput("year2015/Day07").toMutableList() val aPart1 = solve(input, listOf("a"))["a"] println("Part One: $aPart1") input[input.indexOfFirst { "\\d+\\s->\\sb".toRegex().matches(it) }] = "$aPart1 -> b" println("Part Two: ${solve(input, listOf("a"))["a"]}") } } fun solve(input: List<String>, wiresToReturn: List<String>): Map<String, UShort> { val regex1 = "\\s->\\s".toRegex() val regex2 = "\\s(?!or|and|lshift|rshift)".toRegex() val map = mutableMapOf<String, UShort>() while (map.size != input.size) { input.forEach { line -> val expressions = line.split(regex1) val leftPart = expressions[0].split(regex2) when (leftPart.size) { 1 -> { // example: 44430 -> b if (leftPart[0].isNumber()) map[expressions[1]] = leftPart[0].toUShort() else if (leftPart[0].isLetter()) map[leftPart[0]]?.let { map[expressions[1]] = it } } 2 -> { // example: NOT di -> dj if (leftPart[1].isNumber()) map[expressions[1]] = leftPart[1].toUShort().inv() else if (leftPart[1].isLetter()) map[leftPart[1]]?.let { map[expressions[1]] = it.inv() } } 3 -> { // example: dd OR do -> dp val val1 = if (leftPart[0].isNumber()) leftPart[0].toUShort() else if (leftPart[0].isLetter()) map[leftPart[0]] else null val val2 = if (leftPart[2].isNumber()) leftPart[2].toUShort() else if (leftPart[2].isLetter()) map[leftPart[2]] else null if (val1 != null && val2 != null) { when (leftPart[1]) { "AND" -> map[expressions[1]] = val1 and val2 "OR" -> map[expressions[1]] = val1 or val2 "LSHIFT" -> map[expressions[1]] = val1 shl val2 "RSHIFT" -> map[expressions[1]] = val1 shr val2 } } } } } } return map.filter { it.key in wiresToReturn } } private infix fun UShort.shl(shift: UShort): UShort = (this.toInt() shl shift.toInt()).toUShort() private infix fun UShort.shr(shift: UShort): UShort = (this.toInt() shr shift.toInt()).toUShort() }
0
Kotlin
0
3
acc4dceb69350c04f6ae42fc50315745f728cce1
3,059
advent-of-code
MIT License
aoc/src/main/kotlin/com/bloidonia/aoc2023/day19/Main.kt
timyates
725,647,758
false
{"Kotlin": 45518, "Groovy": 202}
package com.bloidonia.aoc2023.day19 import com.bloidonia.aoc2023.text private const val example = """px{a<2006:qkq,m>2090:A,rfg} pv{a>1716:R,A} lnx{m>1548:A,A} rfg{s<537:gd,x>2440:R,A} qs{s>3448:A,lnx} qkq{x<1416:A,crn} crn{x>2662:A,R} in{s<1351:px,qqz} qqz{s>2770:qs,m<1801:hdj,R} gd{a>3333:R,R} hdj{m>838:A,pv} {x=787,m=2655,a=1222,s=2876} {x=1679,m=44,a=2067,s=496} {x=2036,m=264,a=79,s=2244} {x=2461,m=1339,a=466,s=291} {x=2127,m=1623,a=2188,s=1013}""" private typealias Condition = (Part) -> String private data class Rule(val fn: Condition) { fun process(part: Part) = fn(part) companion object { fun parse(input: String): Pair<String, Rule> { Regex("""([a-z]+)\{([^}]+)}""").matchEntire(input)!!.let { val (key, value) = it.destructured val values = value.split(",") var fn = { part: Part -> values.last() } values.dropLast(1).reversed().forEach { condition -> val (k, op, v, then) = Regex("""([a-z])([<>=])(\d+):([A-Za-z]+)""").matchEntire(condition)!!.destructured val oldFn = fn fn = when (op) { "<" -> { part: Part -> if (part.qualities[k]!! < v.toLong()) then else oldFn.invoke(part) } ">" -> { part: Part -> if (part.qualities[k]!! > v.toLong()) then else oldFn.invoke(part) } "=" -> { part: Part -> if (part.qualities[k]!! == v.toLong()) then else oldFn.invoke(part) } else -> throw Exception("Unknown operator: $op") } } return key to Rule(fn) } } } } private data class Part(val qualities: Map<String, Long>) { fun score() = qualities.values.sum().toLong() constructor(input: String) : this(input .removePrefix("{") .removeSuffix("}") .split(",") .associate { val (k, v) = it.split("=") k to v.toLong() }) } private fun part1(input: String) { input.split("\n\n").let { (rules, parts) -> val parsedRules = rules.split("\n").map(Rule::parse).toMap() val parsedParts = parts.split("\n").map(::Part) var score = 0L parsedParts.forEach { part -> var key = "in" while (key != "A" && key != "R") { key = parsedRules[key]!!.process(part) } if (key == "A") { score += part.score() } } println(score) } } fun main() { part1(example) part1(text("/day19.input")) }
0
Kotlin
0
0
158162b1034e3998445a4f5e3f476f3ebf1dc952
2,632
aoc-2023
MIT License
advent-of-code2015/src/main/kotlin/day3/Advent3.kt
REDNBLACK
128,669,137
false
null
package day3 import parseInput /** --- Day 3: Perfectly Spherical Houses in a Vacuum --- Santa is delivering presents to an infinite two-dimensional grid of houses. He begins by delivering a present to the house at his starting location, and then an elf at the North Pole calls him via radio and tells him where to move next. Moves are always exactly one house to the north (^), south (v), east (>), or west (<). After each move, he delivers another present to the house at his new location. However, the elf back at the north pole has had a little too much eggnog, and so his directions are a little off, and Santa ends up visiting some houses more than once. How many houses receive at least one present? For example: > delivers presents to 2 houses: one at the starting location, and one to the east. ^>v< delivers presents to 4 houses in a square, including twice to the house at his starting/ending location. ^v^v^v^v^v delivers a bunch of presents to some very lucky children at only 2 houses. --- Part Two --- The next year, to speed up the process, Santa creates a robot version of himself, Robo-Santa, to deliver presents with him. Santa and Robo-Santa start at the same location (delivering two presents to the same starting house), then take turns moving based on instructions from the elf, who is eggnoggedly reading from the same script as the previous year. This year, how many houses receive at least one present? For example: ^v delivers presents to 3 houses, because Santa goes north, and then Robo-Santa goes south. ^>v< now delivers presents to 3 houses, and Santa and Robo-Santa end up back where they started. ^v^v^v^v^v now delivers presents to 11 houses, with Santa going one direction and Robo-Santa going the other. */ fun main(args: Array<String>) { println(countHouses(">") == 2) println(countHouses("^>v<") == 4) println(countHouses("^v^v^v^v^v") == 2) println(countHousesSecond("^v") == 3) println(countHousesSecond("^>v<") == 3) println(countHousesSecond("^v^v^v^v^v") == 11) val input = parseInput("day3-input.txt") println(countHouses(input)) println(countHousesSecond(input)) } fun countHouses(input: String) = executeMoves(moves = parseMoves(input)).size fun countHousesSecond(input: String) = parseMovesSecond(input) .flatMap { executeMoves(moves = it) } .distinct() .count() private tailrec fun executeMoves(pos: Int = 0, acc: List<State> = listOf(State(0, 0)), moves: List<Move>): List<State> { if (pos == moves.size) return acc.distinct() val m = moves[pos] val s = acc.last() return executeMoves(pos + 1, acc.plus(s.copy(x = s.x + m.x, y = s.y + m.y)), moves) } data class State(val x: Int, val y: Int) enum class Move(val x: Int, val y: Int) { EAST(0, 1), WEST(0, -1), SOUTH(-1, 0), NORTH(1, 0) } private fun parseMoves(input: String) = input.trim() .map { when (it) { '>' -> Move.EAST '<' -> Move.WEST '^' -> Move.NORTH 'v' -> Move.SOUTH else -> throw IllegalArgumentException() } } private fun parseMovesSecond(input: String): List<List<Move>> { fun parse(indexCompare: (Int) -> Boolean) = input.toCharArray() .filterIndexed { i, c -> indexCompare(i) } .joinToString("") .let(::parseMoves) return listOf(parse { it % 2 == 0 }, parse { it % 2 != 0 }) }
0
Kotlin
0
0
e282d1f0fd0b973e4b701c8c2af1dbf4f4a149c7
3,476
courses
MIT License
src/Day02.kt
drothmaler
572,899,837
false
{"Kotlin": 15196}
enum class Shape (val opponent: Char, val response: Char, val score: Int) { Rock('A', 'X', 1), Paper('B', 'Y', 2), Scissors('C', 'Z', 3); private val beats get() = relative(-1) private val loosesTo get() = relative(+1) private fun relative(delta:Int) = Shape.values()[(this.ordinal + delta + size) % size] fun fight(other: Shape): Outcome = when (other) { this -> Outcome.Draw this.beats -> Outcome.Won else -> Outcome.Lost } fun byOutcome(outcome: Outcome) = when(outcome) { Outcome.Lost -> this.beats Outcome.Draw -> this Outcome.Won -> this.loosesTo } companion object { fun byOpponent(char: Char) = Shape.values().find { it.opponent == char }!! fun byResponse(char: Char) = Shape.values().find { it.response == char }!! val size get() = Shape.values().size } } enum class Outcome (val code: Char, val score: Int) { Lost('X', 0), Draw('Y', 3), Won('Z', 6); companion object { fun byCode(code: Char) = Outcome.values().find { it.code == code }!! } } class Strategy(val opponent: Shape, val response: Shape) { val outcome: Outcome = response.fight(opponent) val score: Int = outcome.score + response.score companion object { fun byResponse(string: String): Strategy = Strategy( Shape.byOpponent(string[0]), Shape.byResponse(string[2]) ) fun byOutcome(string: String): Strategy { val opponent = Shape.byOpponent(string[0]) val outcome = Outcome.byCode(string[2]) val response = opponent.byOutcome(outcome) return Strategy(opponent, response) } } } fun main() { fun Sequence<Strategy>.score() = this.map(Strategy::score) fun part1(input: Sequence<String>) = input.map(Strategy.Companion::byResponse).score().toList() fun part2(input: Sequence<String>) = input.map(Strategy.Companion::byOutcome).score().toList() // test if implementation meets criteria from the description, like: val testOutput = useSanitizedInput("Day02_test", ::part1) check(testOutput == listOf(8, 1, 6)) check(testOutput.sum() == 15) val testOutput2 = useSanitizedInput("Day02_test", ::part2) check(testOutput2 == listOf(4, 1, 7)) check(testOutput2.sum() == 12) val output = useSanitizedInput("Day02", ::part1) println(output.sum()) val output2 = useSanitizedInput("Day02", ::part2) println(output2.sum()) }
0
Kotlin
0
0
1fa39ebe3e4a43e87f415acaf20a991c930eae1c
2,519
aoc-2022-in-kotlin
Apache License 2.0
src/main/kotlin/Day3.kt
noamfreeman
572,834,940
false
{"Kotlin": 30332}
private val part1ExampleInput = """ vJrwpWtwJgWrhcsFMMfFFhFp jqHRNqRjqzjGDLGLrsFMfFZSrLrFZsSL PmmdzqPrVvPwwTWBwg wMqvLMZHhHMvwLHjbvcjnnSBnvTQFn ttgJtRGJQctTZtZT CrZsJsPPZsGzwwsLwLmpwMDw """.trimIndent() fun main() { println("day3") println() println("part1") assertEquals(part1(part1ExampleInput), 157) println(part1(readInputFile("day3_input.txt"))) println() println("part2") assertEquals(part2(part1ExampleInput), 70) println(part2(readInputFile("day3_input.txt"))) } private fun part1(string: String): Int = string .lines() .map { sack -> val (a, b) = sack.splitAtMiddle() findCommon(a, b) }.sumOf { char -> char.toValue() } private fun part2(string: String): Int = string .lines() .chunked(3) .map { findCommon(it) }.sumOf { it.toValue() } private fun String.splitAtMiddle(): Pair<String, String> { require(length % 2 == 0) return take(length / 2) to takeLast(length / 2) } private fun findCommon(a: String, b: String) = findCommon(listOf(a, b)) private fun findCommon(strings: List<String>): Char { val occurrences = mutableMapOf<Char, Int>() strings.forEach { string -> string.toSet().forEach { char -> occurrences.incrementOrZero(char) } } return occurrences.toList().firstOrNull { it.second == strings.size }?.first ?: error("no common in $strings") } private fun MutableMap<Char, Int>.incrementOrZero(char: Char) { this[char] = this.getOrDefault(char, 0) + 1 } private fun Char.toValue(): Int { val lower = this - 'a' if (lower > 0) return lower + 1 return this - 'A' + 27 }
0
Kotlin
0
0
1751869e237afa3b8466b213dd095f051ac49bef
1,708
advent_of_code_2022
MIT License
src/Day16.kt
cypressious
572,916,585
false
{"Kotlin": 40281}
import java.lang.IllegalStateException import java.lang.StringBuilder import java.math.BigInteger fun main() { abstract class Packet(val version: Int) { open fun versionSum() = version abstract fun evaluate(): Long } class Literal(version: Int, val value: Long) : Packet(version) { override fun evaluate() = value } class Operator(version: Int, val typeId: Int, val operands: List<Packet>) : Packet(version) { override fun versionSum() = version + operands.sumOf { it.versionSum() } override fun evaluate(): Long = when (typeId) { 0 -> operands.sumOf { it.evaluate() } 1 -> operands.fold(1) { acc, packet -> acc * packet.evaluate() } 2 -> operands.minOf { it.evaluate() } 3 -> operands.maxOf { it.evaluate() } 5 -> if (operands.first().evaluate() > operands.last().evaluate()) 1 else 0 6 -> if (operands.first().evaluate() < operands.last().evaluate()) 1 else 0 7 -> if (operands.first().evaluate() == operands.last().evaluate()) 1 else 0 else -> throw IllegalStateException() } } class Parser(input: String) { val bits = BigInteger(input, 16).toString(2).padStart(input.length * 4, '0') var offset = 0 fun String.read(from: Int, length: Int): Int { return substring(from, from + length).toInt(2) } fun parse(): Packet { val version = bits.read(offset + 0, 3) val typeId = bits.read(offset + 3, 3) offset += 6 return if (typeId == 4) { Literal(version, parseLiteral(bits)) } else { val lengthType = bits.read(offset++, 1) val length = bits.read(offset, if (lengthType == 0) 15 else 11) offset += if (lengthType == 0) 15 else 11 val operands = buildList { if (lengthType == 0) { val lastOffset = offset while (offset - lastOffset < length) add(parse()) } else { repeat(length) { add(parse()) } } } Operator(version, typeId, operands) } } fun parseLiteral(bits: String): Long { var hasNext = true val buffer = StringBuilder() while (hasNext) { hasNext = bits.read(offset, 1) == 1 buffer.append(bits.substring(offset + 1, offset + 5)) offset += 5 } return buffer.toString().toLong(2) } } fun part1(input: List<String>): Int { val parser = Parser(input.first()) val packet = parser.parse() return packet.versionSum() } fun part2(input: List<String>): Long { val parser = Parser(input.first()) val packet = parser.parse() return packet.evaluate() } // test if implementation meets criteria from the description, like: check(part1(listOf("D2FE28")) == 6) check(part1(listOf("38006F45291200")) == 9) val input = readInput("Day16") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
169fb9307a34b56c39578e3ee2cca038802bc046
3,251
AdventOfCode2021
Apache License 2.0
src/Day07.kt
nikolakasev
572,681,478
false
{"Kotlin": 35834}
import ObjectType.Directory import ObjectType.File import java.lang.IllegalStateException fun main() { fun inputToFileSystem(input: List<String>): List<Node> { var currentNode = Node("/", size = 0, Directory, parent = null) val nodes: MutableList<Node> = mutableListOf(currentNode) input.forEach { if (it.startsWith("$ cd")) { val dirName = it.split(" ")[2] currentNode = when (dirName) { //go to root "/" -> nodes[0] //go to parent directory ".." -> (currentNode.parent)?:throw IllegalStateException("can't find parent of ${currentNode.name}") //go to dir !!!! multiple directories with the same name !!!!! else -> (nodes.find { n -> n.name == dirName && n.parent == currentNode })?:throw IllegalStateException("can't find $dirName") } } else if (it.startsWith("$ ls")) { //do nothing } else { //contents val first = it.split(" ")[0] val second = it.split(" ")[1] if (first == "dir") nodes.add(Node(second, 0, Directory, currentNode)) else nodes.add(Node(second, first.toInt(), File, currentNode)) } } nodes.reversed().forEach { if (it.parent != null) { it.parent.size += it.size } } return nodes } fun part1(input: List<String>): Int { val nodes = inputToFileSystem(input) return nodes.sumOf { if (it.type == Directory && it.size <= 100000) it.size else 0 } } fun part2(input: List<String>): Int { val nodes = inputToFileSystem(input) return nodes.filter { it.type == Directory && it.parent != null && it.size + 70000000 - nodes[0].size >= 30000000 }.minOf { it.size } } val testInput = readLines("Day07_test") check(part1(testInput) == 95437) check(part2(testInput) == 24933642) val input = readLines("Day07") println(part1(input)) println(part2(input)) } data class Node(val name: String, var size: Int, val type: ObjectType, val parent: Node?) enum class ObjectType { Directory, File }
0
Kotlin
0
1
5620296f1e7f2714c09cdb18c5aa6c59f06b73e6
2,360
advent-of-code-kotlin-2022
Apache License 2.0
src/Day03.kt
mrugacz95
572,881,300
false
{"Kotlin": 102751}
fun main() { fun part1(input: List<String>): Int { return input.sumOf { val (left, right) = it.chunked(it.length / 2) val common = left.toSet().intersect(right.toSet()).first() if (common.isLowerCase()) { common - 'a' + 1 } else { common - 'A' + 27 } } } fun part2(input: List<String>): Int { return input.chunked(3).sumOf { val commonChars = it.map { it.toHashSet() }.foldRight(HashSet<Char>()){ item, acc -> if (acc.isEmpty()) item else acc.intersect(item).toHashSet() } val common = commonChars.first() if (common.isLowerCase()) { common - 'a' + 1 } else { common - 'A' + 27 } } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day03_test") println(part1(testInput)) println(part2(testInput)) val input = readInput("Day03") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
29aa4f978f6507b182cb6697a0a2896292c83584
1,169
advent-of-code-2022
Apache License 2.0
src/main/kotlin/org/deafsapps/adventofcode/day04/Main.kt
pablodeafsapps
733,033,603
false
{"Kotlin": 6685}
package org.deafsapps.adventofcode.day04 import java.io.File import java.util.Scanner fun main() { val input = Scanner(File("src/main/resources/day04-data.txt")) val scratchCardList = mutableListOf<ScratchCard>() while (input.hasNext()) { val scratchCardLine = input.nextLine() val (winningNumbers, ownedNumbers) = scratchCardLine.getDataByRegex(regex = """Card.*: (.*)\|(.*)${'$'}""".toRegex()) val scratchCard = ScratchCard(winningNumbers = winningNumbers, ownedNumbers = ownedNumbers) scratchCardList.add(scratchCard) } println(scratchCardList.getNumberOfMatches()) } private fun String.getDataByRegex(regex: Regex): Pair<Set<Int>, Set<Int>> { val match = regex.find(this) ?: return emptySet<Int>() to emptySet() val first = match.groupValues[1].trim().split(""" +""".toRegex()).map { it.toInt() }.toSet() val second = match.groupValues[2].trim().split(""" +""".toRegex()).map { it.toInt() }.toSet() return first to second } private fun List<ScratchCard>.getNumberOfMatches(): Int { var sum = 0 forEach { scratchCard -> var tmpAcc = 0 scratchCard.ownedNumbers.forEach { ownedNumber -> if (scratchCard.winningNumbers.contains(ownedNumber)) { tmpAcc++ } } sum += weightedSum(hits = tmpAcc) } return sum } private fun weightedSum(acc: Int = 0, hits: Int): Int = when (hits) { 0 -> 0 1 -> acc + 1 else -> 2 * weightedSum(acc, hits - 1) } private data class ScratchCard(val winningNumbers: Set<Int>, val ownedNumbers: Set<Int>)
0
Kotlin
0
0
3a7ea1084715ab7c2ab1bfa8a1a7e357aa3c4b40
1,622
advent-of-code_2023
MIT License
src/Day12alt.kt
GarrettShorr
571,769,671
false
{"Kotlin": 82669}
fun main() { data class Point(var row: Int, var col: Int, var height: Int) // fun getNeighbors(r: Int, c: Int, maze: List<List<Int>>) : MutableList<Point> { // val height = maze.size // val width = maze[0].size // var neighbors = mutableListOf<Point>() // for(row in -1..1) { // for(col in -1..1) { // if(r + row < height && r + row >= 0 && c + col < width && c + col >= 0 && !(r==0 && c==0)) { // neighbors.add(Point(r+row, c+col, maze[r+row][c+col])) // } // } // } // return neighbors // } fun getNeighbors(r: Int, c: Int, maze: List<List<Int>>) : MutableList<Point> { val height = maze.size val width = maze[0].size var neighbors = mutableListOf<Point>() if(r + 1 < height) { neighbors.add((Point(r + 1, c, maze[r + 1][c]))) } if(r - 1 >= 0) { neighbors.add((Point(r - 1, c, maze[r - 1][c]))) } if(c + 1 < width) { neighbors.add((Point(r, c + 1, maze[r][c + 1]))) } if(c - 1 >= 0) { neighbors.add(Point(r , c - 1, maze[r][c - 1])) } return neighbors } fun part1(input: List<String>): Int { val START = 'S'.code val END = 'E'.code val maze = input.map { it.windowed(1).map { it.first().toChar().code }.toMutableList() }.toMutableList() // you start at a val locations = mutableListOf<Point>() maze.forEachIndexed { r, nums -> nums.forEachIndexed { c, value -> locations.add(Point(r, c, value)) } } val startLoc = locations.find { it.height == START }!! startLoc.height = 'a'.code maze[startLoc.row][startLoc.col] = 'a'.code val end = locations.find { it.height == END }!! end.height = 'z'.code maze[end.row][end.col] = 'z'.code val distances = mutableMapOf<Point, Int>() val precedingPoints = mutableMapOf<Point, Point?>() locations.forEach { distances[it] = Int.MAX_VALUE precedingPoints[it] = null } // set up start node distances[locations[0]] = 0 val start = locations[0] val locationQueue = mutableListOf<Point>() locationQueue.add(start) val visited = mutableListOf<Point>() while(locationQueue.isNotEmpty()) { val loc = locationQueue.removeAt(0) for(pos in getNeighbors(loc.row, loc.col, maze)) { if(!visited.contains(pos) && loc.height >= pos.height - 1) { distances[pos] = distances[loc]!! + 1 locationQueue.add(pos) visited.add(pos) if(pos.height == END) { break } } } } println(distances[locations.filter { it.row == end.row && it.col == end.col }[0]]) return 0 } fun part2(input: List<String>): Int { return 0 } // test if implementation meets criteria from the description, like: val testInput = readInput("Day12_test") println(part1(testInput)) // println(part2(testInput)) val input = readInput("Day12") output(part1(input)) // output(part2(input)) }
0
Kotlin
0
0
391336623968f210a19797b44d027b05f31484b5
2,990
AdventOfCode2022
Apache License 2.0
src/main/kotlin/aoc2017/ParticleSwarm.kt
komu
113,825,414
false
{"Kotlin": 395919}
package komu.adventofcode.aoc2017 import komu.adventofcode.utils.nonEmptyLines import java.util.Comparator.comparing import kotlin.math.sqrt fun particleSwarmClosest(input: String): Int = Particle.parseAll(input).minWithOrNull(comparing(Particle::accelerationDistance) .thenComparing(Particle::velocityDistance) .thenComparing(Particle::positionDistance))!!.index fun particleSwarmSurvivors(input: String): Int { val particles = Particle.parseAll(input).toMutableList() // 40 is enough simulations to get the correct answer val colliders = mutableSetOf<Particle>() repeat(40) { for (p in particles) p.step() particles.forEachIndexed { index, particle -> if (particle !in colliders) { for (other in particles.subList(index + 1, particles.size)) { if (particle.position == other.position) { colliders.add(particle) colliders.add(other) } } } } particles.removeAll(colliders) colliders.clear() } return particles.size } private class Particle(val index: Int, var position: Vector3, var velocity: Vector3, val acceleration: Vector3) { val accelerationDistance get() = acceleration.distance val velocityDistance get() = velocity.distance val positionDistance get() = position.distance fun step() { velocity += acceleration position += velocity } companion object { private val regex = Regex("""p=(.+), v=(.+), a=(.+)""") fun parseAll(input: String): List<Particle> = input.nonEmptyLines().mapIndexed { index, s -> parse(index, s) } fun parse(index: Int, s: String): Particle { val m = regex.matchEntire(s) ?: error("invalid particle: '$s'") val (_, p, v, a) = m.groupValues return Particle(index, Vector3.parse(p), Vector3.parse(v), Vector3.parse(a)) } } } private data class Vector3(val x: Long, val y: Long, val z: Long) { operator fun plus(v: Vector3) = Vector3(x + v.x, y + v.y, z + v.z) operator fun minus(v: Vector3) = Vector3(x - v.x, y - v.y, z - v.z) val distance: Double = sqrt((x * x + y * y + z * z).toDouble()) companion object { private val regex = Regex("""<(-?\d+),(-?\d+),(-?\d+)>""") fun parse(s: String): Vector3 { val m = regex.matchEntire(s) ?: error("invalid vector: '$s'") val (_, x, y, z) = m.groupValues return Vector3(x.toLong(), y.toLong(), z.toLong()) } } }
0
Kotlin
0
0
8e135f80d65d15dbbee5d2749cccbe098a1bc5d8
2,735
advent-of-code
MIT License
src/Day03.kt
bunjix
573,915,819
false
{"Kotlin": 9977}
import java.io.File fun main() { val input = File("src/Day03_input.txt").readLines() println(part1(input)) println(part2(input)) } fun part1(input: List<String>): Int { return input.sumOf { rucksack -> rucksack.chunked(rucksack.length/2) .let { findSharedLetter(it.first(), it.last()).priority() } } } fun part2(input: List<String>): Int { return input.chunked(3).sumOf { group -> findSharedLetter(group).priority() } } fun findSharedLetter(first: String, last: String): Char { first.forEach { c: Char -> if (last.any { it == c }) return c } throw IllegalStateException("No duplicate char between $first and $last") } fun findSharedLetter(group: List<String>): Char { val first = group.first() val others = group.takeLast(2) return first.first { c: Char -> others.first().contains(c, ignoreCase = false) && others.last().contains(c, ignoreCase = false) } } val upperCase = ('A'..'Z') val lowerCase = ('a'..'z') fun Char.priority(): Int { val priority = lowerCase.indexOf(this) if (priority == -1) { return upperCase.indexOf(this) + 27 } return priority + 1 }
0
Kotlin
0
0
ee2a344f6c0bb2563cdb828485e9a56f2ff08fcc
1,168
aoc-2022-kotlin
Apache License 2.0
src/day7/Day7.kt
pocmo
433,766,909
false
{"Kotlin": 134886}
package day7 import java.io.File import kotlin.math.absoluteValue fun readCrabSubmarines(): List<Int> { return File("day7.txt") .readLines()[0] .split(",") .map { it.toInt() } } fun calculateFuelSimple(crabSubmarines: List<Int>, position: Int): Int { return crabSubmarines.sumOf { current -> (current - position).absoluteValue } } fun calculateFuelComplex(crabSubmarines: List<Int>, position: Int): Int { return crabSubmarines.sumOf { current -> val steps = (current - position).absoluteValue (steps * (steps + 1)) / 2 } } fun List<Int>.findCheapestPosition( calculateFuel: (List<Int>, Int) -> Int ): Pair<Int, Int> { val min = minOrNull() ?: throw IllegalStateException("No min") val max = maxOrNull() ?: throw IllegalStateException("No max") println("Range: $min - $max") var cheapestPosition: Int? = null var fuelNeeded: Int? = null for (position in min..max) { val fuel = calculateFuel(this, position) if (fuelNeeded == null || fuel < fuelNeeded) { cheapestPosition = position fuelNeeded = fuel } } return Pair(cheapestPosition!!, fuelNeeded!!) } fun part2() { val crabSubmarines = readCrabSubmarines() val (position, fuel) = crabSubmarines.findCheapestPosition { submarines, position -> calculateFuelComplex(submarines, position) } println("Position: $position") println("Fuel: $fuel") } fun part1() { val crabSubmarines = readCrabSubmarines() val (position, fuel) = crabSubmarines.findCheapestPosition { submarines, position -> calculateFuelSimple(submarines, position) } println("Position: $position") println("Fuel: $fuel") } fun main() { part2() }
0
Kotlin
1
2
73bbb6a41229e5863e52388a19108041339a864e
1,782
AdventOfCode2021
Apache License 2.0
src/main/kotlin/com/github/ferinagy/adventOfCode/aoc2022/2022-05.kt
ferinagy
432,170,488
false
{"Kotlin": 787586}
package com.github.ferinagy.adventOfCode.aoc2022 import com.github.ferinagy.adventOfCode.println import com.github.ferinagy.adventOfCode.readInputText import com.github.ferinagy.adventOfCode.transpose fun main() { val input = readInputText(2022, "05-input") val testInput1 = readInputText(2022, "05-test1") println("Part1:") part1(testInput1).println() part1(input).println() println() println("Part2:") part2(testInput1).println() part2(input).println() } private fun part1(input: String): String { val (crates, moves) = parse(input) moves.forEach { move -> repeat(move.count) { crates[move.to] += crates[move.from].last() crates[move.from].removeLast() } } return crates.map { it.last() }.joinToString(separator = "") } private fun part2(input: String): String { val (crates, moves) = parse(input) moves.forEach { move -> crates[move.to] += crates[move.from].subList(crates[move.from].size - move.count, crates[move.from].size) repeat(move.count) { crates[move.from].removeLast() } } return crates.map { it.last() }.joinToString(separator = "") } private fun parse(input: String): Pair<List<MutableList<Char>>, List<Move>> { val (start, movesText) = input.split("\n\n") val crates = start.lines().dropLast(1).reversed().map { line -> line.mapIndexedNotNull { index, c -> c.takeIf { (index - 1) % 4 == 0 } } }.transpose().map { it.dropLastWhile { it == ' ' }.toMutableList() } val moves = movesText.lines().map { val (count, from, to) = regex.matchEntire(it)!!.destructured Move(count.toInt(), from.toInt() - 1, to.toInt() - 1) } return Pair(crates, moves) } private val regex = """move (\d+) from (\d+) to (\d+)""".toRegex() private data class Move(val count: Int, val from: Int, val to: Int)
0
Kotlin
0
1
f4890c25841c78784b308db0c814d88cf2de384b
1,922
advent-of-code
MIT License
src/main/kotlin/Problem29.kt
jimmymorales
496,703,114
false
{"Kotlin": 67323}
import kotlin.math.pow /** * Distinct powers * * Consider all integer combinations of ab for 2 ≤ a ≤ 5 and 2 ≤ b ≤ 5: * * 2^2=4, 2^3=8, 2^4=16, 2^5=32 * 3^2=9, 3^3=27, 3^4=81, 3^5=243 * 4^2=16, 4^3=64, 4^4=256, 4^5=1024 * 5^2=25, 5^3=125, 5^4=625, 55^=3125 * If they are then placed in numerical order, with any repeats removed, we get the following sequence of 15 distinct * terms: * * 4, 8, 9, 16, 25, 27, 32, 64, 81, 125, 243, 256, 625, 1024, 3125 * * How many distinct terms are in the sequence generated by ab for 2 ≤ a ≤ 100 and 2 ≤ b ≤ 100? * * https://projecteuler.net/problem=29 */ fun main() { println(distinctPowers(limit = 5)) println(distinctPowers(limit = 100)) } private fun distinctPowers(limit: Int): Int = sequence { for (a in 2..limit) { for (b in 2..limit) { yield(a.toDouble().pow(b)) } } }.distinct().count()
0
Kotlin
0
0
e881cadf85377374e544af0a75cb073c6b496998
911
project-euler
MIT License
src/Day01.kt
armatys
573,477,313
false
{"Kotlin": 4015}
fun main() { fun part1(input: List<String>): Int { return mostCalories(input) } fun part2(input: List<String>): Int { return mostCalories(input, topN = 3) } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") check(part1(testInput) == 24000) check(part2(testInput) == 45000) val input = readInput("Day01") println(part1(input)) println(part2(input)) } private fun mostCalories(lines: List<String>, topN: Int = 1): Int { return lines .map { it.toIntOrNull() } .delimitedByNull() .fold(listOf<Int>()) { acc, calories -> (acc + calories.sum()).sortedDescending().take(topN) }.sum() } private fun <T> List<T?>.delimitedByNull(): Sequence<Sequence<T>> = sequence { var i = 0 while (i <= lastIndex) { yield(generateSequence { getOrNull(i).also { i += 1 } }) } }
0
Kotlin
0
0
95e93f7e10cbcba06e2ef88c1785779fbaa7c90f
966
kotlin-aoc-2022
Apache License 2.0
src/day24/Day24.kt
dkoval
572,138,985
false
{"Kotlin": 86889}
package day24 import readInput import java.util.* private const val DAY_ID = "24" private enum class Direction( val dx: Int, val dy: Int ) { UP(-1, 0), DOWN(1, 0), LEFT(0, -1), RIGHT(0, 1); companion object { fun fromChar(c: Char): Direction = when (c) { '^' -> UP 'v' -> DOWN '<' -> LEFT '>' -> RIGHT else -> error("Unknown direction: $c") } } } private data class Position( val row: Int, val col: Int ) { fun isInBounds(numRows: Int, numCols: Int): Boolean = (row in 0 until numRows) && (col in 0 until numCols) fun next(direction: Direction): Position = Position(row + direction.dx, col + direction.dy) fun nextCircular(d: Direction, numRows: Int, numCols: Int): Position { // wrap around, if needed fun mod(x: Int, m: Int): Int = if (x < 0) (m - (-x) % m) % m else x % m return Position(mod(row + d.dx, numRows), mod(col + d.dy, numCols)) } } private data class TimedPosition( val time: Int, val position: Position ) { fun next(direction: Direction): TimedPosition = TimedPosition(time + 1, position.next(direction)) } private data class Blizzard( val position: Position, val direction: Direction ) private data class Grid( val start: Position, val goal: Position, val blizzards: Set<Blizzard>, val numRows: Int, val numCols: Int ) fun main() { fun parseInput(input: List<String>): Grid { val n = input.size // ignore surrounding '#' val numRows = n - 2 val numCols = input[0].length - 2 val source = Position(-1, input[0].indexOf('.') - 1) val target = Position(numRows, input[n - 1].indexOf('.') - 1) val blizzards = mutableSetOf<Blizzard>() for (row in 0 until numRows) { for (col in 0 until numCols) { val c = input[row + 1][col + 1] if (c != '.') { blizzards += Blizzard(Position(row, col), Direction.fromChar(c)) } } } return Grid(source, target, blizzards, numRows, numCols) } fun part1(input: List<String>): Int { val grid = parseInput(input) fun gcd(a: Int, b: Int): Int = if (b == 0) a else gcd(b, a % b) fun lcm(a: Int, b: Int): Int = a * b / gcd(a, b) // generate all possible states blizzards can be in val period = lcm(grid.numRows, grid.numCols) val states = mutableListOf(grid.blizzards) for (i in 1 until period) { val prev = states[i - 1] val curr = mutableSetOf<Blizzard>() // move blizzards for ((position, direction) in prev) { val newPosition = position.nextCircular(direction, grid.numRows, grid.numCols) curr += Blizzard(newPosition, direction) } states += curr } fun occupiedByBlizzards(position: Position, time: Int): Boolean { val blizzards = states[time % period] return Direction.values().any { Blizzard(position, it) in blizzards } } fun solve(start: Position, goal: Position, time: Int): Int { // BFS val q: Queue<TimedPosition> = ArrayDeque() val visited = mutableSetOf<TimedPosition>() fun enqueue(item: TimedPosition) { q.offer(item) visited += item } enqueue(TimedPosition(time, start)) while (!q.isEmpty()) { val curr = q.poll() // move in each possible direction for (direction in Direction.values()) { val next = curr.next(direction) if (next.position == goal) { return next.time } if (!next.position.isInBounds(grid.numRows, grid.numCols) || next in visited) { continue } if (!occupiedByBlizzards(next.position, next.time)) { enqueue(next) } } // wait in place if (!occupiedByBlizzards(curr.position, curr.time + 1)) { enqueue(TimedPosition(curr.time + 1, curr.position)) } } error("Couldn't find the shortest path from $start to $goal") } return solve(grid.start, grid.goal, 0) } fun part2(input: List<String>): Int { val grid = parseInput(input) fun gcd(a: Int, b: Int): Int = if (b == 0) a else gcd(b, a % b) fun lcm(a: Int, b: Int): Int = a * b / gcd(a, b) // generate all possible states blizzards can be in val period = lcm(grid.numRows, grid.numCols) val states = mutableListOf(grid.blizzards) for (i in 1 until period) { val prev = states[i - 1] val curr = mutableSetOf<Blizzard>() // move blizzards for ((position, direction) in prev) { val newPosition = position.nextCircular(direction, grid.numRows, grid.numCols) curr += Blizzard(newPosition, direction) } states += curr } fun occupiedByBlizzards(position: Position, time: Int): Boolean { val blizzards = states[time % period] return Direction.values().any { Blizzard(position, it) in blizzards } } fun solve(start: Position, goal: Position): Int { // BFS val q: Queue<Pair<TimedPosition, Int>> = ArrayDeque() val visited = mutableSetOf<Pair<TimedPosition, Int>>() fun enqueue(item: Pair<TimedPosition, Int>) { q.offer(item) visited += item } // extra `pass` argument in the state: // 0 - 1st trip from start to goal // 1 - trip back from goal to start // 2 - trip back from start to goal again enqueue(TimedPosition(0, start) to 0) while (!q.isEmpty()) { val (curr, pass) = q.poll() // move in each possible direction for (direction in Direction.values()) { val next = curr.next(direction) when { next.position == goal && (pass == 0 || pass == 2) -> { if (pass == 0) { // now trip back to the start q.offer(next to 1) } else { return next.time } } next.position == start && pass == 1 -> { // trip back to the goal again q.offer(next to 2) break } else -> { if (!next.position.isInBounds(grid.numRows, grid.numCols) || occupiedByBlizzards(next.position, next.time) ) { continue } val nextState = next to pass if (nextState !in visited) { enqueue(nextState) } } } } // wait in place if (!occupiedByBlizzards(curr.position, curr.time + 1)) { enqueue(TimedPosition(curr.time + 1, curr.position) to pass) } } error("Couldn't find the shortest path from $start to $goal") } return solve(grid.start, grid.goal) } // test if implementation meets criteria from the description, like: val testInput = readInput("day${DAY_ID}/Day${DAY_ID}_test") check(part1(testInput) == 18) check(part2(testInput) == 54) val input = readInput("day${DAY_ID}/Day${DAY_ID}") println(part1(input)) // answer = 292 println(part2(input)) // answer = 816 }
0
Kotlin
1
0
791dd54a4e23f937d5fc16d46d85577d91b1507a
8,289
aoc-2022-in-kotlin
Apache License 2.0
src/main/kotlin/at/mpichler/aoc/solutions/year2022/Day11.kt
mpichler94
656,873,940
false
{"Kotlin": 196457}
package at.mpichler.aoc.solutions.year2022 import at.mpichler.aoc.lib.Day import at.mpichler.aoc.lib.PartSolution open class Part11A : PartSolution() { internal lateinit var monkeys: MutableList<Monkey> internal open val numRounds = 20 override fun parseInput(text: String) { val lines = text.trim().split("\n") monkeys = mutableListOf() for (i in lines.indices step 7) { val items = lines[i + 1].substring(18).split(", ").map { it.toLong() }.toMutableList() val op = if (lines[i + 2].substring(23, 24) == Monkey.Operation.ADD.value) { Monkey.Operation.ADD } else { Monkey.Operation.MUL } val operand = lines[i + 2].substring(25).toIntOrNull() ?: 0 val divisor = lines[i + 3].substring(21).toLong() val trueNum = lines[i + 4].substring(29).toInt() val falseNum = lines[i + 5].substring(30).toInt() monkeys.add(Monkey(items, op, operand, divisor, trueNum, falseNum)) } } override fun compute(): Long { repeat(numRounds) { monkeys.forEach { it.round(monkeys) } } val counts = monkeys.map { it.count }.toMutableList() counts.sort() return counts.takeLast(2).reduce { acc, i -> acc * i } } override fun getExampleAnswer(): Any { return 10_605 } internal data class Monkey( private val items: MutableList<Long>, private val operation: Operation, private val operand: Int, private val divisor: Long, val trueNum: Int, val falseNum: Int, var relief: Boolean = true ) { private var fac = 0L internal var count = 0L private set private fun addItem(item: Long) { items.add(item) } fun round(monkeys: List<Monkey>) { fac = monkeys.map { it.divisor }.reduce { acc, i -> acc * i } while (items.isNotEmpty()) { processItem(monkeys, items.removeFirst()) } } private fun processItem(monkeys: List<Monkey>, item: Long) { count += 1 var newValue = operation.exec(item, operand) if (relief) { newValue /= 3 } else { newValue %= fac } if (newValue % divisor == 0L) { monkeys[trueNum].addItem(newValue) } else { monkeys[falseNum].addItem(newValue) } } enum class Operation(val value: String) { ADD("+") { override fun exec(old: Long, operand: Int): Long { if (operand == 0) { return 2 * old } return old + operand } }, MUL("*") { override fun exec(old: Long, operand: Int): Long { if (operand == 0) { return old * old } return old * operand } }; abstract fun exec(old: Long, operand: Int): Long } } } class Part11B : Part11A() { override val numRounds = 10_000 override fun config() { monkeys.forEach { it.relief = false } } override fun getExampleAnswer(): Long { return 2_713_310_158 } } fun main() { Day(2022, 11, Part11A(), Part11B()) }
0
Kotlin
0
0
69a0748ed640cf80301d8d93f25fb23cc367819c
3,515
advent-of-code-kotlin
MIT License
src/day06/Day06.kt
ivanovmeya
573,150,306
false
{"Kotlin": 43768}
package day06 import readInput fun main() { /** * As groupBy practically creates a map for each substring * performance: O(n) * space complexity: n/markerLength times allocation of markerLength map (LinkedHashMap) * (each time is eligible for GC after moving forward) */ fun areSymbolsUnique(substring: String, markerLength: Int): Boolean { return substring.groupBy { it }.size == markerLength } fun findMarkerStart(dataStream: String, markerLength: Int): Int { val markerIndex = dataStream.windowed(markerLength, 1).indexOfFirst { areSymbolsUnique(it, markerLength) } return markerIndex } fun areSymbolsUnique(charFrequencies: HashMap<Char, Int>, markerLength: Int): Boolean { //if all characters occurs exactly once -> then they are all unique return charFrequencies.filterValues { charFreq -> charFreq == 1 }.size == markerLength } fun HashMap<Char, Int>.addChar(charToAdd: Char) { this[charToAdd] = this[charToAdd]?.let { it + 1 } ?: 1 } fun HashMap<Char, Int>.removeChar(charToRemove: Char) { this[charToRemove] = this[charToRemove]?.let { it - 1 } ?: 0 } /** * Sliding window approach with char frequencies in hashMap adjustments * performance: O(n) * space complexity: O(C) at worst case map with 25 keys (25 - English lowercase alphabet size) */ fun findMarkerStartOptimized(dataStream: String, markerLength: Int): Int { if (dataStream.length < markerLength) throw IllegalArgumentException("Hey Elfs, the dataStream is too short") var startIndex = 0 var endIndex = markerLength - 1 val charFrequencies = hashMapOf<Char, Int>() //build initial charFrequencies var i = 0 while (i <= endIndex) { charFrequencies.addChar(charToAdd = dataStream[i]) i++ } //go with a flow while (endIndex + 1 < dataStream.length) { val areUnique = areSymbolsUnique(charFrequencies, markerLength) if (areUnique) return endIndex + 1 - markerLength charFrequencies.removeChar(dataStream[startIndex]) charFrequencies.addChar(dataStream[endIndex + 1]) startIndex++ endIndex++ } return -1 } fun part1(input: List<String>): Int { val markerLength = 4 return findMarkerStartOptimized( dataStream = input[0], markerLength = markerLength ) + markerLength } fun part2(input: List<String>): Int { val markerLength = 14 return findMarkerStartOptimized( dataStream = input[0], markerLength = markerLength ) + markerLength } val testInput = readInput("day06/input_test") val test1Result = part1(testInput) val test2Result = part2(testInput) println(test1Result) println(test2Result) check(test1Result == 7) check(test2Result == 19) val input = readInput("day06/input") val part1 = part1(input) val part2 = part2(input) println(part1) println(part2) check(part1 == 1848) check(part2 == 2308) }
0
Kotlin
0
0
7530367fb453f012249f1dc37869f950bda018e0
3,222
advent-of-code-2022
Apache License 2.0
src/Day17.kt
inssein
573,116,957
false
{"Kotlin": 47333}
import kotlin.math.max fun main() { fun List<String>.toJetDeltas() = this.first().map { if (it == '>') 1 else -1 } val rocks = listOf( listOf(Pair(0, 0), Pair(1, 0), Pair(2, 0), Pair(3, 0)), listOf(Pair(1, 0), Pair(0, 1), Pair(1, 1), Pair(2, 1), Pair(1, 2)), listOf(Pair(0, 0), Pair(1, 0), Pair(2, 0), Pair(2, 1), Pair(2, 2)), listOf(Pair(0, 0), Pair(0, 1), Pair(0, 2), Pair(0, 3)), listOf(Pair(0, 0), Pair(0, 1), Pair(1, 0), Pair(1, 1)) ) fun List<Pair<Int, Int>>.canPushTo(toX: Int, toY: Int, chamber: Set<Pair<Int, Int>>) = this.map { (x, y) -> x + toX to y + toY }.all { it.first in 0..6 && !chamber.contains(it) } fun List<Pair<Int, Int>>.canDropDown(toX: Int, toY: Int, dropped: Set<Pair<Int, Int>>) = toY > 1 && this.map { (x, y) -> x + toX to y + toY - 1 }.none { dropped.contains(it) } fun drop(jetDeltas: List<Int>, numRocks: Long): Long { var floor = 0 var jetOffset = 0 val cache = mutableMapOf<Pair<Int, Int>, Pair<Int, Int>>() val chamber = mutableSetOf<Pair<Int, Int>>() for (i in 0 until numRocks) { val rockIndex = (i % 5).toInt() val rock = rocks[rockIndex] var rockX = 2 var rockY = floor + 4 while (true) { val jetIndex = jetOffset++ % jetDeltas.size val cached = cache[rockIndex to jetIndex] if (cached != null) { val (prevRockNum, elevation) = cached val period = i - prevRockNum // @note: not sure if this is the best way to detect a cycle if (i > jetDeltas.size * 3 && i % period == numRocks % period) { val cycleHeight = floor - elevation val rocksRemaining = numRocks - i val cyclesRemaining = (rocksRemaining / period) + 1 return elevation + (cycleHeight * cyclesRemaining) } } else { cache[rockIndex to jetIndex] = i.toInt() to floor } val pushTo = rockX + jetDeltas[jetIndex] if (rock.canPushTo(pushTo, rockY, chamber)) { rockX = pushTo } if (rock.canDropDown(rockX, rockY, chamber)) { rockY-- } else { val toAdd = rock.map { (x, y) -> x + rockX to y + rockY } floor = max(floor, toAdd.maxOf { (_, y) -> y }) chamber.addAll(toAdd) break } } } return floor.toLong() } fun part1(input: List<String>): Long { return drop(input.toJetDeltas(), 2022) } fun part2(input: List<String>): Long { return drop(input.toJetDeltas(), 1_000_000_000_000) } val testInput = readInput("Day17_test") println(part1(testInput)) // 3068 println(part2(testInput)) // 1514285714288 val input = readInput("Day17") println(part1(input)) // 3092 println(part2(input)) // 1528323699442 }
0
Kotlin
0
0
095d8f8e06230ab713d9ffba4cd13b87469f5cd5
3,186
advent-of-code-2022
Apache License 2.0
src/Day03.kt
OskarWalczak
573,349,185
false
{"Kotlin": 22486}
fun main() { fun getItemPriority(item: Char) : Int { val charVal = item.code if (charVal in 'a'.code .. 'z'.code) return charVal - 'a'.code + 1 if(charVal in 'A'.code .. 'Z'.code) return charVal - 'A'.code + 27 return 0 } fun part1(input: List<String>): Int { var sum: Int = 0 input.forEach { line -> val comp1: String = line.substring(0, line.length/2) val comp2: String = line.substring(line.length/2) for(c: Char in comp1){ if(comp2.contains(c)){ sum += getItemPriority(c) break } } } return sum } fun part2(input: List<String>): Int { var sum: Int = 0 for(i: Int in input.indices step 3){ val ruck1: String = input[i] val ruck2: String = input[i+1] val ruck3: String = input[i+2] for(c: Char in ruck1){ if(ruck2.contains(c) && ruck3.contains(c)){ sum += getItemPriority(c) break } } } return sum } // test if implementation meets criteria from the description, like: val testInput = readInput("Day03_test") check(part1(testInput) == 157) val input = readInput("Day03") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
d34138860184b616771159984eb741dc37461705
1,451
AoC2022
Apache License 2.0
src/main/kotlin/org/example/e3fxgaming/adventOfCode/aoc2023/day07/Day07.kt
E3FxGaming
726,041,587
false
{"Kotlin": 38290}
package org.example.e3fxgaming.adventOfCode.aoc2023.day07 import org.example.e3fxgaming.adventOfCode.utility.Day import org.example.e3fxgaming.adventOfCode.utility.IndividualLineInputParser import org.example.e3fxgaming.adventOfCode.utility.InputParser class Day07(input: String) : Day<Pair<String, Int>, Pair<String, Int>> { private abstract class CardComparator : Comparator<String> { protected enum class HandType { HighCard, OnePair, TwoPair, ThreeOfAKind, FullHouse, FourOfAKind, FiveOfAKind } protected fun Map<Int, List<Char>>.handType(): HandType = when { 5 in this -> HandType.FiveOfAKind 4 in this -> HandType.FourOfAKind 3 in this -> if (2 in this) HandType.FullHouse else HandType.ThreeOfAKind this[2]?.size == 2 -> HandType.TwoPair this[2]?.size == 1 && this[1]?.size == 3 -> HandType.OnePair this[1]?.size == 5 -> HandType.HighCard else -> throw IllegalStateException("HandType could not be determined: $this") } protected abstract val cardStrength: List<Char> protected fun countToCardsToResult( o1: String, o2: String, o1CountToCards: Map<Int, List<Char>>, o2CountToCards: Map<Int, List<Char>> ): Int { val o1HandType = o1CountToCards.handType() val o2HandType = o2CountToCards.handType() if (o1HandType != o2HandType) return o1HandType.ordinal - o2HandType.ordinal return o1.zip(o2).firstNotNullOf { val result = cardStrength.indexOf(it.first) - cardStrength.indexOf(it.second) if (result != 0) result else null } } } private class CardComparatorPart1 : CardComparator() { override val cardStrength = listOf('2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A') private fun String.countToCards() = groupingBy { it }.eachCount().asIterable().groupBy( { it.value }, { it.key } ) override fun compare(o1: String, o2: String): Int { val o1CountToCards = o1.countToCards() val o2CountToCards = o2.countToCards() return countToCardsToResult(o1, o2, o1CountToCards, o2CountToCards) } } private class CardComparatorPart2 : CardComparator() { override val cardStrength = listOf('J', '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'Q', 'K', 'A') private fun Map<Char, Int>.improveWithJoker(): Map<Char, Int> { if ('J' !in this || size == 1) return this val withoutJoker = (this - 'J').toMutableMap() val jokerCount = this.getValue('J') val improveEntry = withoutJoker.entries.reduce { largestEntrySoFar, currentEntry -> if (largestEntrySoFar.value < currentEntry.value) { currentEntry } else largestEntrySoFar } withoutJoker[improveEntry.key] = improveEntry.value + jokerCount return withoutJoker } override fun compare(o1: String, o2: String): Int { val o1CharCount = o1.groupingBy { it }.eachCount() val o2CharCount = o2.groupingBy { it }.eachCount() val o1Improved = o1CharCount.improveWithJoker() val o2Improved = o2CharCount.improveWithJoker() val o1CountToCards = o1Improved.asIterable().groupBy( { it.value }, { it.key } ) val o2CountToCards = o2Improved.asIterable().groupBy( { it.value }, { it.key } ) return countToCardsToResult(o1, o2, o1CountToCards, o2CountToCards) } } override val partOneParser: InputParser<Pair<String, Int>> = object : IndividualLineInputParser<Pair<String, Int>>( input ) { override fun parseLine(line: String): Pair<String, Int> = line.split(' ').let { it[0].trim() to it[1].toInt() } } override val partTwoParser: InputParser<Pair<String, Int>> = partOneParser override fun solveFirst(given: List<Pair<String, Int>>): String = solve(given, CardComparatorPart1()) override fun solveSecond(given: List<Pair<String, Int>>): String = solve(given, CardComparatorPart2()) private fun solve(given: List<Pair<String, Int>>, comparator: CardComparator): String { val sortedHands = given.sortedWith(java.util.Comparator.comparing({ it.first }, comparator)) return sortedHands.foldIndexed(0L) { rankMinusOne, result, (_, bid) -> result + ((rankMinusOne + 1) * bid) }.toString() } } fun main() = Day07( Day07::class.java.getResource("/2023/day07/realInput1.txt")!!.readText() ).runBoth()
0
Kotlin
0
0
3ae9e8b60788733d8bc3f6446d7a9ae4b3dabbc0
4,827
adventOfCode
MIT License
ceria/05/src/main/kotlin/Solution.kt
VisionistInc
572,963,504
false
null
import java.io.File; import java.util.Stack fun main(args : Array<String>) { var input = File(args.first()).readLines() var bottomIndex = 0 var numStacks = 0 run findBottomsLine@ { input.forEachIndexed { index, line -> if (!line.contains("[")) { bottomIndex = index - 1 numStacks = line.trim().toList().last().digitToInt() return@findBottomsLine } } } var listOfStacks = mutableListOf<Stack<Char>>() repeat (numStacks) { listOfStacks.add(Stack<Char>()) } var listOfLists = mutableListOf<MutableList<Char>>() repeat (numStacks) { listOfLists.add(mutableListOf<Char>()) } for (i in bottomIndex downTo 0) { var line = input.get(i).toList() var index = 1 for (x in 0..numStacks-1) { var crate = line.get(index) if (!crate.equals(' ')) { listOfStacks.get(x).add(crate) listOfLists.get(x).add(crate) } index += 4 } } // first = how many, second = from stack, third = to stack var listOfMoves = mutableListOf<Triple<Int, Int, Int>>() for (y in bottomIndex + 3..input.size - 1) { var currLine = input.get(y).split(' ') listOfMoves.add(Triple<Int, Int, Int>(currLine.get(1).toInt(), currLine.get(3).toInt(), currLine.get(5).toInt())) } println("Solution 1: ${solution1(listOfStacks, listOfMoves)}") println("Solution 2: ${solution2(listOfLists, listOfMoves)}") } private fun solution1(stacks: List<Stack<Char>>, moves: List<Triple<Int, Int, Int>>) :String { moves.forEach { move -> repeat(move.first) { stacks.get(move.third - 1).push(stacks.get(move.second - 1).pop()) } } return stacks.filter { !it.isEmpty() }.map { it.last().toString() }.joinToString("") } private fun solution2(lists: MutableList<MutableList<Char>>, moves: List<Triple<Int, Int, Int>>) :String { moves.forEach { move -> var fromList = lists.get(move.second -1) lists.get(move.third - 1).addAll(fromList.takeLast(move.first)) lists.set(move.second -1, fromList.dropLast(move.first).toMutableList()) } return lists.filter { !it.isEmpty() }.map { it.last().toString() }.joinToString("") }
0
Rust
0
0
90b348d9c8060a8e967fe1605516e9c126fc7a56
2,408
advent-of-code-2022
MIT License
src/Day05.kt
daividssilverio
572,944,347
false
{"Kotlin": 10575}
private fun buildStacksInfo(stackInput: List<String>): Map<Int, List<String>> { val stacks = mutableMapOf<Int, List<String>>() val iterator = stackInput.iterator() while (iterator.hasNext()) { val line = iterator.next() if (!iterator.hasNext()) break line.chunked(4).forEachIndexed { index, item -> stacks.compute(index + 1) { _, stack -> if (item.isNotBlank()) { listOf(item) + (stack ?: emptyList()) } else stack } } } return stacks } private fun operateMover( stacks: Map<Int, List<String>>, commands: List<String>, moveEngine: (MutableMap<Int, List<String>>, Int, Int, Int) -> Map<Int, List<String>> ): Map<Int, List<String>> { val regex = Regex("move (\\d+) from (\\d+) to (\\d+)") var localStacks = stacks for (command in commands) { val (count, source, destination) = regex.find(command)!!.destructured.toList().map { it.toInt() } localStacks = moveEngine(localStacks.toMutableMap(), count, source, destination) } return localStacks } private fun printTopOfStacks(stacks: Map<Int, List<String>>) { println(stacks.toSortedMap() .mapValues { it.value.last().replace("[", "").replace("]", "").trim() } .values .joinToString(separator = "") ) } fun main() { val input = readInput("Day05_test") val indexOfStartOfCommands = input.indexOfFirst { it.isBlank() } + 1 val startingStacks = buildStacksInfo(input.subList(0, indexOfStartOfCommands)) val commands = input.drop(indexOfStartOfCommands) val mover9000resultingStacks = operateMover(startingStacks, commands) { stacks, count, source, destination -> repeat(count) { val toMove = stacks[source]?.takeLast(1) ?: emptyList() stacks[source] = stacks[source]?.dropLast(1) ?: emptyList() stacks[destination] = (stacks[destination] ?: emptyList()) + toMove } stacks } val mover9001resultingStacks = operateMover(startingStacks, commands) { stacks, count, source, destination -> val toMove = stacks[source]?.takeLast(count) ?: emptyList() stacks[source] = stacks[source]?.dropLast(count) ?: emptyList() stacks[destination] = (stacks[destination] ?: emptyList()) + toMove stacks } printTopOfStacks(mover9000resultingStacks) printTopOfStacks(mover9001resultingStacks) }
0
Kotlin
0
0
141236c67fe03692785e0f3ab90248064a1693da
2,465
advent-of-code-kotlin-2022
Apache License 2.0
src/dynamicprogramming/EditDistance.kt
faniabdullah
382,893,751
false
null
package dynamicprogramming class EditDistance { fun minDistance(word1: String, word2: String): Int { val dp = Array(word1.length + 1) { IntArray(word2.length + 1) { 0 } } for (i in dp.indices) { for (j in dp[i].indices) { when { i == 0 -> { dp[i][j] = j } j == 0 -> { dp[i][j] = i } word1[i - 1] == word2[j - 1] -> { dp[i][j] = dp[i - 1][j - 1] } else -> { dp[i][j] = minOf(dp[i][j - 1], dp[i - 1][j - 1], dp[i - 1][j]) + 1 } } } } repeat(dp.count()) { println(dp[it].contentToString()) } return dp[dp.size - 1][dp[0].size - 1] } fun editDistDP( str1: String, str2: String, m: Int, n: Int ): Int { // Create a table to store results of subproblems val dp = Array(m + 1) { IntArray(n + 1) } // Fill d[][] in bottom up manner for (i in 0..m) { for (j in 0..n) { when { i == 0 -> dp[i][j] = j j == 0 -> dp[i][j] = i str1[i - 1] == str2[j - 1] -> dp[i][j] = dp[i - 1][j - 1] else -> dp[i][j] = (1 + minOf( dp[i][j - 1], dp[i - 1][j], dp[i - 1][j - 1] )) } } } repeat(dp.count()) { println(dp[it].contentToString()) } return dp[m][n] } } fun main() { val str1 = "zoologicoarchaeologist" val str2 = "zoogeologist" val result = EditDistance().minDistance(str1, str2) println("result 2") val result2 = EditDistance().editDistDP(str1, str2, str1.length, str2.length) }
0
Kotlin
0
6
ecf14fe132824e944818fda1123f1c7796c30532
1,941
dsa-kotlin
MIT License
2021/3/Diagnostic.kts
marcoscarceles
317,996,390
false
{"Python": 43384, "Kotlin": 4294}
#!/usr/bin/env kscript fun List<Any>.half():Double = (this.size / 2.0) fun List<Int>.toInt(): Int = this.reversed().withIndex().map { it.value * Math.pow(2.0, it.index.toDouble()) }.toList().sum().toInt() fun getSummary(diagnostic: List<List<Int>>): List<Int> = diagnostic.reduce { acc, next -> acc.zip(next) { a, b -> a + b } } fun getMostFrequent(diagnostic: List<List<Int>>): List<Int> = getSummary(diagnostic).map { if (it >= diagnostic.half()) 1 else 0 } fun getLeastFrequent(diagnostic: List<List<Int>>): List<Int> = getSummary(diagnostic).map { if (it >= diagnostic.half()) 0 else 1 } fun filterByRating(diagnostic: List<List<Int>>, reference: (List<List<Int>>) -> List<Int>): List<Int> = (0..diagnostic[0].size - 1).fold(diagnostic) { acc, i -> val filter = reference(acc) val match = acc.filter { it[i] == filter[i] } // println(""" // ======================== // --- Comparing // ${acc} // ---- Against // ${filter}[${i}] = ${filter[i]} // ---- Match // ${match} // """.trimIndent()) if (match.size > 0) match else listOf(acc.first()) }.first() /** * Part 1 */ val diagnostic = generateSequence(::readLine) .map { it.chunked(1) } .map { it.map(String::toInt) } .toList() println("--------") diagnostic.forEach(::println) println("--------") val gammaArray = getMostFrequent(diagnostic) val epsilonArray = getLeastFrequent(diagnostic) val gamma = gammaArray.toInt() val epsilon = epsilonArray.toInt() println("Gammma: $gamma * Epsilon: $epsilon = ${gamma * epsilon}") /** * Part 2 */ println("Diagnostics") println(diagnostic.map { it.toInt() }) println("Getting oxygen ...") val oxygen = filterByRating(diagnostic, this::getMostFrequent).toInt() println("Getting co2 ...") val co2 = filterByRating(diagnostic, this::getLeastFrequent).toInt() println("oxygen: $oxygen * co2: $co2 = ${oxygen * co2}")
0
Python
0
0
c21c977f029bbe403bf107de1c5294d31d90a686
2,090
adventofcode
MIT License
y2019/src/main/kotlin/adventofcode/y2019/Day20.kt
Ruud-Wiegers
434,225,587
false
{"Kotlin": 503769}
package adventofcode.y2019 import adventofcode.io.AdventSolution import adventofcode.util.vector.Direction import adventofcode.util.vector.Vec2 import java.util.* fun main() { Day20.solve() } object Day20 : AdventSolution(2019, 20, "Donut maze") { override fun solvePartOne(input: String): Any { val (floor, labels) = readMaze(input) val portals = labelPortals(floor, labels, Direction.RIGHT) + labelPortals(floor, labels, Direction.DOWN) val portalNeighbors = portals .asSequence() .mapNotNull { (entrance, entranceName) -> portals.asSequence() .find { (exit, exitName) -> entrance != exit && entranceName == exitName } ?.key ?.let { entrance to it } } .toMap() val vs = Direction.values().map { it.vector } fun neighbors(p: Vec2) = vs.map { it + p } .filter { it in floor } + portalNeighbors[p]?.let { listOf(it) }.orEmpty() val start = portals.asSequence().first { it.value == "AA" }.key val goal = portals.asSequence().first { it.value == "ZZ" }.key var open = listOf(start) val closed = mutableSetOf<Vec2>() var count = 0 while (open.isNotEmpty()) { count++ closed += open open = open.flatMap { neighbors(it) }.filter { it !in closed } if (goal in open) return count } return "failed" } private fun findPortalLinks(portals: Map<Vec2, String>): Map<Vec2, Vec2> = portals .asSequence() .mapNotNull { (entrance, entranceName) -> portals.asSequence() .find { (exit, exitName) -> entrance != exit && entranceName == exitName } ?.key ?.let { entrance to it } } .toMap() private fun labelPortals(floor: Set<Vec2>, labels: Map<Vec2, Char>, direction: Direction): Map<Vec2, String> = labels .filterKeys { k -> k + direction.vector in labels } .mapValues { (k, v) -> v.toString() + labels.getValue(k + direction.vector) } .mapKeys { it.key + if (it.key + direction.reverse.vector in floor) direction.reverse.vector else direction.vector * 2 } private fun readMaze(input: String): Pair<Set<Vec2>, Map<Vec2, Char>> { val floor = mutableSetOf<Vec2>() val objectAtLocation = mutableMapOf<Vec2, Char>() input.lines().forEachIndexed { y, line -> line.forEachIndexed { x, ch -> when (ch) { '.' -> floor += Vec2(x, y) ' ', '#' -> { } else -> objectAtLocation[Vec2(x, y)] = ch } } } return Pair(floor, objectAtLocation) } private fun bfs(floor: Set<Vec2>, portals: Map<Vec2, String>, start: Vec2): Map<Vec2, Int> { val vs = Direction.values().map { it.vector } fun neighbors(p: Vec2) = vs.map { it + p } .filter { it in floor } val found = mutableMapOf<Vec2, Int>() var open = listOf(start) val closed = mutableSetOf<Vec2>() var count = 0 while (open.isNotEmpty()) { count++ closed += open open = open.flatMap { neighbors(it) }.filter { it !in closed } open.filter { it in portals.keys }.forEach { found[it] = count } } return found } override fun solvePartTwo(input: String): Int { val (floor, labels) = readMaze(input) val portals = labelPortals(floor, labels, Direction.RIGHT) + labelPortals(floor, labels, Direction.DOWN) fun Vec2.isInside() = x == 34 || y == 34 || x == 92 || y == 92 val links = findPortalLinks(portals) .mapValues { (entrance, exit) -> if (entrance.isInside()) Pair(exit, 1) else Pair(exit, -1) } val distanceMap = portals.keys.associateWith { bfs(floor, portals, it) } val start = portals.asSequence().first { it.value == "AA" }.key val goal = portals.asSequence().first { it.value == "ZZ" }.key val open = PriorityQueue<Pair<State, Int>>(compareBy { it.second }) val closed = mutableSetOf<State>() open.add(State(start, 0) to 0) while (open.isNotEmpty()) { val (candidate, distance) = open.poll() closed += candidate distanceMap[candidate.pos].orEmpty().mapNotNull { (entrance, delta) -> if (entrance == goal && candidate.floor == 0) return distance + delta val (exit, fDelta) = links[entrance] ?: return@mapNotNull null if (candidate.floor + fDelta < 0) return@mapNotNull null State(exit, candidate.floor + fDelta) to distance + delta + 1 } .forEach { open += it } } return -closed.size } } data class State(val pos: Vec2, val floor: Int)
0
Kotlin
0
3
fc35e6d5feeabdc18c86aba428abcf23d880c450
5,102
advent-of-code
MIT License
year2022/src/main/kotlin/net/olegg/aoc/year2022/day13/Day13.kt
0legg
110,665,187
false
{"Kotlin": 511989}
package net.olegg.aoc.year2022.day13 import net.olegg.aoc.someday.SomeDay import net.olegg.aoc.utils.toPair import net.olegg.aoc.year2022.DayOf2022 import net.olegg.aoc.year2022.day13.Day13.Node.Collection import net.olegg.aoc.year2022.day13.Day13.Node.Value /** * See [Year 2022, Day 13](https://adventofcode.com/2022/day/13) */ object Day13 : DayOf2022(13) { override fun first(): Any? { val inputs = data .split("\n\n") .map { it.lines().toPair() } return inputs .map { (first, second) -> parseLine(first) to parseLine(second) } .withIndex() .filter { (_, value) -> value.first < value.second } .sumOf { it.index + 1 } } override fun second(): Any? { val two = parseLine("[[2]]") val six = parseLine("[[6]]") val inputs = lines .filter { it.isNotBlank() } .map { parseLine(it) } .plus(listOf(two, six)) .sorted() return (inputs.indexOf(two) + 1) * (inputs.indexOf(six) + 1) } private fun parseLine(line: String): Node { val queue = ArrayDeque(line.toList()) val stack = ArrayDeque<MutableList<Node>>() stack.add(mutableListOf()) while (queue.isNotEmpty()) { when (val top = queue.removeFirst()) { '[' -> { stack.add(mutableListOf()) } ']' -> { val items = stack.removeLast() stack.last().add( Collection(items), ) } in '0'..'9' -> { val number = buildString { append(top) while (queue.isNotEmpty() && queue.first() in '0'..'9') { append(queue.removeFirst()) } }.toInt() stack.last().add( Value(number), ) } else -> Unit } } return stack.first().first() } sealed interface Node : Comparable<Node> { data class Value( val value: Int, ) : Node { override fun compareTo(other: Node): Int { return when (other) { is Value -> value - other.value is Collection -> Collection(listOf(this)).compareTo(other) } } } data class Collection( val values: List<Node>, ) : Node { override fun compareTo(other: Node): Int { return when (other) { is Value -> this.compareTo(Collection(listOf(other))) is Collection -> { val maybeDiff = values.zip(other.values).firstOrNull { (first, second) -> first.compareTo(second) != 0 } when { maybeDiff != null -> maybeDiff.first.compareTo(maybeDiff.second) else -> values.size - other.values.size } } } } } } } fun main() = SomeDay.mainify(Day13)
0
Kotlin
1
7
e4a356079eb3a7f616f4c710fe1dfe781fc78b1a
2,762
adventofcode
MIT License
src/main/kotlin/day8/Day08.kt
Avataw
572,709,044
false
{"Kotlin": 99761}
package day8 fun solveA(input: List<String>): Int { val columns = input.getRows() return input.mapIndexed { y, line -> line.filterIndexed { x, tree -> val height = tree.digitToInt() findOutwardTrees(input, columns, x, y).any { it.checkVisibility(height) } }.length }.sum() } fun solveB(input: List<String>): Int { val columns = input.getRows() return input.mapIndexed { y, line -> line.mapIndexed { x, tree -> val height = tree.digitToInt() findOutwardTrees(input, columns, x, y).calcScenicScore(height) } }.flatten().max() } fun findOutwardTrees(rows: List<String>, columns: List<String>, x: Int, y: Int): List<List<Int>> { val left = rows[y].subSequence(0, x).reversed() val right = rows[y].subSequence(x + 1, rows[y].length) val up = columns[x].subSequence(0, y).reversed() val down = columns[x].subSequence(y + 1, columns.size) return listOf(left, right, up, down).map { it.map(Char::digitToInt) } } fun List<Int>.checkVisibility(height: Int): Boolean { val highestTreeInTheWay = this.maxOrNull() ?: return true return highestTreeInTheWay < height } fun List<String>.getRows(): List<String> { val columns = mutableListOf<String>() for (row in this) { for (i in row.indices) { if (columns.size <= i) columns.add("") columns[i] = columns[i].plus(row[i]) } } return columns } fun List<List<Int>>.calcScenicScore(height: Int): Int = this.map { it.calcViewingDistance(height) }.reduce(Int::times) fun List<Int>.calcViewingDistance(start: Int): Int = this .indexOfFirst { it >= start } .let { if (it == -1) this.size else it + 1 } // // ////35:08 //fun solveA(input: List<String>): Int { // // val trees = mutableListOf<Tree>() // // val columns = input.getRows() // // println(input) // println(columns) // // for (y in input.indices) { // for (x in input[y].indices) { // val left = input[y].subSequence(0, x).map { it.digitToInt() } // val right = input[y].subSequence(x + 1, input[y].length).map { it.digitToInt() } // val up = columns[x].subSequence(0, y).map { it.digitToInt() } // val down = columns[x].subSequence(y + 1, input.size).map { it.digitToInt() } // trees.add(Tree(input[y][x].digitToInt(), left, right, up, down)) // } // } // // return trees.filter { it.isVisible() }.size //} // //fun List<String>.getRows(): List<String> { // val columns = mutableListOf<String>() // // for (i in this[0].indices) { // columns.add("") // } // // for (row in this) { // for (i in row.indices) { // columns[i] = columns[i].plus(row[i]) // } // } // // return columns //} // //fun solveB(input: List<String>): Int { // // val trees = mutableListOf<Tree>() // // val columns = input.getRows() // // println(input) // println(columns) // // for (y in input.indices) { // for (x in input[y].indices) { // val left = input[y].subSequence(0, x).map { it.digitToInt() }.reversed() // val right = input[y].subSequence(x + 1, input[y].length).map { it.digitToInt() } // val up = columns[x].subSequence(0, y).map { it.digitToInt() }.reversed() // val down = columns[x].subSequence(y + 1, input.size).map { it.digitToInt() } // trees.add(Tree(input[y][x].digitToInt(), left, right, up, down)) // } // } // // trees.forEach { println("$it ${it.scenicScore()}") } // return trees.maxOf { it.scenicScore() } //} // //data class Tree( // val height: Int, // val left: List<Int>, // val right: List<Int>, // val up: List<Int>, // val down: List<Int>, //) { // fun isVisible(): Boolean { // val visible = listOf(left, right, up, down).any { it.all { h -> h < height } } // println("Height: $height left $left right $right up $up down $down visible $visible") // return visible // } // // fun scenicScore(): Int { // // return listOf(left, right, up, down).map { calcViewingDistance(it, height) }.reduce(Int::times) // } //} // ////40:20 //fun calcViewingDistance(heights: List<Int>, start: Int): Int { // // if (heights.isEmpty()) return 0 // // var distance = 0 // // for (height in heights) { // distance++ // if (height >= start) break // } // // println("$start: $distance for $heights ") // return distance //}
0
Kotlin
2
0
769c4bf06ee5b9ad3220e92067d617f07519d2b7
4,551
advent-of-code-2022
Apache License 2.0
src/Day07.kt
lsimeonov
572,929,910
false
{"Kotlin": 66434}
fun main() { data class Object(var size: Int, val name: String, val isDir: Boolean, var current: Boolean, val parent: Object?) fun executeCommand(cmd: String, fs: MutableList<Object>) { if (cmd.startsWith("$ cd")) { val dir = cmd.split(" ")[2] val cur = fs.first { it.current } cur.current = false if (dir == "..") { if (cur.name != "/") { cur.parent?.current = true } } else if (dir == "/") { fs.first { it.name == dir }.current = true } else { val newDir = fs.firstOrNull { it.name == dir && it.parent == cur } if (newDir != null) { newDir.current = true } } } } // calculate size of all directories fun calculateSize(fs: MutableList<Object>) { fs.asReversed().forEach { if (it.isDir) { it.size = fs.filter { o -> o.parent == it }.sumOf { s -> s.size } } } } fun processInput(input: List<String>, fs: MutableList<Object>) { var lsmode = false input.forEach { out -> if (out.startsWith("$ ls")) { lsmode = true return@forEach } if (out.startsWith("$")) { lsmode = false executeCommand(out, fs) return@forEach } if (lsmode) { val parent = fs.first { it.current } if (out.startsWith("dir")) { val dir = out.split(" ") val size = 0 val name = dir[1] fs.add(Object(size, name, isDir = true, current = false, parent = parent)) } else { val (size, name) = out.split(" ") fs.add(Object(size.toInt(), name, isDir = false, current = false, parent = parent)) } } } } fun part1(input: List<String>): Int { val fs = mutableListOf<Object>() fs.add(0, Object(0, "/", isDir = true, current = true, parent = null)) processInput(input, fs) calculateSize(fs) val size = fs.filter { it.size < 100000 && it.isDir }.sumOf { it.size } return size } fun part2(input: List<String>): Int { val fs = mutableListOf<Object>() fs.add(0, Object(0, "/", isDir = true, current = true, parent = null)) processInput(input, fs) calculateSize(fs) val free = 70000000 - fs.first{ it.name == "/" }.size val delete = 30000000 - free return fs.filter { it.isDir && it.size > delete }.minOf { it.size } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day07_test") check(part1(testInput) == 95437) check(part2(testInput) == 24933642) val input = readInput("Day07") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
9d41342f355b8ed05c56c3d7faf20f54adaa92f1
3,069
advent-of-code-2022
Apache License 2.0
src/Day07.kt
ivancordonm
572,816,777
false
{"Kotlin": 36235}
fun main() { fun dirSizes(commands: List<String>): Map<String, Int> { val sizes = mutableMapOf<String, Int>() var cwd = "" for (command in commands) { val splitCommand = command.split(" ") if (splitCommand[1] == "cd") { cwd = when (splitCommand[2]) { ".." -> cwd.substringBeforeLast("/") "/" -> "/" else -> "$cwd/${splitCommand[2]}" } } else if ("\\d+".toRegex().matches(splitCommand[0])) { val sz = splitCommand[0].toInt() var dir = cwd while (true) { sizes[dir] = sizes.getOrElse(dir) { 0 } + sz if (dir == "/") break dir = dir.substringBeforeLast("/") } } } return sizes.toMap() } fun part1(input: List<String>): Int { return dirSizes(input).filter { it.value <= 100000 }.map { it.value }.sum() } fun part2(input: List<String>): Int { val sizes = dirSizes(input) val rescue = 30000000 - 70000000 + sizes.getValue("/") return (sizes.toList().filter { it.second >= rescue }.minByOrNull { it.second }!!.second) } val testInput = readInput("Day07_test") val input = readInput("Day07") println(part1(testInput)) check(part1(testInput) == 95437) println(part1(input)) println(part2(testInput)) check(part2(testInput) == 24933642) println(part2(input)) }
0
Kotlin
0
2
dc9522fd509cb582d46d2d1021e9f0f291b2e6ce
1,556
AoC-2022
Apache License 2.0
src/challenges/Day03.kt
paralleldynamic
572,256,326
false
{"Kotlin": 15982}
package challenges import utils.readInput private const val LABEL = "Day03" private const val SCORES = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" fun scoreCompartments(rucksack: String): Int { val mid: Int = rucksack.length / 2 val (first, second) = rucksack.chunked((mid)).map{ compartment -> compartment.toSet() } val commonItem = first.intersect(second) return SCORES.indexOf(commonItem.first()) + 1 // item values are 1-indexed } fun main() { fun part1(rucksacks: List<String>): Int = rucksacks.sumOf { rucksack -> scoreCompartments(rucksack) } fun part2(rucksacks: List<String>): Int = rucksacks.chunked(3) .map { elfGroup -> elfGroup.map { rucksack -> rucksack.toSet() }.reduce { badges, rucksack -> badges.intersect(rucksack) } }.sumOf { badge -> SCORES.indexOf(badge.first()) + 1 } // Reading input val testRucksacks = readInput("${LABEL}_test") val rucksacks = readInput(LABEL) // // // Part 1 check(part1(testRucksacks) == 157) println(part1(rucksacks)) // // // Part 2 check(part2(testRucksacks) == 70) println(part2(rucksacks)) }
0
Kotlin
0
0
ad32a9609b5ce51ac28225507f77618482710424
1,238
advent-of-code-kotlin-2022
Apache License 2.0
src/Day04.kt
Iamlooker
573,103,288
false
{"Kotlin": 5744}
fun main() { fun convertToRange(start: String, end: String): IntRange = start.toInt()..end.toInt() fun part1(input: List<String>): Long = input.sumOf { work -> val workPerElf = work.split(',') val firstWork = workPerElf.first().split('-') val secondWork = workPerElf.last().split('-') val firstRange = convertToRange(firstWork.first(), firstWork.last()) val secondRange = convertToRange(secondWork.first(), secondWork.last()) if (secondRange.count() >= firstRange.count()) { if (firstRange.last in secondRange && firstRange.first in secondRange) 1L else 0L } else { if (secondRange.last in firstRange && secondRange.first in firstRange) 1L else 0L } } fun part2(input: List<String>): Long = input.sumOf { work -> val workPerElf = work.split(',') val firstWork = workPerElf.first().split('-') val secondWork = workPerElf.last().split('-') val firstRange = convertToRange(firstWork.first(), firstWork.last()) val secondRange = convertToRange(secondWork.first(), secondWork.last()) if (secondRange.count() >= firstRange.count()) { if (firstRange.last in secondRange || firstRange.first in secondRange) 1L else 0L } else { if (secondRange.last in firstRange || secondRange.first in firstRange) 1L else 0L } } // val testInput = readInput("Day04_test") // println(part2(testInput)) // val input = readInput("Day04") // println(part2(input)) }
0
Kotlin
0
0
91a335428a99db2f2b1fd5c5f51a6b1e55ae2245
1,551
aoc-2022-kotlin
Apache License 2.0
y2017/src/main/kotlin/adventofcode/y2017/Day24.kt
Ruud-Wiegers
434,225,587
false
{"Kotlin": 503769}
package adventofcode.y2017 import adventofcode.io.AdventSolution object Day24 : AdventSolution(2017, 24, "Electromagnetic Moat") { override fun solvePartOne(input: String): String { val pairs = parseInput(input) return buildAllBridges(emptyList(), pairs, 0) .map { it.sumOf { (a, b) -> a + b } } .maxOrNull() .toString() } override fun solvePartTwo(input: String): String { val pairs = parseInput(input) return buildAllBridges(emptyList(), pairs, 0) .map { it.size to it.sumOf { (a, b) -> a + b } } .maxWithOrNull(compareBy({ it.first }, { it.second })) ?.second .toString() } private fun buildAllBridges(bridge: List<Pair<Int, Int>>, available: List<Pair<Int, Int>>, last: Int): List<List<Pair<Int, Int>>> = available .filter { it.first == last || it.second == last } .flatMap { buildAllBridges(bridge + it, available - it, if (last == it.first) it.second else it.first) } .let { it.ifEmpty { listOf(bridge) } } private fun parseInput(input: String): List<Pair<Int, Int>> = input .lines() .map { it.split("/") } .map { it[0].toInt() to it[1].toInt() } }
0
Kotlin
0
3
fc35e6d5feeabdc18c86aba428abcf23d880c450
1,164
advent-of-code
MIT License
src/main/kotlin/com/colinodell/advent2022/Day13.kt
colinodell
572,710,708
false
{"Kotlin": 105421}
package com.colinodell.advent2022 class Day13(input: List<String>) { private val packets = input.filter { it.isNotBlank() }.map { Packet(it) } private val dividerPackets = listOf( Packet("[[2]]"), Packet("[[6]]") ) fun solvePart1() = packets .chunked(2) .withIndex() .sumOf { (index, pair) -> if (pair.first() < pair.last()) index + 1 else 0 } fun solvePart2() = packets .toMutableList() .also { it.addAll(dividerPackets) } .sorted() // Find the indices of the divider packets and add 1 to them .mapIndexed { i, p -> if (dividerPackets.contains(p)) i + 1 else 0 } .filter { it > 0 } .reduce(Int::times) private class Packet(contents: String) : Comparable<Packet> { private val children: MutableList<Packet> = mutableListOf() private val value: Int? init { if (contents.containsInt()) { value = contents.toInt() } else { // This is a list of other packets value = null // Remove left and right brackets val trimmed = contents.substring(1, contents.length - 1) var depth = 0 var tmp = "" for (c in trimmed.toCharArray()) { if (depth == 0 && c == ',') { // Create a new packet with everything up to this point children.add(Packet(tmp)) tmp = "" } else { // Continue reading chars, keeping track of our depth as we move into and out of lists depth += if (c == '[') 1 else if (c == ']') -1 else 0 tmp += c } } // Add any remaining chars if (tmp.isNotEmpty()) { children.add(Packet(tmp)) } } } override operator fun compareTo(other: Packet): Int { return when { (value != null && other.value != null) -> value - other.value (value == null && other.value == null) -> compareChildren(other) else -> coerceToList().compareTo(other.coerceToList()) } } private fun compareChildren(other: Packet): Int { for (i in 0 until children.size.coerceAtMost(other.children.size)) { val diff = children[i].compareTo(other.children[i]) if (diff != 0) { return diff } } return children.size - other.children.size } private fun coerceToList() = if (value != null) Packet("[$value]") else this } }
0
Kotlin
0
1
32da24a888ddb8e8da122fa3e3a08fc2d4829180
2,845
advent-2022
MIT License
src/year_2022/day_10/Day10.kt
scottschmitz
572,656,097
false
{"Kotlin": 240069}
package year_2022.day_10 import readInput sealed class Operation(var cycleCount: Int) { object NoOp: Operation(1) class Add( val quantity: Int ): Operation(2) { override fun toString(): String { return "Add $quantity - in $cycleCount cyclces" } } } object Day10 { /** * @return */ fun solutionOne(text: List<String>): Int { val operations = parseCommands(text) var cycleCount = 1 var currentOperation = 0 var currentValue = 1 var solution = 0 while (currentOperation < operations.size) { cycleCount += 1 val operation = operations[currentOperation] operation.cycleCount -= 1 if (operation.cycleCount < 1) { if (operation is Operation.Add) { currentValue += operation.quantity } currentOperation +=1 } if (cycleCount == 20 || (cycleCount - 20) % 40 == 0) { solution += (cycleCount * currentValue) } } return solution } /** * @return */ fun solutionTwo(text: List<String>): List<String> { val operations = parseCommands(text) var cycleCount = 1 var currentOperation = 0 var currentValue = 1 var solution = "" while (currentOperation < operations.size) { val operation = operations[currentOperation] operation.cycleCount -= 1 solution += if ((cycleCount -1) % 40 in listOf(currentValue -1, currentValue, currentValue +1)) { "#" } else { "." } if (operation.cycleCount < 1) { if (operation is Operation.Add) { currentValue += operation.quantity } currentOperation +=1 } cycleCount += 1 } val screen = solution.windowed(40, 40) screen.forEach { println(it) } return screen } private fun parseCommands(text: List<String>): List<Operation> { return text.map { line -> val split = line.split(" ") when (split.size) { 1 -> Operation.NoOp else -> Operation.Add( quantity = Integer.parseInt(split[1]) ) } } } } fun main() { val inputText = readInput("year_2022/day_10/Day10.txt") val solutionOne = Day10.solutionOne(inputText) println("Solution 1: $solutionOne") val solutionTwo = Day10.solutionTwo(inputText) println("Solution 2: $solutionTwo") }
0
Kotlin
0
0
70efc56e68771aa98eea6920eb35c8c17d0fc7ac
2,731
advent_of_code
Apache License 2.0
src/Day5/Day5.kt
tomashavlicek
571,148,715
false
{"Kotlin": 23780}
package Day5 import readInputAsText import java.util.Stack fun main() { data class Instruction(val move: Int, val from: Int, val to: Int) fun parseInput(input: String): Pair<List<Stack<Char>>, MutableList<Instruction>> { val (cratesInput, instructionInput) = input.split("\n\n") val cratesSize = cratesInput.last().digitToInt() val cratesLines = cratesInput.split('\n').dropLast(1).reversed() val crates = List<Stack<Char>>(cratesSize) { Stack() } for (line in cratesLines) { line.windowed(size = 3, step = 4).forEachIndexed { index, s -> if (s[1] != ' ') { crates[index].push(s[1]) } } } val instructions = mutableListOf<Instruction>() val regex = Regex("move (\\d+) from (\\d+) to (\\d+)") for (line in instructionInput.split('\n')) { regex.matchEntire(line)?.destructured?.let { (move, from, to) -> instructions.add(Instruction(move.toInt(), from.toInt() - 1, to.toInt() - 1)) } } return crates to instructions } fun part1(input: String): String { val (crates, instructions) = parseInput(input) for (instruction in instructions) { repeat(instruction.move) { val crate = crates[instruction.from].pop() crates[instruction.to].push(crate) } } return String(crates.map { it.pop() }.toCharArray()) } fun part2(input: String): String { val (crates, instructions) = parseInput(input) for (instruction in instructions) { val batch = mutableListOf<Char>() repeat(instruction.move) { batch += crates[instruction.from].pop() } batch.reversed().forEach { crates[instruction.to].push(it) } } return String(crates.map { it.pop() }.toCharArray()) } // test if implementation meets criteria from the description, like: val testInput = readInputAsText("Day5/Day5_test") check(part1(testInput) == "CMZ") check(part2(testInput) == "MCD") val input = readInputAsText("Day5/Day5") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
899d30e241070903fe6ef8c4bf03dbe678310267
2,296
aoc-2022-in-kotlin
Apache License 2.0
src/Day02.kt
nordberg
573,769,081
false
{"Kotlin": 47470}
fun main() { val perms = listOf( "ABC", // "ACB", // "CAB", // "BAC", // "BCA", // "CBA" ) fun rockPaperScissors(oppC: Char, myC: Char): Int { return when { oppC == myC -> 3 oppC == 'A' && myC == 'C' -> 0 oppC == 'B' && myC == 'A' -> 0 oppC == 'C' && myC == 'B' -> 0 oppC == 'C' && myC == 'A' -> 6 oppC == 'A' && myC == 'B' -> 6 oppC == 'B' && myC == 'C' -> 6 else -> throw IllegalStateException("$myC vs $oppC") } } fun mapping(c: Char, perm: String): Char { return when (c) { 'X' -> perm[0] 'Y' -> perm[1] 'Z' -> perm[2] else -> throw IllegalStateException("Got $c") } } fun pointsForRockPaperScissor(c: Char): Int { return when (c) { 'A' -> 1 'B' -> 2 'C' -> 3 else -> throw IllegalStateException("Got $c") } } /** * Misread the instructions, thought I had to find the best mapping (XYZ) -> (ABC) to maximize points... */ fun part1(input: List<String>): Int? { return perms.maxOfOrNull { p -> input.sumOf { s -> val (oppMoveStr, myMoveStr) = s.split(" ") val myMove = mapping(myMoveStr[0], p) rockPaperScissors(oppMoveStr[0], myMove) + pointsForRockPaperScissor(myMove) } } } fun part2(input: List<String>): Int { return input.sumOf { val (oppMove, myMove) = it.split(" ") val scoreFromOutcome = when (myMove[0]) { 'X' -> 0 'Y' -> 3 'Z' -> 6 else -> throw IllegalStateException("aaa") } val scoreFromWhatPlayed = when (oppMove[0]) { 'A' -> when (scoreFromOutcome) { 0 -> 3 // I lost -> I played scissors 3 -> 1 // I drew -> I played rock 6 -> 2 // I won -> I played paper else -> throw java.lang.IllegalStateException(":((") } 'B' -> when (scoreFromOutcome) { 0 -> 1 // I lost -> I played scissors 3 -> 2 // I drew -> I played rock 6 -> 3 // I won -> I played paper else -> throw java.lang.IllegalStateException(":((") } 'C' -> when (scoreFromOutcome) { 0 -> 2 // I lost -> I played scissors 3 -> 3 // I drew -> I played rock 6 -> 1 // I won -> I played paper else -> throw java.lang.IllegalStateException(":((") } else -> throw IllegalStateException(":(") } scoreFromOutcome + scoreFromWhatPlayed } } // test if implementation meets criteria from the description, like: // val testInput = readInput("Day01_test") //check(part1(testInput) == 1) val input = readInput("Day02") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
3de1e2b0d54dcf34a35279ba47d848319e99ab6b
3,206
aoc-2022
Apache License 2.0
src/Day05.kt
mikrise2
573,939,318
false
{"Kotlin": 62406}
import java.util.* fun main() { fun part1(input: List<String>): String { val middleIndex = input.indexOfFirst { it.contains("1") } val indexes = input[middleIndex].mapIndexed { index, c -> if (c == ' ') -1 else index }.filter { it != -1 } val stacks = MutableList(indexes.size) { Stack<Char>() } for (i in middleIndex - 1 downTo 0) { indexes.forEachIndexed { index, value -> if (input[i].length > value) { val element = input[i][value] if (element != ' ') stacks[index].push(element) } } } for (i in middleIndex + 2 until input.size) { val command = input[i].split(" ") repeat(command[1].toInt()) { stacks[command[5].toInt() - 1].push(stacks[command[3].toInt() - 1].pop()) } } return stacks.map { it.pop() }.joinToString("") } fun part2(input: List<String>): String { val middleIndex = input.indexOfFirst { it.contains("1") } val indexes = input[middleIndex].mapIndexed { index, c -> if (c == ' ') -1 else index }.filter { it != -1 } val stacks = MutableList(indexes.size) { Stack<Char>() } for (i in middleIndex - 1 downTo 0) { indexes.forEachIndexed { index, value -> if (input[i].length > value) { val element = input[i][value] if (element != ' ') stacks[index].push(element) } } } for (i in middleIndex + 2 until input.size) { val command = input[i].split(" ") val temp = mutableListOf<Char>() repeat(command[1].toInt()) { temp.add(stacks[command[3].toInt() - 1].pop()) } temp.reversed().forEach { stacks[command[5].toInt() - 1].push(it) } } return stacks.map { it.pop() }.joinToString("") } val input = readInput("Day05") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
d5d180eaf367a93bc038abbc4dc3920c8cbbd3b8
2,125
Advent-of-code
Apache License 2.0
src/main/kotlin/adventofcode2017/potasz/P03SpiralMemory.kt
potasz
113,064,245
false
null
package adventofcode2017.potasz import kotlin.math.abs import kotlin.math.max import kotlin.math.min // http://adventofcode.com/2017/day/3 object P03SpiralMemory { data class Move(val x: Int, val y: Int) data class Position(val x: Int, val y: Int) { operator fun plus(move: Move) = Position(x + move.x, y + move.y) fun distanceFromCenter() = abs(x) + abs(y) fun distanceFrom(other: Position) = ((x - other.x).square() + (y - other.y).square()) fun isWithin(topRight: Position, bottomLeft: Position): Boolean = x >= topRight.x && x <= bottomLeft.x && y <= topRight.y && y >= bottomLeft.y private fun Int.square() = this * this } data class Square(val value: Long, val position: Position) val moves = arrayOf(Move(1, 0), Move(0, 1), Move(-1, 0), Move(0, -1)) val input = 289326 private fun findSquare(v: (Square, Position) -> Long, stopAt: (Square) -> Boolean): Square { var moveIndex = 0 var square = Square(1, Position(0, 0)) var topRight = square.position var bottomLeft = square.position while (true) { val move = moves[moveIndex++ % moves.size] while (square.position.isWithin(topRight, bottomLeft)) { val newPosition = square.position + move val newValue = v(square, newPosition) square = Square(newValue, newPosition) if (stopAt(square)) return square } topRight = Position(min(topRight.x, square.position.x), max(topRight.y, square.position.y)) bottomLeft = Position(max(bottomLeft.x, square.position.x), min(bottomLeft.y, square.position.y)) } } fun solve1(input: Int): Int = findSquare({ square, _ -> square.value + 1 }, { it.value >= input}).position.distanceFromCenter() fun solve2(input: Int): Long { val squares = mutableListOf<Square>() return findSquare({ square, newPosition -> squares.add(square) squares.filter { it.position.distanceFrom(newPosition) <= 2 }.fold(0L) { acc, s -> acc + s.value } }, { it.value > input}).value } @JvmStatic fun main(args: Array<String>) { println(listOf(1, 12, 23, 1024, input).map { solve1(it) }) println(listOf(1, 12, 23, 1024, input).map { solve2(it) }) } }
0
Kotlin
0
1
f787d9deb1f313febff158a38466ee7ddcea10ab
2,385
adventofcode2017
Apache License 2.0
src/Day05.kt
weberchu
573,107,187
false
{"Kotlin": 91366}
private fun numberOfStack(input: List<String>): Int { return input.find { it.startsWith(" 1 ") }?.let { 1 + it.length / 4 }!! } private fun startingStacks(input: List<String>): Pair<List<MutableList<Char>>, Int> { val numberOfStack = numberOfStack(input) val stacks = List(numberOfStack) { mutableListOf<Char>() } var i = 0 while (!input[i].startsWith(" 1 ")) { for (s in 0 until numberOfStack) { val crateIndex = 1 + s * 4 if (crateIndex >= input[i].length) { break } val crate = input[i][crateIndex] if (crate != ' ') { stacks[s].add(0, crate) } } i++ } return Pair(stacks, i) } private fun part1(input: List<String>): String { var (stacks, i) = startingStacks(input) i += 2 while (i < input.size) { val line = input[i] val moveCount = line.substring(5, line.indexOf(" from ")).toInt() val from = line.substring(line.indexOf(" from ") + 6, line.indexOf(" to ")).toInt() val to = line.substring(line.indexOf(" to ") + 4).toInt() for (c in 0 until moveCount) { val crate = stacks[from - 1].removeLast() stacks[to - 1].add(crate) } i++ } return stacks.map { it.last() }.toCharArray().concatToString() } private fun part2(input: List<String>): String { var (stacks, i) = startingStacks(input) i += 2 while (i < input.size) { val line = input[i] val moveCount = line.substring(5, line.indexOf(" from ")).toInt() val from = line.substring(line.indexOf(" from ") + 6, line.indexOf(" to ")).toInt() val to = line.substring(line.indexOf(" to ") + 4).toInt() for (c in moveCount downTo 1) { val crate = stacks[from - 1].removeAt(stacks[from - 1].size - c) stacks[to - 1].add(crate) } i++ } return stacks.map { it.last() }.toCharArray().concatToString() } fun main() { val input = readInput("Day05") // val input = readInput("Test") println("Part 1: " + part1(input)) println("Part 2: " + part2(input)) }
0
Kotlin
0
0
903ff33037e8dd6dd5504638a281cb4813763873
2,209
advent-of-code-2022
Apache License 2.0
src/Day11.kt
hufman
573,586,479
false
{"Kotlin": 29792}
class MonkeyBrains(val operation: (Long) -> Long, val modulus: Int, val trueDest: Int, val falseDest: Int, var state: State ) { class Builder() { var items: MutableList<Long> = ArrayList() var operation: ((Long) -> Long)? = null var modulus = 0 var trueDest = 0 var falseDest = 0 fun build(): MonkeyBrains { return MonkeyBrains(operation!!, modulus, trueDest, falseDest, State(0, items)) } } data class State(val inspections: Int, val items: MutableList<Long>) } fun main() { fun parse(input: List<String>): List<MonkeyBrains> { val monkeys = ArrayList<MonkeyBrains>() val listMatcher = Regex("""Starting items: ((?:\d+(?:, )?)+)""") val operation = Regex("""Operation: new = (\w+) (.) (\w+)""") val testMatcher = Regex("""Test: divisible by (\d+)""") val trueDest = Regex("""If true: throw to monkey (\d+)""") val falseDest = Regex("""If false: throw to monkey (\d+)""") var monkey = MonkeyBrains.Builder() input.forEach { line -> listMatcher.find(line)?.also { monkey.items = it.groupValues[1].split(", ").map { it.toLong() }.toMutableList() // println("Starting items ${monkey.items}") } operation.find(line)?.also { val (_, op, right) = it.destructured monkey.operation = { old -> val factor = if (right == "old") old else right.toLong() if (op == "+") old + factor else old * factor } } testMatcher.find(line)?.also { monkey.modulus = it.groupValues[1].toInt() } trueDest.find(line)?.also { monkey.trueDest = it.groupValues[1].toInt() } falseDest.find(line)?.also { monkey.falseDest = it.groupValues[1].toInt() } if (line == "") { monkeys.add(monkey.build()) monkey = MonkeyBrains.Builder() } } monkeys.add(monkey.build()) return monkeys } fun runBusiness(monkeys: List<MonkeyBrains>): Sequence<List<MonkeyBrains.State>> = sequence { while (true) { monkeys.forEach { monkey -> monkey.state.items.forEach { current -> val next = monkey.operation(current) / 3 // println("Converted $current to $next") if (next % monkey.modulus == 0L) { monkeys[monkey.trueDest].state.items.add(next) } else { monkeys[monkey.falseDest].state.items.add(next) } } monkey.state = MonkeyBrains.State(monkey.state.inspections + monkey.state.items.size, ArrayList()) } yield(monkeys.mapIndexed { i, monkey -> // println("$i: ${monkey.state}") monkey.state }) } } fun part1(input: List<String>): Int { return runBusiness(parse(input)) .take(20).last() // 20 rounds .sortedByDescending { monkey -> monkey.inspections }.take(2) // top monkeys .fold(1) {acc, next -> acc * next.inspections} // multiply together } fun runBusiness2(monkeys: List<MonkeyBrains>): Sequence<List<MonkeyBrains.State>> = sequence { while (true) { val maxModulus = monkeys.fold(1) { acc, monkey -> acc * monkey.modulus } monkeys.forEach { monkey -> monkey.state.items.forEach { current -> val next = monkey.operation(current) % maxModulus // println("Converted $current to $next") if (next % monkey.modulus == 0L) { monkeys[monkey.trueDest].state.items.add(next) } else { monkeys[monkey.falseDest].state.items.add(next) } } monkey.state = MonkeyBrains.State(monkey.state.inspections + monkey.state.items.size, ArrayList()) } yield(monkeys.mapIndexed { i, monkey -> // println("$i: ${monkey.state}") monkey.state }) } } fun part2(input: List<String>): Long { return runBusiness2(parse(input)) .take(10000).last() // 20 rounds .sortedByDescending { monkey -> monkey.inspections }.take(2) // top monkeys .fold(1) {acc, next -> acc * next.inspections} // multiply together } // test if implementation meets criteria from the description, like: val testInput = readInput("Day11_test") check(part1(testInput) == 10605) check(part2(testInput) == 2713310158) val input = readInput("Day11") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
1bc08085295bdc410a4a1611ff486773fda7fcce
5,065
aoc2022-kt
Apache License 2.0
src/main/kotlin/name/valery1707/problem/leet/code/CanPlaceFlowersK.kt
valery1707
541,970,894
false
null
package name.valery1707.problem.leet.code import kotlin.math.max import kotlin.math.roundToInt /** * # 605. Can Place Flowers * * You have a long flowerbed in which some of the plots are planted, and some are not. * However, flowers cannot be planted in **adjacent** plots. * * Given an integer array `flowerbed` containing `0`'s and `1`'s, where `0` means *empty* and `1` means not *empty*, and an integer `n`, * return *if* `n` new flowers can be planted in the `flowerbed` without violating the no-adjacent-flowers rule. * * ### Constraints * * `1 <= flowerbed.length <= 2 * 10^4` * * `flowerbed[i]` is `0` or `1` * * There are no two adjacent flowers in `flowerbed` * * `0 <= n <= flowerbed.length` * * @see <a href="https://leetcode.com/problems/can-place-flowers/">605. Can Place Flowers</a> */ interface CanPlaceFlowersK { fun canPlaceFlowers(flowerbed: IntArray, n: Int): Boolean @Suppress("EnumEntryName", "unused") enum class Implementation : CanPlaceFlowersK { regexp { override fun canPlaceFlowers(flowerbed: IntArray, n: Int): Boolean { //Цветов больше чем возможных мест в принципе if (n > (flowerbed.size / 2.0).roundToInt()) { return false } //0 цветов всегда поместится if (n == 0) { return true } val str = flowerbed .joinToString(separator = "", prefix = "0", postfix = "0", transform = Int::toString) val count = "00+".toRegex() .findAll(str) .map { it.value.length } //"0"->[1]->0 //"00"->[2]->0 //"000"->[3]->1 //"0000"->[4]->1 //"00000"->[5]->2 //"000000"->[6]->2 //"0000000"->[7]->3 .map { (it + 1) / 2 - 1 } .filter { it > 0 }.sum() return n <= count } }, indexes { override fun canPlaceFlowers(flowerbed: IntArray, n: Int): Boolean { //Цветов больше чем возможных мест в принципе if (n > (flowerbed.size / 2.0).roundToInt()) { return false } //0 цветов всегда поместится if (n == 0) { return true } val count: (curr: Int, prev: Int) -> Int = { curr, prev -> val count = curr - prev - 1 //1->0, 2->0, 3->1, 4->1, 5->2, 6->2 max(0, (count + 1) / 2 - 1) } var possible = 0 var prevUsed = -2 for (i in flowerbed.indices) { if (flowerbed[i] == 1) { possible += count(i, prevUsed) prevUsed = i } } possible += count(flowerbed.lastIndex + 2, prevUsed) return n <= possible } }, } }
3
Kotlin
0
0
76d175f36c7b968f3c674864f775257524f34414
3,272
problem-solving
MIT License
src/main/kotlin/com/hj/leetcode/kotlin/problem835/Solution.kt
hj-core
534,054,064
false
{"Kotlin": 619841}
package com.hj.leetcode.kotlin.problem835 /** * LeetCode page: [835. Image Overlap](https://leetcode.com/problems/image-overlap/); */ class Solution { /* Complexity: * Time O(N^4) and Space O(N^2) where N is the size of img1 and img2; */ fun largestOverlap(img1: Array<IntArray>, img2: Array<IntArray>): Int { val numOnesInImg1 = countOnes(img1) val numOnesInImg2 = countOnes(img2) val minNumOnes = minOf(numOnesInImg1, numOnesInImg2) if (minNumOnes == 0 || minNumOnes == 1) return minNumOnes val (lessContent, moreContent) = if (numOnesInImg1 < numOnesInImg2) img1 to img2 else img2 to img1 val coordinatesOfOnes = findCoordinatesOfOnes(lessContent) val size = img1.size val possibleShift = -(size - 1) until size var largestOverlap = 0 for (rowShift in possibleShift) { for (columnShift in possibleShift) { val overlap = countOverlap(moreContent, rowShift, columnShift, coordinatesOfOnes) largestOverlap = maxOf(largestOverlap, overlap) val reachLargestPossible = largestOverlap == minNumOnes if (reachLargestPossible) return largestOverlap } } return largestOverlap } private fun countOnes(image: Array<IntArray>): Int { var count = 0 for (row in image.indices) { count += image[row].count { it == 1 } } return count } private fun findCoordinatesOfOnes(image: Array<IntArray>): List<Coordinates> { val coordinates = mutableListOf<Coordinates>() for (row in image.indices) { for (column in image[row].indices) { if (image[row][column] == 1) coordinates.add(Coordinates(row, column)) } } return coordinates } private data class Coordinates(val row: Int, val column: Int) private fun countOverlap( imageToShift: Array<IntArray>, rowShift: Int, columnShift: Int, coordinatesOfOnesInBaseImage: List<Coordinates> ): Int { var overlap = 0 for (coordinate in coordinatesOfOnesInBaseImage) { val isOverlap = with(coordinate) { 1 == imageToShift .getOrNull(row - rowShift) ?.getOrNull(column - columnShift) } if (isOverlap) overlap++ } return overlap } }
1
Kotlin
0
1
14c033f2bf43d1c4148633a222c133d76986029c
2,475
hj-leetcode-kotlin
Apache License 2.0
src/year2022/02/Day02_more_adequate_solution.kt
Vladuken
573,128,337
false
{"Kotlin": 327524, "Python": 16475}
package year2022.`02` import readInput fun main() { fun part1(input: List<String>): Int { return input .map { it.split(" ") } .map { val opponentFigure = Figure.from(it.first()) val yourFigure = Figure.from(it[1]) calculateOutcomeForYou( opponent = opponentFigure, you = yourFigure ) to yourFigure } .sumOf { (outcome, yourFigure) -> outcome.amount + yourFigure.amount } } fun part2(input: List<String>): Int { return input .map { it.split(" ") } .map { val opponentFigure = Figure.from(it.first()) val outcome = Outcome.from(it[1]) calculateFigureForOutcome( opponent = opponentFigure, outcome = outcome ) to outcome } .sumOf { (outcome, yourFigure) -> outcome.amount + yourFigure.amount } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day02_test") val part1Test = part1(testInput) //println(part1Test) check(part1Test == 15) val input = readInput("Day02") println(part1(input)) println(part2(input)) } /** * Representation of `year2022.02`.Figure with its value */ enum class Figure(val amount: Int) { ROCK(1), PAPER(2), SCISSORS(3); companion object { fun from(code: String): Figure { return when (code) { "A", "X" -> ROCK "B", "Y" -> PAPER "C", "Z" -> SCISSORS else -> error("Illegal state") } } } } /** * `year2022.02`.Outcome Representation with it value */ enum class Outcome(val amount: Int) { LOSE(0), DRAW(3), WIN(6); companion object { fun from(code: String): Outcome { return when (code) { "X" -> LOSE "Y" -> DRAW "Z" -> WIN else -> error("Illegal state") } } } } fun calculateOutcomeForYou(opponent: Figure, you: Figure): Outcome { return when (opponent) { Figure.ROCK -> when (you) { Figure.ROCK -> Outcome.DRAW Figure.PAPER -> Outcome.WIN Figure.SCISSORS -> Outcome.LOSE } Figure.PAPER -> when (you) { Figure.ROCK -> Outcome.LOSE Figure.PAPER -> Outcome.DRAW Figure.SCISSORS -> Outcome.WIN } Figure.SCISSORS -> when (you) { Figure.ROCK -> Outcome.WIN Figure.PAPER -> Outcome.LOSE Figure.SCISSORS -> Outcome.DRAW } } } fun calculateFigureForOutcome(opponent: Figure, outcome: Outcome): Figure { return when (opponent) { Figure.ROCK -> when (outcome) { Outcome.LOSE -> Figure.SCISSORS Outcome.DRAW -> Figure.ROCK Outcome.WIN -> Figure.PAPER } Figure.PAPER -> when (outcome) { Outcome.LOSE -> Figure.ROCK Outcome.DRAW -> Figure.PAPER Outcome.WIN -> Figure.SCISSORS } Figure.SCISSORS -> when (outcome) { Outcome.LOSE -> Figure.PAPER Outcome.DRAW -> Figure.SCISSORS Outcome.WIN -> Figure.ROCK } } }
0
Kotlin
0
5
c0f36ec0e2ce5d65c35d408dd50ba2ac96363772
3,481
KotlinAdventOfCode
Apache License 2.0
project/src/problems/MaxSlice.kt
informramiz
173,284,942
false
null
package problems object MaxSlice { /** * https://codility.com/media/train/7-MaxSlice.pdf * * NOTE: We assume that the slice can be empty and its sum equals 0 SO * a slice CAN NOT be smaller than 0 * * Example: * 5 -7 3 5 -2 4 -1 * In the picture, the slice with the largest sum is highlighted in gray. The sum of this slice * equals 10 (A[2..5]) and there is no slice with a larger sum. */ fun findMaxSliceSum(A: Array<Int>): Int { var maxSum = 0 var runningSum = 0 A.forEach { value -> runningSum += value //sum can't be less than 0 as we must assume an empty slice has sum = 0 runningSum = Math.max(0, runningSum) //check if new running sum is greater than last max sum maxSum = Math.max(runningSum, maxSum) } return maxSum } fun findMaxSumSlice(A: Array<Int>): Slice { var maxSum = Slice() val runningSum = Slice() A.forEachIndexed { index, value -> runningSum.sum += value runningSum.q = index //sum can't be less than 0 (as in that case empty slice has 0 sum) if (runningSum.sum < 0) { //reset running sum to 0 runningSum.sum = 0 runningSum.p = index + 1 runningSum.q = index + 1 } if (maxSum.sum < runningSum.sum) { maxSum = runningSum.copy() } } return maxSum } /** * https://app.codility.com/programmers/lessons/9-maximum_slice_problem/max_profit/ */ fun findMaximumProfit(A: Array<Int>): Int { if (A.isEmpty()) return 0 var maxProfit = 0 var minBuyPrice = A[0] for (i in 1 until A.size) { //define new value for readability val currentDayPrice = A[i] //keep track of min buy price on any day. minBuyPrice = Math.min(minBuyPrice, currentDayPrice) maxProfit = Math.max(maxProfit, currentDayPrice - minBuyPrice) } //we have to return 0 if profit is not possible return Math.max(maxProfit, 0) } /** * https://app.codility.com/programmers/lessons/9-maximum_slice_problem/max_slice_sum/ * Note: The max sum can be negative so this is different problem than the one solved above */ fun findMaxSliceSumWithNegativePossibleValue(A: Array<Int>): Int { var maxSum = A[0] var runningSum = A[0] for (i in 1 until A.size) { runningSum = Math.max(A[i], runningSum + A[i]) maxSum = Math.max(maxSum, runningSum) } return maxSum } /** * https://app.codility.com/programmers/lessons/9-maximum_slice_problem/max_double_slice_sum/ * MaxDoubleSliceSum * Find the maximal sum of any double slice. * The sum of double slice (X, Y, Z) is the total of * A[X + 1] + A[X + 2] + ... + A[Y − 1] + A[Y + 1] + A[Y + 2] + ... + A[Z − 1]. * Solution help: https://www.martinkysel.com/codility-maxdoubleslicesum-solution/ */ fun maxDoubleSliceSum(A: Array<Int>): Int { val prefixSums = Array(A.size) {0} val suffixSums = Array(A.size) {0} //we can't include 0 or lastIndex because x and z are not included in sum //also, sum can't be less than 0 because empty slice has sum 0 so for (i in 1 until A.size-1) { //pick max of 0 or current element + previous prefix sum prefixSums[i] = Math.max(0, prefixSums[i-1] + A[i]) } for (i in A.size-2 downTo 1) { //pick max of 0 or previous prefix sum (i+1 because we are going reverse suffixSums[i] = Math.max(0, suffixSums[i+1] + A[i]) } var maxDoubleSliceSum = 0 for (y in 1 until A.size-1) { //as y is not part of max slice sum so we check for each index Yi where //max(0, maxSum(1..Yi-1) + maxSum(Yi+1..N-1)) = max(0, prefixSums(Yi-1) + suffixSums(Yi+1)) maxDoubleSliceSum = Math.max(maxDoubleSliceSum, prefixSums[y-1] + suffixSums[y+1]) } return maxDoubleSliceSum } } data class Slice(var sum: Int = 0, var p: Int = 0, var q: Int = 0)
0
Kotlin
0
0
a38862f3c36c17b8cb62ccbdb2e1b0973ae75da4
4,339
codility-challenges-practice
Apache License 2.0
src/Day01.kt
hottendo
572,708,982
false
{"Kotlin": 41152}
fun main() { fun part1(input: List<String>): Int { var mostCalories = 0 var sumCalories = 0 for (item in input) { if (item.length == 0) { if (sumCalories > mostCalories) { mostCalories = sumCalories } sumCalories = 0 // println("Maximum calories: $mostCalories") } else { sumCalories = sumCalories + item.toInt() // println("Sum of calories: $sumCalories") } } return mostCalories } fun part2(input: List<String>): Int { val topThreeMostCalories: IntArray = intArrayOf(0, 0, 0) var sumCalories = 0 for (item in input) if (item.length == 0) { if (sumCalories > topThreeMostCalories[0]) { topThreeMostCalories[0] = sumCalories topThreeMostCalories.sort() for(cal in topThreeMostCalories) { print("$cal ") } println() } sumCalories = 0 } else { sumCalories += item.toInt() } return topThreeMostCalories.sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") println(part1(testInput)) println(part2(testInput)) // check(part1(testInput) == 1) val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
a166014be8bf379dcb4012e1904e25610617c550
1,520
advent-of-code-2022
Apache License 2.0
src/algorithmdesignmanualbook/sorting/FindNumberOfOccurrence.kt
realpacific
234,499,820
false
null
package algorithmdesignmanualbook.sorting import algorithmdesignmanualbook.print import java.util.* import kotlin.test.assertTrue /** * Get the left most index using binary search */ private fun getLeftMostMatch(str: String, array: Array<String>, low: Int, high: Int): Int { if (low <= high) { val mid = (low + high) / 2 if ((mid == 0 || array[mid - 1] != str) && array[mid] == str) { // if the left of mid is different than str, then this is the left most index return mid } else if (str > array[mid]) { return getLeftMostMatch(str, array, mid + 1, high) } else { return getLeftMostMatch(str, array, low, mid - 1) } } return -1 } private fun getRightMostMatch(str: String, array: Array<String>, low: Int, high: Int): Int { if (low <= high) { val mid = (low + high) / 2 if ((mid == array.lastIndex || array[mid + 1] != str) && array[mid] == str) { // if the right of mid is different than str, then this is the right most index return mid } else if (str < array[mid]) { return getRightMostMatch(str, array, low, mid - 1) } else { return getRightMostMatch(str, array, mid + 1, high) } } return -1 } /** * Find the range in which [str] occurs in [array]. * * [Solution here](https://tutorialspoint.dev/algorithm/searching-algorithms/count-number-of-occurrences-or-frequency-in-a-sorted-array) */ private fun findNumberOfOccurrence(str: String, array: Array<String>): IntRange? { val left = getLeftMostMatch(str, array, 0, array.lastIndex) // if no occurrence in left, then no such item if (left == -1) { return null } val right = getRightMostMatch(str, array, left + 1, array.lastIndex) // if no occurrence in left, since we started from left+1, then this is the only one item in array if (right == -1) { return left..left } return left..right } fun main() { val input = "search, sort, search, ball, sort, hello, hi, hello, hello, hello, hello, apple, string, string, zebra" .split(", ") .toTypedArray().sortedArray() input.print("Input", printer = Arrays::toString) assertTrue { val str = "hello" findNumberOfOccurrence(str, input).print("Occurrence range for $str") == 2..6 } assertTrue { val str = "zoo" findNumberOfOccurrence(str, input).print("Occurrence range for $str") == null } assertTrue { val str = "hi" findNumberOfOccurrence(str, input).print("Occurrence range for $str") == 7..7 } assertTrue { val str = "sort" findNumberOfOccurrence(str, input).print("Occurrence range for $str") == 10..11 } assertTrue { val str = "zebra" findNumberOfOccurrence(str, input).print("Occurrence range for $str") == 14..14 } }
4
Kotlin
5
93
22eef528ef1bea9b9831178b64ff2f5b1f61a51f
2,931
algorithms
MIT License
2021/src/main/kotlin/days/Day5.kt
pgrosslicht
160,153,674
false
null
package days import Day import com.google.common.collect.HashBasedTable import kotlin.math.sign class Day5 : Day(5) { private val regex = Regex("^((\\d*),(\\d*))\\s->\\s((\\d*),(\\d*))\$") private val lines = dataList.filter { it.isNotEmpty() }.mapNotNull { regex.matchEntire(it) }.map { it.destructured }.map { Line( Point(it.component2().toInt(), it.component3().toInt()), Point(it.component5().toInt(), it.component6().toInt()) ) } override fun partOne(): Int { return Map(lines).overlapping() } override fun partTwo(): Int { return Map(lines, true).overlapping() } class Map(private val lines: List<Line>, val diagonal: Boolean = false) { private val table: HashBasedTable<Int, Int, Int> = HashBasedTable.create() init { lines.forEach { mark(it) } //print() } private fun mark(line: Line) { line.forEachPoint(diagonal) { p -> table.put(p.x, p.y, table.get(p.x, p.y).let { it?.plus(1) ?: 1 }) } } fun overlapping(): Int = table.values().count { it >= 2 } fun print() { val rows = table.rowMap().maxOf { it.key } val columns = table.columnMap().maxOf { it.key } (0..rows).forEach { y -> (0..columns).forEach { x -> print(table.get(x, y) ?: ".") } println() } } } data class Line(val p1: Point, val p2: Point) { private fun points(withDiagonals: Boolean): Set<Point> { if (withDiagonals || p1.x == p2.x || p1.y == p2.y) { val dx = (p2.x - p1.x).sign val dy = (p2.y - p1.y).sign val set = mutableSetOf(p2) var x = p1.x var y = p1.y while (x != p2.x || y != p2.y) { set.add(Point(x, y)) x += dx y += dy } return set } return setOf() } fun forEachPoint(withDiagonals: Boolean = false, f: (Point) -> Unit) = points(withDiagonals).forEach(f) } data class Point(val x: Int, val y: Int) } fun main() = Day.mainify(Day5::class)
0
Kotlin
0
0
1f27fd65651e7860db871ede52a139aebd8c82b2
2,335
advent-of-code
MIT License
src/day4/Code.kt
fcolasuonno
221,697,249
false
null
package day4 import java.io.File fun main() { val name = if (false) "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)}") } data class Room(val obfuscated: String, val sector: Int, val checksum: String) { val decoded get() = sector.let { it % ('z' - 'a' + 1) }.let { key -> obfuscated.map { c -> if (c == '-') ' ' else 'a' + ((c - 'a' + key) % ('z' - 'a' + 1)) }.joinToString(separator = "") } val isReal: Boolean = obfuscated.filterNot { it == '-' }.groupingBy { it }.eachCount().toList() .sortedWith(compareByDescending<Pair<Char, Int>> { it.second }.thenBy { it.first }) .take(checksum.length).map { it.first }.joinToString(separator = "") == checksum } private val lineStructure = """([a-z-]+)-(\d+)\[(\w+)]""".toRegex() fun parse(input: List<String>) = input.map { lineStructure.matchEntire(it)?.destructured?.let { val (obfuscated, sector, checksum) = it.toList() Room(obfuscated, sector.toInt(), checksum) } }.requireNoNulls() fun part1(input: List<Room>): Any? = input.filter { it.isReal }.sumBy { it.sector } fun part2(input: List<Room>): Any? = input.filter { it.isReal && it.decoded.contains("north", ignoreCase = true) }.single().sector
0
Kotlin
0
0
73110eb4b40f474e91e53a1569b9a24455984900
1,518
AOC2016
MIT License
advent-of-code-2022/src/Day24.kt
osipxd
572,825,805
false
{"Kotlin": 141640, "Shell": 4083, "Scala": 693}
fun main() { val (testBlizzards, testSize) = readInput("Day24_test") val (inputBlizzards, inputSize) = readInput("Day24") "Part 1" { part1(testBlizzards, testSize) shouldBe 18 measureAnswer { part1(inputBlizzards, inputSize) } } "Part 2" { part2(testBlizzards, testSize) shouldBe 54 measureAnswer { part2(inputBlizzards, inputSize) } } } private fun part1(blizzards: Map<Pair<Int, Int>, Blizzard>, size: Pair<Int, Int>): Int { val (height, width) = size val valley = BlizzardBasin(blizzards, height, width) return valley.findShortestPathTo(targetR = height, targetC = width - 1) } private fun part2(blizzards: Map<Pair<Int, Int>, Blizzard>, size: Pair<Int, Int>): Int { val (height, width) = size val valley = BlizzardBasin(blizzards, height, width) return valley.findShortestPathTo(targetR = height, targetC = width - 1) + valley.findShortestPathTo(targetR = -1, targetC = 0) + valley.findShortestPathTo(targetR = height, targetC = width - 1) } private class BlizzardBasin( blizzards: Map<Pair<Int, Int>, Blizzard>, private val height: Int, private val width: Int ) { private var blizzardsPositions = blizzards.mapValues { (_, blizzard) -> listOf(blizzard) } private var positionR = -1 private var positionC = 0 fun findShortestPathTo(targetR: Int, targetC: Int): Int { val queue = ArrayDeque<Step>() queue.addLast(Step(r = positionR, c = positionC, turn = 0)) val seen = mutableSetOf<Step>() fun addNextStep(step: Step) { if (step in seen) return queue.addLast(step) seen += step } var currentTurn = 0 while (queue.isNotEmpty()) { val (r, c, turn) = queue.removeFirst() // Should we move blizzards? if (currentTurn != turn) { currentTurn = turn moveBlizzards() } // We can not share the same position with blizzards if (r to c in blizzardsPositions) continue // If current position is the target, return it if (r == targetR && c == targetC) { positionR = r positionC = c return turn } // Try to wait addNextStep(Step(r, c, turn + 1)) // Or go to one of neighbors for ((nr, nc) in neighborsOf(r, c)) { addNextStep(Step(nr, nc, turn + 1)) } } error("No way!") } private fun moveBlizzards() { blizzardsPositions = buildMap { for ((position, blizzards) in blizzardsPositions) { val (r, c) = position for (blizzard in blizzards) { val newPosition = blizzard.nextPosition(r, c) put(newPosition, getOrDefault(newPosition, emptyList()) + blizzard) } } } } fun Blizzard.nextPosition(r: Int, c: Int): Pair<Int, Int> { return (r + dr).mod(height) to (c + dc).mod(width) } private fun neighborsOf(r: Int, c: Int): Sequence<Pair<Int, Int>> { if (r == -1 && c == 0) return sequenceOf(0 to 0) if (r == height && c == width - 1) return sequenceOf(height - 1 to width - 1) return sequence { if (r > 0) yield(r - 1 to c) if (r < height - 1) yield(r + 1 to c) if (c > 0) yield(r to c - 1) if (c < width - 1) yield(r to c + 1) if (r == 0 && c == 0) yield(-1 to 0) if (r == height - 1 && c == width - 1) yield(height to width - 1) } } private data class Step(val r: Int, val c: Int, val turn: Int) } private fun readInput(name: String): Pair<Map<Pair<Int, Int>, Blizzard>, Pair<Int, Int>> { val lines = readLines(name) val blizzards = mutableMapOf<Pair<Int, Int>, Blizzard>() for (r in 1 until lines.lastIndex) { for (c in 1 until lines[r].lastIndex) { val blizzard = Blizzard.of(lines[r][c]) if (blizzard != null) blizzards[r - 1 to c - 1] = blizzard } } return blizzards to (lines.size - 2 to lines[0].length - 2) } private enum class Blizzard(val symbol: Char, val dr: Int, val dc: Int) { UP(symbol = '^', dr = -1, dc = 0), DOWN(symbol = 'v', dr = +1, dc = 0), LEFT(symbol = '<', dr = 0, dc = -1), RIGHT(symbol = '>', dr = 0, dc = +1); companion object { fun of(symbol: Char): Blizzard? = values().find { it.symbol == symbol } } }
0
Kotlin
0
5
6a67946122abb759fddf33dae408db662213a072
4,602
advent-of-code
Apache License 2.0
src/Day07.kt
MarkRunWu
573,656,261
false
{"Kotlin": 25971}
import java.lang.IllegalStateException import java.util.* import kotlin.collections.ArrayList fun main() { data class File(val name: String, val size: Int) data class Directory( val name: String, val parent: Directory?, val files: ArrayList<File> = arrayListOf(), val childDirectory: ArrayList<Directory> = arrayListOf(), var calculatedSize: Int = 0 ) fun parseDirectory(input: List<String>): Directory { var curIndex = 0 val root = Directory("/", null) var currentDirectory: Directory? = null while (curIndex < input.size) { val curLine = input[curIndex] if (curLine.startsWith("$")) { val texts = curLine.split(" ") when (texts[1]) { "cd" -> { currentDirectory = when (val dir = texts[2]) { "/" -> root ".." -> currentDirectory?.parent else -> { currentDirectory?.childDirectory?.find { it.name == dir } } } curIndex++ } "ls" -> { if (currentDirectory == null) { throw IllegalStateException("Directory is not available") } var lsIndex = curIndex + 1 while (lsIndex < input.size && !input[lsIndex].startsWith("$")) { val lineTexts = input[lsIndex].split(" ") when (lineTexts[0]) { "dir" -> currentDirectory.childDirectory.add( Directory(lineTexts[1], currentDirectory) ) else -> { currentDirectory.files.add( File( lineTexts[1], lineTexts[0].toInt() ) ) } } lsIndex++ } curIndex = lsIndex } } } } return root } fun calculateDirectorySize(dir: Directory) { dir.calculatedSize = dir.childDirectory.sumOf { calculateDirectorySize(it) it.calculatedSize } + dir.files.sumOf { it.size } } fun findDirs(dir: Directory, filter: (Int) -> Boolean): List<Directory> { val queue = LinkedList<Directory>() queue.addFirst(dir) val qualifiedDirs = ArrayList<Directory>() while (queue.isNotEmpty()) { val d = queue.poll() if (filter(d.calculatedSize)) { qualifiedDirs.add(d) } queue.addAll(d.childDirectory) } return qualifiedDirs } fun part1(input: List<String>): Int { val dir: Directory = parseDirectory(input) calculateDirectorySize(dir) return findDirs(dir) { size -> size < 100000 }.sumOf { it.calculatedSize } } fun part2(input: List<String>): Int { val dir = parseDirectory(input) calculateDirectorySize(dir) val goal = 30000000 - (70000000 - dir.calculatedSize) return findDirs(dir) { size -> size > goal } .minOf { it.calculatedSize } } val input = readInput("Day07") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
ced885dcd6b32e8d3c89a646dbdcf50b5665ba65
3,758
AOC-2022
Apache License 2.0
src/twentytwentythree/day04/Day04.kt
colinmarsch
571,723,956
false
{"Kotlin": 65403, "Python": 6148}
package twentytwentythree.day04 import readInput import kotlin.math.pow fun main() { fun part1(input: List<String>): Int { return input.sumOf { line -> val numbers = line.split(":")[1].split("|") val winningNumbers = numbers[0].split(" ").mapNotNull { it.toIntOrNull() }.toSet() val myNumbers = numbers[1].split(" ").mapNotNull { it.toIntOrNull() }.toSet() 2.toDouble().pow(winningNumbers.intersect(myNumbers).size - 1).toInt() } } fun part2(input: List<String>): Int { val stackCounts = mutableListOf<Int>() for (i in input.indices) { stackCounts.add(1) } return input.sumOf { line -> val currentCount = stackCounts.removeFirst() val numbers = line.split(":")[1].split("|") val winningNumbers = numbers[0].split(" ").mapNotNull { it.toIntOrNull() }.toSet() val myNumbers = numbers[1].split(" ").mapNotNull { it.toIntOrNull() }.toSet() val newCards = winningNumbers.intersect(myNumbers).size for (i in 0 until newCards) { stackCounts[i] += currentCount } currentCount } } val input = readInput("twentytwentythree/day04", "Day04_input") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
bcd7a08494e6db8140478b5f0a5f26ac1585ad76
1,343
advent-of-code
Apache License 2.0
src/aoc2022/Day08.kt
miknatr
576,275,740
false
{"Kotlin": 413403}
package aoc2022 import kotlin.math.max fun main() { fun parseGrid(input: List<String>) = input .filter { it != "" } .map { it.map { char -> char.digitToInt() } } fun List<List<Int>>.countVisibleTrees(): Int { val gridSize = first().size var invisibleCount = 0 withIndex().forEach { (x, line) -> line.withIndex().forEach inner@{ (y, height) -> val lineBefore = (0 until x) if (lineBefore.isEmpty()) return@inner if (height > lineBefore.map { this[it][y] }.max()) return@inner val lineAfter = (x + 1 until gridSize) if (lineAfter.isEmpty()) return@inner if (height > lineAfter.map { this[it][y] }.max()) return@inner val columnBefore = (0 until y) if (columnBefore.isEmpty()) return@inner if (height > columnBefore.map { this[x][it] }.max()) return@inner val columnAfter = (y + 1 until gridSize) if (columnAfter.isEmpty()) return@inner if (height > columnAfter.map { this[x][it] }.max()) return@inner invisibleCount++ } } return gridSize * gridSize - invisibleCount } fun List<List<Int>>.getScore(x: Int, y: Int): Int { val gridSize = first().size val height = this[x][y] var lineBeforeScore = 0 for (i in x - 1 downTo 0) { if (this[i][y] >= height) { lineBeforeScore++ break } lineBeforeScore++ } var lineAfterScore = 0 for (i in x + 1 until gridSize) { if (this[i][y] >= height) { lineAfterScore++ break } lineAfterScore++ } var columnBeforeScore = 0 for (i in y - 1 downTo 0) { if (this[x][i] >= height) { columnBeforeScore++ break } columnBeforeScore++ } var columnAfterScore = 0 for (i in y + 1 until gridSize) { if (this[x][i] >= height) { columnAfterScore++ break } columnAfterScore++ } return lineBeforeScore * lineAfterScore * columnBeforeScore * columnAfterScore } fun part1(input: List<String>) = parseGrid(input).countVisibleTrees() fun part2(input: List<String>): Int { val grid = parseGrid(input) var maxScore = 0 grid.withIndex().forEach { (x, line) -> line.withIndex().forEach { (y, _) -> maxScore = max(grid.getScore(x, y), maxScore) } } return maxScore } val testInput = readInput("Day08_test") part1(testInput).println() part2(testInput).println() val input = readInput("Day08") part1(input).println() part2(input).println() }
0
Kotlin
0
0
400038ce53ff46dc1ff72c92765ed4afdf860e52
2,983
aoc-in-kotlin
Apache License 2.0
archive/2022/Day12_submission.kt
mathijs81
572,837,783
false
{"Kotlin": 167658, "Python": 725, "Shell": 57}
private const val EXPECTED_1 = 31 private const val EXPECTED_2 = 29 /** * Pretty horrible code written during the race. Rushed too quickly to dfs before I * realized that that won't work without revisiting nodes when you see that they can be reached * in fewer steps than before. Fortunately it could be patched up and was still fast enough to * complete the challenge */ private class Day12_submission(isTest: Boolean) : Solver(isTest) { val MAX = 100000000 var X = 0 var Y = 0 var targ = 0 to 0 lateinit var best: List<MutableList<Int>> val dirs = listOf(0 to 1, 0 to -1, 1 to 0, -1 to 0) var reverse = false fun dfs(loc: Pair<Int, Int>, heights: List<List<Int>>, steps: Int) { if (loc.second !in 0 until X || loc.first !in 0 until Y) { return } if (best[loc.first][loc.second] <= steps) { return } best[loc.first][loc.second] = steps for (dir in dirs) { val n = (loc.first + dir.first) to (loc.second + dir.second) if (n.first in 0 until Y && n.second in 0 until X) { if ((if (reverse) -1 else 1) * (heights[n.first][n.second] - heights[loc.first][loc.second]) <= 1) { dfs(n, heights, steps + 1) } } } } fun part1(): Any { var start = 0 to 0 val heights = readAsLines().withIndex().map { (y, line) -> line.toCharArray().toList().withIndex().map { (x, value) -> if (value == 'S') { start = y to x 0 } else if (value == 'E') { targ = y to x 'z' - 'a' } else value - 'a' } } Y = heights.size X = heights[0].size best = heights.map { IntArray(it.size) { MAX }.toMutableList() } dfs(start, heights, 0) return best[targ.first][targ.second] } fun part2(): Any { var start = 0 to 0 val heights = readAsLines().withIndex().map { (y, line) -> line.toCharArray().toList().withIndex().map { (x, value) -> if (value == 'S') { start = y to x 0 } else if (value == 'E') { targ = y to x 'z' - 'a' } else value - 'a' } } Y = heights.size X = heights[0].size best = heights.map { IntArray(it.size) { MAX }.toMutableList() } reverse = true dfs(targ, heights, 0) var answer = MAX for (y in 0 until Y) for (x in 0 until X) { if (heights[y][x] == 0) { answer = answer.coerceAtMost(best[y][x]) } } return answer } } fun main() { val testInstance = Day12_submission(true) val instance = Day12_submission(false) testInstance.part1().let { check(it == EXPECTED_1) { "part1: $it != $EXPECTED_1" } } println("part1 ANSWER: ${instance.part1()}") testInstance.part2().let { check(it == EXPECTED_2) { "part2: $it != $EXPECTED_2" } println("part2 ANSWER: ${instance.part2()}") } }
0
Kotlin
0
2
92f2e803b83c3d9303d853b6c68291ac1568a2ba
3,258
advent-of-code-2022
Apache License 2.0
src/Day01.kt
Jessenw
575,278,448
false
{"Kotlin": 13488}
fun main() { fun part1(input: String): Int { // Split into each elves' list of carried calories val carriedCalories = input.split("\n\n") var maxCalories = -1 carriedCalories.forEach { carried -> val calorieItems = carried.split("\n") var totalCalories = 0 calorieItems.forEach { if (it != "") totalCalories += it.toInt() } if (totalCalories > maxCalories) maxCalories = totalCalories } return maxCalories } fun part2(input: String) : Int { // Find the total amount of calories each elf if carrying val totalCalories = input.split("\n\n") .map { bag -> bag.lines().sumOf { it.toIntOrNull() ?: 0 // Handle empty string } } // Order sums and then pick the 3 highest to sum return totalCalories .sortedDescending() .toIntArray() .take(3) .sum() } val testInput = readInputText("Day01_test") println(part1(testInput)) println(part2(testInput)) check(part1(testInput) == 24000) check(part2(testInput) == 45000) val input = readInputText("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
05c1e9331b38cfdfb32beaf6a9daa3b9ed8220a3
1,321
aoc-22-kotlin
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/MinimumCostToCutStick.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2020 <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.Arrays import kotlin.math.min /** * 1547. Minimum Cost to Cut a Stick * @see <a href="https://leetcode.com/problems/minimum-cost-to-cut-a-stick">Source</a> */ fun interface MinimumCostToCutStick { fun minCost(n: Int, cuts: IntArray): Int } /** * Approach 1: Top-down Dynamic Programming */ class MinimumCostToCutStickTopDown : MinimumCostToCutStick { private lateinit var memo: Array<IntArray> private lateinit var newCuts: IntArray override fun minCost(n: Int, cuts: IntArray): Int { val m: Int = cuts.size newCuts = IntArray(m + 2) System.arraycopy(cuts, 0, newCuts, 1, m) newCuts[m + 1] = n Arrays.sort(newCuts) memo = Array(m + 2) { IntArray(m + 2) } for (r in 0 until m + 2) { Arrays.fill(memo[r], -1) } return cost(0, newCuts.size - 1) } private fun cost(left: Int, right: Int): Int { if (memo[left][right] != -1) { return memo[left][right] } if (right - left == 1) { return 0 } var ans = Int.MAX_VALUE for (mid in left + 1 until right) { val cost = cost(left, mid) + cost(mid, right) + newCuts[right] - newCuts[left] ans = min(ans, cost) } memo[left][right] = ans return ans } } /** * Approach 2: Bottom-up Dynamic Programming */ class MinimumCostToCutStickBottomUp : MinimumCostToCutStick { override fun minCost(n: Int, cuts: IntArray): Int { val m: Int = cuts.size val newCuts = IntArray(m + 2) System.arraycopy(cuts, 0, newCuts, 1, m) newCuts[m + 1] = n newCuts.sort() val dp = Array(m + 2) { IntArray(m + 2) } for (diff in 2 until m + 2) { for (left in 0 until m + 2 - diff) { val right = left + diff var ans = Int.MAX_VALUE for (mid in left + 1 until right) { ans = min(ans, dp[left][mid] + dp[mid][right] + newCuts[right] - newCuts[left]) } dp[left][right] = ans } } return dp[0][m + 1] } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
2,816
kotlab
Apache License 2.0
src/Day05.kt
vjgarciag96
572,719,091
false
{"Kotlin": 44399}
private val INSTRUCTION_PATTERN = Regex("[0-9]+") fun main() { fun part1(input: List<String>): String { val cratesPlan = input.takeWhile { it.isNotBlank() } val stackCount = cratesPlan.last().trimEnd().last().digitToInt() val maxStackHeight = cratesPlan.size - 1 val crates = Array(stackCount) { i -> val stack = ArrayList<Char>() val charIndex = 1 + 4 * i repeat(maxStackHeight) { j -> val row: String = cratesPlan[j] if (charIndex < row.length) { val char = row[charIndex] if (char != ' ') { stack.add(row[charIndex]) } } } stack } val instructions = input.takeLast(input.size - (cratesPlan.size + 1)) instructions.forEach { instruction -> val (move, from, to) = INSTRUCTION_PATTERN .findAll(input = instruction) .map { it.value } .toList() repeat(move.toInt()) { val fromItem = crates[from.toInt() - 1].removeFirstOrNull() fromItem?.let { crates[to.toInt() - 1].add(0, it) } } } return crates.joinToString(separator = "") { column -> column.first().toString() } } fun part2(input: List<String>): String { val cratesPlan = input.takeWhile { it.isNotBlank() } val stackCount = cratesPlan.last().trimEnd().last().digitToInt() val maxStackHeight = cratesPlan.size - 1 val crates = Array(stackCount) { i -> val stack = ArrayList<Char>() val charIndex = 1 + 4 * i repeat(maxStackHeight) { j -> val row: String = cratesPlan[j] if (charIndex < row.length) { val char = row[charIndex] if (char != ' ') { stack.add(row[charIndex]) } } } stack } val instructions = input.takeLast(input.size - (cratesPlan.size + 1)) instructions.forEach { instruction -> val (move, from, to) = INSTRUCTION_PATTERN .findAll(input = instruction) .map { it.value } .toList() val originStack = crates[from.toInt() - 1] val nItemsToMove = move.toInt().coerceAtMost(originStack.size) val itemsToMove = originStack.subList(0, nItemsToMove) crates[to.toInt() - 1].addAll(0, itemsToMove) repeat(nItemsToMove) { originStack.removeFirst() } } return crates.joinToString(separator = "") { column -> column.first().toString() } } 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
ee53877877b21166b8f7dc63c15cc929c8c20430
2,991
advent-of-code-2022
Apache License 2.0
src/Day10.kt
ricardorlg-yml
573,098,872
false
{"Kotlin": 38331}
class Day10Solver(private val input: List<String>) { enum class Command(private val _name: String, val cost: Int) { NOOP("noop", 1), ADD("addx", 2); companion object { fun fromName(name: String) = values().first { it._name == name } } } data class Instruction(val command: Command, val value: Int) private fun parseInput(): List<Instruction> = input.map { val line = it.split(" ") val command = Command.fromName(line[0]) val value = line.getOrNull(1)?.toInt() ?: 0 Instruction(command, value) } private fun loadRegistry(program: List<Instruction>, registry: MutableMap<Int, Int>) { var x = 1 var cycle = 1 registry[cycle] = x program.forEach { instruction -> cycle += instruction.command.cost registry[cycle - 1] = x x += instruction.value registry[cycle] = x } } fun solvePart1(): Long { val cycles = (20..220 step 40) val instructions = parseInput() val registry = mutableMapOf<Int, Int>() loadRegistry(instructions, registry) return cycles.sumOf { registry[it]!! * it.toLong() } } fun solvePart2() { val instructions = parseInput() val registry = mutableMapOf<Int, Int>() loadRegistry(instructions, registry) (0 until 240) .chunked(40) .joinToString("\n") { it.joinToString("") { i -> val sp = registry[i + 1]!! val crtPos = i % 40 "#".takeIf { crtPos >= sp - 1 && crtPos <= sp + 1 } ?: " " } }.also { println(BLACK_BOLD + it + ANSI_RESET) } } } fun main() { // val input = readInput("Day10_test") val input = readInput("Day10") val solver = Day10Solver(input) //check(solver.solvePart1().also { println(it) } == 13140L) println(solver.solvePart1()) solver.solvePart2() }
0
Kotlin
0
0
d7cd903485f41fe8c7023c015e4e606af9e10315
2,061
advent_code_2022
Apache License 2.0
src/main/kotlin/com/chriswk/aoc/advent2015/Day15.kt
chriswk
317,863,220
false
{"Kotlin": 481061}
package com.chriswk.aoc.advent2015 import com.chriswk.aoc.AdventDay import com.chriswk.aoc.util.report import java.lang.Math.max class Day15: AdventDay(2015, 15) { companion object { @JvmStatic fun main(args: Array<String>) { val day = Day15() report { day.part1() } report { day.part2() } } val regex = """(.*): capacity (-?\d+), durability (-?\d+), flavor (-?\d+), texture (-?\d+), calories (-?\d+)""".toRegex() } private fun List<Ingredient>.capacity(num: List<Int>) = 0L.coerceAtLeast(mapIndexed { index: Int, ingredient: Ingredient -> num[index] * ingredient.capacity }.sum() .toLong() ) private fun List<Ingredient>.durability(num: List<Int>) = 0L.coerceAtLeast(mapIndexed { index: Int, ingredient: Ingredient -> num[index] * ingredient.durability }.sum() .toLong() ) private fun List<Ingredient>.flavor(num: List<Int>) = 0L.coerceAtLeast(mapIndexed { index: Int, ingredient: Ingredient -> num[index] * ingredient.flavor }.sum() .toLong() ) private fun List<Ingredient>.texture(num: List<Int>) = 0L.coerceAtLeast(mapIndexed { index: Int, ingredient: Ingredient -> num[index] * ingredient.texture }.sum() .toLong() ) private fun List<Ingredient>.calories(num: List<Int>) = 0L.coerceAtLeast(mapIndexed { index: Int, ingredient: Ingredient -> num[index] * ingredient.calories }.sum() .toLong() ) private fun score(ingredients: List<Ingredient>, i: Int, j: Int, k: Int, l: Int): Long { val capacity = ingredients.capacity(listOf(i, j, k, l)) val durability = ingredients.durability(listOf(i, j, k, l)) val flavor = ingredients.flavor(listOf(i, j, k, l)) val texture = ingredients.texture(listOf(i, j, k, l)) return capacity * durability * flavor * texture } fun maxValueFor500Calories(ingredients: List<Ingredient>): Long { return (0..100).asSequence().flatMap { i -> (0..(100 - i)).asSequence().flatMap { j -> (0..(100 - i - j)).asSequence().flatMap { k -> (0..(100 - i - j - k)).asSequence().map { l -> ingredients.calories(listOf(i, j, k, l)) to score(ingredients, i, j, k, l) } } } }.filter { it.first == 500L }.maxOf { it.second } } fun calculateMaxValue(ingredients: List<Ingredient>): Long { return (0..100).asSequence().flatMap { i -> (0 .. (100 - i)).asSequence().flatMap { j -> (0 .. (100 - i - j)).asSequence().flatMap { k -> (0 .. (100-i-j-k)).asSequence().map { l -> score(ingredients, i, j, k, l) } } } }.max() } fun parseInput(input: List<String>): List<Ingredient> { return input.map { Ingredient(it) } } fun part1(): Long { return calculateMaxValue(parseInput(inputAsLines)) } fun part2(): Long { return maxValueFor500Calories(parseInput(inputAsLines)) } data class Ingredient(val name: String, val capacity: Int, val durability: Int, val flavor: Int, val texture: Int, val calories: Int) { constructor(str: String, mr: MatchResult.Destructured = regex.find(str)!!.destructured) : this( mr.component1(), mr.component2().toInt(), mr.component3().toInt(), mr.component4().toInt(), mr.component5().toInt(), mr.component6().toInt(), ) } }
116
Kotlin
0
0
69fa3dfed62d5cb7d961fe16924066cb7f9f5985
3,740
adventofcode
MIT License
src/Day21.kt
azat-ismagilov
573,217,326
false
{"Kotlin": 75114}
enum class Operation { PLUS, MINUS, MUL, DIV } data class MonkeyYellOperation(val nameLeft: String, val nameRight: String, val operation: Operation) { fun apply(valueLeft: Long, valueRight: Long) = when (operation) { Operation.PLUS -> valueLeft + valueRight Operation.MINUS -> valueLeft - valueRight Operation.MUL -> valueLeft * valueRight Operation.DIV -> valueLeft / valueRight } fun dependentOn() = listOf(nameLeft, nameRight) fun getLeftValue(value: Long, wantedResult: Long): Pair<String, Long> = Pair( nameLeft, when (operation) { Operation.PLUS -> wantedResult - value Operation.MINUS -> wantedResult + value Operation.MUL -> wantedResult / value Operation.DIV -> wantedResult * value } ) fun getRightValue(value: Long, wantedResult: Long): Pair<String, Long> = Pair( nameRight, when (operation) { Operation.PLUS -> wantedResult - value Operation.MINUS -> value - wantedResult Operation.MUL -> wantedResult / value Operation.DIV -> value / wantedResult } ) companion object { fun of(string: String): MonkeyYellOperation { val tokens = string.split(' ') val operation = when (tokens[1]) { "+" -> Operation.PLUS "-" -> Operation.MINUS "*" -> Operation.MUL "/" -> Operation.DIV else -> throw RuntimeException() } return MonkeyYellOperation(tokens[0], tokens[2], operation) } } } fun String.isLong() = this.toLongOrNull() != null sealed interface YellingMonkey { companion object { fun of(string: String): Pair<String, YellingMonkey> { val (name, other) = string.split(": ") return if (other.isLong()) name to SimpleYellingMonkey(other.toLong()) else name to ComplexYellingMonkey(MonkeyYellOperation.of(other)) } } } data class SimpleYellingMonkey(val value: Long) : YellingMonkey data class ComplexYellingMonkey(val yellOperation: MonkeyYellOperation) : YellingMonkey fun main() { val day = 21 fun part1(input: List<String>): Long { val monkeys = input.associate { YellingMonkey.of(it) }.toMutableMap() repeat(monkeys.size) { for ((name, currentMonkey) in monkeys) { if (currentMonkey is ComplexYellingMonkey) { with(currentMonkey.yellOperation) { val dependentMonkeys = dependentOn().map { searchName -> monkeys[searchName] } if (dependentMonkeys.all { it is SimpleYellingMonkey }) { val (leftValue, rightValue) = dependentMonkeys.map { (it as SimpleYellingMonkey).value } monkeys[name] = SimpleYellingMonkey(apply(leftValue, rightValue)) } } } if (name == "root" && currentMonkey is SimpleYellingMonkey) { return currentMonkey.value } } } return 0 } fun part2(input: List<String>): Long { val monkeys = input.associate { YellingMonkey.of(it) }.toMutableMap() monkeys.remove("humn") val root = monkeys["root"] as ComplexYellingMonkey monkeys.remove("root") var someThingInterestingHappened = true while (someThingInterestingHappened) { someThingInterestingHappened = false for ((name, currentMonkey) in monkeys) { if (currentMonkey is ComplexYellingMonkey) { with(currentMonkey.yellOperation) { val dependentMonkeys = dependentOn().map { searchName -> monkeys[searchName] } if (dependentMonkeys.all { it is SimpleYellingMonkey }) { val (leftValue, rightValue) = dependentMonkeys.map { (it as SimpleYellingMonkey).value } monkeys[name] = SimpleYellingMonkey(apply(leftValue, rightValue)) someThingInterestingHappened = true } } } } } var necessaryPair = with(root.yellOperation) { val (leftMonkey, rightMonkey) = dependentOn().map { searchName -> searchName to monkeys[searchName] } if (leftMonkey.second is SimpleYellingMonkey) rightMonkey.first to (leftMonkey.second as SimpleYellingMonkey).value else leftMonkey.first to (rightMonkey.second as SimpleYellingMonkey).value } while (necessaryPair.first != "humn") with((monkeys[necessaryPair.first] as ComplexYellingMonkey).yellOperation) { val (leftMonkey, rightMonkey) = dependentOn().map { searchName -> searchName to monkeys[searchName] } necessaryPair = if (leftMonkey.second is SimpleYellingMonkey) getRightValue((leftMonkey.second as SimpleYellingMonkey).value, necessaryPair.second) else getLeftValue((rightMonkey.second as SimpleYellingMonkey).value, necessaryPair.second) } return necessaryPair.second } // test if implementation meets criteria from the description, like: val testInput = readInput("Day${day}_test") check(part1(testInput) == 152L) check(part2(testInput) == 301L) val input = readInput("Day${day}") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
abdd1b8d93b8afb3372cfed23547ec5a8b8298aa
5,809
advent-of-code-kotlin-2022
Apache License 2.0
src/Day05.kt
armandmgt
573,595,523
false
{"Kotlin": 47774}
fun main() { val indexesPattern = Regex("(:? \\d ? ?)+") val cratePattern = Regex(".{3} ?") fun parseCrates(inputIterator: ListIterator<String>): Map<Int, ArrayDeque<Char>> { val stacks = mutableMapOf<Int, MutableList<Char>>() run breaking@ { inputIterator.forEach { line -> if (line.matches(indexesPattern)) return@breaking val m = cratePattern.findAll(line) m.forEachIndexed { idx, matchResult -> if (matchResult.value[1] == ' ') return@forEachIndexed if (stacks[idx + 1] == null) stacks[idx + 1] = mutableListOf() stacks[idx + 1]!!.add(0, matchResult.value[1]) } } } inputIterator.next() return stacks.mapValues { entry -> ArrayDeque(entry.value) } } val opPattern = Regex("move (\\d+) from (\\d+) to (\\d+)") fun part1(input: List<String>): String { val crane = ArrayDeque<Char>() val iterator = input.listIterator() val stacks = parseCrates(iterator) iterator.forEachRemaining { operation -> val (count, origin, dest) = opPattern.find(operation)!!.destructured.toList().map(String::toInt) repeat(count) { crane.addLast(stacks[origin]!!.removeLast()) } repeat(count) { stacks[dest]!!.addLast(crane.removeFirst()) } } return (1 until stacks.size + 1).map { stacks[it]!!.last() }.joinToString("") } fun part2(input: List<String>): String { val crane = ArrayDeque<Char>() val iterator = input.listIterator() val stacks = parseCrates(iterator) iterator.forEachRemaining { operation -> val (count, origin, dest) = opPattern.find(operation)!!.destructured.toList().map(String::toInt) repeat(count) { crane.addLast(stacks[origin]!!.removeLast()) } repeat(count) { stacks[dest]!!.addLast(crane.removeLast()) } } return (1 until stacks.size + 1).map { stacks[it]!!.last() }.joinToString("") } // test if implementation meets criteria from the description, like: val testInput = readInput("resources/Day05_test") check(part1(testInput) == "CMZ") val input = readInput("resources/Day05") println(part1(input)) check(part2(testInput) == "MCD") println(part2(input)) }
0
Kotlin
0
1
0d63a5974dd65a88e99a70e04243512a8f286145
2,387
advent_of_code_2022
Apache License 2.0
src/day03/Day03.kt
ivanovmeya
573,150,306
false
{"Kotlin": 43768}
package day03 import readInput data class IndexCount(val stringIndex: Int, val commonCount: Int) fun main() { fun Char.toPriority() = when { this.isLowerCase() -> this - 'a' + 1 else -> this - 'A' + 27 } fun String.toCompartments() = substring(0, length / 2) to substring(length / 2, length) fun findSameChar(strings: List<String>): Char? { val frequencyTable = hashMapOf<Char, IndexCount>() strings.forEachIndexed { index, s -> s.forEach { val indexCount = frequencyTable[it] if (indexCount == null) { frequencyTable[it] = IndexCount(index, 1) } else { if (indexCount.stringIndex != index) { frequencyTable[it] = IndexCount(index, indexCount.commonCount + 1) } } } } val sameChar = frequencyTable.firstNotNullOfOrNull { if (it.value.commonCount == strings.size) { it.key } else { null } } return sameChar } fun findSameChar(vararg params: String): Char? { return findSameChar(params.toList()) } fun part1(input: List<String>): Int { return input.sumOf { rucksack -> val (first, second) = rucksack.toCompartments() findSameChar(first, second)?.toPriority() ?: throw IllegalStateException("Rucksack $rucksack does not share element in it's compartmets") } } fun part2(input: List<String>): Int { return input.chunked(3).sumOf { findSameChar(it[0], it[1], it[2])?.toPriority() ?: throw IllegalStateException("Group of three Elfs ${it.joinToString("\n")} do not have shared element") } } val testInput = readInput("day03/input_test") val test1Result = part1(testInput) val test2Result = part2(testInput) println(test1Result) println(test2Result) check(test1Result == 157) check(test2Result == 70) val input = readInput("day03/input") check(part1(input) == 7850) check(part2(input) == 2581) }
0
Kotlin
0
0
7530367fb453f012249f1dc37869f950bda018e0
2,195
advent-of-code-2022
Apache License 2.0
src/Day08.kt
MwBoesgaard
572,857,083
false
{"Kotlin": 40623}
import kotlin.math.max import kotlin.math.min fun main() { fun isTreeHighestLowerBound(tree: Int, list: List<Int>, index: Int): Boolean { if (index == 0) { return true } return list.slice(0 until index).max() < tree } fun isTreeHighestUpperBound(tree: Int, list: List<Int>, index: Int): Boolean { val max = list.size if (index + 1 >= max) { return true } return tree > list.slice(index + 1 until max).max() } fun isTreeHighestForRowIndex(tree: Int, rowIndex: Int, colIndex: Int, matrix: List<List<Int>>): Boolean { val row = matrix[rowIndex] val lowerBound = isTreeHighestLowerBound(tree, row, colIndex) val upperBound = isTreeHighestUpperBound(tree, row, colIndex) return lowerBound || upperBound } fun isTreeHighestForColIndex(tree: Int, rowIndex: Int, colIndex: Int, matrix: List<List<Int>>): Boolean { val listOfColValues = mutableListOf<Int>() for (row in matrix) { listOfColValues.add(row[colIndex]) } val lowerBound = isTreeHighestLowerBound(tree, listOfColValues, rowIndex) val upperBound = isTreeHighestUpperBound(tree, listOfColValues, rowIndex) return lowerBound || upperBound } fun buildMatrix(input: List<String>): List<List<Int>> { val matrix = arrayListOf<List<Int>>() for (line in input) { matrix.add(line.chunked(1).map { it.toInt() }) } return matrix } fun isTreeVisible(tree: Int, rowIndex: Int, colIndex: Int, matrix: List<List<Int>>): Boolean { return isTreeHighestForColIndex(tree, rowIndex, colIndex, matrix) || isTreeHighestForRowIndex( tree, rowIndex, colIndex, matrix ) } fun getMatrixSliceAroundIndex(rowIndex: Int, colIndex: Int, size: Int, matrix: List<List<Int>>): List<List<Int>> { val colLowerBound = max(colIndex - size, 0) val colUpperBound = min(colIndex + size, matrix.size - 1) val rowLowerBound = max(rowIndex - size, 0) val rowUpperBound = min(rowIndex + size, matrix[0].size - 1) // Mark the tree in question val mutMatrixCopy = matrix.toMutableList().map { it.toMutableList() } mutMatrixCopy[rowIndex][colIndex] = -1 return mutMatrixCopy.slice(rowLowerBound..rowUpperBound).map { it.slice(colLowerBound..colUpperBound) } } fun getAdjustedTreeIndexes(matrixSlice: List<List<Int>>): Pair<Int, Int>? { for ((i, row) in matrixSlice.withIndex()) { for ((j, tree) in row.withIndex()) { if (tree == -1) { return Pair(i, j) } } } return null } fun isAnOuterTree(rowIndex: Int, colIndex: Int, matrix: List<List<Int>>): Boolean { if (rowIndex == 0 || rowIndex == matrix.size - 1) { return true } if (colIndex == 0 || colIndex == matrix[0].size - 1) { return true } return false } fun part1(input: List<String>): Int { val matrix = buildMatrix(input) val answerMatrix = mutableListOf<List<Int>>() for ((rowIndex, row) in matrix.withIndex()) { val newRow = mutableListOf<Int>() for ((colIndex, tree) in row.withIndex()) { newRow.add(if (isTreeVisible(tree, rowIndex, colIndex, matrix)) 1 else 0) } answerMatrix.add(newRow) } return answerMatrix.sumOf { it.sum() } } fun part2(input: List<String>): Int { val matrix = buildMatrix(input) val listOfScenicScores = mutableListOf<Int>() for ((rowIndex, row) in matrix.withIndex()) { for ((colIndex, tree) in row.withIndex()) { if (isAnOuterTree(rowIndex, colIndex, matrix)) { continue } var northDist = 0 var eastDist = 0 var southDist = 0 var westDist = 0 for (size in 1 until matrix.size) { if (listOf(northDist, eastDist, southDist, westDist).all { it != 0 }) { break } val matrixSlice = getMatrixSliceAroundIndex(rowIndex, colIndex, size, matrix) val (adjustedRowIndex, adjustedColIndex) = getAdjustedTreeIndexes(matrixSlice)!! val adjustedRow = matrixSlice[adjustedRowIndex] val adjustedCol = mutableListOf<Int>() for (rowSlice in matrixSlice) { adjustedCol.add(rowSlice[adjustedColIndex]) } adjustedCol.reverse() // North if (northDist == 0 && (!isTreeHighestUpperBound( tree, adjustedCol, adjustedRowIndex ) || rowIndex - size <= 0) ) { northDist = size } // East if (eastDist == 0 && (!isTreeHighestUpperBound( tree, adjustedRow, adjustedColIndex ) || colIndex + size >= matrix.size - 1) ) { eastDist = size } // South if (southDist == 0 && (!isTreeHighestLowerBound( tree, adjustedCol, adjustedRowIndex ) || rowIndex + size >= matrix.size - 1) ) { southDist = size } // West if (westDist == 0 && (!isTreeHighestLowerBound( tree, adjustedRow, adjustedColIndex ) || colIndex - size <= 0) ) { westDist = size } } if (northDist == 0) { northDist = matrix.size } if (eastDist == 0) { eastDist = matrix.size } if (southDist == 0) { southDist = matrix.size } if (westDist == 0) { westDist = matrix.size } listOfScenicScores.add(northDist * eastDist * southDist * westDist) } } return listOfScenicScores.max() } printSolutionFromInputLines("Day08", ::part1) printSolutionFromInputLines("Day08", ::part2) }
0
Kotlin
0
0
3bfa51af6e5e2095600bdea74b4b7eba68dc5f83
6,924
advent_of_code_2022
Apache License 2.0
src/main/kotlin/dev/patbeagan/days/Day08.kt
patbeagan1
576,401,502
false
{"Kotlin": 57404}
package dev.patbeagan.days import dev.patbeagan.CanTraverse import dev.patbeagan.takeUntil /** * [Day 8](https://adventofcode.com/2022/day/8) */ class Day08 : AdventDay<Int> { override fun part1(input: String) = parseInput(input) .let { treeGrid -> var count = 0 treeGrid.walk { _, x, y -> if (treeGrid.isTreeVisibleAt(x, y)) { count++ } } count } override fun part2(input: String): Int { val treeGrid = parseInput(input) val scenicScores = mutableListOf<Int>() treeGrid.walk { _, x, y -> treeGrid.scenicScoreAt(x, y).let { scenicScores.add(it) } } return scenicScores.max() } fun parseInput(input: String) = input .trim() .split("\n") .map { s -> s.map { Tree(it.toString().toInt()) } } .let { TreeGrid(it) } .also { println(it) } @JvmInline value class Tree(val height: Int) @JvmInline value class TreeGrid(private val trees: List<List<Tree>>) : CanTraverse { fun isTreeVisibleAt(x: Int, y: Int): Boolean { val tree = trees[y][x] TreeScanner(trees) .getLanes(x, y) .run { if (left.all { it.height < tree.height }) return true if (right.all { it.height < tree.height }) return true if (top.all { it.height < tree.height }) return true if (bottom.all { it.height < tree.height }) return true return false } } fun walk(action: (tree: Tree, x: Int, y: Int) -> Unit) = trees.traverse(action) fun scenicScoreAt(x: Int, y: Int): Int { val tree = trees[y][x] TreeScanner(trees) .getLanes(x, y) .run { return listOf( left.asReversed().takeUntil { it.height < tree.height }.count(), top.asReversed().takeUntil { it.height < tree.height }.count(), right.takeUntil { it.height < tree.height }.count(), bottom.takeUntil { it.height < tree.height }.count(), ).fold(1) { acc, each -> each * acc } } } override fun toString(): String = buildString { trees.forEachIndexed { indexY, each -> each.forEachIndexed { indexX, _ -> if (isTreeVisibleAt(indexX, indexY)) { append("X") } else { append("-") } } appendLine() } appendLine("-----") trees.forEach { eachRow -> eachRow.forEach { each -> append(each.height) } appendLine() } } @JvmInline value class TreeScanner(private val trees: List<List<Tree>>) { fun getLanes( x: Int, y: Int ): TreeLane { val row = trees[y] val col = trees.map { it[x] } val (left, right) = splitTrees(row, x) val (top, bottom) = splitTrees(col, y) return TreeLane(left, top, right, bottom) } private fun splitTrees(list: List<Tree>, pivot: Int): Pair<List<Tree>, List<Tree>> { val prevList = mutableListOf<Tree>() val nextList = mutableListOf<Tree>() list.forEachIndexed { index, each -> when { index < pivot -> prevList.add(each) index > pivot -> nextList.add(each) } } return prevList to nextList } data class TreeLane( val left: List<Tree>, val top: List<Tree>, val right: List<Tree>, val bottom: List<Tree> ) { fun printLanes() { val indent = buildString { repeat(left.size) { append(" ") } } for (i in top) { println(indent + i.height) } for (i in left) { print(i.height) } print("X") for (i in right) { print(i.height) } print("\n") for (i in bottom) { println(indent + i.height) } println() } } } } }
0
Kotlin
0
0
4e25b38226bcd0dbd9c2ea18553c876bf2ec1722
4,830
AOC-2022-in-Kotlin
Apache License 2.0
src/Day03.kt
TrevorSStone
573,205,379
false
{"Kotlin": 9656}
fun Char.points(): Int = when { isLowerCase() -> code - 'a'.code + 1 isUpperCase() -> code - 'A'.code + 27 else -> 0 } fun main() { check('a'.points() == 1) check('z'.points() == 26) check('A'.points() == 27) check('Z'.points() == 52) fun part1(input: List<String>): Int = input.sumOf { line -> line .chunkedSequence(line.length / 2) .map { it.toSet() } .reduce { intersection, half -> intersection.intersect(half) } .sumOf { it.points() } } fun part2(input: List<String>): Int = input.chunked(3).sumOf { lines -> lines .asSequence() .map { it.toSet() } .reduce { intersection, line -> intersection.intersect(line) } .sumOf { it.points() } } 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
2a48776f8bc10fe1d7e2bbef171bf65be9939400
1,011
advent-of-code-2022-kotlin
Apache License 2.0
src/main/kotlin/dev/bogwalk/batch1/Problem11.kt
bog-walk
381,459,475
false
null
package dev.bogwalk.batch1 import dev.bogwalk.util.custom.IntMatrix2D import dev.bogwalk.util.custom.product /** * Problem 11: Largest Product in a Grid * * https://projecteuler.net/problem=11 * * Goal: Find the largest product of 4 adjacent integers in the same direction (up, down, left, * right, diagonal) in an NxN grid. * * Constraints: 0 <= integer <= 100, 4 <= N <= 20 * * e.g.: 1 1 1 1 * 1 1 2 1 * 1 1 3 1 * 1 1 1 1 * column {1,2,3,1} = 6 */ class LargestProductInGrid { private val series: Int = 4 /** * Solution uses custom class IntMatrix2D to abstract away most of the functions. * * SPEED (BETTER) 2.07ms for N = 20 */ fun largestProductInGridCustom(grid: IntMatrix2D): Int { return maxOf( getMaxProduct(grid), getMaxProduct(grid.transpose(), allDirections = false) ) } private fun getMaxProduct(grid: IntMatrix2D, allDirections: Boolean = true): Int { var maxProd = 0 for ((i, row) in grid.withIndex()) { var col = 0 while (col <= row.size - series) { val right = row.sliceArray(col until col + series).product() var leadingDiag = 0 var counterDiag = 0 if (allDirections && i <= grid.size - series) { leadingDiag = IntArray(series) { grid[i+it][col+it] }.product() counterDiag = IntArray(series) { grid[i+it][col+series-1-it] }.product() } maxProd = maxOf(maxProd, right, leadingDiag, counterDiag) col++ } } return maxProd } /** * SPEED (WORSE) 4.16ms for N = 20 */ fun largestProductInGrid(grid: Array<IntArray>): Int { var largest = 0 for (row in grid.indices) { for (col in 0..(grid[0].size - series)) { val right = grid[row].sliceArray(col until (col + series)).product() val down = IntArray(series) { grid[col+it][row] }.product() var leadingDiag = 0 var counterDiag = 0 if (row <= grid.size - series) { leadingDiag = IntArray(series) { grid[row+it][col+it] }.product() counterDiag = IntArray(series) { grid[row+it][col+series-1-it] }.product() } largest = maxOf(largest, right, down, leadingDiag, counterDiag) } } return largest } }
0
Kotlin
0
0
62b33367e3d1e15f7ea872d151c3512f8c606ce7
2,531
project-euler-kotlin
MIT License
src/Day10.kt
rromanowski-figure
573,003,468
false
{"Kotlin": 35951}
object Day10 : Runner<Int, String>(10, 13140, "") { override fun part1(input: List<String>): Int { val states = mutableListOf(State(0, 0, 1, 1)) input.forEach { s -> states.add(states.lastOrNull()!!.next(Instruction.of(s))) } val output = generateSequence(20) { it + 40 }.takeWhile { it <= 220 }.map { i -> i to states.first { i in it.startCycle..it.endCycle } } return output.sumOf { it.first * it.second.valueDuring } } override fun part2(input: List<String>): String { val states = mutableListOf(State(0, 0, 1, 1)) input.forEach { s -> val instruction = Instruction.of(s) val state = states.lastOrNull()!!.next(instruction) states.add(state) } val screen = CRT() for (cycle in 1..(screen.height * screen.width)) { val row = (cycle - 1) / screen.width val column = (cycle - 1) mod screen.width screen.append( row, states.first { cycle in it.startCycle..it.endCycle }.sprite( screen.width, " ", "@", )[column] ) } println(screen) return "" } class CRT(val height: Int = 6, val width: Int = 40) { var screen = MutableList(height) { "" } fun append(x: Int, c: Char) { screen[x] += c.toString() } override fun toString() = screen.joinToString("\n") } data class State( val startCycle: Int, val endCycle: Int, val valueDuring: Int, val valueAfter: Int, ) { fun next(i: Instruction): State { return State( endCycle + 1, endCycle + i.cycles, valueAfter, valueAfter + when (i) { is Add -> i.x Noop -> 0 } ) } fun sprite(width: Int = 40, dark: String = ".", light: String = "#"): String { val prefixSize = Integer.min(width, Integer.max(0, valueDuring - 1)) val spriteSize = Integer.max(0, (Integer.min(40, valueDuring + 2) - Integer.max(0, valueDuring - 1))) val suffixSize = Integer.min(width, (width - Integer.min(valueDuring + 2, width))) return dark.repeat(prefixSize) + light.repeat(spriteSize) + dark.repeat(suffixSize) } } sealed interface Instruction { val cycles: Int companion object { fun of(s: String): Instruction { return with(s.split(" ")) { when (this[0]) { "noop" -> Noop "addx" -> Add(this[1].toInt()) else -> error("unknown instruction") } } } } } object Noop : Instruction { override val cycles: Int get() = 1 override fun toString() = "Noop" } data class Add(val x: Int) : Instruction { override val cycles: Int get() = 2 } infix fun Int.mod(other: Int) = this % other }
0
Kotlin
0
0
6ca5f70872f1185429c04dcb8bc3f3651e3c2a84
3,212
advent-of-code-2022-kotlin
Apache License 2.0
src/Day05.kt
lassebe
573,423,378
false
{"Kotlin": 33148}
data class Instruction(val count: Int, val from: Int, val to: Int) fun main() { fun getBoxes(input: List<String>): List<ArrayDeque<String>> { val stacks = mutableListOf<ArrayDeque<String>>() val cargoLines = input.filter { l -> l.contains("[") }.reversed() for (i in (0 until cargoLines.first().chunked(4).size)) stacks.add(ArrayDeque()) for (line in cargoLines) { line.chunked(4).withIndex().forEach { (i, box) -> if (box.contains("[")) stacks[i].addLast(box) } } return stacks } fun instructions(input: List<String>): List<Instruction> { return input.filter { it.startsWith("move ") }.map { line -> val ins = line.split(" ") .filter { w -> w.matches(Regex("\\d+")) } .map { d -> d.toInt() } Instruction(ins[0], ins[1], ins[2]) } } fun solve(input: List<String>, move: (boxes: List<ArrayDeque<String>>, ins: List<Instruction>) -> Unit): String { val boxes = getBoxes(input) move(boxes, instructions(input)) return boxes.joinToString("") { it.last()[1].toString() } } fun part1(input: List<String>) = solve(input) { boxes, ins -> for (instruction in ins) { for (i in (0 until instruction.count)) { boxes[instruction.to - 1] .addLast(boxes[instruction.from - 1].removeLast()) } } } fun part2(input: List<String>) = solve(input) { boxes, ins -> for (instruction in ins) { val tmp = mutableListOf<String>() for (i in (0 until instruction.count)) { tmp.add(boxes[instruction.from - 1].removeLast()) } for (t in tmp.reversed()) { boxes[instruction.to - 1].add(t) } } } val testInput = readInput("Day05_test") check(part1(testInput) == "CMZ") val input = readInput("Day05") println(part1(input)) check(part2(testInput) == "MCD") println(part2(input)) }
0
Kotlin
0
0
c3157c2d66a098598a6b19fd3a2b18a6bae95f0c
2,227
advent_of_code_2022
Apache License 2.0
src/Day20.kt
weberchu
573,107,187
false
{"Kotlin": 91366}
private fun mix(originalFile: List<Pair<Long, Int>>, mixedFile: MutableList<Pair<Long, Int>>): MutableList<Pair<Long, Int>> { val fileSizeMinusOne = originalFile.size - 1 for (nextNum in originalFile) { val index = mixedFile.indexOf(nextNum) mixedFile.removeAt(index) var newIndex = index + nextNum.first if (newIndex > fileSizeMinusOne) { newIndex %= fileSizeMinusOne } else if (newIndex < 0) { newIndex = newIndex % fileSizeMinusOne + fileSizeMinusOne } mixedFile.add(newIndex.toInt(), nextNum) } return mixedFile } private fun part1(input: List<String>): Long { val originalFile = input.mapIndexed { i, num -> Pair(num.toLong(), i) } val mixedFile = mix(originalFile, originalFile.toMutableList()) val indexZero = mixedFile.indexOfFirst { it.first == 0L } val index1000 = (indexZero + 1000) % originalFile.size val index2000 = (indexZero + 2000) % originalFile.size val index3000 = (indexZero + 3000) % originalFile.size return mixedFile[index1000].first + mixedFile[index2000].first + mixedFile[index3000].first } private fun part2(input: List<String>): Long { val originalFile = input .map { it.toLong() * 811589153 } .mapIndexed { i, num -> Pair(num, i) } var mixedFile = originalFile.toMutableList() for (i in 1..10) { mixedFile = mix(originalFile, mixedFile) } val indexZero = mixedFile.indexOfFirst { it.first == 0L } val index1000 = (indexZero + 1000) % originalFile.size val index2000 = (indexZero + 2000) % originalFile.size val index3000 = (indexZero + 3000) % originalFile.size return mixedFile[index1000].first + mixedFile[index2000].first + mixedFile[index3000].first } fun main() { val input = readInput("Day20") // val input = readInput("Test") println("Part 1: " + part1(input)) println("Part 2: " + part2(input)) }
0
Kotlin
0
0
903ff33037e8dd6dd5504638a281cb4813763873
1,947
advent-of-code-2022
Apache License 2.0
src/Day03.kt
Kanialdo
573,165,497
false
{"Kotlin": 15615}
fun main() { fun Char.priority() = if (isLowerCase()) { this.code - 'a'.code + 1 } else { this.code - 'A'.code + 27 } fun part1(input: String): Int { val rucksacks = input.lines() return rucksacks.sumOf { rucksack -> rucksack.chunked(size = rucksack.length / 2) // two parts of rucksack .map { it.toSet() } // unique values in each part .flatten().sorted() // sorted list with all unique chars from each part .reduce { acc, x -> if (acc == x) return@sumOf x.priority() else x } // value of first repeated char throw IllegalStateException() } } fun part2(input: String): Int { val rucksacks = input.lines() return rucksacks.chunked(3).sumOf { subRucksacks -> subRucksacks.map { it.toSet() } // every rucksack with unique values .flatten().sorted() // sorted list with all unique chars from each rucksack .windowed(3).first { it.toSet().size == 1 } // first sequence with same values .first().priority() // value of shared char } } val testInput = readInputAsText("Day03_test") check(part1(testInput), 157) check(part2(testInput), 70) val input = readInputAsText("Day03") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
10a8550a0a85bd0a928970f8c7c5aafca2321a4b
1,368
advent-of-code-2022
Apache License 2.0
kotlin/0441-arranging-coins.kt
neetcode-gh
331,360,188
false
{"JavaScript": 473974, "Kotlin": 418778, "Java": 372274, "C++": 353616, "C": 254169, "Python": 207536, "C#": 188620, "Rust": 155910, "TypeScript": 144641, "Go": 131749, "Swift": 111061, "Ruby": 44099, "Scala": 26287, "Dart": 9750}
/* * Optimized with Binary Search and Gauss summation formula: Time Complexity O(LogN) and Space Complexity O(1) */ class Solution { fun arrangeCoins(n: Int): Int { var left = 1 var right = n var res = 0 while (left <= right) { val mid = left + (right - left) / 2 //avoid a potential 32bit Integer overflow (Where left is 1 and right is Integer.MAX_VALUE) val coins = (mid.toDouble() / 2) * (mid.toDouble() + 1) if(coins > n) right = mid -1 else { left = mid + 1 res = maxOf(res, mid) } } return res.toInt() } } /* * Optimized and almost cheat-like solution (Technically not cheating) with both space and time complexity being O(1) * Here we solve for x in gauss summation formula where the result is our input variable n: * (x/2) * (x+1) = n ====> x = 1/2 * sqrt( 8n+1 ) -1 (We ignore the other possible solution since it gives us (wrong) negative x's */ class Solution { fun arrangeCoins(n: Int): Int { val x = 0.5 * Math.sqrt(8.0 * n.toDouble() + 1.0) - 1.0 return Math.round(x).toInt() // round() will round up or down to nearest whole number, which we need to correctly output result } } // Or if you prefer oneliner: class Solution { fun arrangeCoins(n: Int) = Math.round( 0.5 * Math.sqrt(8.0 * n.toDouble() + 1.0) - 1.0 ).toInt() } /* * Naive way with brute force: Time Complexity O(N) and Space Complexity O(1) */ class Solution { fun arrangeCoins(_n: Int): Int { var res = 0 var n = _n var step = 0 while( true ) { step++ if(n - step < 0) return res n -= step res++ } return res } }
337
JavaScript
2,004
4,367
0cf38f0d05cd76f9e96f08da22e063353af86224
1,799
leetcode
MIT License
advent-of-code-2022/src/main/kotlin/eu/janvdb/aoc2022/day12/Day12.kt
janvdbergh
318,992,922
false
{"Java": 1000798, "Kotlin": 284065, "Shell": 452, "C": 335}
package eu.janvdb.aoc2022.day12 import eu.janvdb.aocutil.kotlin.ShortestPathMove import eu.janvdb.aocutil.kotlin.findShortestPath import eu.janvdb.aocutil.kotlin.point2d.Point2D import eu.janvdb.aocutil.kotlin.readLines //const val FILENAME = "input12-test.txt" const val FILENAME = "input12.txt" fun main() { val map = Map.parse(readLines(2022, FILENAME)) println(map.findShortestPath()) println(map.findShortestPathWithAnyStart()) } class Map(val width: Int, val height: Int, val elevations: List<Int>, val start: Point2D, val end: Point2D) { fun findShortestPath(): Int? { return findShortestPath(start, end, this::neighbours)?.cost } fun findShortestPathWithAnyStart(): Int { return elevations.asSequence() .mapIndexed() { index, elevation -> Pair(elevation, Point2D(index % width, index / width)) } .filter { it.first == 0 } .map { findShortestPath(it.second, end, this::neighbours) } .filter { it != null } .map { it!! } .minOf { it.cost } } private fun neighbours(point: Point2D): Sequence<ShortestPathMove<Point2D>> { val startElevation = elevationAt(point) return sequenceOf(point.left(), point.up(), point.right(), point.down()) .filter { it.x in 0 until width && it.y in 0 until height } .filter { elevationAt(it) - startElevation <= 1 } .map { ShortestPathMove(it, 1) } } private fun elevationAt(point: Point2D): Int { return elevations[point.x + point.y * width] } companion object { fun parse(lines: List<String>): Map { val width = lines[0].length val height = lines.size val elevations = mutableListOf<Int>() var start: Point2D? = null var end: Point2D? = null for (y in 0 until height) { for (x in 0 until width) { val ch = lines[y][x] elevations.add( when (ch) { 'S' -> 0 'E' -> 25 in 'a'..'z' -> ch - 'a' else -> throw IllegalArgumentException("Invalid: $ch") } ) if (ch == 'S') start = Point2D(x, y) if (ch == 'E') end = Point2D(x, y) } } return Map(width, height, elevations, start!!, end!!) } } }
0
Java
0
0
78ce266dbc41d1821342edca484768167f261752
2,080
advent-of-code
Apache License 2.0
src/main/kotlin/Day05.kt
JPQuirmbach
572,636,904
false
{"Kotlin": 11093}
import java.util.* import kotlin.collections.ArrayDeque fun main() { fun createStack(input: String): List<ArrayDeque<Char>> { val stack = List(9) { ArrayDeque<Char>() } val crates = input.lines() .dropLast(1) .reversed() .map { it -> it.chunked(4) { if (it[1].isLetter()) it[1] else null } } for (row in crates) { for ((idx, char) in row.withIndex()) { if (char != null) stack[idx].addLast(char) } } return stack } fun part1(input: String): String { val (ship, moves) = input.split("\n\n") val stack = createStack(ship) moves.lines() .map { it.split(" ") .filter { Objects.nonNull(it.toIntOrNull()) } .map { it.toInt() } } .forEach { val (amount, from, to) = it val fromStack = stack[from - 1] val toStack = stack[to - 1] repeat(amount) { toStack.addLast(fromStack.removeLast()) } } return stack.filter { it.isNotEmpty() } .joinToString("") { "${it.last()}" } } fun part2(input: String): String { val (ship, moves) = input.split("\n\n") val stack = createStack(ship) moves.lines() .map { it.split(" ") .filter { Objects.nonNull(it.toIntOrNull()) } .map { it.toInt() } } .forEach { val (amount, from, to) = it val fromStack = stack[from - 1] val toStack = stack[to - 1] val inClaw = fromStack.takeLast(amount) repeat(amount) { fromStack.removeLast() } for (crate in inClaw) { toStack.addLast(crate) } } return stack.filter { it.isNotEmpty() } .joinToString("") { "${it.last()}" } } // 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
829e11bd08ff7d613280108126fa6b0b61dcb819
2,407
advent-of-code-Kotlin-2022
Apache License 2.0
src/Day02.kt
Migge
572,695,764
false
{"Kotlin": 9496}
private fun part1(input: List<String>): Int = input .map { it.toGame() } .fold(0) { acc, game -> acc + game.score() } private fun part2(input: List<String>): Int = input .map { it.toForcedGame() } .fold(0) { acc, game -> acc + game.score() } fun main() { val testInput = readInput("Day02_test") check(part1(testInput) == 15) check(part2(testInput) == 12) val input = readInput("Day02") println(part1(input)) println(part2(input)) } private fun String.toGame() = Game( when (substringBefore(" ")) { "A" -> Move.ROCK "B" -> Move.PAPER "C" -> Move.SCISSOR else -> throw RuntimeException("invalid move") }, when (substringAfter(" ")) { "X" -> Move.ROCK "Y" -> Move.PAPER "Z" -> Move.SCISSOR else -> throw RuntimeException("invalid move") } ) private fun String.toForcedGame() = toGame().newGame(substringAfter(" ")) private enum class Move { ROCK, PAPER, SCISSOR } private enum class Result { WIN, DRAW, LOSS } private data class Game(val opp: Move, val me: Move) { fun result() = when { opp == me -> Result.DRAW opp == Move.ROCK && me == Move.SCISSOR -> Result.LOSS opp == Move.PAPER && me == Move.ROCK -> Result.LOSS opp == Move.SCISSOR && me == Move.PAPER -> Result.LOSS else -> Result.WIN } private fun gameScore() = when (result()) { Result.WIN -> 6 Result.DRAW -> 3 Result.LOSS -> 0 } private fun moveScore() = when (me) { Move.ROCK -> 1 Move.PAPER -> 2 Move.SCISSOR -> 3 } fun score() = gameScore() + moveScore() fun forceWin() = when (opp) { Move.ROCK -> Game(Move.ROCK, Move.PAPER) Move.PAPER -> Game(Move.PAPER, Move.SCISSOR) Move.SCISSOR -> Game(Move.SCISSOR, Move.ROCK) } fun forceLoss() = when (opp) { Move.ROCK -> Game(Move.ROCK, Move.SCISSOR) Move.PAPER -> Game(Move.PAPER, Move.ROCK) Move.SCISSOR -> Game(Move.SCISSOR, Move.PAPER) } fun forceDraw() = Game(opp, opp) fun newGame(str: String) = when (str) { "X" -> forceLoss() "Y" -> forceDraw() "Z" -> forceWin() else -> throw RuntimeException("invalide code") } }
0
Kotlin
0
0
c7ca68b2ec6b836e73464d7f5d115af3e6592a21
2,281
adventofcode2022
Apache License 2.0