path
stringlengths
5
169
owner
stringlengths
2
34
repo_id
int64
1.49M
755M
is_fork
bool
2 classes
languages_distribution
stringlengths
16
1.68k
content
stringlengths
446
72k
issues
float64
0
1.84k
main_language
stringclasses
37 values
forks
int64
0
5.77k
stars
int64
0
46.8k
commit_sha
stringlengths
40
40
size
int64
446
72.6k
name
stringlengths
2
64
license
stringclasses
15 values
src/Day03.kt
LesleySommerville-Ki
577,718,331
false
{"Kotlin": 9590}
fun main() { fun getItemPriority(char: Char): Int { val lowerCase = "abcdefghijklmnopqrstuvwxyz" val upperCase = "abcdefghijklmnopqrstuvwxyz".toUpperCase() return if (char.isUpperCase() ) upperCase.indexOf(char) + 27 else { lowerCase.indexOf(char) + 1 } } data class Item ( val char: Char = '\u0000', val priority: Int = 0 ) fun createItemList( input: List<String>, currentItem: Item, listOfItems: ArrayDeque<Item>, ) { var currentItem1 = currentItem input.forEach { line -> val chunked = line.chunked(line.length / 2) val common = chunked[0].toList().intersect(chunked[1].toList().toSet()) currentItem1 = Item(char = common.first().toChar(), getItemPriority(common.first().toChar())) listOfItems.add(currentItem1) } } fun part1(input: List<String>): Int { val listOfItems = ArrayDeque<Item>() var currentItem = Item() createItemList(input, currentItem, listOfItems) return listOfItems.sumOf { it.priority } } fun part2(input: List<String>): Int { val listOfItems = ArrayDeque<Item>() var currentItem: Item val split = input.chunked(3) for (strings in split) { val item = strings[0].filter(strings[1]::contains).toSet().filter(strings[2]::contains).toSet().first().toChar() currentItem = Item(char = item, getItemPriority(item)) listOfItems.add(currentItem) } return listOfItems.sumOf { it.priority } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day03_test") check(part1(testInput) == 157) val input = readInput("Day03") part1(input).println() part2(input).println() }
0
Kotlin
0
0
ea657777d8f084077df9a324093af9892c962200
1,867
AoC
Apache License 2.0
app/src/main/kotlin/day18/Day18.kt
W3D3
572,447,546
false
{"Kotlin": 159335}
package day18 import common.InputRepo import common.readSessionCookie import common.solve import util.Pos3D fun main(args: Array<String>) { val day = 18 val input = InputRepo(args.readSessionCookie()).get(day = day) solve(day, input, ::solveDay18Part1, ::solveDay18Part2) } fun solveDay18Part1(input: List<String>): Int { val cubes = input.map { line -> line.split(",").let { Cube(Pos3D(it[0].toLong(), it[1].toLong(), it[2].toLong())) } } return cubes.sumOf { it.countExposedSides((cubes - it).toSet()) } } fun solveDay18Part2(input: List<String>): Int { val cubes = input.map { line -> line.split(",").let { Cube(Pos3D(it[0].toLong(), it[1].toLong(), it[2].toLong())) } } val visitedPositions = floodFill(cubes.toSet()) return cubes.sumOf { it.countTouchingSidesPos(visitedPositions) } } fun floodFill(cubes: Set<Cube>): Set<Pos3D> { val xRange = cubes.minOf { it.pos.x } - 1..cubes.maxOf { it.pos.x } + 1 val yRange = cubes.minOf { it.pos.y } - 1..cubes.maxOf { it.pos.y } + 1 val zRange = cubes.minOf { it.pos.z } - 1..cubes.maxOf { it.pos.z } + 1 val startPos = Pos3D(xRange.first, yRange.first, zRange.first) val visitedPositions = mutableSetOf(startPos) var basePositions = setOf(startPos) val exploredPositions: MutableList<Pos3D> = mutableListOf() do { for (basePos in basePositions) { exploredPositions += basePos.directNeighbors .filter { it.x in xRange && it.y in yRange && it.z in zRange } .filter { floodPos -> floodPos !in cubes.map { it.pos } } .toSet() } basePositions = (exploredPositions - visitedPositions).toSet() visitedPositions.addAll(basePositions) } while (basePositions.isNotEmpty()) return visitedPositions } data class Cube(val pos: Pos3D) { fun countExposedSides(others: Set<Cube>): Int { return 6 - countTouchingSides(others) } fun countTouchingSides(others: Set<Cube>): Int { return countTouchingSidesPos(others.map { it.pos }.toSet()) } fun countTouchingSidesPos(others: Set<Pos3D>): Int { return others.count { otherPos -> this.pos.isDirectNeighbor(otherPos) } } }
0
Kotlin
0
0
34437876bf5c391aa064e42f5c984c7014a9f46d
2,249
AdventOfCode2022
Apache License 2.0
src/main/kotlin/codes/jakob/aoc/solution/Day09.kt
The-Self-Taught-Software-Engineer
433,875,929
false
{"Kotlin": 56277}
package codes.jakob.aoc.solution import codes.jakob.aoc.shared.Grid object Day09 : Solution() { override fun solvePart1(input: String): Any { val grid: Grid<Int> = Grid(parseInput(input)) return grid.getLowPoints().sumOf { 1 + it.value } } override fun solvePart2(input: String): Any { val grid: Grid<Int> = Grid(parseInput(input)) val basins: Map<Grid.Cell<Int>, Collection<Grid.Cell<Int>>> = grid.cells .filterNot { it.value == 9 } .groupBy { it.getClosestLowPoint() } return basins.values.sortedByDescending { it.count() }.take(3).productOf { it.count() } } private fun parseInput(input: String): List<List<(Grid.Cell<Int>) -> Int>> { return input.splitMultiline().map { row -> row.split("").filter { it.isNotBlank() }.map { value -> { value.toInt() } } } } private fun Grid<Int>.getLowPoints(diagonally: Boolean = false): List<Grid.Cell<Int>> { return this.cells.map { it.getClosestLowPoint(diagonally) }.distinct() } private fun Grid.Cell<Int>.getClosestLowPoint(diagonally: Boolean = false): Grid.Cell<Int> { val adjacentCells: List<Grid.Cell<Int>> = this.getAdjacent(diagonally) return if (adjacentCells.all { this.value < it.value }) { this } else { val localLowPoint: Grid.Cell<Int> = adjacentCells.minByOrNull { it.value }!! localLowPoint.getClosestLowPoint(diagonally) } } } fun main() { Day09.solve() }
0
Kotlin
0
6
d4cfb3479bf47192b6ddb9a76b0fe8aa10c0e46c
1,562
advent-of-code-2021
MIT License
src/main/kotlin/day24.kt
gautemo
725,273,259
false
{"Kotlin": 79259}
import shared.* import kotlin.math.abs import kotlin.math.max import kotlin.math.min fun main() { val input = Input.day(24) println(day24A(input)) println(day24B(input)) } fun day24A(input: Input, min: Long = 200000000000000, max: Long = 400000000000000): Int { val hailstones = input.lines.map { line -> line.toLongs().let { Hailstone(it[0], it[1], it[2], it[3].toInt(), it[4].toInt(), it[5].toInt()) } } var count = 0 hailstones.forEachIndexed { index, h1 -> hailstones.drop(index + 1).forEach { h2 -> intersect(h1.px, h1.vx, h1.py, h1.vy, h2.px, h2.vx, h2.py, h2.vy)?.let { if (min <= it.first && it.first <= max && min <= it.second && it.second <= max) { count++ } } } } return count } fun day24B(input: Input): Long { val hailstones = input.lines.map { line -> line.toLongs().let { Hailstone(it[0], it[1], it[2], it[3].toInt(), it[4].toInt(), it[5].toInt()) } } return findIntersect(hailstones) } private fun findIntersect(hailstones: List<Hailstone>): Long { val checkVelocity = 500 for(vx in -checkVelocity .. checkVelocity) { for(vy in -checkVelocity .. checkVelocity) { for(vz in -checkVelocity .. checkVelocity) { val relativeVelocity1x = hailstones[0].vx - vx val relativeVelocity1y = hailstones[0].vy - vy val relativeVelocity2x = hailstones[1].vx - vx val relativeVelocity2y = hailstones[1].vy - vy val slopeDiff = relativeVelocity1x * relativeVelocity2y - relativeVelocity1y * relativeVelocity2x if(slopeDiff != 0) { val t = (relativeVelocity2y * (hailstones[1].px - hailstones[0].px) - relativeVelocity2x * (hailstones[1].py - hailstones[0].py)) / slopeDiff if(t >= 0) { val x = hailstones[0].px + (hailstones[0].vx - vx) * t val y = hailstones[0].py + (hailstones[0].vy - vy) * t val z = hailstones[0].pz + (hailstones[0].vz - vz) * t val hitAll = hailstones.all { it.willColide(Hailstone(x, y, z, vx, vy, vz)) } if(hitAll) { return x + y + z } } } } } } throw Exception() } private class Hailstone(val px: Long, val py: Long, val pz: Long, val vx: Int, val vy: Int, val vz: Int) { fun willColide(other: Hailstone): Boolean { val t = when { vx != other.vx -> (other.px - px).toDouble() / (vx - other.vx) vy != other.vy -> (other.py - py).toDouble() / (vy - other.vy) vz != other.vz -> (other.pz - pz).toDouble() / (vz - other.vz) else -> return false } if (t < 0) return false return positionAfterTime(t) == other.positionAfterTime(t) } fun positionAfterTime(time: Double): Triple<Double, Double, Double> = Triple( first = px + vx * time, second = py + vy * time, third = pz + vz * time, ) } private fun intersect( px1: Long, vx1: Int, py1: Long, vy1: Int, px2: Long, vx2: Int, py2: Long, vy2: Int, ): Pair<Float, Float>? { val a1 = vy1.toFloat() val b1 = -vx1.toFloat() val c1 = (vy1 * px1 - vx1 * py1).toFloat() val a2 = vy2.toFloat() val b2 = -vx2.toFloat() val c2 = (vy2 * px2 - vx2 * py2).toFloat() if (a1 * b2 == b1 * a2) { // parallel return null } val x = (c1 * b2 - c2 * b1) / (a1 * b2 - a2 * b1) val y = (c2 * a1 - c1 * a2) / (a1 * b2 - a2 * b1) if ((x - px1) * vx1 >= 0 && (y - py1) * vy1 >= 0) { if ((x - px2) * vx2 >= 0 && (y - py2) * vy2 >= 0) { return x to y } } return null }
0
Kotlin
0
0
6862b6d7429b09f2a1d29aaf3c0cd544b779ed25
4,011
AdventOfCode2023
MIT License
src/Day07.kt
oleskrede
574,122,679
false
{"Kotlin": 24620}
fun main() { fun part1(input: List<String>): Long { val maxDirSize = 100_000 val fs = FileSystem() fs.recreateFromBrowsingHistory(input) val dirsWithSizeBelowMax = fs.findDirs { it.size < maxDirSize } return dirsWithSizeBelowMax.sumOf { it.size } } fun part2(input: List<String>): Long { val totalDiskSize = 70_000_000L val requiredUnusedSize = 30_000_000L val fs = FileSystem() fs.recreateFromBrowsingHistory(input) val diskSizeUsed = fs.root.size val unusedDiskSize = totalDiskSize - diskSizeUsed val missingSpace = requiredUnusedSize - unusedDiskSize val deletionCandidates = fs.findDirs { it.size >= missingSpace } val smallestDeletionCandidate = deletionCandidates.minBy { it.size } return smallestDeletionCandidate.size } // test if implementation meets criteria from the description, like: val testInput = readInput("Day07_test") test(part1(testInput), 95437L) test(part2(testInput), 24933642L) val input = readInput("Day07") timedRun { part1(input) } timedRun { part2(input) } } private class FileSystem { val root = Directory("/", null) private var currentDirectory = root fun recreateFromBrowsingHistory(history: List<String>) { history.forEach { line -> val tokens = line.trim().split(" ") when (tokens.first()) { "$" -> { if (tokens[1] == "cd") { this.changeDirectory(tokens[2]) } // we can ignore $ ls. Either we change directory or we are parsing the result of $ ls } "dir" -> this.makeDirectory(tokens[1]) else -> this.createFile(tokens[1], tokens[0].toInt()) } } } fun changeDirectory(name: String) { currentDirectory = when (name) { "/" -> root ".." -> currentDirectory.parent!! else -> currentDirectory.subDirectories[name]!! } } fun makeDirectory(name: String) { require(currentDirectory.subDirectories[name] == null) { "Directory $name already exists." } currentDirectory.subDirectories[name] = Directory(name, currentDirectory) } fun createFile(name: String, size: Int) { require(currentDirectory.files[name] == null) { "File $name already exists." } currentDirectory.files[name] = size currentDirectory.updateSize(size) } // Returns all directories that fullfill the given predicate, starting from and including root fun findDirs(predicate: (Directory) -> Boolean): List<Directory> { return findDirs(root, predicate) } // Returns all directories that fullfill the given predicate, starting from and including the given directory fun findDirs(dir: Directory, predicate: (Directory) -> Boolean): List<Directory> { val result = mutableListOf<Directory>() if (predicate(dir)) { result.add(dir) } dir.subDirectories.forEach { result.addAll(findDirs(it.value, predicate)) } return result } data class Directory( val name: String, val parent: Directory?, val subDirectories: MutableMap<String, Directory> = mutableMapOf(), val files: MutableMap<String, Int> = mutableMapOf(), ) { var size: Long = 0 private set fun updateSize(delta: Int) { size += delta parent?.updateSize(delta) } } }
0
Kotlin
0
0
a3484088e5a4200011335ac10a6c888adc2c1ad6
3,628
advent-of-code-2022
Apache License 2.0
src/main/kotlin/com/github/ferinagy/adventOfCode/aoc2015/2015-14.kt
ferinagy
432,170,488
false
{"Kotlin": 787586}
package com.github.ferinagy.adventOfCode.aoc2015 import com.github.ferinagy.adventOfCode.println import com.github.ferinagy.adventOfCode.readInputLines import kotlin.math.min fun main() { val input = readInputLines(2015, "14-input") val test1 = readInputLines(2015, "14-test1") println("Part1:") part1(test1, 1000).println() part1(input).println() println() println("Part2:") part2(test1, 1000).println() part2(input).println() } private fun part1(input: List<String>, totalTime: Int = 2503): Int { val reindeer = input.map { Reindeer.parse(it) } return reindeer.maxOf { var traveled = 0 var remainingTime = totalTime while (0 < remainingTime) { traveled += min(remainingTime, it.flyTime) * it.speed remainingTime -= it.flyTime + it.restTime } traveled } } private fun part2(input: List<String>, totalTime: Int = 2503): Int { val reindeer = input.map { Reindeer.parse(it) } val points = IntArray(reindeer.size) for (i in 1..totalTime) { reindeer.forEach { it.tick() } val max = reindeer.maxOfOrNull { it.dist } reindeer.forEachIndexed { index, r -> if (r.dist == max) points[index]++ } } return points.maxOrNull()!! } private class Reindeer(val speed: Int, val flyTime: Int, val restTime: Int) { private var isFlying: Boolean = true private var remainingFlightTime: Int = flyTime private var remainingRestTime: Int = restTime var dist = 0 private set fun tick(): Int { if (isFlying) { dist += speed remainingFlightTime-- if (remainingFlightTime == 0) { isFlying = false remainingFlightTime = flyTime } } else { remainingRestTime-- if (remainingRestTime == 0) { isFlying = true remainingRestTime = restTime } } return dist } companion object { fun parse(input: String): Reindeer { val (speed, flyTime, restTime) = regex.matchEntire(input)!!.destructured return Reindeer(speed.toInt(), flyTime.toInt(), restTime.toInt()) } } } private val regex = """\w+ can fly (\d+) km/s for (\d+) seconds, but then must rest for (\d+) seconds.""".toRegex()
0
Kotlin
0
1
f4890c25841c78784b308db0c814d88cf2de384b
2,398
advent-of-code
MIT License
src/main/kotlin/com/hj/leetcode/kotlin/problem1802/Solution.kt
hj-core
534,054,064
false
{"Kotlin": 619841}
package com.hj.leetcode.kotlin.problem1802 /** * LeetCode page: [1802. Maximum Value at a Given Index in a Bounded Array](https://leetcode.com/problems/maximum-value-at-a-given-index-in-a-bounded-array/); */ class Solution { /* Complexity: * Time O(Log(maxSum)) and Space O(1); */ fun maxValue(n: Int, index: Int, maxSum: Int): Int { require(n >= 1) require(index in 0 until n) require(maxSum >= n) /* The idea is to form the resulting array using a greedy approach, where the value at * each index i is calculated by subtracting the distance between index i and the given * index from the value at the given index, with the resulting value constrained to be * at least one. * * Since the sum of the resulting array increases or decreases as the value at the given * index increases or decreases, we can perform a binary search to find the maximum value * at the given index. */ var lowerBound = 1 var upperBound = maxSum while (lowerBound <= upperBound) { val guessValue = (lowerBound + upperBound) ushr 1 val sum = sumGreedyArray(n, index, guessValue) when { sum < maxSum -> lowerBound = guessValue + 1 sum > maxSum -> upperBound = guessValue - 1 else -> return guessValue } } return upperBound } private fun sumGreedyArray(n: Int, index: Int, indexValue: Int): Long { return (sumGreedyArrayUpToIndex(index, indexValue) + sumGreedyArrayFromIndex(n, index, indexValue) - indexValue) } private fun sumGreedyArrayUpToIndex(index: Int, indexValue: Int): Long { require(index >= 0) require(indexValue >= 1) // First value of the resulting array if it can be zero or negative val looseFirst = indexValue - index return if (looseFirst >= 1) { (looseFirst.toLong() + indexValue) * (index + 1) / 2 } else { (1L + indexValue) * indexValue / 2 - looseFirst + 1 } } private fun sumGreedyArrayFromIndex(n: Int, index: Int, indexValue: Int): Long { require(index in 0 until n) require(indexValue >= 1) // Last value of the resulting array if it can be zero or negative val looseLast = indexValue + index - (n - 1) return if (looseLast >= 1) { (indexValue.toLong() + looseLast) * (n - index) / 2 } else { (1L + indexValue) * indexValue / 2 - looseLast + 1 } } }
1
Kotlin
0
1
14c033f2bf43d1c4148633a222c133d76986029c
2,646
hj-leetcode-kotlin
Apache License 2.0
src/net/sheltem/aoc/y2022/Day02.kt
jtheegarten
572,901,679
false
{"Kotlin": 178521}
package net.sheltem.aoc.y2022 import net.sheltem.common.readInput import net.sheltem.aoc.y2022.RPS.PAPER import net.sheltem.aoc.y2022.RPS.ROCK import net.sheltem.aoc.y2022.RPS.SCISSORS import net.sheltem.aoc.y2022.Result.DRAW import net.sheltem.aoc.y2022.Result.LOSS import net.sheltem.aoc.y2022.Result.WIN import kotlin.Int import kotlin.Pair import kotlin.String import kotlin.enumValues import kotlin.let import kotlin.to fun main() { fun part1(input: List<String>): Int = input.sumOf { it.toGame().score() } fun part2(input: List<String>): Int = input.sumOf { it.toGame().scorePredicting() } val input = readInput("Day02") println("Part 1: ${part1(input)}") println("Part 2: ${part2(input)}") } private fun Pair<String, String>.score() = second.toRPS().let { it.score + it.play(first.toRPS()).value } private fun Pair<String, String>.scorePredicting(): Int = Result.fromCode(second).let { it.played(first.toRPS()).score + it.value } private fun String.toGame(): Pair<String, String> = split(" ").let { it.component1() to it.component2() } private fun String.toRPS() = RPS.fromCode(this) private enum class Result(val value: Int, val code: String) { WIN(6, "Z"), DRAW(3, "Y"), LOSS(0, "X"); fun played(opponent: RPS) = when (this) { LOSS -> when (opponent) { ROCK -> SCISSORS PAPER -> ROCK SCISSORS -> PAPER } DRAW -> opponent WIN -> when (opponent) { ROCK -> PAPER PAPER -> SCISSORS SCISSORS -> ROCK } } companion object { fun fromCode(code: String) = enumValues<Result>().single { it.code == code } } } private enum class RPS(val code: List<String>, val score: Int) { ROCK(listOf("A", "X"), 1), PAPER(listOf("B", "Y"), 2), SCISSORS(listOf("C", "Z"), 3); fun play(opponent: RPS) = when (this) { ROCK -> when (opponent) { ROCK -> DRAW PAPER -> LOSS SCISSORS -> WIN } PAPER -> when (opponent) { ROCK -> WIN PAPER -> DRAW SCISSORS -> LOSS } SCISSORS -> when (opponent) { ROCK -> LOSS PAPER -> WIN SCISSORS -> DRAW } } companion object { fun fromCode(code: String) = enumValues<RPS>().single { it.code.contains(code) } } }
0
Kotlin
0
0
ac280f156c284c23565fba5810483dd1cd8a931f
2,572
aoc
Apache License 2.0
src/Day05/day05.kt
NST-d
573,224,214
false
null
package Day05 import utils.* import java.util.* fun main() { fun parseInput(input: String): Pair<Array<Stack<Char>>, List<String>> { val split = input.split("\n\n".toRegex(), limit = 2) val cratesString = split[0].split("\n").toMutableList() val moves = split[1].split("\n") val amountCrates = cratesString.removeLast().split(" ").count() val crates = Array(amountCrates) { Stack<Char>() } cratesString.reversed() .forEach { it -> //entry is "[A] " -> max 4 chars it.chunked(4).forEachIndexed { j, entry -> if (entry.isNotBlank()) { crates[j].push(entry[1]) } } } return Pair(crates, moves) } fun part1(input: String): String { val (crates, moves) = parseInput(input) //println(crates.contentToString()) moves.map { val words = it.split(" ") Triple(words[1].toInt(), words[3].toInt() - 1, words[5].toInt() - 1) }.forEach { (amount, src, dest) -> repeat(amount) { crates[dest].push(crates[src].pop()) } //println(crates.contentToString()) } return String(crates.map { it.peek() }.toCharArray()) } fun part2(input: String): String { val (crates, moves) = parseInput(input) //println(crates.contentToString()) moves.map { val words = it.split(" ") Triple(words[1].toInt(), words[3].toInt() - 1, words[5].toInt() - 1) }.forEach { (amount, src, dest) -> val temp = List(amount) { crates[src].pop() } temp.reversed().forEach { crates[dest].push(it) } //println(crates.contentToString()) } return String(crates.map { it.peek() }.toCharArray()) } val test = readTestString("Day05").trimIndent() val input = readInputString("Day05").trimIndent() println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
c4913b488b8a42c4d7dad94733d35711a9c98992
2,094
aoc22
Apache License 2.0
src/Day06.kt
rod41732
572,917,438
false
{"Kotlin": 85344}
class Multiset<T> { private val unique: MutableSet<T> = mutableSetOf() private val count: MutableMap<T, Int> = mutableMapOf() fun add(v: T) { count[v] = (count[v] ?: 0) + 1 if (count[v] == 1) unique.add(v) } fun remove(v: T) { count[v] = (count[v] ?: 0) - 1 if (count[v] == 0) unique.remove(v) } val items: Set<T> get() = unique.toSet() } fun main() { val line = readInput("Day06")[0] fun solve(text: String, uniqueCount: Int): Int { val s = Multiset<Char>() return text.zip("_".repeat(uniqueCount) + text).indexOfFirst { (new, old) -> s.add(new); s.remove(old) s.items.size == uniqueCount } + 1 } /** shorter implementation but "less efficient" (won't matter for this small input anyway) */ fun solveEasy(text: String, uniqueCount: Int): Int { return text.windowed(uniqueCount).indexOfFirst { it.toSet().size == uniqueCount } + uniqueCount } fun part1(text: String) = solve(text, 4) fun part2(text: String) = solve(text, 14) print(part1("bwbjplbgvbhsrlpgdmjqwftvncz")) check(part1("bwbjplbgvbhsrlpgdmjqwftvncz") == 5) check(part1("nppdvjthqldpwncqszvftbrmjlhg") == 6) check(part1("nznrnfrfntjfmvfwmzdfjlvtqnbhcprsg") == 10) check(part1("zcfzfwzzqfrljwzlrfnpqdbhtmscgvjw") == 11) check(part2("mjqjpqmgbljsphdztnvjfqwrcgsmlb") == 19) check(part2("bvwbjplbgvbhsrlpgdmjqwftvncz") == 23) check(part2("nppdvjthqldpwncqszvftbrmjlhg") == 23) check(part2("nznrnfrfntjfmvfwmzdfjlvtqnbhcprsg") == 29) check(part2("zcfzfwzzqfrljwzlrfnpqdbhtmscgvjw") == 26) println("Part 1") println(part1(line)) println("Part 2") println(part2(line)) }
0
Kotlin
0
0
1d2d3d00e90b222085e0989d2b19e6164dfdb1ce
1,740
advent-of-code-kotlin-2022
Apache License 2.0
src/main/kotlin/se/brainleech/adventofcode/aoc2021/Aoc2021Day10.kt
fwangel
435,571,075
false
{"Kotlin": 150622}
package se.brainleech.adventofcode.aoc2021 import se.brainleech.adventofcode.compute import se.brainleech.adventofcode.readLines import se.brainleech.adventofcode.verify import java.util.* class Aoc2021Day10 { companion object { private val BUDDIES = mapOf( '(' to ')', '[' to ']', '{' to '}', '<' to '>' ) private val ERROR_SCORES = mapOf( ')' to 3, ']' to 57, '}' to 1_197, '>' to 25_137 ) private val MISSING_SCORES = mapOf( ')' to 1, ']' to 2, '}' to 3, '>' to 4 ) } class SyntaxChecker(private val line: String) { fun syntaxErrorScore(): Long { val expectedChars = LinkedList<Char>() for (char in line) { if (BUDDIES.containsValue(char)) { if (char != expectedChars.pop()) { return ERROR_SCORES[char]!!.toLong() } } else { expectedChars.push(BUDDIES[char]) } } return 0L } fun missingCharsScore(): Long { val expectedChars = LinkedList<Char>() for (char in line) { if (BUDDIES.containsValue(char)) { expectedChars.pop() } else { expectedChars.push(BUDDIES[char]) } } return expectedChars .map { char -> MISSING_SCORES[char]!!.toLong() } .reduce { total, score -> total.times(5).plus(score) } } } fun part1(input: List<String>): Long { return input .sumOf { line -> SyntaxChecker(line).syntaxErrorScore() } } fun part2(input: List<String>): Long { val missingScores = input .asSequence() .map { line -> SyntaxChecker(line) } .filter { checker -> checker.syntaxErrorScore() == 0L } .map { checker -> checker.missingCharsScore() } .sorted() .toList() return missingScores.drop(missingScores.size / 2).first() } } fun main() { val solver = Aoc2021Day10() val prefix = "aoc2021/aoc2021day10" val testData = readLines("$prefix.test.txt") val realData = readLines("$prefix.real.txt") verify(26_397L, solver.part1(testData)) compute({ solver.part1(realData) }, "$prefix.part1 = ") verify(288_957L, solver.part2(testData)) compute({ solver.part2(realData) }, "$prefix.part2 = ") }
0
Kotlin
0
0
0bba96129354c124aa15e9041f7b5ad68adc662b
2,634
adventofcode
MIT License
solution/kotlin/aoc/src/main/kotlin/codes/jakob/aoc/Day09.kt
loehnertz
573,145,141
false
{"Kotlin": 53239}
package codes.jakob.aoc import codes.jakob.aoc.shared.Coordinates import codes.jakob.aoc.shared.ExpandedDirection import codes.jakob.aoc.shared.ExpandedDirection.* import codes.jakob.aoc.shared.splitMultiline import codes.jakob.aoc.shared.toPair class Day09 : Solution() { override fun solvePart1(input: String): Any { return simulateVisitedTailCoordinates(parseInstructions(input), 1).count() } override fun solvePart2(input: String): Any { return simulateVisitedTailCoordinates(parseInstructions(input), 9).count() } private fun simulateVisitedTailCoordinates(instructions: List<Instruction>, knotAmount: Int): Set<Coordinates> { var headCoordinates = Coordinates(0, 0) val allKnotCoordinates: MutableList<Coordinates> = MutableList(knotAmount) { headCoordinates } val visitedTailCoordinates: MutableSet<Coordinates> = mutableSetOf(allKnotCoordinates.last()) for (instruction: Instruction in instructions) { repeat(instruction.distance) { headCoordinates = headCoordinates.inDirection(instruction.direction) for ((index: Int, knotCoordinates: Coordinates) in allKnotCoordinates.withIndex()) { val inFront: Coordinates = if (index == 0) { headCoordinates } else { allKnotCoordinates[index - 1] } if (knotCoordinates distanceToDiagonally inFront > 1) { val inWhichDirection: ExpandedDirection = knotCoordinates.inWhichDirection(inFront)!! allKnotCoordinates[index] = knotCoordinates.inDirection(inWhichDirection) if (index == allKnotCoordinates.size - 1) visitedTailCoordinates += allKnotCoordinates[index] } } } } return visitedTailCoordinates } private fun parseInstructions(input: String): List<Instruction> { return input .splitMultiline() .map { it.split(" ").toPair() } .map { (a, b) -> Instruction(parseDirection(a), b.toInt()) } } private fun parseDirection(directionalLetter: String): ExpandedDirection { return when (directionalLetter) { "U" -> NORTH "R" -> EAST "D" -> SOUTH "L" -> WEST else -> error("Direction unknown") } } data class Instruction( val direction: ExpandedDirection, val distance: Int, ) } fun main() = Day09().solve()
0
Kotlin
0
0
ddad8456dc697c0ca67255a26c34c1a004ac5039
2,599
advent-of-code-2022
MIT License
src/main/kotlin/g2201_2300/s2245_maximum_trailing_zeros_in_a_cornered_path/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g2201_2300.s2245_maximum_trailing_zeros_in_a_cornered_path // #Medium #Array #Matrix #Prefix_Sum #2023_06_27_Time_888_ms_(100.00%)_Space_79.6_MB_(100.00%) @Suppress("NAME_SHADOWING") class Solution { fun maxTrailingZeros(grid: Array<IntArray>): Int { val m = grid.size val n = grid[0].size var max = 0 val row2 = Array(m + 1) { IntArray(n + 1) } val row5 = Array(m + 1) { IntArray(n + 1) } val col2 = Array(m + 1) { IntArray(n + 1) } val col5 = Array(m + 1) { IntArray(n + 1) } val factor2 = Array(m) { IntArray(n) } val factor5 = Array(m) { IntArray(n) } for (r in 0 until m) { for (c in 0 until n) { val factorTwo = findFactor(grid[r][c], 2) val factorFive = findFactor(grid[r][c], 5) row2[r + 1][c + 1] = row2[r + 1][c] + factorTwo row5[r + 1][c + 1] = row5[r + 1][c] + factorFive col2[r + 1][c + 1] = col2[r][c + 1] + factorTwo col5[r + 1][c + 1] = col5[r][c + 1] + factorFive factor2[r][c] = factorTwo factor5[r][c] = factorFive } } for (r in 0 until m) { for (c in 0 until n) { val cur2 = factor2[r][c] val cur5 = factor5[r][c] val up2 = col2[r + 1][c + 1] val up5 = col5[r + 1][c + 1] val down2 = col2[m][c + 1] - col2[r][c + 1] val down5 = col5[m][c + 1] - col5[r][c + 1] val left2 = row2[r + 1][c + 1] val left5 = row5[r + 1][c + 1] val right2 = row2[r + 1][n] - row2[r + 1][c] val right5 = row5[r + 1][n] - row5[r + 1][c] max = Math.max(max, Math.min(left2 + up2 - cur2, left5 + up5 - cur5)) max = Math.max(max, Math.min(right2 + up2 - cur2, right5 + up5 - cur5)) max = Math.max(max, Math.min(left2 + down2 - cur2, left5 + down5 - cur5)) max = Math.max(max, Math.min(right2 + down2 - cur2, right5 + down5 - cur5)) } } return max } private fun findFactor(a: Int, b: Int): Int { var a = a var factors = 0 while (a % b == 0) { a /= b factors++ } return factors } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
2,375
LeetCode-in-Kotlin
MIT License
src/Day13.kt
bananer
434,885,332
false
{"Kotlin": 36979}
data class Dot( val x: Int, val y: Int, ) enum class FoldAxis { X, Y } data class FoldInstruction( val axis: FoldAxis, val coordinate: Int, ) fun main() { fun parseInput(input: List<String>): Pair<Set<Dot>, List<FoldInstruction>> { val dots = mutableSetOf<Dot>() val foldInstructions = mutableListOf<FoldInstruction>() var i = 0 while (i < input.size && input[i].isNotEmpty()) { val (x, y) = input[i].split(",") dots.add(Dot(x.toInt(), y.toInt())) i++ } // empty line i++ while (i < input.size) { val l = input[i] check(l.startsWith("fold along ")) val axis = FoldAxis.valueOf(l[11].toString().uppercase()) val coordinate = l.substring(13).toInt() foldInstructions.add(FoldInstruction(axis, coordinate)) i++ } return Pair(dots, foldInstructions) } fun fold(dots: Set<Dot>, instruction: FoldInstruction): Set<Dot> { return dots.map { when (instruction.axis) { FoldAxis.Y -> { if (it.y > instruction.coordinate) { val dy = (it.y - instruction.coordinate) Dot(it.x, it.y - 2 * dy) } else { it } } FoldAxis.X -> { if (it.x > instruction.coordinate) { val dx = (it.x - instruction.coordinate) Dot(it.x - 2 * dx, it.y) } else { it } } } }.toSet() } fun part1(input: List<String>): Int { val (dots, foldInstructions) = parseInput(input) return fold(dots, foldInstructions.first()).size } fun part2(input: List<String>): String { val (startDots, foldInstructions) = parseInput(input) var dots = startDots foldInstructions.forEach { dots = fold(dots, it) } // print it val h = dots.maxOf { it.y } + 1 val w = dots.maxOf { it.x } + 1 return (0 until h).map { y -> (0 until w).map { x -> if (dots.contains(Dot(x, y))) { '#' } else { '.' } }.joinToString("") }.joinToString("\n") } // test if implementation meets criteria from the description, like: val testInput = readInput("Day13_test") val testOutput1 = part1(testInput) println("test output1: $testOutput1") check(testOutput1 == 17) val testOutput2 = part2(testInput) println("test output2:\n$testOutput2") check( testOutput2 == "#####\n" + "#...#\n" + "#...#\n" + "#...#\n" + "#####" ) val input = readInput("Day13") println("output part1: ${part1(input)}") println("output part2:\n${part2(input)}") }
0
Kotlin
0
0
98f7d6b3dd9eefebef5fa3179ca331fef5ed975b
3,121
advent-of-code-2021
Apache License 2.0
src/main/kotlin/g1901_2000/s1928_minimum_cost_to_reach_destination_in_time/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g1901_2000.s1928_minimum_cost_to_reach_destination_in_time // #Hard #Dynamic_Programming #Graph #2023_06_20_Time_414_ms_(100.00%)_Space_53.3_MB_(100.00%) import java.util.PriorityQueue class Solution { fun minCost(maxTime: Int, edges: Array<IntArray>, passingFees: IntArray): Int { val pq = PriorityQueue { a: Tuple, b: Tuple -> if (a.cost == b.cost) a.time - b.time else a.cost - b.cost } val n = passingFees.size val minTime = IntArray(n) minTime.fill(Int.MAX_VALUE) val graph = Graph() for (edge in edges) { graph.addEdge(edge[0], edge[1], edge[2]) } pq.offer(Tuple(0, passingFees[0], 0)) while (pq.isNotEmpty()) { val curr = pq.poll() if (curr.time <= maxTime && curr.time < minTime[curr.node]) { minTime[curr.node] = curr.time if (curr.node == n - 1) { return curr.cost } for (edge in graph.getEdges(curr.node)) { val time = curr.time + edge.weight if (time > maxTime || time >= minTime[edge.dst]) { continue } pq.offer(Tuple(edge.dst, curr.cost + passingFees[edge.dst], time)) } } } return -1 } private class Graph { private val edges: MutableMap<Int, MutableList<Edge>> = HashMap() fun addEdge(src: Int, dst: Int, weight: Int) { edges.computeIfAbsent(src) { _: Int? -> ArrayList() }.add(Edge(dst, weight)) edges.computeIfAbsent(dst) { _: Int? -> ArrayList() }.add(Edge(src, weight)) } fun getEdges(node: Int): List<Edge> { return edges.getOrDefault(node, ArrayList()) } } private class Edge(val dst: Int, val weight: Int) private class Tuple(val node: Int, val cost: Int, val time: Int) }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,950
LeetCode-in-Kotlin
MIT License
src/Day10.kt
illarionov
572,508,428
false
{"Kotlin": 108577}
private sealed class Instruction { object noop : Instruction() data class addx(val amount: Int) : Instruction() } private fun String.toInstruction(): Instruction { return if (this == "noop") { Instruction.noop } else { this.split(" ").let { (addx, count) -> if (addx != "addx") { error("Unknown instruction $this") } Instruction.addx(count.toInt()) } } } fun main() { fun part1(input: List<Instruction>): Int { var x = 1 var current: Instruction = Instruction.noop var currentEndTimeCycle = 1 var sum = 0 var ic = 0 (1..220).forEach { cycle -> if (cycle == currentEndTimeCycle) { when (current) { is Instruction.addx -> { x += (current as Instruction.addx).amount currentEndTimeCycle = cycle + 2 } Instruction.noop -> { currentEndTimeCycle = cycle + 1 } } current = if (input.lastIndex >= ic) input[ic] else Instruction.noop currentEndTimeCycle = when (current) { is Instruction.addx -> { cycle + 2 } Instruction.noop -> { cycle + 1 } } ic += 1 } if (cycle in setOf(20, 60, 100, 140, 180, 220)) { sum += cycle * x } } return sum } fun part2(input: List<Instruction>) { var x = 1 var current: Instruction = Instruction.noop var currentEndTimeCycle = 1 var ic = 0 val field = List(6) { MutableList(40) { ' ' } } (1..40 * 6).forEach { cycle -> if (cycle == currentEndTimeCycle) { when (current) { is Instruction.addx -> { x += (current as Instruction.addx).amount currentEndTimeCycle = cycle + 2 } Instruction.noop -> { currentEndTimeCycle = cycle + 1 } } current = if (input.lastIndex >= ic) input[ic] else Instruction.noop currentEndTimeCycle = when (current) { is Instruction.addx -> cycle + 2 Instruction.noop -> cycle + 1 } ic += 1 } val symbol = if (((cycle - 1) % 40) in (x - 1..x + 1)) '#' else '.' field[(cycle - 1) / 40][(cycle - 1) % 40] = symbol } field.forEach { println(it.joinToString("")) } } val testInput = readInput("Day10_test") .map(String::toInstruction) val part1CheckResult = part1(testInput) println(part1CheckResult) check(part1CheckResult == 13140) val input = readInput("Day10") .map(String::toInstruction) println(part1(input)) part2(input) }
0
Kotlin
0
0
3c6bffd9ac60729f7e26c50f504fb4e08a395a97
3,164
aoc22-kotlin
Apache License 2.0
src/day16/Day16.kt
ritesh-singh
572,210,598
false
{"Kotlin": 99540}
package day16 import com.github.shiguruikai.combinatoricskt.combinations import readInput class Graph(lines: List<String>) { private data class Valve(val name: String, val flowRate: Int) { override fun toString() = "$name($flowRate)" } private val graph = hashMapOf<Valve, List<Valve>>() private var valvesWithPosFlowRates = hashSetOf<Valve>() init { lines.forEach { string -> val name = string.substringAfter("Valve").substringBefore("has").trim() val flowRate = string.substringAfter("flow rate=").substringBefore(";").trim().toInt() graph[Valve(name = name, flowRate = flowRate)] = if (string.contains("valves")) { string.substringAfter("valves").trim().split(",").map { it.trim() } .map { Valve(name = it, flowRate = flowRate) } } else { string.substringAfter("valve").trim().split(",").map { it.trim() }.map { Valve(name = it, flowRate) } }.toList() } graph.forEach { (key, canReachTo) -> graph[key] = canReachTo.map { valve -> valve.copy(flowRate = graph.keys.find { it.name == valve.name }!!.flowRate) } if (key.flowRate > 0) valvesWithPosFlowRates.add(key) } } private val shortestDistMap = hashMapOf<Pair<Valve, Valve>, Int>() private fun findShortestDistance(src: Valve, dst: Valve): Int { if (shortestDistMap.contains(Pair(src, dst))) return shortestDistMap[Pair(src, dst)]!! if (shortestDistMap.contains(Pair(dst, src))) return shortestDistMap[Pair(dst, src)]!! val deque = ArrayDeque<Pair<Valve, Int>>() deque.addLast(Pair(src, 0)) val visited = hashSetOf<Valve>() while (deque.isNotEmpty()) { val (valve, dist) = deque.removeFirst() if (dst == valve) return dist visited.add(valve) for (neighbor in graph[valve]!!) { if (!visited.contains(neighbor)) { deque.addLast(Pair(neighbor, dist + 1)) } } } error("Destination node un-reachable") } fun maxPressureReleased(part1: Boolean): Int { data class State( val minutesLeft: Int, val openedValves: HashSet<Valve>, val currentValve: Valve, val pressureReleased: Int, ) var maxPressureRelieved = Int.MIN_VALUE // Valves opened to pressure relieved // Maximum pressure relieved after opening every combination of valves val maxValvesOpened = hashMapOf<HashSet<Valve>, Int>() val stateQueue = ArrayDeque<State>() stateQueue.addLast( State( minutesLeft = if (part1) 30 else 26, openedValves = hashSetOf(), currentValve = Valve(name = "AA", flowRate = 0), pressureReleased = 0 ) ) while (stateQueue.isNotEmpty()) { val currentState = stateQueue.removeFirst() if (!part1) { maxValvesOpened[currentState.openedValves] = maxOf( maxValvesOpened[currentState.openedValves] ?: Int.MIN_VALUE, currentState.pressureReleased ) } if (currentState.openedValves.size == valvesWithPosFlowRates.size || currentState.minutesLeft <= 0) { maxPressureRelieved = maxOf(maxPressureRelieved, currentState.pressureReleased) continue } for (valvesToOpen in valvesWithPosFlowRates - currentState.openedValves) { val shortPath = findShortestDistance(currentState.currentValve, valvesToOpen) val state = State( minutesLeft = currentState.minutesLeft - shortPath - 1, openedValves = hashSetOf<Valve>().apply { add(valvesToOpen) addAll(currentState.openedValves) }, currentValve = valvesToOpen, pressureReleased = currentState.pressureReleased + ((currentState.minutesLeft - shortPath - 1) * valvesToOpen.flowRate) ) stateQueue.addLast(state) } } return if (part1) maxPressureRelieved else maxValvesOpened .filter { it.key.isNotEmpty() }.toList() .combinations(2) .filter { val (you, elephant) = it you.first.intersect(elephant.first).isEmpty() } .map { val (you, elephant) = it you.second + elephant.second }.max() } } fun main() { fun part1(input: List<String>): Int { val graph = Graph(lines = input) return graph.maxPressureReleased(part1 = true) } fun part2(input: List<String>): Int { val graph = Graph(lines = input) return graph.maxPressureReleased(part1 = false) } val input = readInput("/day16/Day16") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
17fd65a8fac7fa0c6f4718d218a91a7b7d535eab
5,198
aoc-2022-kotlin
Apache License 2.0
src/Day02.kt
nguyendanv
573,066,311
false
{"Kotlin": 18026}
fun main() { val beatsMap = mapOf( 1 to 3, 2 to 1, 3 to 2 ) val losesMap = beatsMap .map { (k, v) -> v to k } .toMap() val pointValues = mapOf( "A" to 1, "B" to 2, "C" to 3, "X" to 1, "Y" to 2, "Z" to 3 ) val resultMap = mapOf( "X" to 0, "Y" to 3, "Z" to 6 ) fun part1(input: List<String>): Int { return input .map { it.split(" ") } .map { pointValues[it[0]]!! to pointValues[it[1]]!! } .sumOf { (elfShape, myShape) -> myShape + when (elfShape) { myShape -> 3 beatsMap[myShape]!! -> 6 else -> 0 } } } fun part2(input: List<String>): Int { return input .map { it.split(" ") } .map { pointValues[it[0]]!! to resultMap[it[1]]!! } .sumOf { (elfShape, result) -> result + when (result) { 3 -> elfShape 0 -> beatsMap[elfShape]!! else -> losesMap[elfShape]!! } } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day02_test") check(part1(testInput)==15) check(part2(testInput)==12) val input = readInput("Day02") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
376512583af723b4035b170db1fa890eb32f2f0f
1,486
advent2022
Apache License 2.0
kotlin/src/com/s13g/aoc/aoc2018/Day22.kt
shaeberling
50,704,971
false
{"Kotlin": 300158, "Go": 140763, "Java": 107355, "Rust": 2314, "Starlark": 245}
package com.s13g.aoc.aoc2018 import com.s13g.aoc.Result import com.s13g.aoc.Solver /** https://adventofcode.com/2018/day/22 */ class Day22 : Solver { override fun solve(lines: List<String>): Result { val depth = lines[0].substringAfter("depth: ").toInt() val targetCoords = lines[1].substringAfter("target: ").split(',') val tX = targetCoords[0].toInt() val tY = targetCoords[1].toInt() val creator = RegionCreator(depth) val cavern = hashMapOf<XY, Region>() // Times to to make room for paths in solution B. for (y in 0..tY * 2) { for (x in 0..tX * 2) { cavern[XY(x, y)] = if ((x == 0 && y == 0) || (x == tX && y == tY)) creator.create(0) else if (x == 0) { creator.create(y * 48271) } else if (y == 0) { creator.create(x * 16807) } else { creator.create(cavern[XY(x - 1, y)]!!.erosion * cavern[XY(x, y - 1)]!!.erosion) } } } // printMap(cavern, tX * 2, tY * 2) val solutionA = riskLevel(cavern, tX, tY) // For part B we only really care about the types val cavernB = cavern.mapValues { (k, v) -> v.type } val pathFinder = PathFinder(cavernB, XY(tX, tY)) val solutionB = pathFinder.findShortest() return Result("$solutionA", "$solutionB") } } private fun riskLevel(cavern: Map<XY, Region>, tX: Int, tY: Int): Int { var riskLevel = 0 for (y in 0..tY) { for (x in 0..tX) { riskLevel += when (cavern[XY(x, y)]!!.type) { Type.ROCKY -> 0 Type.WET -> 1 Type.NARROW -> 2 } } } return riskLevel } private fun printMap(cavern: Map<XY, Region>, tX: Int, tY: Int) { for (y in 0..tY) { for (x in 0..tX) { val r = cavern[XY(x, y)] print(when (r!!.type) { Type.ROCKY -> "." Type.WET -> "=" Type.NARROW -> "|" }) } print("\n") } } private class RegionCreator(val depth: Int) { fun create(geoIdx: Int): Region { val erosion = (geoIdx + depth) % 20183 val type = typeFromInt(erosion % 3) return Region(geoIdx, erosion, type) } } private data class Region(val geoIdx: Int, val erosion: Int, val type: Type) private data class XY(val x: Int, val y: Int) private enum class Type { ROCKY, WET, NARROW } private fun typeFromInt(n: Int) = when (n) { 0 -> Type.ROCKY 1 -> Type.WET 2 -> Type.NARROW else -> throw Exception("Invalid type number") } private enum class Tool { TORCH, CLIMBING, NEITHER } /** The state with which a traveler entered a region. */ private data class EnterState(val pos: XY, val tool: Tool) private class Traveler { val pos = mutableListOf<EnterState>() val time = 0 fun currentPos() = pos.last().pos fun currentTool() = pos.last().tool } private class PathFinder(val cavern: Map<XY, Type>, val targetLoc: XY) { val shortest = hashMapOf<XY, Int>() val travelers = arrayListOf<Traveler>() fun findShortest(): Int { val firstTraveler = Traveler() firstTraveler.pos.add(EnterState(XY(0, 0), Tool.TORCH)) travelers.add(firstTraveler) while (!isTargetFound()) { // TODO: Continue here.... } return 42 } private fun toolsAllowed(t: Type) = when (t) { Type.ROCKY -> arrayListOf(Tool.CLIMBING, Tool.TORCH) Type.WET -> arrayListOf(Tool.CLIMBING, Tool.NEITHER) Type.NARROW -> arrayListOf(Tool.TORCH, Tool.NEITHER) } private fun isTargetFound(): Boolean { for (t in travelers) { if (t.currentPos() == targetLoc) { return true } } return false } }
0
Kotlin
1
2
7e5806f288e87d26cd22eca44e5c695faf62a0d7
3,601
euler
Apache License 2.0
src/aoc2022/day09/AoC09.kt
Saxintosh
576,065,000
false
{"Kotlin": 30013}
package aoc2022.day09 import readLines import kotlin.math.abs data class P(val x: Int, val y: Int) { fun up() = P(x + 1, y) fun down() = P(x - 1, y) fun left() = P(x, y - 1) fun right() = P(x, y + 1) } class Board(private val len: Int) { private var rope = Array(len) { P(0, 0) } private var head get() = rope[0] set(p) { rope[0] = p } private val tail get() = rope.last() val tailSet = HashSet<P>().apply { add(tail) } private fun moveTails() { for (k in 1 until len) { val dx = rope[k - 1].x - rope[k].x val dy = rope[k - 1].y - rope[k].y if (abs(dx) <= 1 && abs(dy) <= 1) continue if (abs(dx) == 2 && abs(dy) == 2) { rope[k] = P(rope[k].x + dx / 2, rope[k].y + dy / 2) continue } // solo uno è a 2 when { dx == 2 -> rope[k] = rope[k - 1].down() dx == -2 -> rope[k] = rope[k - 1].up() dy == 2 -> rope[k] = rope[k - 1].left() dy == -2 -> rope[k] = rope[k - 1].right() } } tailSet.add(tail) } fun process(line: String, draw: Boolean = false) { val (p1, p2) = line.split(" ") val rep = p2.toInt() when (p1) { "U" -> repeat(rep) { head = head.up(); moveTails() } "D" -> repeat(rep) { head = head.down(); moveTails() } "L" -> repeat(rep) { head = head.left(); moveTails() } "R" -> repeat(rep) { head = head.right(); moveTails() } } if (draw) draw() } fun draw() { val fullSet = tailSet.plus(rope) val xr = fullSet.minOf { it.x }..fullSet.maxOf { it.x } val yr = fullSet.maxOf { it.y } downTo fullSet.minOf { it.y } for (y in yr) { for (x in xr) { val curr = P(x, y) val ch = when { curr == head -> "H" curr in rope -> rope.indexOfFirst { it == curr }.toString() 0 == x && 0 == y -> "s" P(x, y) in tailSet -> "#" else -> "." } print(ch) } println() } println() } } fun main() { fun part1(lines: List<String>): Int { val b = Board(2) lines.forEach(b::process) return b.tailSet.count() } fun part2(lines: List<String>): Int { val b = Board(10) lines.forEach(b::process) return b.tailSet.count() } // readLines(13, 1, ::part1, ::part2) readLines(88, 36, ::part1, ::part2) }
0
Kotlin
0
0
877d58367018372502f03dcc97a26a6f831fc8d8
2,199
aoc2022
Apache License 2.0
aoc21/pathutils/lib.kt
viktormalik
436,281,279
false
{"Rust": 227300, "Go": 86273, "OCaml": 82410, "Kotlin": 78968, "Makefile": 13967, "Roff": 9981, "Shell": 2796}
package pathutils data class Pos(val x: Int, val y: Int) data class Path(val ps: List<Pos>, val dst: Int) { fun len(): Int = ps.size - 1 } fun fourNeighs( pos: Pos, xMin: Int? = null, xMax: Int? = null, yMin: Int? = null, yMax: Int? = null ): List<Pos> = listOf( Pos(pos.x + 1, pos.y), Pos(pos.x - 1, pos.y), Pos(pos.x, pos.y + 1), Pos(pos.x, pos.y - 1) ).filter { (xMin == null || it.x >= xMin) && (xMax == null || it.x <= xMax) && (yMin == null || it.y >= yMin) && (yMax == null || it.y <= yMax) } fun <M> shortest( from: Pos, to: Pos, map: M, neighs: (Pos, M) -> List<Pos>, dst: ((Pos, Pos, M) -> Int)? = null, ): Path? { var todo = mutableListOf<Path>(Path(listOf(from), 0)) val seen = mutableSetOf<Pos>() while (!todo.isEmpty()) { val path = todo.first() todo.removeFirst() for (n in neighs(path.ps.last(), map)) { if (!seen.contains(n)) { val newPath = Path( path.ps + listOf(n), path.dst + (dst?.invoke(path.ps.last(), n, map) ?: 1) ) todo.add(newPath) if (dst != null) todo = todo.sortedBy { it.dst }.toMutableList() seen.add(n) if (n == to) return newPath } } } return null } fun <M> reachable( from: Pos, map: M, neighs: (Pos, M) -> List<Pos>, maxSteps: Int? = null ): Set<Pos> { val todo = mutableListOf(from to 0) val reachable = mutableSetOf<Pos>() while (!todo.isEmpty()) { val (pos, dst) = todo.first() todo.removeFirst() for (n in neighs(pos, map)) { if (!reachable.contains(n)) { if (maxSteps == null || dst < maxSteps) { todo.add(n to dst + 1) reachable.add(n) } } } } return reachable }
0
Rust
1
0
f47ef85393d395710ce113708117fd33082bab30
2,062
advent-of-code
MIT License
src/year2021/Day12.kt
drademacher
725,945,859
false
{"Kotlin": 76037}
package year2021 import readLines private var counter = 0 fun main() { val input = parseInput(readLines("2021", "day12")) val testInput = parseInput(readLines("2021", "day12_test")) check(part1(testInput) == 226) println("Part 1:" + part1(input)) check(part2(testInput) == 3509) println("Part 2:" + part2(input)) } private fun parseInput(lines: List<String>): Day12Input { val filter = lines .map { line -> line.split("-") } .filter { it.size == 2 } return filter .fold(hashMapOf()) { acc, edge -> acc.putIfAbsent(edge[0], mutableListOf()) acc[edge[0]]!!.add(edge[1]) acc.putIfAbsent(edge[1], mutableListOf()) acc[edge[1]]!!.add(edge[0]) acc } } private fun part1(input: Day12Input): Int { counter = 0 dfs(input, "start", mutableListOf("start"), false) return counter } private fun part2(input: Day12Input): Int { counter = 0 dfs(input, "start", mutableListOf("start"), true) return counter } private fun dfs( input: Day12Input, current: String, smallCavesVisited: MutableList<String>, canVisitSmallCaveTwice: Boolean, ) { for (cave in input[current]!!) { var canVisitSmallCaveTwice = canVisitSmallCaveTwice val isSmallCave = cave[0].isLowerCase() if (isSmallCave && smallCavesVisited.contains(cave)) { if (canVisitSmallCaveTwice && cave != "start") { canVisitSmallCaveTwice = false } else { continue } } if (cave == "end") { counter += 1 } else { smallCavesVisited.add(cave) dfs(input, cave, smallCavesVisited, canVisitSmallCaveTwice) smallCavesVisited.remove(cave) } } } typealias Day12Input = HashMap<String, MutableList<String>>
0
Kotlin
0
0
4c4cbf677d97cfe96264b922af6ae332b9044ba8
1,905
advent_of_code
MIT License
src/cn/leetcode/codes/simple105/Simple105.kt
shishoufengwise1234
258,793,407
false
{"Java": 771296, "Kotlin": 68641}
package cn.leetcode.codes.simple105 import cn.leetcode.codes.common.TreeNode import cn.leetcode.codes.outTreeNote fun main() { val preOrder = intArrayOf(3, 9, 20, 15, 7) val inOrder = intArrayOf(9, 3, 15, 20, 7) var treeNode:TreeNode? = null treeNode = buildTree(preOrder, inOrder) // treeNode = Simple105_2().buildTree(preOrder,inOrder) // [[3], [9], [20], [15], [7]] outTreeNote(treeNode) } /** * 刷题情况 * * 题目地址:https://leetcode-cn.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/ * * 1 刷是否通过: * * * 2 刷是否完成: * * * 3 刷是否完成: * * * 4 刷是否完成: * * * 5 刷是否完成: * * 最优解析:https://leetcode-cn.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/solution/xiang-xi-tong-su-de-si-lu-fen-xi-duo-jie-fa-by--22/ * */ /* 根据一棵树的前序遍历与中序遍历构造二叉树。 注意: 你可以假设树中没有重复的元素。 例如,给出 前序遍历 preorder =[3,9,20,15,7] 中序遍历 inorder = [9,3,15,20,7] 返回如下的二叉树: 3 / \ 9 20 / \ 15 7 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 */ val map = HashMap<Int, Int>() fun buildTree(preorder: IntArray, inorder: IntArray): TreeNode? { if (preorder.size != inorder.size) { return null } //使用map存储数据 inorder.forEachIndexed { p, i -> map.put(p, i) } return buildTreeHelper(preorder, 0, preorder.size, inorder, 0, inorder.size) } private fun buildTreeHelper(preorder: IntArray, preStart: Int, preEnd: Int, inorder: IntArray, inStart: Int, inEnd: Int): TreeNode? { if (preStart > preEnd) { return null } //前序遍历的根节点 val preRoot = preorder[preStart] val root = TreeNode(preRoot) val inOrderRootStart = map.getOrDefault(preRoot, 0) val leftNum = inOrderRootStart - inStart root.left = buildTreeHelper(preorder, preStart + 1, preStart + leftNum + 1, inorder, inStart, inOrderRootStart) root.right = buildTreeHelper(preorder, preStart + leftNum + 1, preEnd, inorder, inOrderRootStart + 1, inEnd) return root }
0
Java
0
0
f917a262bcfae8cd973be83c427944deb5352575
2,388
LeetCodeSimple
Apache License 2.0
src/day14/Day14.kt
palpfiction
572,688,778
false
{"Kotlin": 38770}
package day14 import readInput data class Coordinate(val x: Int, val y: Int) { override fun toString() = "($x, $y)" } fun main() { val sandSource = Coordinate(500, 0) fun getRangeOf(first: Int, second: Int): IntProgression = if (first < second) first.rangeTo(second) else second.rangeTo(first).reversed() fun Coordinate.traceLineTo(other: Coordinate): List<Coordinate> = if (this.x == other.x) { getRangeOf(this.y, other.y) .drop(1) .map { this.copy(y = it) } } else { getRangeOf(this.x, other.x) .drop(1) .map { this.copy(x = it) } } fun parseRockPath(input: String): List<Coordinate> = input .replace(" ", "") .split("->") .map { it.split(",") } .map { (x, y) -> Coordinate(x.toInt(), y.toInt()) } .fold(listOf()) { acc, coordinate -> acc + (acc.lastOrNull()?.traceLineTo(coordinate) ?: listOf(coordinate)) } fun parseRocks(input: List<String>): List<Coordinate> = input .map { parseRockPath(it) } .flatten() fun Coordinate.isOutOfBounds(bounds: Pair<Coordinate, Coordinate>): Boolean = this.x !in bounds.first.x..bounds.second.x || this.y !in bounds.first.y..bounds.second.y fun dropSand(items: List<Coordinate>, shouldStop: (Coordinate) -> Boolean, floor: Int? = null): Coordinate? { var currentPosition = sandSource while (!shouldStop(currentPosition)) { val downwards = currentPosition.copy(y = currentPosition.y + 1) currentPosition = if (!items.contains(downwards) && !(floor != null && downwards.y >= floor)) { downwards } else { val leftDiagonal = currentPosition.copy(x = currentPosition.x - 1, y = currentPosition.y + 1) if (!items.contains(leftDiagonal) && !(floor != null && leftDiagonal.y >= floor)) { leftDiagonal } else { val rightDiagonal = currentPosition.copy(x = currentPosition.x + 1, y = currentPosition.y + 1) if (!items.contains(rightDiagonal) && !(floor != null && rightDiagonal.y >= floor)) { rightDiagonal } else { return currentPosition } } } } return null } fun computeBounds(rocks: List<Coordinate>): Pair<Coordinate, Coordinate> = Coordinate(rocks.minBy { it.x }.x, 0) to Coordinate(rocks.maxBy { it.x }.x, rocks.maxBy { it.y }.y) fun part1(input: List<String>): Int { val rocks = parseRocks(input) val bounds = computeBounds(rocks) val items = rocks.toMutableList() println(bounds) do { val lastSandAdded = dropSand(items, { it.isOutOfBounds(bounds) }) if (lastSandAdded != null) items.add(lastSandAdded) } while (lastSandAdded != null) return items.size - rocks.size } fun part2(input: List<String>): Int { val rocks = parseRocks(input) val floor = rocks.maxBy { it.y }.y + 2 val bounds = Coordinate(-Int.MAX_VALUE, 0) to Coordinate(Int.MAX_VALUE, Int.MAX_VALUE) val items = rocks.toMutableList() println(bounds) do { val lastSandAdded = dropSand(items, { it.isOutOfBounds(bounds) }, floor) if (lastSandAdded != null) items.add(lastSandAdded) } while (lastSandAdded != Coordinate(500, 0)) return items.size - rocks.size } val testInput = readInput("/day14/Day14_test") println(part1(testInput)) println(part2(testInput)) //check(part1(testInput) == 2) //check(part2(testInput) == 4) val input = readInput("/day14/Day14") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
5b79ec5fa4116e496cd07f0c7cea7dabc8a371e7
3,961
advent-of-code
Apache License 2.0
advent-of-code2016/src/main/kotlin/day04/Advent4.kt
REDNBLACK
128,669,137
false
null
package day04 import parseInput import splitToLines import java.util.* /** --- Day 4: Security Through Obscurity --- Finally, you come across an information kiosk with a list of rooms. Of course, the list is encrypted and full of decoy data, but the instructions to decode the list are barely hidden nearby. Better remove the decoy data first. Each room consists of an encrypted name (lowercase letters separated by dashes) followed by a dash, a sector ID, and a checksum in square brackets. A room is real (not a decoy) if the checksum is the five most common letters in the encrypted name, in order, with ties broken by alphabetization. For example: aaaaa-bbb-z-y-x-123[abxyz] is a real room because the most common letters are a (5), b (3), and then a tie between x, y, and z, which are listed alphabetically. a-b-c-d-e-f-g-h-987[abcde] is a real room because although the letters are all tied (1 of each), the first five are listed alphabetically. not-a-real-room-404[oarel] is a real room. totally-real-room-200[decoy] is not. Of the real rooms from the list above, the sum of their sector IDs is 1514. What is the sum of the sector IDs of the real rooms? --- Part Two --- With all the decoy data out of the way, it's time to decrypt this list and get moving. The room names are encrypted by a state-of-the-art shift cipher, which is nearly unbreakable without the right software. However, the information kiosk designers at Easter Bunny HQ were not expecting to deal with a master cryptographer like yourself. To decrypt a room name, rotate each letter forward through the alphabet a number of times equal to the room's sector ID. A becomes B, B becomes C, Z becomes A, and so on. Dashes become spaces. For example, the real name for qzmt-zixmtkozy-ivhz-343 is very encrypted name. What is the sector ID of the room where North Pole objects are stored? */ fun main(args: Array<String>) { val test = """aaaaa-bbb-z-y-x-123[abxyz] |a-b-c-d-e-f-g-h-987[abcde] |not-a-real-room-404[oarel] |totally-real-room-200[decoy] """.trimMargin() val input = parseInput("day4-input.txt") println(findRealRoom(test).sumBy(Room::sectorId) == 1514) println(findRealRoom(input).sumBy(Room::sectorId)) println(findRoomContainsDecryptedMessage(input, "northpole")) } data class Room(val name: String, val sectorId: Int, val checksum: String) { fun isValid() = name.filter { it != '-' } .groupBy { it } .map { -it.value.size to it.key } .sortedWith(Comparator.comparing(Pair<Int, Char>::first).thenComparing(Pair<Int, Char>::second)) .take(5) .map { it.second } .joinToString("") == this.checksum } fun findRealRoom(input: String) = parseRooms(input).filter(Room::isValid) fun findRoomContainsDecryptedMessage(input: String, message: String): List<Room> { fun Char.shift(times: Int): Char { val alphabet = ('a'..'z').toList() return when (this) { '-' -> ' ' in alphabet -> alphabet[(alphabet.indexOf(this) + times) % alphabet.size] else -> this } } fun String.decrypt(times: Int) = map { it.shift(times) }.joinToString("") return parseRooms(input).filter { it.name.decrypt(it.sectorId).contains(message) } } private fun parseRooms(input: String) = input.splitToLines() .map { val (name, sectorId, checksum) = Regex("""(.+)-(\d+)\[(.+)\]""") .matchEntire(it) ?.groupValues!! .drop(1) Room(name, sectorId.toInt(), checksum) }
0
Kotlin
0
0
e282d1f0fd0b973e4b701c8c2af1dbf4f4a149c7
3,672
courses
MIT License
src/main/kotlin/_2022/Day2.kt
thebrightspark
227,161,060
false
{"Kotlin": 548420}
package _2022 import aoc import parseInput import java.util.regex.Pattern private val INPUT_REGEX = Pattern.compile("([A-C]) ([X-Z])") fun main() { aoc(2022, 2) { aocRun { processPart1(it) } aocRun { processPart2(it) } } } private fun processPart1(input: String): Long { val parsedInput = parseInput(INPUT_REGEX, input) { RPS.getOpponentRPS(it.group(1)) to RPS.getYourRPS(it.group(2)) } var score = 0L parsedInput.forEach { (other, yours) -> val result = yours.calculateResult(other) score += result.calculateScore(yours) } return score } private fun processPart2(input: String): Long { val parsedInput = parseInput(INPUT_REGEX, input) { RPS.getOpponentRPS(it.group(1)) to DesiredResult.get(it.group(2)) } var score = 0L parsedInput.forEach { (other, desiredResult) -> val yours = other.getOtherFromDesiredResult(desiredResult) val result = yours.calculateResult(other) score += result.calculateScore(yours) } return score } private enum class RPS(val opponentChar: Char, val yourChar: Char, val score: Long) { ROCK('A', 'X', 1), PAPER('B', 'Y', 2), SCISSORS('C', 'Z', 3); companion object { val OPPONENT_CHAR_MAP: Map<Char, RPS> = values().associateBy { it.opponentChar } val YOUR_CHAR_MAP: Map<Char, RPS> = values().associateBy { it.yourChar } fun getOpponentRPS(char: String): RPS = OPPONENT_CHAR_MAP[char[0]]!! fun getYourRPS(char: String): RPS = YOUR_CHAR_MAP[char[0]]!! } private val winsAgainst: RPS by lazy { when (this) { ROCK -> SCISSORS PAPER -> ROCK SCISSORS -> PAPER } } private val losesAgainst: RPS by lazy { when (this) { ROCK -> PAPER PAPER -> SCISSORS SCISSORS -> ROCK } } fun calculateResult(other: RPS): RPSResult = when { this == other -> RPSResult.DRAW winsAgainst == other -> RPSResult.WIN else -> RPSResult.LOSE } fun getOtherFromDesiredResult(result: DesiredResult): RPS = when (result) { DesiredResult.WIN -> losesAgainst DesiredResult.DRAW -> this DesiredResult.LOSE -> winsAgainst } } private enum class RPSResult(val score: Long) { WIN(6), DRAW(3), LOSE(0); fun calculateScore(yourRps: RPS): Long = yourRps.score + score } private enum class DesiredResult(val char: Char) { WIN('Z'), DRAW('Y'), LOSE('X'); companion object { val CHAR_MAP: Map<Char, DesiredResult> = values().associateBy { it.char } fun get(char: String): DesiredResult = CHAR_MAP[char[0]]!! } }
0
Kotlin
0
0
ac62ce8aeaed065f8fbd11e30368bfe5d31b7033
2,709
AdventOfCode
Creative Commons Zero v1.0 Universal
src/Day09.kt
slawa4s
573,050,411
false
{"Kotlin": 20679}
import kotlin.math.sign class Coordinates(var x: Int, var y: Int) { fun plus(other: Coordinates) { x += other.x y += other.y } fun dist(other: Coordinates): Coordinates { return Coordinates(this.x - other.x, this.y - other.y) } } private val allMoves = mapOf( "U" to Coordinates(0, 1), "D" to Coordinates(0, -1), "L" to Coordinates(-1, 0), "R" to Coordinates(1, 0) ) fun main() { fun isTouch(headCoordinates: Coordinates, tailCoordinates: Coordinates): Boolean { return (tailCoordinates.x in headCoordinates.x - 1 .. headCoordinates.x + 1) and (tailCoordinates.y in headCoordinates.y - 1 .. headCoordinates.y + 1) } fun tailFollow(headCoordinates: Coordinates, tailCoordinates: Coordinates) { if (!isTouch(headCoordinates, tailCoordinates)) { val dist = headCoordinates.dist(tailCoordinates) tailCoordinates.y += dist.y.sign tailCoordinates.x += dist.x.sign } } fun prepareInput(input: List<String>): List<Pair<Coordinates, Int>> = input.map { val split = it.split(" ") Pair(allMoves[split[0]]!!, Integer.parseInt(split[1])) } fun part1(input: List<Pair<Coordinates, Int>>): Int { val tailCoordinates = Coordinates(0, 0) val headCoordinates = Coordinates(0, 0) val savedCoords = mutableSetOf(Pair(0, 0)) input.forEach { (move, num) -> for (i in 1..num) { headCoordinates.plus(move) tailFollow(headCoordinates, tailCoordinates) savedCoords.add(Pair(tailCoordinates.x, tailCoordinates.y)) } } return savedCoords.size } fun part2(input: List<Pair<Coordinates, Int>>): Int { val rope = MutableList(10) { Coordinates(0, 0) } val savedCoords = mutableSetOf(Pair(0, 0)) input.forEach { (move, num) -> for (i in 1..num) { rope[0].plus(move) for (ropeIndex in 0 until rope.lastIndex) { tailFollow(rope[ropeIndex], rope[ropeIndex + 1]) } savedCoords.add(Pair(rope.last().x, rope.last().y)) } } return savedCoords.size } val preparedInput = prepareInput(readInput("Day09")) println(part1(preparedInput)) println(part2(preparedInput)) }
0
Kotlin
0
0
cd8bbbb3a710dc542c2832959a6a03a0d2516866
2,402
aoc-2022-in-kotlin
Apache License 2.0
src/main/kotlin/days/Day7.kt
sicruse
315,469,617
false
null
package days class Day7 : Day(7) { // The target of our investigation is... private val targetBag = "shiny gold" // create a "Bag name" lookup map for convenience private val bags: Map<String, List<Rule>> by lazy { inputList .map { description -> bagFromDescription(description) } .associateBy({ it.first }, { it.second }) } // simple representation of "sub-bag" rules data class Rule(val name: String, val quantity: Int) fun bagFromDescription(description: String) : Pair<String, List<Rule>> { val nameAndContents = description.split(" bags contain ") val name = nameAndContents.first() val contents = nameAndContents.last() return when { // when the contents contain the phrase "no other bags" there is no further rule to extract contents == "no other bags." -> Pair(name, emptyList()) // otherwise, proceed to extract each "sub-bag" rule else -> Pair(name, contents // each bag rule is separated with a comma .split(", ") .map { bag -> // Bag quantity is the first char val quantity = bag.first().toString().toInt() // Bag name comes after first two chars and before the word "bag" val bagName = bag.drop(2).split(" bag").first() Rule(bagName, quantity) }) } } // Find the set of Bags which contain the target bag fun findBagsWhichContain(target: String): Set<String> { val bagsWhichDirectlyContain = bags.filter { bag -> bag.value.any{ content -> content.name == target } }.keys.toSet() val bagsWhichIndirectlyContain = bagsWhichDirectlyContain.flatMap { bagName -> findBagsWhichContain( bagName ) }.toSet() return bagsWhichDirectlyContain.union(bagsWhichIndirectlyContain) } // Find the set of bags which must be packed in the target bag fun findBagsRequired(target: String, num: Int): List<Pair<String,Int>> { val rules = bags[target] val additionalBags = rules?.flatMap { bag -> findBagsRequired(bag.name, bag.quantity * num) } return when { additionalBags == null -> listOf(Pair(target, num)) else -> listOf(Pair(target, num)) + additionalBags } } override fun partOne(): Any { return findBagsWhichContain(targetBag) .count() } override fun partTwo(): Any { return findBagsRequired(targetBag, 1) .fold(0) { acc, pair -> acc + pair.second } - 1 } }
0
Kotlin
0
0
9a07af4879a6eca534c5dd7eb9fc60b71bfa2f0f
2,722
aoc-kotlin-2020
Creative Commons Zero v1.0 Universal
src/Day03.kt
Sghazzawi
574,678,250
false
{"Kotlin": 10945}
val priorities = ('a'..'z') + ('A'..'Z') fun String.getPriority(priorities: List<Char>): Int { val firstCompartment = substring(0 until (length / 2)).toSet() val secondCompartment = substring(length / 2 until length) return priorities.indexOf(secondCompartment.first { firstCompartment.contains(it) }) + 1 } fun main() { fun part1(input: List<String>): Int { return input.fold(0) { acc, current -> acc + current.getPriority(priorities) } } fun part2(input: List<String>): Int { return input.map { it.toCharArray() } .chunked(3) .fold(0) { acc, current -> acc + priorities.indexOf(current.reduce { ac, s -> ac.intersect(s.asIterable().toSet()).toCharArray() } .first()) + 1 } } val input = readInput("Day03") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
a26111fa1bcfec28cc43a2f48877455b783acc0d
887
advent-of-code-kotlin
Apache License 2.0
src/main/kotlin/co/csadev/advent2021/Day14.kt
gtcompscientist
577,439,489
false
{"Kotlin": 252918}
/** * Copyright (c) 2021 by <NAME> * Advent of Code 2021, Day 14 * Problem Description: http://adventofcode.com/2021/day/14 */ package co.csadev.advent2021 import co.csadev.adventOfCode.BaseDay import co.csadev.adventOfCode.Resources.resourceAsList class Day14(override val input: List<String> = resourceAsList("21day14.txt")) : BaseDay<List<String>, Long, Long> { private var polymer = input.first().map { it.toString() } private val rules = input.drop(2).associate { it.split(" -> ").let { s -> s[0] to s[1] } } override fun solvePart1() = expSeq.take(10).last() override fun solvePart2() = expSeq.take(40).last() private val expSeq: Sequence<Long> by lazy { sequence { var polymerPairs = polymer.zipWithNext().map { "${it.first}${it.second}" }.groupingBy { it }.eachCount() .mapValues { it.value.toLong() } while (true) { polymerPairs = polymerPairs.expand() val charPairs = mutableMapOf<Char, Long>() polymerPairs.forEach { (p, count) -> charPairs[p.first()] = count + charPairs.getOrDefault(p.first(), 0L) } yield(charPairs.maxOf { it.value } - charPairs.minOf { it.value } + 1) } } } private fun List<String>.expand(count: Int): Long { var polymerPairs = zipWithNext() .map { "${it.first}${it.second}" } .groupingBy { it } .eachCount() .mapValues { it.value.toLong() } repeat(count) { val newPairs = mutableMapOf<String, Long>() polymerPairs.forEach { (p, count) -> val seq = rules[p]!! newPairs[p.first() + seq] = count + newPairs.getOrDefault(p.first() + seq, 0L) newPairs[seq + p.last()] = count + newPairs.getOrDefault(seq + p.last(), 0L) } polymerPairs = newPairs } val charPairs = mutableMapOf<Char, Long>() polymerPairs.forEach { (p, count) -> charPairs[p.first()] = count + charPairs.getOrDefault(p.first(), 0L) } return charPairs.maxOf { it.value } - charPairs.minOf { it.value } + 1 } private fun Map<String, Long>.expand(): Map<String, Long> { val newPairs = mutableMapOf<String, Long>() forEach { (p, count) -> val seq = rules[p]!! newPairs[p.first() + seq] = count + newPairs.getOrDefault(p.first() + seq, 0L) newPairs[seq + p.last()] = count + newPairs.getOrDefault(seq + p.last(), 0L) } return newPairs } }
0
Kotlin
0
1
43cbaac4e8b0a53e8aaae0f67dfc4395080e1383
2,641
advent-of-kotlin
Apache License 2.0
leetcode/3Sum.kt
migafgarcia
63,630,233
false
{"C++": 121354, "Kotlin": 38202, "C": 34840, "Java": 23043, "C#": 10596, "Python": 8343}
import java.util.* class Solution { fun threeSum(nums: IntArray): List<List<Int>> { val solution = HashSet<Triple<Int, Int, Int>>() for (i in IntRange(0, nums.lastIndex)) { val sols = twoSum(nums, IntRange(i + 1, nums.lastIndex), -nums[i]) sols.forEach { pair -> val list = arrayListOf(pair.first, pair.second, nums[i]).sorted() solution.add(Triple(list[0], list[1], list[2])) } } return solution.map { it.toList() } } fun bruteForceThreeSum(nums: IntArray): List<List<Int>> { val solution = HashSet<Triple<Int, Int, Int>>() for (i in IntRange(0, nums.lastIndex)) { for (j in IntRange(i + 1, nums.lastIndex)) { for (k in IntRange(j + 1, nums.lastIndex)) { if (nums[i] + nums[j] + nums[k] == 0) { val list = arrayListOf(nums[i], nums[j], nums[k]).sorted() solution.add(Triple(list[0], list[1], list[2])) } } } } return solution.map { it.toList() } } fun twoSum(nums: IntArray, range: IntRange, target: Int): List<Pair<Int, Int>> { val solution = LinkedList<Pair<Int, Int>>() val map = HashMap<Int, Int>() for (i in range) { if (map.contains(nums[i])) { solution.add(Pair(nums[map.getValue(nums[i])], nums[i])) } else { map[target - nums[i]] = i } } return solution } }
0
C++
3
9
82f5e482c0c3c03fd39e46aa70cab79391ed2dc5
1,603
programming-challenges
MIT License
src/day05/Day05.kt
GrinDeN
574,680,300
false
{"Kotlin": 9920}
fun main() { fun parseMovements(input: List<String>): List<Triple<Int, Int, Int>> { return input .map { it.split(" ") } .map { Triple(it[1].toInt(), it[3].toInt(), it[5].toInt()) } } fun singleMove(stacks: List<ArrayDeque<Char>>, from: Int, to: Int, numberOfCrates: Int) { for (i in 1..numberOfCrates) { val crate = stacks[from - 1].removeFirst() stacks[to - 1].addFirst(crate) } } fun stackMove(stacks: List<ArrayDeque<Char>>, from: Int, to: Int, numberOfCrates: Int) { val middleStack = ArrayDeque<Char>() for (i in 1..numberOfCrates) { val crate = stacks[from - 1].removeFirst() middleStack.addLast(crate) } stacks[to - 1].addAll(0, middleStack) } fun stacks(): List<ArrayDeque<Char>> { return listOf( ArrayDeque(listOf('V', 'C', 'W', 'L', 'R', 'M', 'F', 'Q')), ArrayDeque(listOf('L', 'Q', 'D')), ArrayDeque(listOf('B', 'N', 'C', 'W', 'G', 'R', 'S', 'P')), ArrayDeque(listOf('G', 'Q', 'B', 'H', 'D', 'C', 'L')), ArrayDeque(listOf('S', 'Z', 'F', 'L', 'G', 'V')), ArrayDeque(listOf('P', 'N', 'G', 'D')), ArrayDeque(listOf('W', 'C', 'F', 'V', 'P', 'Z', 'D')), ArrayDeque(listOf('S', 'M', 'D', 'P', 'C')), ArrayDeque(listOf('C', 'P', 'M', 'V', 'T', 'W', 'N', 'Z')) ) } fun part1(input: List<String>): String { val stacks = stacks() val instructions = parseMovements(input) instructions .forEach { singleMove(stacks, it.second, it.third, it.first) } return stacks .map { it.first() } .joinToString("") } fun part2(input: List<String>): String { val stacks = stacks() val instructions = parseMovements(input) instructions .forEach { stackMove(stacks, it.second, it.third, it.first) } return stacks .map { it.first() } .joinToString("") } // test if implementation meets criteria from the description, like: val testInput = readInput("day05/Day05_test") check(part1(testInput) == "CMZ") val input = readInput("day05/Day05") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
f25886a7a3112c330f80ec2a3c25a2ff996d8cf8
2,335
aoc-2022
Apache License 2.0
src/Day05.kt
flex3r
572,653,526
false
{"Kotlin": 63192}
import java.util.Stack fun main() { val testInput = readInput("Day05_test") check(part1(testInput) == "CMZ") check(part2(testInput) == "MCD") val input = readInput("Day05") println(part1(input)) println(part2(input)) } private fun part1(input: List<String>): String { val (crateInput, procedure) = input.partitionBy { it.isEmpty() } val stacks = parseCrates(crateInput) procedure.forEachAction { (amount, from, to) -> repeat(amount) { val crate = stacks[from - 1].pop() stacks[to - 1].push(crate) } } return stacks.joinToString(separator = "") { it.peek().toString() } } private fun part2(input: List<String>): String { val (crateInput, procedure) = input.partitionBy { it.isEmpty() } val stacks = parseCrates(crateInput) procedure.forEachAction { (amount, from, to) -> val cratesToPush = (0 until amount).map { stacks[from - 1].pop() }.reversed() stacks[to - 1].addAll(cratesToPush) } return stacks.joinToString(separator = "") { it.peek().toString() } } private fun parseCrates(rows: List<String>): List<Stack<Char>> { val lastRow = rows.last() val stacks = List(lastRow.substringAfterLast(" ").toInt()) { Stack<Char>() } rows.dropLast(1) .reversed() .forEach { row -> row.chunked(size = 4) .forEachIndexed { chunkIdx, crate -> if (crate.isBlank()) return@forEachIndexed stacks[chunkIdx].push(crate[1]) } } return stacks } private val procedureRegex = """move (\d+) from (\d+) to (\d+)""".toRegex() private fun parseAction(action: String): List<Int> = procedureRegex.find(action)!!.groupValues.drop(1).map { it.toInt() } private fun List<String>.forEachAction(action: (List<Int>) -> Unit) = forEach { action(parseAction(it)) }
0
Kotlin
0
0
8604ce3c0c3b56e2e49df641d5bf1e498f445ff9
1,878
aoc-22
Apache License 2.0
src/Day15.kt
arhor
572,349,244
false
{"Kotlin": 36845}
import kotlin.math.abs import kotlin.math.absoluteValue import kotlin.streams.asStream import kotlin.system.measureTimeMillis //fun main() { // val input = readInput {} // // println("Part 1: ${solvePuzzle2(input)}") //} private const val TARGET_Y = 2_000_000 private const val LIMIT = 4_000_000 private val inputPattern = Regex("^Sensor at x=(-?[0-9]+), y=(-?[0-9]+): closest beacon is at x=(-?[0-9]+), y=(-?[0-9]+)$") private fun solvePuzzle1(input: List<String>): Int { val table = HashMap<Point, Int>() val beacons = HashSet<Point>() var xMin = Int.MIN_VALUE var xMax = Int.MIN_VALUE var yMin = Int.MIN_VALUE var yMax = Int.MIN_VALUE for (line in input) { inputPattern.find(line)?.let { matchResult -> val (x1, y1, x2, y2) = matchResult.groupValues.drop(1).map(String::toInt) val radius = determineTaxicabDistance(x1, y1, x2, y2) xMin = if (xMin != Int.MIN_VALUE) minOf(xMin, x1 - radius) else x1 - radius xMax = if (xMax != Int.MIN_VALUE) maxOf(xMax, x1 + radius) else x1 + radius yMin = if (yMin != Int.MIN_VALUE) minOf(yMin, y1 - radius) else y1 - radius yMax = if (yMax != Int.MIN_VALUE) maxOf(yMax, y1 + radius) else y1 + radius val scaner = Point(x1, y1) val beacon = Point(x2, y2) table[scaner] = radius beacons.add(beacon) } } var cellsUnderScaner = 0 for (x in xMin..xMax) { for ((scaner, radius) in table) { val dist = determineTaxicabDistance(x1 = x, y1 = TARGET_Y, x2 = scaner.x, y2 = scaner.y) val diff = radius - dist if (diff >= 0) { cellsUnderScaner++ break } } } return cellsUnderScaner - beacons.count { it.y == TARGET_Y } } private fun solvePuzzle2(input: List<String>): Int { val table = HashMap<Point, Int>() val beacons = HashSet<Point>() val xMin = 0 val xMax = LIMIT val yMin = 0 val yMax = LIMIT for (line in input) { val (x1, y1, x2, y2) = inputPattern.find(line)!!.groupValues.drop(1).map(String::toInt) val radius = determineTaxicabDistance(x1, y1, x2, y2) val scaner = Point(x1, y1) val beacon = Point(x2, y2) table[scaner] = radius beacons.add(beacon) } var y = yMin y@ while (y++ <= yMax) { println("current y: ${y.toString().padStart(7)}") var x = xMin x@ while (x++ <= xMax) { val distances = table.map { (scaner, radius) -> val dist = determineTaxicabDistance(x1 = x, y1 = y, x2 = scaner.x, y2 = scaner.y) val diff = radius - dist scaner to diff }.filter { it.second >= 0 }.sortedBy { it.second } if (distances.isNotEmpty()) { val (excitingPoint, diff) = distances.first() if (excitingPoint.x > x) { x += ((excitingPoint.x - x).absoluteValue + diff) } continue@x } return x * 4000000 + y } } return 0 } private fun determineTaxicabDistance(x1: Int, y1: Int, x2: Int, y2: Int): Int = abs(x1 - x2) + abs(y1 - y2) fun Point.tuningFrequency() = x * 4_000_000L + y data class SensorMeasurement(val sensor: Point, val beacon: Point) { fun sensorRangePerY(): Sequence<Pair<Int, IntRange>> { val distance = sensor.manhattanDistanceTo(beacon) return (0..distance).asSequence().flatMap { yOffset -> val xOffset = distance - yOffset val xRange = (sensor.x - xOffset)..(sensor.x + xOffset) sequence { yield(sensor.y + yOffset to xRange) yield(sensor.y - yOffset to xRange) } } } } fun main() { val lines = readInput { } val cave: Cave measureTimeMillis { cave = parseModel(lines) }.let { println("Parsing and optimizing cave in $it ms") } val y = 2000000 val cannotBeBeaconAtY: Int measureTimeMillis { cannotBeBeaconAtY = cave.cannotBeBeaconAtY(y) }.let { println("Checking y for beacon stuff in $it ms") } println("At y=$y, $cannotBeBeaconAtY positions cannot be beacons") val beaconPos: Point measureTimeMillis { beaconPos = cave.findBeaconIn(0..4_000_000) }.let { println("Found beacon pos in $it ms") } println("The beacon must be at $beaconPos, its tuning frequency is ${beaconPos.tuningFrequency()}") } private fun parseModel(data: List<String>): Cave = data.map { inputPattern.matchEntire(it)!!.groupValues } .map { (_, sensorX, sensorY, beaconX, beaconY) -> val sensor = Point(sensorX.toInt(), sensorY.toInt()) val beacon = Point(beaconX.toInt(), beaconY.toInt()) SensorMeasurement(sensor, beacon) } .let(::Cave) data class Cave(private val sensorMeasurements: List<SensorMeasurement>) { private val minX: Int private val maxX: Int private val minY: Int private val maxY: Int private val grid = HashMap<Point, Entity>() private val sensorCoverageRangesY = HashMap<Int, MutableList<IntRange>>() init { sensorMeasurements.forEach { grid[it.sensor] = Entity.SENSOR grid[it.beacon] = Entity.BEACON } // Coverage sensorMeasurements.flatMap { it.sensorRangePerY() }.forEach { (y, xRange) -> sensorCoverageRangesY.getOrPut(y, ::ArrayList).add(xRange) } sensorCoverageRangesY.keys.forEach { sensorCoverageRangesY[it] = sensorCoverageRangesY[it]!!.compressed().toMutableList() } // Limits sequenceOf( sensorMeasurements.map { it.beacon.y }, sensorCoverageRangesY.keys, ) .flatten() .asStream() .mapToInt { it } .summaryStatistics() .let { minY = it.min maxY = it.max } sequenceOf( sensorMeasurements.map { it.beacon.x }, sensorCoverageRangesY.values.flatMap { it.flatMap { xRange -> listOf(xRange.first, xRange.last) } } ) .flatten() .asStream() .mapToInt { it } .summaryStatistics() .let { minX = it.min maxX = it.max } } fun cannotBeBeaconAtY(y: Int) = (minX..maxX).map { Point(it, y) }.count(::cannotBeBeacon) fun findBeaconIn(range: IntRange): Point = range.flatMap { y -> searchRanges(sensorCoverageRangesY[y] ?: emptyList()) .restrictToView(range) .flatten() .map { x -> Point(x, y) } }.first(::canBeNewBeacon) private fun isCoveredBySensor(point: Point) = sensorCoverageRangesY[point.y]?.any { point.x in it } ?: false private fun cannotBeBeacon(point: Point) = when (grid[point]) { Entity.SENSOR -> true Entity.BEACON -> false else -> isCoveredBySensor(point) } private fun canBeNewBeacon(point: Point) = when (grid[point]) { Entity.SENSOR -> false Entity.BEACON -> false else -> !isCoveredBySensor(point) } private fun searchRanges(sensorCoveredRange: List<IntRange>): List<IntRange> { if (sensorCoveredRange.isEmpty()) { return listOf(minX..maxX) } val searchRanges = mutableListOf(minX until sensorCoveredRange.first().first) searchRanges += sensorCoveredRange.zipWithNext { left, right -> left.last + 1 until right.first } searchRanges += sensorCoveredRange.last().last + 1..maxX return searchRanges } private fun List<IntRange>.compressed(): List<IntRange> = sortedBy { it.first }.fold(ArrayList()) { result, range -> val lastCompressed = result.lastOrNull() if (lastCompressed?.overlaps(range) == true) { result[result.lastIndex] = lastCompressed.merge(range) } else { result += range } result } private fun List<IntRange>.restrictToView(view: IntRange): List<IntRange> { val result = ArrayList<IntRange>() for (range in this) { when { range.first in view && range.last in view -> result += range range.first in view && range.last !in view -> result += range.first..view.last range.first !in view && range.last in view -> result += view.first..range.last } } return result } } enum class Entity { SENSOR, BEACON }
0
Kotlin
0
0
047d4bdac687fd6719796eb69eab2dd8ebb5ba2f
8,702
aoc-2022-in-kotlin
Apache License 2.0
src/Day03.kt
WilsonSunBritten
572,338,927
false
{"Kotlin": 40606}
fun main() { fun part1(input: List<String>): Int { return input.map { rucksack -> println(rucksack) val firstHalf = rucksack.take(rucksack.length / 2).toList() val secondHalf = rucksack.takeLast(rucksack.length / 2).toList() val matchingCharacters = firstHalf.toSet().intersect(secondHalf.toSet()) // println("here") // println(matchingCharacters) val result = matchingCharacters.toList().map { if(it.toInt() > 90) { it.toInt() - 96} else { it.toInt() - 64 + 26 } }.sum() result }.sum() } fun part2(input: List<String>): Int { return input.windowed(3, 3).map { rucksackGroup -> rucksackGroup.fold(rucksackGroup.first().toSet()) { acc, current -> acc.intersect(current.toSet()) } }.map { val value = it.single() if(value.toInt() > 90) { value.toInt() - 96} else { value.toInt() - 64 + 26 } }.also { println(it) }.sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day03_test") val p1Result = part1(testInput) println(p1Result) check(p1Result == 157) println(part2(testInput)) check(part2(testInput) == 70) val input = readInput("Day03") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
363252ffd64c6dbdbef7fd847518b642ec47afb8
1,361
advent-of-code-2022-kotlin
Apache License 2.0
src/com/ncorti/aoc2023/Day08.kt
cortinico
723,409,155
false
{"Kotlin": 76642}
package com.ncorti.aoc2023 fun main() { fun play(pattern: CharArray, graph: Map<String, Pair<String, String>>): Int { var idx = 0 var current = "AAA" var steps = 0 while (current != "ZZZ") { current = if (pattern[idx] == 'L') { graph[current]!!.first } else { graph[current]!!.second } idx = (idx + 1) % pattern.size steps++ } return steps } fun findLoop(start: String, pattern: CharArray, graph: Map<String, Pair<String, String>>): Int { var idx = 0 var current = start var steps = 0 while (true) { current = if (pattern[idx] == 'L') { graph[current]!!.first } else { graph[current]!!.second } idx = (idx + 1) % pattern.size steps++ if (current.endsWith("Z")) { break } } return steps } fun gcd(a: Long, b: Long): Long = if (b == 0L) a else gcd(b, a % b) fun lcm(a: Long, b: Long): Long = a * b / gcd(a, b) fun parseInput(): Pair<CharArray, Map<String, Pair<String, String>>> { val input = getInputAsText("08") { split("\n").filter(String::isNotBlank) } val pattern = input[0].toCharArray() val graph = input.drop(1).map { line -> val from = line.substringBefore(" = ") val (l, r) = line.substringAfter(" = ").removeSurrounding("(", ")").split(", ") from to (l to r) }.toMap() return pattern to graph } fun part1(): Int { val (pattern, graph) = parseInput() return play(pattern, graph) } fun part2(): Long { val (pattern, graph) = parseInput() val starts = graph.keys.filter { it.endsWith("A") }.toMutableList() return starts.map { findLoop(it, pattern, graph) }.fold(1L) { acc, i -> lcm(acc, i.toLong()) } } println(part1()) println(part2()) }
1
Kotlin
0
1
84e06f0cb0350a1eed17317a762359e9c9543ae5
2,086
adventofcode-2023
MIT License
src/Day13.kt
michaelYuenAE
573,094,416
false
{"Kotlin": 74685}
class Day13(lines: List<String>) { private val packets = lines.mapNotNull { if (it.isNotEmpty()) it.toPacket() else null } fun part1(): Int = packets.chunked(2) { (a, b) -> a <= b }.withIndex().filter { it.value }.sumOf { it.index + 1 } fun part2(): Int { var x = 1 var y = 1 for (packet in packets) { when { packet < a -> x++ packet < b -> y++ } } return x * (x + y) } private sealed class Packet : Comparable<Packet> { data class Literal(val value: Int) : Packet() { override fun compareTo(other: Packet): Int = when (other) { is Literal -> this.value compareTo other.value is List -> List(listOf(this)) compareTo other } override fun hashCode(): Int = value } data class List(val list: kotlin.collections.List<Packet>) : Packet() { override fun compareTo(other: Packet): Int { return when (other) { is Literal -> this compareTo List(listOf(other)) is List -> { val i = this.list.iterator() val j = other.list.iterator() while (i.hasNext() && j.hasNext()) { val comparison = i.next() compareTo j.next() if (comparison != 0) return comparison } i.hasNext() compareTo j.hasNext() } } } override fun hashCode(): Int = list.fold(0) { acc, value -> 31 * acc + value.hashCode() } } override fun equals(other: Any?): Boolean = other is Packet && compareTo(other) == 0 abstract override fun hashCode(): Int } companion object { private val a: Packet = Packet.List(listOf(Packet.List(listOf(Packet.Literal(2))))) private val b: Packet = Packet.List(listOf(Packet.List(listOf(Packet.Literal(6))))) private val parser = DeepRecursiveFunction<IndexedValue<String>, IndexedValue<Packet>> { (startIndex, string) -> if (string[startIndex] == '[') { var index = startIndex + 1 val list = buildList { while (string[index] != ']') { val (endIndex, value) = callRecursive(IndexedValue(index, string)) add(value) index = if (string[endIndex] == ',') endIndex + 1 else endIndex } } IndexedValue(index + 1, Packet.List(list)) } else { var index = startIndex + 1 while (index < string.length && string[index] in '0'..'9') index++ IndexedValue(index, Packet.Literal(string.substring(startIndex, index).toInt())) } } private fun String.toPacket(): Packet { val (index, packet) = parser.invoke(IndexedValue(0, this)) require(index == length) return packet } } } fun main() { println(Day13(readInput("day13_input")).part2()) }
0
Kotlin
0
0
ee521263dee60dd3462bea9302476c456bfebdf8
3,207
advent22
Apache License 2.0
src/day22/Day22.kt
gautemo
317,316,447
false
null
package day22 import shared.getLines fun combat(input: List<String>): Int{ val (player1, player2) = mapPlayers(input) while (player1.isNotEmpty() && player2.isNotEmpty()){ if(player1.first() > player2.first()){ player1.add(player1.removeAt(0)) player1.add(player2.removeAt(0)) }else{ player2.add(player2.removeAt(0)) player2.add(player1.removeAt(0)) } } val winner = if(player1.size > 0) player1 else player2 return winner.withIndex().sumBy { (i, card) -> (winner.size - i) * card } } fun recursiveCombat(input: List<String>): Int{ val (player1, player2) = playGame(mapPlayers(input)) val winner = if(player1.size > 0) player1 else player2 return winner.withIndex().sumBy { (i, card) -> (winner.size - i) * card } } fun playGame(players: List<MutableList<Int>>): List<MutableList<Int>>{ val history = mutableListOf<String>() val (player1, player2) = players while (player1.isNotEmpty() && player2.isNotEmpty()){ if(history.contains("${player1.joinToString()}:${player2.joinToString()}")){ player2.clear() break } history.add("${player1.joinToString()}:${player2.joinToString()}") val cardPlayer1 = player1.removeAt(0) val cardPlayer2 = player2.removeAt(0) var player1Wins = cardPlayer1 > cardPlayer2 if(cardPlayer1 <= player1.size && cardPlayer2 <= player2.size){ player1Wins = playGame(listOf(player1.take(cardPlayer1).toMutableList(), player2.take(cardPlayer2).toMutableList()))[0].size > 0 } if(player1Wins){ player1.add(cardPlayer1) player1.add(cardPlayer2) }else{ player2.add(cardPlayer2) player2.add(cardPlayer1) } } return listOf(player1, player2) } fun mapPlayers(input: List<String>): List<MutableList<Int>>{ val players = listOf( mutableListOf<Int>(), mutableListOf() ) var index = 0 for(line in input){ when(line){ "Player 1:" -> continue "Player 2:" -> index = 1 "" -> continue else -> players[index].add(line.toInt()) } } return players } fun main(){ val input = getLines("day22.txt") val result = combat(input) println(result) val result2 = recursiveCombat(input) println(result2) }
0
Kotlin
0
0
ce25b091366574a130fa3d6abd3e538a414cdc3b
2,430
AdventOfCode2020
MIT License
aoc2022/day12.kt
davidfpc
726,214,677
false
{"Kotlin": 127212}
package aoc2022 import utils.InputRetrieval fun main() { Day12.execute() } object Day12 { fun execute() { val input = readInput() println("Part 1: ${part1(input)}") println("Part 2: ${part2(input)}") } private fun part1(input: Graph): Int { calculateShortestPathFromSource(input, input.startNode) return input.endNode.distance } /** * 🔨, love it! Just throw CPU power at the problem! */ private fun part2(input: Graph): Int = input.nodes.filter { it.name.startsWith('a') }.minOf { input.reset() calculateShortestPathFromSource(input, it) input.endNode.distance } private fun readInput(): Graph { var input = InputRetrieval.getFile(2022, 12).readLines() val graph = Graph() val nodesMap = mutableMapOf<Pair<Int, Int>, Node>() (input.indices).forEach { y -> input[0].indices.forEach { x -> val node = Node("${input[y][x]}: $x-$y") // Check if start Node when (input[y][x]) { 'S' -> graph.startNode = node 'E' -> graph.endNode = node } graph.nodes.add(node) nodesMap[x to y] = node } } input = input.map { it.replace('S', 'a').replace('E', 'z') } // Set the start and end elevation (input.indices).forEach { y -> input[0].indices.forEach { x -> val currentElevation = input[y][x] val currentNode = nodesMap[x to y]!! val positions = listOf(-1 to 0, 0 to -1, 0 to 1, 1 to 0).map { (x + it.first to y + it.second) } .filter { it.first >= 0 && it.first < input[0].length } .filter { it.second >= 0 && it.second < input.size } positions.forEach { if (input[it.second][it.first] - currentElevation <= 1) { currentNode.addDestination(nodesMap[it.first to it.second]!!) } } } } return graph } private fun calculateShortestPathFromSource(graph: Graph, source: Node): Graph { source.distance = 0 val settledNodes = mutableSetOf<Node>() val unsettledNodes = mutableSetOf(source) while (unsettledNodes.size != 0) { val currentNode = unsettledNodes.minBy { it.distance } unsettledNodes.remove(currentNode) for ((adjacentNode, edgeWeight) in currentNode.adjacentNodes.entries) { if (!settledNodes.contains(adjacentNode)) { val sourceDistance: Int = currentNode.distance if ((sourceDistance + edgeWeight) < adjacentNode.distance) { adjacentNode.distance = sourceDistance + edgeWeight val shortestPath = currentNode.shortestPath.toMutableList() shortestPath.add(currentNode) adjacentNode.shortestPath = shortestPath } unsettledNodes.add(adjacentNode) } } settledNodes.add(currentNode) } return graph } class Graph { lateinit var startNode: Node lateinit var endNode: Node val nodes: MutableSet<Node> = mutableSetOf() fun reset() { nodes.forEach { it.reset() } } } class Node(val name: String) { var shortestPath = mutableListOf<Node>() var distance = Int.MAX_VALUE var adjacentNodes: MutableMap<Node, Int> = HashMap() fun addDestination(destination: Node) { adjacentNodes[destination] = 1 } fun reset() { this.distance = Int.MAX_VALUE this.shortestPath = mutableListOf() } override fun toString(): String = "Node($name)" } }
0
Kotlin
0
0
8dacf809ab3f6d06ed73117fde96c81b6d81464b
3,973
Advent-Of-Code
MIT License
advent-of-code-2022/src/Day04.kt
osipxd
572,825,805
false
{"Kotlin": 141640, "Shell": 4083, "Scala": 693}
fun main() { val testInput = readInput("Day04_test") check(part1(testInput) == 2) val input = readInput("Day04") println("Part 1: " + part1(input)) println("Part 2: " + part2(input)) } private fun part1(input: Sequence<List<IntRange>>): Int = input.count { (a, b) -> b in a || a in b } private fun part2(input: Sequence<List<IntRange>>): Int = input.count { (a, b) -> a.first in b || b.first in a } // Parse each line to lists of ranges: // "1-3,4-6" -> [1..3, 4..6] private fun readInput(name: String) = readLines(name).asSequence().map { line -> line.split(",").map { range -> val (start, end) = range.split("-").map(String::toInt) start..end } } // Checks if [this] range contains both the start and the end of the [other] range // It is an operator, so we can call it using "in": // a.contains(b) == b in a private operator fun IntRange.contains(other: IntRange): Boolean = this.first <= other.first && this.last >= other.last
0
Kotlin
0
5
6a67946122abb759fddf33dae408db662213a072
984
advent-of-code
Apache License 2.0
src/nativeMain/kotlin/com.qiaoyuang.algorithm/special/Questions11.kt
qiaoyuang
100,944,213
false
{"Kotlin": 338134}
package com.qiaoyuang.algorithm.special fun test11() { printlnResult(intArrayOf(1, 0, 1)) printlnResult(intArrayOf(1, 1, 0, 1)) printlnResult(intArrayOf(1, 1, 0, 1, 0, 0, 1)) } /** * Questions 11: Find the counts of consistent sub-arrays that their counts of * 1 and 0 equal in an IntArray that just contain 0 and 1, and the sub-arrays * contain 2 elements at least. */ private fun IntArray.findCountOf0and1(): Int { require(size > 2) { "The size of IntArray must greater than 2" } var count = 0 val aux = IntArray(size) for (subSize in 2 ..< size) { var i = 0 var j = i + subSize - 1 while (j < size) aux[subSum(i++ ,j++)]++ count += aux.foldIndexed(0) { index, acc, singleCount -> when (singleCount) { 0 -> acc 1 -> { aux[index] = 0 acc } else -> { aux[index] = 0 acc + singleCount } } } } return count } private fun IntArray.subSum(i: Int, j: Int): Int { var sum = 0 for (index in i..j) sum += this[index] return sum } private fun printlnResult(array: IntArray) = println("The count of consistent sub-arrays that counts of 0 and 1 equal is (${array.findCountOf0and1()}) in array: ${array.toList()}")
0
Kotlin
3
6
66d94b4a8fa307020d515d4d5d54a77c0bab6c4f
1,408
Algorithm
Apache License 2.0
kotlin/src/katas/kotlin/leetcode/longest_string_without_consequetive_chars/LongestString.kt
dkandalov
2,517,870
false
{"Roff": 9263219, "JavaScript": 1513061, "Kotlin": 836347, "Scala": 475843, "Java": 475579, "Groovy": 414833, "Haskell": 148306, "HTML": 112989, "Ruby": 87169, "Python": 35433, "Rust": 32693, "C": 31069, "Clojure": 23648, "Lua": 19599, "C#": 12576, "q": 11524, "Scheme": 10734, "CSS": 8639, "R": 7235, "Racket": 6875, "C++": 5059, "Swift": 4500, "Elixir": 2877, "SuperCollider": 2822, "CMake": 1967, "Idris": 1741, "CoffeeScript": 1510, "Factor": 1428, "Makefile": 1379, "Gherkin": 221}
package katas.kotlin.leetcode.longest_string_without_consequetive_chars import datsok.shouldEqual import org.junit.Test import java.util.* /** * https://leetcode.com/discuss/interview-question/330356/Amazon-or-Online-Assessment-2019-or-Longest-string-without-3-consecutive-characters */ class LongestStringTests { @Test fun examples() { findMaxLengthString(a = 0, b = 0, c = 0) shouldEqual "" findMaxLengthString(a = 1, b = 0, c = 0) shouldEqual "a" findMaxLengthString(a = 0, b = 1, c = 0) shouldEqual "b" findMaxLengthString(a = 0, b = 0, c = 1) shouldEqual "c" findMaxLengthString(a = 3, b = 0, c = 0) shouldEqual "aa" findMaxLengthString(a = 1, b = 1, c = 1) shouldEqual "acb" findMaxLengthString(a = 2, b = 1, c = 1) shouldEqual "acab" findMaxLengthString(a = 1, b = 1, c = 6) shouldEqual "ccaccbcc" findMaxLengthString(a = 1, b = 2, c = 3) shouldEqual "cbcbca" } } private fun findMaxLengthString(a: Int, b: Int, c: Int): String { val heap = PriorityQueue<Pair<Int, Char>>(Comparator { o1, o2 -> -o1.first.compareTo(o2.first) }) if (a > 0) heap.add(Pair(a, 'a')) if (b > 0) heap.add(Pair(b, 'b')) if (c > 0) heap.add(Pair(c, 'c')) var onHold: Pair<Int, Char>? = null var result = "" while (heap.isNotEmpty()) { val (count, char) = heap.remove() result += char if (onHold != null) { heap.add(onHold) onHold = null } val updatedCount = count - 1 if (updatedCount > 0) { if (result.length >= 2 && result[result.length - 2] == char) { onHold = Pair(updatedCount, char) } else { heap.add(Pair(updatedCount, char)) } } } return result } private fun findMaxLengthString_(a: Int, b: Int, c: Int): String { fun findMaxLengthString(solution: Solution): List<Solution> { if (solution.isComplete()) return listOf(solution) return solution.nextSteps() .filter { it.isValid() } .flatMap { findMaxLengthString(it) } } return findMaxLengthString(Solution(List(a) { 'a' }, List(b) { 'b' }, List(c) { 'c' })) .maxByOrNull { it.value.length }!!.value } private data class Solution(val a: List<Char>, val b: List<Char>, val c: List<Char>, val value: String = "") { fun isComplete() = a.isEmpty() && b.isEmpty() && c.isEmpty() fun isValid() = value.length < 3 || value.takeLast(3).toSet().size > 1 fun nextSteps(): List<Solution> { return listOfNotNull( if (a.isNotEmpty()) Solution(a.drop(1), b, c, value + a.first()) else null, if (b.isNotEmpty()) Solution(a, b.drop(1), c, value + b.first()) else null, if (c.isNotEmpty()) Solution(a, b, c.drop(1), value + c.first()) else null ) } }
7
Roff
3
5
0f169804fae2984b1a78fc25da2d7157a8c7a7be
2,877
katas
The Unlicense
src/main/kotlin/de/jball/aoc2022/day13/Day13.kt
fibsifan
573,189,295
false
{"Kotlin": 43681}
package de.jball.aoc2022.day13 import de.jball.aoc2022.Day class Day13(test: Boolean = false) : Day<Int>(test, 13, 140) { private val pairs = input.chunked(3).map {Pair(parsePacket(it[0]), parsePacket(it[1])) } private fun parsePacket(packetString: String): Packet { var workingString = packetString val context = mutableListOf<MutableList<Packet>>() while (workingString.isNotEmpty()) { if (workingString.startsWith("[")) { val startedList = mutableListOf<Packet>() context.add(startedList) workingString = workingString.substring(1) } else if (workingString.startsWith("]")) { val finishedList = ListPacket(context.removeLast()) val parent = context.lastOrNull() if (parent != null) { parent.add(finishedList) workingString = workingString.substring(1) } else { return finishedList } } else if (workingString.startsWith(",")) { workingString = workingString.substring(1) } else { val numberRegex = "^(\\d+).*".toRegex() if (workingString matches numberRegex) { val numberString = numberRegex.find(workingString)!!.groups[1]!!.value context.last().add(NumberPacket(numberString.toInt())) workingString = workingString.substring(numberString.length) } else { error("Unexpected input $workingString") } } } error("Should have returned in while loop") } override fun part1(): Int { return pairs.mapIndexed { index, pair -> Pair(index, pair) } .filter { (_, pair) -> pair.first <= pair.second } .sumOf { (index, _) -> index+1 } } override fun part2(): Int { val divider1 = ListPacket(listOf(ListPacket(listOf(NumberPacket(2))))) val divider2 = ListPacket(listOf(ListPacket(listOf(NumberPacket(6))))) val sortedArray = pairs.flatMap { it.toList() }.sorted().toTypedArray() val indexDivider1 = -sortedArray.binarySearch(divider1) val indexDivider2 = -sortedArray.binarySearch(divider2) + 1 return indexDivider2 * indexDivider1 } } sealed class Packet: Comparable<Packet> class ListPacket(val packets: List<Packet>): Packet() { override fun compareTo(other: Packet): Int { return if (other is ListPacket) { val foundPair = packets.zip(other.packets) .firstOrNull { (a, b) -> a.compareTo(b) != 0 } foundPair?.first?.compareTo(foundPair.second) ?: packets.size.compareTo(other.packets.size) } else { compareTo(ListPacket(listOf(other))) } } override fun toString(): String { return packets.joinToString(",", "[", "]") } } class NumberPacket(val value: Int): Packet() { override fun compareTo(other: Packet): Int { return if (other is NumberPacket) { value.compareTo(other.value) } else { ListPacket(listOf(this)).compareTo(other) } } override fun toString(): String { return value.toString() } } fun main() { Day13().run() }
0
Kotlin
0
3
a6d01b73aca9b54add4546664831baf889e064fb
3,389
aoc-2022
Apache License 2.0
code-sample-kotlin/algorithms/src/main/kotlin/com/codesample/leetcode/easy/111_minimumDepthTree.kt
aquatir
76,377,920
false
{"Java": 674809, "Python": 143889, "Kotlin": 112192, "Haskell": 57852, "Elixir": 33284, "TeX": 20611, "Scala": 17065, "Dockerfile": 6314, "HTML": 4714, "Shell": 387, "Batchfile": 316, "Erlang": 269, "CSS": 97}
package com.codesample.leetcode.easy fun main() { val s = Solution() //Input: root = [3,9,20,null,null,15,7] //Output: 2 val root2 = TreeNode(3) root2.left = TreeNode(9) root2.right = TreeNode(20) root2.right!!.left = TreeNode(15) root2.right!!.right = TreeNode(7) println(s.minDepth(root2)) //Input: root = [2,null,3,null,4,null,5,null,6] //Output: 5 val root1 = TreeNode(2) root1.right = TreeNode(3) root1.right!!.right = TreeNode(4) root1.right!!.right!!.right = TreeNode(5) root1.right!!.right!!.right!!.right = TreeNode(5) println(s.minDepth(root1)) } class TreeNode(var `val`: Int) { var left: TreeNode? = null var right: TreeNode? = null } /** * 111. Minimum Depth of Binary Tree https://leetcode.com/problems/minimum-depth-of-binary-tree/ * * Given a binary tree, find its minimum depth. * The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. * Note: A leaf is a node with no children. */ class Solution { // DFS -> go down until need to go back up. // When starting to traverse a subtree and existing minLength is < then possible -> stop traversing. fun minDepth(root: TreeNode?): Int { var minimum = Integer.MAX_VALUE fun curMinOrLess(node: TreeNode, curLength: Int): Int { if (curLength >= minimum) { return minimum } if (node.left == null && node.right == null) { return curLength } if (node.left != null) { minimum = Math.min(minimum, curMinOrLess(node.left!!, curLength + 1)) } if (node.right != null) { minimum = Math.min(minimum, curMinOrLess(node.right!!, curLength + 1)) } return minimum } if (root == null) return 0 return curMinOrLess(root, 1) } fun minDepth2(root: TreeNode?): Int { if (root == null) return 0 if (root.left != null && root.right != null) { return Math.min(minDepth(root.left), minDepth(root.right)) + 1 } else { return Math.max(minDepth(root.left), minDepth(root.right)) + 1 } } }
1
Java
3
6
eac3328ecd1c434b1e9aae2cdbec05a44fad4430
2,281
code-samples
MIT License
src/Day21.kt
i-tatsenko
575,595,840
false
{"Kotlin": 90644}
import java.lang.IllegalArgumentException private interface Num { fun eval(): Long fun init(monkeys: Map<String, Num>) {} val isHumn: Boolean fun balance(value: Long): Long } private data class ScalarMonkey(val scalar: Long, override val isHumn: Boolean) : Num { override fun eval(): Long = scalar override fun balance(value: Long): Long = if (isHumn) value else throw IllegalArgumentException("Humn is in another castle") } private data class RefMonkey(private val refs: Pair<String, String>, val operation: String): Num { lateinit var leftRef: Num lateinit var rightRef: Num override fun init(monkeys: Map<String, Num>) { leftRef = monkeys[refs.first]!! rightRef = monkeys[refs.second]!! leftRef.init(monkeys) rightRef.init(monkeys) } override fun eval(): Long { val leftArg = leftRef.eval() val rightArg = rightRef.eval() return when(operation) { "*" -> leftArg * rightArg "/" -> leftArg / rightArg "+" -> leftArg + rightArg else -> leftArg - rightArg } } override val isHumn: Boolean get() = leftRef.isHumn || rightRef.isHumn override fun balance(value: Long): Long { val (toBalance, static) = if (leftRef.isHumn) leftRef to rightRef else rightRef to leftRef val staticValue = static.eval() return toBalance.balance(when(operation) { "*" -> value / staticValue "/" -> if (leftRef === toBalance) staticValue * value else staticValue / value "+" -> value - staticValue else -> if ((leftRef === toBalance)) staticValue + value else staticValue - value }) } } fun main() { val operationRegexp = "^(\\w+) ([+/\\-*]) (\\w+)$".toRegex() fun linkMonkeys(input: List<String>): RefMonkey { val monkeys = mutableMapOf<String, Num>() input.forEach { val (monkeyName, monkeyEval) = it.split(": ") val refMatch = operationRegexp.matchEntire(monkeyEval) if (refMatch == null) { monkeys[monkeyName] = ScalarMonkey(monkeyEval.toLong(), monkeyName == "humn") } else { val (first, operation, second) = refMatch.destructured monkeys[monkeyName] = RefMonkey(first to second, operation) } } val root = monkeys["root"]!! (root as RefMonkey).init(monkeys) return root } fun part1(input: List<String>): Long { val root = linkMonkeys(input) return root.eval() } fun part2(input: List<String>): Long { val root = linkMonkeys(input) if (root.leftRef.isHumn) return root.leftRef.balance(root.rightRef.eval()) return root.rightRef.balance(root.leftRef.eval()) } // test if implementation meets criteria from the description, like: val testInput = readInput("Day21_test") println(part1(testInput)) check(part1(testInput) == 152L) val part2 = part2(testInput) println(part2) check(part2 == 301L) val input = readInput("Day21") println(part1(input)) check(part1(input) == 309248622142100) println(part2(input)) }
0
Kotlin
0
0
0a9b360a5fb8052565728e03a665656d1e68c687
3,231
advent-of-code-2022
Apache License 2.0
src/Lesson5PrefixSums/MinAvgTwoSlice.kt
slobodanantonijevic
557,942,075
false
{"Kotlin": 50634}
/** * 100/100 * @param A * @return */ fun solution(A: IntArray): Int { val prefixSums = getPrefixSums(A) var minAvg = Float.MAX_VALUE var minPos = 0 for (i in A.indices) { if (i < A.size - 1) { val avg = (prefixSums[i + 2] - prefixSums[i]) / 2.0f //((i + 1) - i) + 1 = 2 if (avg < minAvg) { minAvg = avg minPos = i } } if (i < A.size - 2) { val avg = (prefixSums[i + 3] - prefixSums[i]) / 3.0f //((i + 2) - i) + 1 = 3 if (avg < minAvg) { minAvg = avg minPos = i } } } return minPos } fun getPrefixSums(A: IntArray): IntArray { val prefixSums = IntArray(A.size + 1) for (i in A.indices) { prefixSums[i + 1] = prefixSums[i] + A[i] } return prefixSums } // Logic from: https://codesays.com/2014/solution-to-min-avg-two-slice-by-codility/ // Helper solution: https://gist.github.com/arielm/b2b38a01185a816cf27fba2ae6467129 /** * A non-empty array A consisting of N integers is given. A pair of integers (P, Q), such that 0 ≤ P < Q < N, is called a slice of array A (notice that the slice contains at least two elements). The average of a slice (P, Q) is the sum of A[P] + A[P + 1] + ... + A[Q] divided by the length of the slice. To be precise, the average equals (A[P] + A[P + 1] + ... + A[Q]) / (Q − P + 1). * * For example, array A such that: * * A[0] = 4 * A[1] = 2 * A[2] = 2 * A[3] = 5 * A[4] = 1 * A[5] = 5 * A[6] = 8 * contains the following example slices: * * slice (1, 2), whose average is (2 + 2) / 2 = 2; * slice (3, 4), whose average is (5 + 1) / 2 = 3; * slice (1, 4), whose average is (2 + 2 + 5 + 1) / 4 = 2.5. * The goal is to find the starting position of a slice whose average is minimal. * * Write a function: * * class Solution { public int solution(int[] A); } * * that, given a non-empty array A consisting of N integers, returns the starting position of the slice with the minimal average. If there is more than one slice with a minimal average, you should return the smallest starting position of such a slice. * * For example, given array A such that: * * A[0] = 4 * A[1] = 2 * A[2] = 2 * A[3] = 5 * A[4] = 1 * A[5] = 5 * A[6] = 8 * the function should return 1, as explained above. * * Write an efficient algorithm for the following assumptions: * * N is an integer within the range [2..100,000]; * each element of array A is an integer within the range [−10,000..10,000]. */
0
Kotlin
0
0
155cf983b1f06550e99c8e13c5e6015a7e7ffb0f
2,624
Codility-Kotlin
Apache License 2.0
src/Day07.kt
jorander
571,715,475
false
{"Kotlin": 28471}
import java.util.* import kotlin.collections.ArrayList fun main() { val day = "Day07" data class Directory(val name: String, var size: Int = 0) fun parseDirectorySizes(input: List<String>): List<Directory> { fun String.toFileSize() = split(" ")[0].toInt() data class State(val path: Stack<Directory>, val total: MutableList<Directory>) { fun addFile(fileSize: Int) { path.peek().size += fileSize } fun moveInto(name: String) { path.push( Directory( if (path.isEmpty()) { name } else { "${path.peek().name.dropLastWhile { it == '/' }}/$name" } ) ) } fun moveUp() { val currentDir = path.pop() total.add(currentDir) if (path.isNotEmpty()) { path.peek().size += currentDir.size } } fun moveToRoot() { while (path.isNotEmpty()) { moveUp() } } } return input .filter { !it.startsWith("dir") } .filter { !it.startsWith("$ ls") } .fold(State(Stack(), ArrayList())) { state, s -> if (s == "$ cd ..") { state.apply { moveUp() } } else if (s.startsWith("$ cd ")) { state.apply { moveInto(s.removePrefix("$ cd ")) } } else { state.apply { addFile(s.toFileSize()) } } }.apply { moveToRoot() }.total } fun part1(input: List<String>): Int { return parseDirectorySizes(input) .filter { it.size <= 100000 } .sumOf(Directory::size) } fun part2(input: List<String>): Int { val directories = parseDirectorySizes(input) val usedSpace = directories.first { it.name == "/" }.size val freeSpace = 70000000 - usedSpace val spaceNeeded = 30000000 - freeSpace return directories .filter { it.size >= spaceNeeded } .minBy { it.size } .size } // test if implementation meets criteria from the description, like: val testInput = readInput("${day}_test") val input = readInput(day) check(part1(testInput) == 95437) val result1 = part1(input) println(result1) check(result1 == 1908462) check(part2(testInput) == 24933642) val result2 = part2(input) println(result2) check(result2 == 3979145) }
0
Kotlin
0
0
1681218293cce611b2c0467924e4c0207f47e00c
2,804
advent-of-code-2022
Apache License 2.0
src/day08/Day08.kt
gr4cza
572,863,297
false
{"Kotlin": 93944}
package day08 import readInput private fun Array<Array<Int>>.checkLeft(column: Int, row: Int): Boolean { val selectedColumns = (0 until column).map { this[row][it] } return selectedColumns.any { it >= this[row][column] }.not() } private fun Array<Array<Int>>.checkRight(column: Int, row: Int): Boolean { val selectedColumns = (column + 1 until this.first().size).map { this[row][it] } return selectedColumns.any { it >= this[row][column] }.not() } private fun Array<Array<Int>>.checkDown(column: Int, row: Int): Boolean { val selectedColumns = (0 until row).map { this[it][column] } return selectedColumns.any { it >= this[row][column] }.not() } private fun Array<Array<Int>>.checkUp(column: Int, row: Int): Boolean { val selectedColumns = (row + 1 until this.first().size).map { this[it][column] } return selectedColumns.any { it >= this[row][column] }.not() } private fun Array<Array<Int>>.countLeft(column: Int, row: Int): Int { val selectedColumns = (0 until column).map { this[row][it] } var isSmaller = true return selectedColumns.reversed().takeWhile { val r = isSmaller isSmaller = (it < this[row][column]) and isSmaller r }.count() } private fun Array<Array<Int>>.countRight(column: Int, row: Int): Int { val selectedColumns = (column + 1 until this.first().size).map { this[row][it] } var isSmaller = true return selectedColumns.takeWhile { val r = isSmaller isSmaller = (it < this[row][column]) and isSmaller r }.count() } private fun Array<Array<Int>>.countUp(column: Int, row: Int): Int { val selectedColumns = (0 until row).map { this[it][column] } var isSmaller = true return selectedColumns.reversed().takeWhile { val r = isSmaller isSmaller = (it < this[row][column]) and isSmaller r }.count() } private fun Array<Array<Int>>.countDown(column: Int, row: Int): Int { val selectedColumns = (row + 1 until this.first().size).map { this[it][column] } var isSmaller = true return selectedColumns.takeWhile { val r = isSmaller isSmaller = (it < this[row][column]) and isSmaller r }.count() } fun main() { fun readMap(input: List<String>) = input.map { row -> row.chunked(1).map { it.toInt() }.toTypedArray() }.toTypedArray() fun part1(input: List<String>): Int { val map = readMap(input) return map.mapIndexed { row, r -> r.mapIndexed { column, _ -> map.checkLeft(column, row) || map.checkUp(column, row) || map.checkRight(column, row) || map.checkDown(column, row) } }.flatten().count { it } } fun part2(input: List<String>): Int { val map = readMap(input) return map.mapIndexed { row, r -> r.mapIndexed { column, _ -> map.countLeft(column, row) * map.countUp(column, row) * map.countRight(column, row) * map.countDown(column, row) } }.flatten().max() } // test if implementation meets criteria from the description, like: val testInput = readInput("day08/Day08_test") println(part2(testInput)) check(part2(testInput) == 8) val input = readInput("day08/Day08") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
ceca4b99e562b4d8d3179c0a4b3856800fc6fe27
3,447
advent-of-code-kotlin-2022
Apache License 2.0
src/main/kotlin/com/chriswk/aoc/advent2021/Day19.kt
chriswk
317,863,220
false
{"Kotlin": 481061}
package com.chriswk.aoc.advent2021 import com.chriswk.aoc.AdventDay import com.chriswk.aoc.util.Point3D import com.chriswk.aoc.util.pairs import com.chriswk.aoc.util.report class Day19 : AdventDay(2021, 19) { companion object { @JvmStatic fun main(args: Array<String>) { val day = Day19() report { day.part1() } report { day.part2() } } } fun parse3dPoint(input: String): Point3D { return input.split(",").let { p -> Point3D(x = p[0].toInt(), y = p[1].toInt(), z = p[2].toInt()) } } data class Transform(val scanner: Point3D, val beacons: Set<Point3D>) data class Solution(val scanners: Set<Point3D>, val beacons: Set<Point3D>) fun solve(scanners: List<Set<Point3D>>): Solution { val base = scanners.first().toMutableSet() val foundScanners = mutableSetOf(Point3D(0, 0, 0)) val unmappedSectors = ArrayDeque<Set<Point3D>>().apply { addAll(scanners.drop(1)) } while(unmappedSectors.isNotEmpty()) { val thisSector = unmappedSectors.removeFirst() when(val transform = findIntersects(base, thisSector)) { null -> unmappedSectors.add(thisSector) else -> { base.addAll(transform.beacons) foundScanners.add(transform.scanner) } } } return Solution(foundScanners, base) } fun parseInput(input: String): List<Set<Point3D>> { return input.split("\n\n").map { single -> single.lines() .drop(1) .map { parse3dPoint(it) } .toSet() } } val inputScanners = parseInput(inputAsString) fun findIntersects(left: Set<Point3D>, right: Set<Point3D>): Transform? { return (0 until 6).firstNotNullOfOrNull { face -> (0 until 4).firstNotNullOfOrNull { rotation -> val rightOrientations = right.map { it.face(face).rotate(rotation) }.toSet() left.firstNotNullOfOrNull { s1 -> rightOrientations.firstNotNullOfOrNull { s2 -> val diff = s1 - s2 val moved = rightOrientations.map { it + diff }.toSet() if (moved.intersect(left).size >= 12) { Transform(diff, moved) } else { null } } } } } } fun part1(): Int { return solve(inputScanners).beacons.size } fun part2(): Int { return solve(inputScanners).scanners.pairs().maxOf { it.first manhattan it.second } } }
116
Kotlin
0
0
69fa3dfed62d5cb7d961fe16924066cb7f9f5985
2,821
adventofcode
MIT License
src/Day09.kt
ChAoSUnItY
572,814,842
false
{"Kotlin": 19036}
import kotlin.math.abs import kotlin.math.sign fun main() { data class Position(val x: Int = 0, val y: Int = 0) { fun offset(x: Int = 0, y: Int = 0): Position = copy(x = this.x + x, y = this.y + y) } data class Instruction(val direction: Char, val steps: Int) fun processData(data: List<String>): List<Instruction> = data.map { val (direction, step) = it.split(" ") Instruction(direction[0], step.toInt()) } fun moveHead(head: Position, direction: Char): Position = when (direction) { 'U' -> head.offset(y = 1) 'D' -> head.offset(y = -1) 'R' -> head.offset(x = 1) 'L' -> head.offset(x = -1) else -> head } fun followHead(head: Position, tail: Position): Position = when { head.x == tail.x && abs(head.y - tail.y) > 1 -> tail.offset(y = (head.y - tail.y).sign) head.y == tail.y && abs(head.x - tail.x) > 1 -> tail.offset(x = (head.x - tail.x).sign) abs(head.y - tail.y) + abs(head.x - tail.x) >= 3 -> tail.offset( x = (head.x - tail.x).sign, y = (head.y - tail.y).sign ) else -> tail } fun traverse(data: List<Instruction>, length: Int): Int { val traversedPositions = mutableSetOf<Position>() val rope = Array(length) { Position() } for ((direction, step) in data) { for (_i in 0 until step) { rope[0] = moveHead(rope[0], direction) for (i in 1 until rope.size) rope[i] = followHead(rope[i - 1], rope[i]) traversedPositions += rope.last() } } return traversedPositions.size } fun part1(data: List<Instruction>): Int = traverse(data, 2) fun part2(data: List<Instruction>): Int = traverse(data, 10) val input = readInput("Day09") val data = processData(input) println(part1(data)) println(part2(data)) }
0
Kotlin
0
3
4fae89104aba1428820821dbf050822750a736bb
1,994
advent-of-code-2022-kt
Apache License 2.0
src/Day05_SupplyStacks.kt
raipc
574,467,742
false
{"Kotlin": 9511}
fun main() { checkAndSolve("Day05", "CMZ") { solve(it.iterator(), MoveStrategy.ONE_BY_ONE) } checkAndSolve("Day05", "MCD") { solve(it.iterator(), MoveStrategy.ALL_AT_ONCE) } } private fun solve(lines: Iterator<String>, moveStrategy: MoveStrategy): String { val stacks = readInitialStacks(lines) for (line in lines) { moveStrategy.move(stacks, CommandParser.parse(line)) } return buildString { stacks.forEach { if (it.isNotEmpty()) this.append(it.last().toChar()) } } } enum class MoveStrategy { ONE_BY_ONE { override fun move(stacks: Array<ArrayDeque<Int>>, command: Command) { for (i in 1..command.count) { stacks[command.to - 1].addLast(stacks[command.from - 1].removeLast()) } } }, ALL_AT_ONCE { override fun move(stacks: Array<ArrayDeque<Int>>, command: Command) { if (command.count == 1) { stacks[command.to - 1].addLast(stacks[command.from - 1].removeLast()) } else { val removed = (1..command.count).map { stacks[command.from - 1].removeLast() } stacks[command.to - 1].addAll(removed.asReversed()) } } }; abstract fun move(stacks: Array<ArrayDeque<Int>>, command: Command) } private fun readInitialStacks(lines: Iterator<String>): Array<ArrayDeque<Int>> { var line = lines.next() val arrayCount = 9 val result = (1..arrayCount).map { ArrayDeque<Int>() }.toTypedArray() do { if (!line[0].isDigit()) { // last line, skip if (line.length < 35) line = line.padEnd(length = 35, padChar = ' ') for (i in 0 until arrayCount) { line[i * 4 + 1].let { if (it != ' ') result[i].addFirst(it.code) } } } line = lines.next() } while (line.isNotEmpty()) return result } object CommandParser { private const val pattern = "move X from Y to Z" private val indexOfCount = pattern.indexOf('X') private val indexOfFrom = pattern.indexOf('Y') private val indexOfTo = pattern.indexOf('Z') private val command = Command(0, 0, 0) fun parse(line: String): Command { val offset = line.length - pattern.length val crateCount = if (offset == 0) { line[indexOfCount].digitToInt() } else { line.substring(indexOfCount, indexOfCount + offset + 1).toInt() } val from = line[indexOfFrom + offset].digitToInt() val to = line[indexOfTo + offset].digitToInt() return command.apply { this.count = crateCount this.from = from this.to = to } } } data class Command(var count: Int, var from: Int, var to: Int)
0
Kotlin
0
0
9068c21dc0acb5e1009652b4a074432000540d71
2,745
adventofcode22
Apache License 2.0
puzzles/kotlin/src/bender2.kt
hitszjsy
337,974,982
true
{"Python": 88057, "Java": 79734, "Kotlin": 52113, "C++": 33407, "TypeScript": 20480, "JavaScript": 17133, "PHP": 15544, "Go": 15296, "Ruby": 12722, "Haskell": 12635, "C#": 2600, "Scala": 1555, "Perl": 1250, "Shell": 1220, "Clojure": 753, "C": 598, "Makefile": 58}
import java.util.Scanner import java.util.PriorityQueue const val EXIT = -1 const val START = 0 fun main(args : Array<String>) { val building = Building() building.readRooms() building.calcAllMaxDepths() println(building.maxMoney()) } class Room(val number: Int, val money: Int, door1: String, door2: String) : Comparable<Room> { val doors = ArrayList<Int>() var depth = -1 init { readDoor(door1) readDoor(door2) } fun readDoor(door: String) { if (door == "E") { doors.add(EXIT) } else { doors.add(door.toInt()) } } // reversed operator for max heap override fun compareTo(other: Room): Int { return other.depth - depth } } // graph representation of the building class Building { val rooms = ArrayList<Room>() fun readRooms() { val input = Scanner(System.`in`) val n = input.nextInt() if (input.hasNextLine()) { input.nextLine() } for (i in 0 until n) { val (number, money, door1, door2) = input.nextLine().split(" ") val room = Room(number.toInt(), money.toInt(), door1, door2) rooms.add(room) } } // Calculate the max depth of each room reachable from the start with DFS fun calcAllMaxDepths() { calcMaxDepth(rooms[START], -1) } fun calcMaxDepth(room: Room, parentDepth: Int) { room.depth = parentDepth + 1 for (door in room.doors) { if (door != EXIT) { val neighbor = rooms[door] if (neighbor.depth <= room.depth) { calcMaxDepth(neighbor, room.depth) } } } } // Find the path with the max total money (inspired by Dijkstra's algorithm) fun maxMoney(): Int { val unvisited = PriorityQueue<Room>() val money = ArrayList<Int>() for (number in 0 until rooms.size) { money.add(0) unvisited.add(rooms[number]) } // loop through each depth level of the graph in descending order while (!unvisited.isEmpty()) { // find max depth val maxRoom = unvisited.poll() val maxNumber = maxRoom.number // find the best path for each subproblem val nextNumber = nextDoor(maxNumber, money) money[maxNumber] = maxRoom.money if (nextNumber != EXIT) { money[maxNumber] += money[nextNumber] } if (maxNumber == START) { break } } return money[START] } fun nextDoor(maxNumber: Int, money: ArrayList<Int>): Int { val door1 = rooms[maxNumber].doors[0] val door2 = rooms[maxNumber].doors[1] return when { door1 == EXIT -> door2 door2 == EXIT -> door1 money[door1] > money[door2] -> door1 else -> door2 } } }
0
null
0
1
59d9856e66b1c4a3d660c60bc26a19c4dfeca6e2
2,654
codingame
MIT License
kotlin/src/main/kotlin/com/github/jntakpe/aoc2021/days/day12/Day12.kt
jntakpe
433,584,164
false
{"Kotlin": 64657, "Rust": 51491}
package com.github.jntakpe.aoc2021.days.day12 import com.github.jntakpe.aoc2021.days.day12.Day12.Cave.Companion.END import com.github.jntakpe.aoc2021.days.day12.Day12.Cave.Companion.START import com.github.jntakpe.aoc2021.shared.Day import com.github.jntakpe.aoc2021.shared.readInputLines object Day12 : Day { override val input = readInputLines(12).flatMap { l -> l.split('-').let { Path.from(Cave(it.first()), Cave(it.last())) } } override fun part1() = visit(START) { visited, _ -> big || this !in visited } override fun part2() = visit(START, emptyList(), true) { visited, wildcard -> this != START && wildcard || big || this !in visited } private fun visit( cave: Cave, visited: List<Cave> = emptyList(), wildcard: Boolean = true, notVisited: Cave.(List<Cave>, Boolean) -> Boolean, ): Int { val allVisited = visited + cave if (cave == END) return 1 return input .filter { p -> p.start == cave && p.end.notVisited(allVisited, wildcard) } .fold(0) { a, c -> a + visit(c.end, allVisited, if (c.end.notVisited(allVisited, false)) wildcard else false, notVisited) } } data class Cave(val name: String) { companion object { val START = Cave("start") val END = Cave("end") } val big = name.uppercase() == name } class Path(val start: Cave, val end: Cave) { companion object { fun from(start: Cave, end: Cave) = listOf(Path(start, end), Path(end, start)) } } }
0
Kotlin
1
5
230b957cd18e44719fd581c7e380b5bcd46ea615
1,566
aoc2021
MIT License
src/Day14.kt
RusticFlare
574,508,778
false
{"Kotlin": 78496}
import kotlin.math.sign fun main() { infix fun Int.towards(to: Int) = IntProgression.fromClosedRange( rangeStart = this, rangeEnd = to, step = (to - this).sign.takeUnless { it == 0 } ?: 1, ) fun getCave(input: List<String>) = input.flatMap { it.splitToSequence(" -> ", ",").map(String::toInt).chunked(size = 2).zipWithNext() } .flatMap { (a, b) -> (a[0] towards b[0]).flatMap { x -> (a[1] towards b[1]).map { y -> x to y } } } .toMutableSet() fun MutableSet<Pair<Int, Int>>.fallingSand(maxDepth: Int) = generateSequence(seed = 500 to 0) { (x, y) -> sequenceOf(x, x - 1, x + 1).map { it to (y + 1) }.filterNot { it in this }.firstOrNull() }.take(maxDepth).last() fun part1(input: List<String>): Int { val cave = getCave(input) val maxDepth = cave.maxOf { it.second } fun MutableSet<Pair<Int, Int>>.addSand() = fallingSand(maxDepth + 1) .takeUnless { (_, y) -> y == maxDepth } ?.let { add(it) } ?: false return generateSequence { cave.addSand() } .takeWhile { it } .count() } fun part2(input: List<String>): Int { val cave = getCave(input) val maxDepth = cave.maxOf { it.second } + 2 fun MutableSet<Pair<Int, Int>>.addSand() = add(fallingSand(maxDepth)) return generateSequence { cave.addSand() } .takeWhile { it } .count() } // test if implementation meets criteria from the description, like: val testInput = readLines("Day14_test") check(part1(testInput) == 24) check(part2(testInput) == 93) val input = readLines("Day14") with(part1(input)) { check(this == 698) println(this) } with(part2(input)) { check(this == 28594) println(this) } }
0
Kotlin
0
1
10df3955c4008261737f02a041fdd357756aa37f
1,855
advent-of-code-kotlin-2022
Apache License 2.0
src/Day05.kt
stcastle
573,145,217
false
{"Kotlin": 24899}
import java.util.Stack data class Move(val numMoves: Int, val from: Int, val to: Int) data class Crates(val stacks: Map<Int, Stack<Char>>, val moves: List<Move>) fun parseInput(input: List<String>): Crates { val stacks: MutableMap<Int, Stack<Char>> = mutableMapOf() val moves: MutableList<Move> = mutableListOf() var initialStacksAreBuilt = false input.forEach { line -> if (line.startsWith('1')) { initialStacksAreBuilt = true } if (!initialStacksAreBuilt) { line.forEachIndexed { index, char -> if (char in 'A'..'Z') { val stackNumber = index / 4 + 1 // "zero-indexed" stack is ignored. if (!stacks.containsKey(stackNumber)) { stacks[stackNumber] = Stack<Char>() } stacks[stackNumber]!!.add(0, char) // Add it to the bottom ;). } } } if (line.startsWith("move")) { // stacks are built so we may be creating moves val elems = line.split(" ") moves.add(Move(numMoves = elems[1].toInt(), from = elems[3].toInt(), to = elems[5].toInt())) } } return Crates(stacks, moves) } fun main() { fun part1(input: List<String>): String { val crates = parseInput(input) for (move in crates.moves) { repeat(move.numMoves) { crates.stacks[move.to]!!.push(crates.stacks[move.from]!!.pop()) } } var s = "" crates.stacks.toSortedMap().forEach { s += it.value.peek() } return s } fun part2(input: List<String>): String { val crates = parseInput(input) val intermediateStack = Stack<Char>() // use an intermediate stack. We could also add each to the same position. for (move in crates.moves) { // either add each crate to an intermediate stack or add each new one to the same index. repeat(move.numMoves) { intermediateStack.push(crates.stacks[move.from]!!.pop()) } while (!intermediateStack.empty()) { crates.stacks[move.to]!!.push(intermediateStack.pop()) } } var s = "" crates.stacks.toSortedMap().forEach { s += it.value.peek() } return s } val day = "05" val testInput = readInput("Day${day}_test") println("Part 1 test = ${part1(testInput)}") val input = readInput("Day${day}") println("part1 = ${part1(input)}") println("Part 2 test = ${part2(testInput)}") println("part2 = ${part2(input)}") }
0
Kotlin
0
0
746809a72ea9262c6347f7bc8942924f179438d5
2,345
aoc2022
Apache License 2.0
src/P4LargersPalindromOf3Digits.kt
rhavran
250,959,542
false
null
fun main(args: Array<String>) { println("Res: " + largestLargestPalindromeProduct()) } /** * A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99. * Find the largest palindrome made from the product of two 3-digit numbers. */ private fun largestLargestPalindromeProduct(): Int { val largest = 999 val smallest = 100 // largest number * largest number could be the first largest palindrome result val palindrome = largest * largest for (x in palindrome downTo 1) { for (b in largest downTo smallest step 1) { val a = x / b; if (x % b == 0 && a <= largest && a >= smallest && isPalindrome(x.toString())) { return x } } } return 0 } fun isPalindrome(palindrome: String): Boolean { var isPalindrome = true for (ch in 0 until (palindrome.length / 2) step 1) { isPalindrome = isPalindrome && palindrome[ch] == palindrome[palindrome.length - 1 - ch] } return isPalindrome; }
0
Kotlin
0
0
11156745ef0512ab8aee625ac98cb6b7d74c7e92
1,081
ProjectEuler
MIT License
src/Day04.kt
imavroukakis
572,438,536
false
{"Kotlin": 12355}
fun main() { val regex = "(\\d+)-(\\d+),(\\d+)-(\\d+)".toRegex() operator fun MatchResult?.component1() = this?.destructured?.let { (start, end, _, _) -> start.toInt()..end.toInt() } ?: IntRange.EMPTY operator fun MatchResult?.component2() = this?.destructured?.let { (_, _, start, end) -> start.toInt()..end.toInt() } ?: IntRange.EMPTY fun part1(input: List<String>): Int { val solution: (String) -> Int = { //IDE suggestion is bad due to https://youtrack.jetbrains.com/issue/KT-46360 val (elfOneRange, elfTwoRange) = regex.matchEntire(it) val union = elfOneRange.union(elfTwoRange).size if (elfOneRange.count() == union || elfTwoRange.count() == union) 1 else 0 } return input.sumOf(solution) } fun part2(input: List<String>): Int { val solution: (String) -> Int = { //IDE suggestion is bad due to https://youtrack.jetbrains.com/issue/KT-46360 val (elfOneRange, elfTwoRange) = regex.matchEntire(it) if (elfOneRange.intersect(elfTwoRange).isNotEmpty()) 1 else 0 } return input.sumOf(solution) } val testInput = readInput("Day04_test") check(part1(testInput) == 2) println(part1(readInput("Day04"))) check(part2(testInput) == 4) println(part2(readInput("Day04"))) }
0
Kotlin
0
0
bb823d49058aa175d1e0e136187b24ef0032edcb
1,405
advent-of-code-kotlin
Apache License 2.0
src/main/kotlin/aoc2016/day01_no_time_for_taxi/NoTimeForTaxi.kt
barneyb
425,532,798
false
{"Kotlin": 238776, "Shell": 3825, "Java": 567}
package aoc2016.day01_no_time_for_taxi import geom2d.Dir import geom2d.Point fun main() { util.solve(288, ::partOne) util.solve(111, ::partTwo) } data class Heading(val location: Point, val dir: Dir) { companion object { val ORIGIN = Heading(Point.ORIGIN, Dir.NORTH) } fun turn(turn: Turn) = copy(dir = dir.turn(turn)) fun step(steps: Long = 1) = copy(location = location.step(dir, steps)) fun manhattanDistance() = location.manhattanDistance() } fun Char.toTurn() = when (this) { 'S' -> Turn.STRAIGHT 'R' -> Turn.RIGHT 'A' -> Turn.AROUND 'L' -> Turn.LEFT else -> throw IllegalArgumentException("Unknown '$this' turn") } enum class Turn { STRAIGHT, RIGHT, AROUND, LEFT } fun Dir.turn(turn: Turn) = when (turn) { Turn.STRAIGHT -> this Turn.RIGHT -> when (this) { Dir.NORTH -> Dir.EAST Dir.EAST -> Dir.SOUTH Dir.SOUTH -> Dir.WEST Dir.WEST -> Dir.NORTH } Turn.AROUND -> when (this) { Dir.NORTH -> Dir.SOUTH Dir.EAST -> Dir.WEST Dir.SOUTH -> Dir.NORTH Dir.WEST -> Dir.EAST } Turn.LEFT -> when (this) { Dir.NORTH -> Dir.WEST Dir.EAST -> Dir.NORTH Dir.SOUTH -> Dir.EAST Dir.WEST -> Dir.SOUTH } } fun partOne(input: String) = input.toPairs() .fold(Heading.ORIGIN) { curr, (t, n) -> curr.turn(t).step(n) } .location .manhattanDistance() private fun String.toPairs() = split(",") .map { it.trim() } .map { Pair( it[0].toTurn(), it.substring(1, it.length).toLong() ) } fun partTwo(input: String): Long { val origin = Heading.ORIGIN val visited = hashSetOf(origin.location) input.toPairs() .fold(origin) { curr, (t, n) -> var next = curr.turn(t) for (i in 0 until n) { next = next.step() if (!visited.add(next.location)) { return next.manhattanDistance() } } next } throw IllegalStateException("huh?") }
0
Kotlin
0
0
a8d52412772750c5e7d2e2e018f3a82354e8b1c3
2,140
aoc-2021
MIT License
src/main/kotlin/Day13.kt
SimonMarquis
434,880,335
false
{"Kotlin": 38178}
class Day13(raw: String) { private val input = raw.split("\n\n").let { (a, b) -> val points = a.lines().map { it.split(",").map { coords -> coords.toInt() }.let { (x, y) -> Point(x, y) } }.toSet() val folds = b.lines().map { it.split(" ", "=").takeLast(2).let { (d, c) -> Fold(d.toDir(), c.toInt()) } } points to folds } fun part1(): Int = input.let { (points, folds) -> points.fold(folds.first()).size } fun part2(): String = input.let { (points, folds) -> folds.fold(points) { pts, fold -> pts.fold(fold) } }.stringify() data class Point(val x: Int, val y: Int) data class Fold(val dir: Dir, val coordinate: Int) enum class Dir { X, Y } private fun String.toDir() = when (this) { "x" -> Dir.X "y" -> Dir.Y else -> TODO() } private fun Set<Point>.fold(fold: Fold) = map { when (fold.dir) { Dir.X -> if (it.x < fold.coordinate) it else it.copy(x = it.x - (it.x - fold.coordinate) * 2) Dir.Y -> if (it.y < fold.coordinate) it else it.copy(y = it.y - (it.y - fold.coordinate) * 2) } }.toSet() private fun Set<Point>.stringify(): String { val width = this@stringify.maxByOrNull { it.x }!!.x val height = this@stringify.maxByOrNull { it.y }!!.y return (0..height).joinToString(separator = "\n") { y -> (0..width).joinToString(separator = "") { x -> if (Point(x, y) in this@stringify) "█" else " " } } } }
0
Kotlin
0
0
8fd1d7aa27f92ba352e057721af8bbb58b8a40ea
1,605
advent-of-code-2021
Apache License 2.0
aoc-2020/src/commonMain/kotlin/fr/outadoc/aoc/twentytwenty/Day21.kt
outadoc
317,517,472
false
{"Kotlin": 183714}
package fr.outadoc.aoc.twentytwenty import fr.outadoc.aoc.scaffold.Day import fr.outadoc.aoc.scaffold.readDayInput class Day21 : Day<String> { private data class Food(val ingredients: List<String>, val allergens: List<String>) private val foodRegex = Regex("^([a-z ]+) \\(contains ([a-z, ]+)\\)$") private val foodz: List<Food> = readDayInput() .lines() .map { line -> foodRegex.find(line)!!.groupValues.let { groups -> Food( ingredients = groups[1].split(' '), allergens = groups[2].split(", ") ) } } private val initialState = foodz.fold(State()) { state, food -> state.copy( possibleAllergensPerIngredient = state.possibleAllergensPerIngredient + food.ingredients.map { ingredient -> val possibleExistingAllergens = state.possibleAllergensPerIngredient[ingredient] ?: emptySet() val possibleNewAllergens = food.allergens.filterNot { allergen -> // Remove all allergens that are already present in a food without this ingredient foodz.any { food -> allergen in food.allergens && ingredient !in food.ingredients } } ingredient to (possibleExistingAllergens + possibleNewAllergens) } ) } private data class State( val possibleAllergensPerIngredient: Map<String, Set<String>> = emptyMap() ) override fun step1(): String { return initialState.possibleAllergensPerIngredient .filterValues { allergens -> allergens.isEmpty() } .map { (ingredient, _) -> ingredient } .sumOf { ingredient -> foodz.count { food -> ingredient in food.ingredients } } .toString() } private tailrec fun State.findFinalState(): State { if (possibleAllergensPerIngredient.none { (_, allergens) -> allergens.size > 1 }) return this val listOfAlreadyKnownAllergens: Set<String> = possibleAllergensPerIngredient .filterValues { allergens -> allergens.size == 1 } .values .map { it.first() } .toSet() val next = copy( possibleAllergensPerIngredient = possibleAllergensPerIngredient .mapValues { (_, allergens) -> if (allergens.size > 1) { allergens - listOfAlreadyKnownAllergens } else allergens } ) return next.findFinalState() } override fun step2(): String { return initialState .findFinalState() .possibleAllergensPerIngredient .mapNotNull { (ingredient, allergens) -> allergens.firstOrNull()?.let { ingredient to it } } .sortedBy { (_, allergen) -> allergen } .joinToString(separator = ",") { (ingredient, _) -> ingredient } } override val expectedStep1: String = "2573" override val expectedStep2: String = "bjpkhx,nsnqf,snhph,zmfqpn,qrbnjtj,dbhfd,thn,sthnsg" }
0
Kotlin
0
0
54410a19b36056a976d48dc3392a4f099def5544
3,309
adventofcode
Apache License 2.0
src/main/kotlin/solutions/Day15BeaconExclusionZone.kt
aormsby
571,002,889
false
{"Kotlin": 80084}
package solutions import models.Coord2d import utils.Input import utils.Solution import java.text.NumberFormat import kotlin.math.abs // run only this day fun main() { Day15BeaconExclusionZone() } class Day15BeaconExclusionZone : Solution() { init { begin("Day 15 - Beacon Exclusion Zone") val input = Input.parseLines(filename = "/d15_sensors.txt") .map { line -> val match = """x=(.+), y=(.+):.*x=(.+), y=(.+)""".toRegex() .find(line)!!.groupValues.drop(1) // reversed coordinates to match list index order val sensor = Coord2d(match[1].toInt(), match[0].toInt()) val beacon = Coord2d(match[3].toInt(), match[2].toInt()) Pair(sensor, beacon) } val beaconList = input.map { it.second } val targetRow = 2_000_000 val beaconTargetY = beaconList.filter { it.x == targetRow }.map { it.y }.toSet() val targetRowScanSet = scanRow(targetRow, input).first().toSet() val sol1 = targetRowScanSet.subtract(beaconTargetY).size output(String.format("Empty Points at Row ${NumberFormat.getNumberInstance().format(targetRow)}"), sol1) val sol2 = findDistressBeaconFrequency(input) output("Distress Beacon Frequency", sol2) } // returns a merged IntRange of all spaces in this row scanned by all beacons private fun scanRow(curRow: Int, input: List<Pair<Coord2d, Coord2d>>): List<IntRange> { val scanIntervals = mutableListOf<IntRange>() for ((sensor, beacon) in input) { val mhDist = sensor.manhattanDistanceTo(beacon) // if the current row being checked was inside the scan val rowDist = abs(curRow - sensor.x) if (rowDist <= mhDist) { val spread = abs(mhDist - rowDist) scanIntervals.mergeUpdate((sensor.y - spread)..(sensor.y + spread)) } } return scanIntervals } // runs scanRow() on all rows until the beacon is founr private fun findDistressBeaconFrequency(input: List<Pair<Coord2d, Coord2d>>): Long { val fourMil = 4_000_000 (0..fourMil).forEach { y -> val result = scanRow(y, input) // if the row scan has a gap, that gap is the missing beacon! if (result.size > 1) { val x = result.first().last + 1 return (x.toLong() * fourMil) + y } } return -1 } // tries to merge the latest IntRange with the range(s) already scanned in a row, adds range if no merge private fun MutableList<IntRange>.mergeUpdate(inRange: IntRange) { // find the first range in the list where the incoming interval may overlap an existing one val lowIndex = binarySearch { stored -> stored.last.compareTo(inRange.first - 1) }.let { it shr 31 xor it } // find the last range in the list where the incoming interval may overlap an existing one val highIndex = this.binarySearch(fromIndex = lowIndex) { stored -> stored.first.compareTo(inRange.last + 1) }.let { it shr 31 xor it } // note - the 'it xor it' is a neat bit shift trick to keep a positive index or convert a negative one to a matching index, // great combo with the binary search for merging these intervals // if start and end overlaps are different indices, we can merge some intervals val mergedRange = if (lowIndex < highIndex) minOf(this[lowIndex].first, inRange.first)..maxOf(this[highIndex - 1].last, inRange.last) else inRange // clear any overlapped ranges subList(lowIndex, highIndex).clear() // add merged range or inRange add(index = lowIndex, element = mergedRange) } }
0
Kotlin
0
0
1bef4812a65396c5768f12c442d73160c9cfa189
3,896
advent-of-code-2022
MIT License
src/Day03.kt
DeltaSonic62
572,718,847
false
{"Kotlin": 8676}
fun getPriority(ch: Char): Int { return if (ch.code in 97..122) ch.code - 96 else ch.code - 38 } fun main() { fun part1(input: List<String>): Int { var total = 0 for (line in input) { val sec1 = line.substring(0 until line.length / 2) val sec2 = line.substringAfter(sec1) var matches = mutableListOf<Char>() for (ch in sec1) { if (!matches.contains(ch) && sec2.contains(ch)) matches.add(ch) } for (match in matches) total += getPriority(match) } return total } fun part2(input: List<String>): Int { var total = 0 var groups = mutableListOf<List<String>>() for (i in 0 until input.size step 3) groups.add(input.subList(i, i + 3)) for (group in groups) { var matches = mutableListOf<Char>() for (item in group[0]) { if (!matches.contains(item) && group[1].contains(item) && group[2].contains(item)) { matches.add(item) } } for (match in matches) total += getPriority(match) } return total } // test if implementation meets criteria from the description, like: val testInput = readInput("Day03_test") check(part1(testInput) == 157) check(part2(testInput) == 70) val input = readInput("Day03") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
7cdf94ad807933ab4769ce4995a43ed562edac83
1,464
aoc-2022-kt
Apache License 2.0
src/main/kotlin/com/ginsberg/advent2022/Day13.kt
tginsberg
568,158,721
false
{"Kotlin": 113322}
/* * Copyright (c) 2022 by <NAME> */ /** * Advent of Code 2022, Day 13 - Distress Signal * Problem Description: http://adventofcode.com/2022/day/13 * Blog Post/Commentary: https://todd.ginsberg.com/post/advent-of-code/2022/day13/ */ package com.ginsberg.advent2022 class Day13(input: List<String>) { private val packets = input.filter { it.isNotBlank() }.map { Packet.of(it) } fun solvePart1(): Int = packets.chunked(2).mapIndexed { index, pair -> if (pair.first() < pair.last()) index + 1 else 0 }.sum() fun solvePart2(): Int { val dividerPacket1 = Packet.of("[[2]]") val dividerPacket2 = Packet.of("[[6]]") val ordered = (packets + dividerPacket1 + dividerPacket2).sorted() return (ordered.indexOf(dividerPacket1) + 1) * (ordered.indexOf(dividerPacket2) + 1) } private sealed class Packet : Comparable<Packet> { companion object { fun of(input: String): Packet = of( input.split("""((?<=[\[\],])|(?=[\[\],]))""".toRegex()) .filter { it.isNotBlank() } .filter { it != "," } .iterator() ) private fun of(input: Iterator<String>): Packet { val packets = mutableListOf<Packet>() while (input.hasNext()) { when (val symbol = input.next()) { "]" -> return ListPacket(packets) "[" -> packets.add(of(input)) else -> packets.add(IntPacket(symbol.toInt())) } } return ListPacket(packets) } } } private class IntPacket(val amount: Int) : Packet() { fun asList(): Packet = ListPacket(listOf(this)) override fun compareTo(other: Packet): Int = when (other) { is IntPacket -> amount.compareTo(other.amount) is ListPacket -> asList().compareTo(other) } } private class ListPacket(val subPackets: List<Packet>) : Packet() { override fun compareTo(other: Packet): Int = when (other) { is IntPacket -> compareTo(other.asList()) is ListPacket -> subPackets.zip(other.subPackets) .map { it.first.compareTo(it.second) } .firstOrNull { it != 0 } ?: subPackets.size.compareTo(other.subPackets.size) } } }
0
Kotlin
2
26
2cd87bdb95b431e2c358ffaac65b472ab756515e
2,535
advent-2022-kotlin
Apache License 2.0
src/main/kotlin/Day13.kt
ueneid
575,213,613
false
null
class Day13(inputs: List<String>) { private sealed class Packet : Comparable<Packet> { companion object { fun of(input: String): Packet { var listInput = mutableListOf<String>() var tempNumber = "" for (c in input) { if (c.isDigit()) { tempNumber += c continue } if (tempNumber.isNotEmpty()) { listInput.add(tempNumber) tempNumber = "" } if (c == ',') { continue } listInput.add(c.toString()) } return of(listInput.iterator()) } private fun of(input: Iterator<String>): Packet { val packets = mutableListOf<Packet>() while (input.hasNext()) { when (val symbol = input.next()) { "]" -> return ListPacket(packets) "[" -> packets.add(of(input)) else -> packets.add(IntPacket(symbol.toInt())) } } return ListPacket(packets) } } } private class IntPacket(val amount: Int) : Packet() { fun asList(): Packet = ListPacket(listOf(this)) override fun compareTo(other: Packet): Int = when (other) { is IntPacket -> amount.compareTo(other.amount) is ListPacket -> asList().compareTo(other) } } private class ListPacket(val subPackets: List<Packet>) : Packet() { override fun compareTo(other: Packet): Int = when (other) { is IntPacket -> compareTo(other.asList()) is ListPacket -> subPackets.zip(other.subPackets) .map { it.first.compareTo(it.second) } .firstOrNull { it != 0 } ?: subPackets.size.compareTo(other.subPackets.size) } } private val packets = inputs.filter { it.isNotBlank() }.map { Packet.of(it) } fun solve1(): Int { return packets.chunked(2).mapIndexed { index, pair -> if (pair.first() < pair.last()) index + 1 else 0 }.sum() } fun solve2(): Int { val divider1 = Packet.of("[[2]]") val divider2 = Packet.of("[[6]]") var key = 1 (packets + divider1 + divider2).sorted().forEachIndexed { index, packet -> if (packet == divider1 || packet == divider2) { key *= index + 1 } } return key } } fun main() { val obj = Day13(Resource.resourceAsListOfString("day13/input.txt")) println(obj.solve1()) println(obj.solve2()) }
0
Kotlin
0
0
743c0a7adadf2d4cae13a0e873a7df16ddd1577c
2,855
adventcode2022
MIT License
src/day08/Day08Part1.kt
armanaaquib
572,849,507
false
{"Kotlin": 34114}
package day08 import readInput fun main() { fun parseInput(input: List<String>) = input.map { row -> row.split("").filter { it.isNotEmpty() }.map { it.toInt() } } fun lefViewCount(data: List<List<Int>>, visited: MutableList<MutableList<Boolean>>) { for (r in data.indices) { var height = -1 for (c in data[r].indices) { if(data[r][c] > height) { height = data[r][c] visited[r][c] = true } } } } fun topViewCount(data: List<List<Int>>, visited: MutableList<MutableList<Boolean>>) { for (c in data[0].indices) { var height = -1 for (r in data.indices) { if(data[r][c] > height) { height = data[r][c] visited[r][c] = true } } } } fun rightViewCount(data: List<List<Int>>, visited: MutableList<MutableList<Boolean>>) { for (r in data.indices) { var height = -1 for (c in data[r].lastIndex downTo 0) { if(data[r][c] > height) { height = data[r][c] visited[r][c] = true } } } } fun bottomViewCount(data: List<List<Int>>, visited: MutableList<MutableList<Boolean>>) { for (c in data[data.lastIndex].indices) { var height = -1 for (r in data.lastIndex downTo 0) { if(data[r][c] > height) { height = data[r][c] visited[r][c] = true } } } } fun part1(input: List<String>): Int { val data = parseInput(input) val visited = MutableList(data.size) { MutableList(data[0].size) { false } } lefViewCount(data, visited) topViewCount(data, visited) rightViewCount(data, visited) bottomViewCount(data, visited) println(visited) return visited.sumOf { r -> r.count { it } } } // fun part2(input: List<String>): Int { // val data = parseInput(input) // // return score // } // test if implementation meets criteria from the description, like: check(part1(readInput("Day08_test")) == 21) println(part1(readInput("Day08"))) // check(part2(readInput("Day02_test")) == 12) // println(part2(readInput("Day02"))) }
0
Kotlin
0
0
47c41ceddacb17e28bdbb9449bfde5881fa851b7
2,444
aoc-2022
Apache License 2.0
src/Day11_part1.kt
armandmgt
573,595,523
false
{"Kotlin": 47774}
fun main() { data class Monkey( val id: Int, var inspections: Int = 0, val items: MutableList<Int>, val operation: (Int) -> Int, val destination: (Int) -> Int ) { override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as Monkey if (id != other.id) return false return true } override fun hashCode(): Int { return id } } val multiplication = Regex("new = old \\* (\\d+)") val square = Regex("new = old \\* old") val addition = Regex("new = old \\+ (\\d+)") fun makeOperation(operation: String): (Int) -> Int { when { multiplication.matches(operation) -> { val (factor) = multiplication.find(operation)!!.destructured return fun(old: Int): Int { return old * factor.toInt() } } square.matches(operation) -> return fun(old: Int): Int { return old * old } addition.matches(operation) -> { val (operand) = addition.find(operation)!!.destructured return fun(old: Int): Int { return old + operand.toInt() } } } throw IllegalArgumentException("operation non matched: $operation") } fun makeDestination(divisor: Int, destTrueId: Int, destFalseId: Int): (Int) -> Int { return fun(worriness: Int): Int = if (worriness % divisor == 0) destTrueId else destFalseId } fun parseMonkeyList(input: List<String>): List<Monkey> { val monkeys = mutableListOf<Monkey>() input.chunked(7).forEach { monkeyDef -> val (id) = Regex("Monkey (\\d+):").find(monkeyDef[0])!!.destructured val (items) = Regex("Starting items: (.*)").find(monkeyDef[1])!!.destructured val (operation) = Regex("Operation: (.*)").find(monkeyDef[2])!!.destructured val (divisor) = Regex("Test: divisible by (.*)").find(monkeyDef[3])!!.destructured val (destTrue) = Regex("If true: throw to monkey (.*)").find(monkeyDef[4])!!.destructured val (destFalse) = Regex("If false: throw to monkey (.*)").find(monkeyDef[5])!!.destructured monkeys.add( Monkey( id.toInt(), items = items.split(", ").map { it.toInt() }.toMutableList(), operation = makeOperation(operation), destination = makeDestination(divisor.toInt(), destTrue.toInt(), destFalse.toInt()) ) ) } return monkeys } fun part1(input: List<String>): Int { val monkeys = parseMonkeyList(input) repeat(20) { monkeys.forEach { monkey -> monkey.items.forEach { item -> val newVal = monkey.operation(item) / 3 monkey.inspections = Math.addExact(monkey.inspections, 1) val destMonkey = monkey.destination(newVal) monkeys[destMonkey].items.add(newVal) } monkey.items.clear() } } return top(2, monkeys.map { it.inspections }).fold(1) { acc, i -> acc * i } } // test if implementation meets criteria from the description, like: val testInput = readInput("resources/Day11_test") check(part1(testInput) == 10605) val input = readInput("resources/Day11") println(part1(input)) }
0
Kotlin
0
1
0d63a5974dd65a88e99a70e04243512a8f286145
3,629
advent_of_code_2022
Apache License 2.0
src/Day05.kt
zsmb13
572,719,881
false
{"Kotlin": 32865}
fun main() { data class Move(val count: Int, val from: Int, val to: Int) fun parse(testInput: List<String>): Pair<List<MutableList<Char>>, List<Move>> { val blankIndex = testInput.indexOfFirst(String::isBlank) val crateCount = testInput[blankIndex - 1] .last(Char::isDigit) .digitToInt() val crates = List(size = crateCount) { mutableListOf<Char>() } testInput.subList(0, blankIndex - 1).asReversed().forEach { line -> line.chunked(4).forEachIndexed { index, content -> content[1].takeIf(Char::isLetter)?.let(crates[index]::plusAssign) } } val moves = testInput.subList(blankIndex + 1, testInput.size) .map { val split = it.split(" ") Move(split[1].toInt(), split[3].toInt() - 1, split[5].toInt() - 1) } return Pair(crates, moves) } fun topsOf(crates: List<MutableList<Char>>) = crates.map(List<Char>::last).joinToString(separator = "") fun part1(testInput: List<String>): String { val (crates, moves) = parse(testInput) moves.forEach { move -> repeat(move.count) { crates[move.to] += crates[move.from].removeLast() } } return topsOf(crates) } fun <T> MutableList<T>.removeLast(count: Int): List<T> { val removeIndex = this.size - count return List(size = count) { this.removeAt(removeIndex) } } fun part2(testInput: List<String>): String { val (crates, moves) = parse(testInput) moves.forEach { move -> crates[move.to] += crates[move.from].removeLast(move.count) } return topsOf(crates) } 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
6
32f79b3998d4dfeb4d5ea59f1f7f40f7bf0c1f35
1,968
advent-of-code-2022
Apache License 2.0
src/main/kotlin/com/ikueb/advent18/Day11.kt
h-j-k
159,901,179
false
null
package com.ikueb.advent18 import com.ikueb.advent18.model.Point object Day11 { private val range = (1..300) fun getTopSquareTopCorner(input: Int) = process(input) { point -> if (point.x < 3 || point.y < 3) emptySequence() else sequenceOf(3) }.first fun getTopVariableSquareTopCornerSize(input: Int) = process(input).let { (corner, size, _) -> String.format("%d,%d,%d", corner.x, corner.y, size) } private fun process(input: Int, toSequence: (Point) -> Sequence<Int> = Point::squareSizesTo) = generateGrid(input).entries .fold(mutableMapOf<Point, Int>()) { grid, entry -> grid.also { it[entry.key] = entry.value.cumulativeSum(it) } }.let { it.keys.asSequence().flatMap { point -> toSequence(point).map { size -> Triple(point.nw(size - 1), size, squarePowerTo(it, point, size)) } }.maxBy { (_, _, power) -> power }!! } private fun generateGrid(serial: Int) = range .flatMap { x -> range.map { y -> Point(x, y) } } .associateWith { Cell(it.x, it.y, serial) } private fun squarePowerTo(grid: Map<Point, Int>, pointTo: Point, size: Int) = setOf(pointTo, pointTo.nw(size)).sumBy { grid[it] ?: 0 } - setOf(pointTo.n(size), pointTo.w(size)).sumBy { grid[it] ?: 0 } } private data class Cell(val point: Point, val value: Int) { constructor(x: Int, y: Int, serial: Int) : this(Point(x, y), (x + 10).let { ((((it * y) + serial) * it / 100) % 10) - 5 }) fun cumulativeSum(grid: Map<Point, Int>) = value + setOf(point.n(), point.w()).sumBy { grid[it] ?: 0 } - (grid[point.nw()] ?: 0) } private fun Point.squareSizesTo() = (1..minOf(x, y)).asSequence()
0
Kotlin
0
0
f1d5c58777968e37e81e61a8ed972dc24b30ac76
2,131
advent18
Apache License 2.0
src/main/kotlin/day02/cubes.kt
cdome
726,684,118
false
{"Kotlin": 17211}
package day02 import java.io.File data class Game(val number: Int, val hands: List<Hand>) { fun maxRed() = hands.maxOfOrNull { it.red } ?: 0 fun maxBlue() = hands.maxOfOrNull { it.blue } ?: 0 fun maxGreen() = hands.maxOfOrNull { it.green } ?: 0 } data class Hand(val red: Int, val blue: Int, val green: Int) fun main() { val games = gamesFromFile("src/main/resources/day02-cubes") println("Playable games: " + games.filter { isPlayable(it, 12, 14, 13) }.sumOf { it.number }) println("Total power: " + games.sumOf { game -> game.hands.maxOf { it.red } * game.hands.maxOf { it.blue } * game.hands.maxOf { it.green } }) } fun isPlayable(game: Game, reds: Int, blues: Int, greens: Int) = reds >= game.maxRed() && blues >= game.maxBlue() && greens >= game.maxGreen() private fun gamesFromFile(fileName: String) = File(fileName).readLines().map { line -> val (number, hands) = line.split(":").map { it.trim() } Game( number = number.split(" ")[1].toInt(), hands = hands.split(";").map { it.trim() }.map { hand -> hand.split(", ").associate { cube -> cube.split(" ").run { this[1] to this[0].toInt() } }.let { cubesMap -> Hand(cubesMap["red"] ?: 0, cubesMap["blue"] ?: 0, cubesMap["green"] ?: 0) } } ) }
0
Kotlin
0
0
459a6541af5839ce4437dba20019b7d75b626ecd
1,307
aoc23
The Unlicense
src/main/kotlin/ReactorReboot_22.kt
Flame239
433,046,232
false
{"Kotlin": 64209}
import RebootOperation.ON import kotlin.math.max import kotlin.math.min private val steps: List<RebootStep> by lazy { readFile("ReactorReboot").split("\n").map { val (operation, remaining) = it.split(" ") val (x, y, z) = remaining.split(",").map { parseRange(it) } RebootStep(RebootOperation.valueOf(operation.uppercase()), Cube(x, y, z)) } } fun stupidIntersection(): Int { val onPoints = mutableSetOf<V3>() steps.forEach { for (x in max(it.x.first, -50)..min(it.x.last, 50)) { for (y in max(it.y.first, -50)..min(it.y.last, 50)) { for (z in max(it.z.first, -50)..min(it.z.last, 50)) { if (it.operation == ON) { onPoints.add(V3(x, y, z)) } else { onPoints.remove(V3(x, y, z)) } } } } } return onPoints.size } private fun cleverIntersection(): Long { val xs = steps.flatMap { listOf(it.x.first, it.x.last + 1) }.sorted() val ys = steps.flatMap { listOf(it.y.first, it.y.last + 1) }.sorted() val zs = steps.flatMap { listOf(it.z.first, it.z.last + 1) }.sorted() val n = xs.size val compressedGrid = Array(n) { Array(n) { IntArray(n) } } steps.forEach { s -> for (x in xs.indexOf(s.x.first) until xs.indexOf(s.x.last + 1)) { for (y in ys.indexOf(s.y.first) until ys.indexOf(s.y.last + 1)) { for (z in zs.indexOf(s.z.first) until zs.indexOf(s.z.last + 1)) { compressedGrid[x][y][z] = if (s.operation == ON) 1 else 0 } } } } var totalOn = 0L for (x in 0 until n - 1) { for (y in 0 until n - 1) { for (z in 0 until n - 1) { totalOn += compressedGrid[x][y][z].toLong() * (xs[x + 1] - xs[x]) * (ys[y + 1] - ys[y]) * (zs[z + 1] - zs[z]) } } } return totalOn } fun main() { println(stupidIntersection()) println(cleverIntersection()) } private fun parseRange(s: String): IntRange { val (beg, end) = s.substring(2).split("..").map { it.toInt() } return IntRange(beg, end) } private open class Cube(val x: IntRange, val y: IntRange, val z: IntRange) { override fun toString(): String { return "(${x.first}..${x.last},${y.first}..${y.last},${z.first}..${z.last})" } } private data class RebootStep(val operation: RebootOperation, val cube: Cube) { val x: IntRange by cube::x val y: IntRange by cube::y val z: IntRange by cube::z } private enum class RebootOperation { ON, OFF }
0
Kotlin
0
0
ef4b05d39d70a204be2433d203e11c7ebed04cec
2,647
advent-of-code-2021
Apache License 2.0
src/day03/Day03.kt
martin3398
572,166,179
false
{"Kotlin": 76153}
package day03 import readInput typealias Day03InputType1 = List<Pair<Set<Char>, Set<Char>>> typealias Day03InputType2 = List<Set<Char>> fun main() { fun getCommonItem(fst: Set<Char>, snd: Set<Char>): Char = fst.intersect(snd).first() fun getCommonItem(fst: Set<Char>, snd: Set<Char>, trd: Set<Char>): Char = fst.intersect(snd).intersect(trd).first() fun getPriority(c: Char): Int = if (c.isLowerCase()) { c - 'a' + 1 } else { c - 'A' + 26 + 1 } fun part1(input: Day03InputType1): Int = input.sumOf { getPriority(getCommonItem(it.first, it.second)) } fun part2(input: Day03InputType2): Int { var total = 0 for (i in input.indices step 3) { total += getPriority(getCommonItem(input[i], input[i+1], input[i+2])) } return total } fun preprocess1(input: List<String>): Day03InputType1 = input.map { Pair(it.substring(0, it.length / 2).toSet(), it.substring(it.length / 2).toSet()) } fun preprocess2(input: List<String>): Day03InputType2 = input.map { it.toSet() } // test if implementation meets criteria from the description, like: val testInput = readInput(3, true) check(part1(preprocess1(testInput)) == 157) val input = readInput(3) println(part1(preprocess1(input))) check(part2(preprocess2(testInput)) == 70) println(part2(preprocess2(input))) }
0
Kotlin
0
0
4277dfc11212a997877329ac6df387c64be9529e
1,424
advent-of-code-2022
Apache License 2.0
app/src/main/kotlin/advent/of/code/twentytwenty/Day14.kt
obarcelonap
320,300,753
false
null
package advent.of.code.twentytwenty import java.lang.Long.parseLong import java.lang.Long.toBinaryString typealias Mask = String typealias Memory = Map<Long, Long> typealias MaskedMemory = Pair<Memory, Mask> fun main() { val input = getResourceAsText("/day14-input") val part1Sum = memorySum(input, ::valueBitMaskDecoder) println("Part1: final memory sum is $part1Sum") val part2Sum = memorySum(input, ::memoryAddressDecoder) println("Part2: final memory sum is $part2Sum") } fun memorySum(input: String, decoder: (mem: MaskedMemory, address: Long, value: Long) -> MaskedMemory): Long { val initialMask = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" val initialMemory = emptyMap<Long, Long>() val (finalMemory) = input.lines() .map(fun(line: String): (mem: MaskedMemory) -> MaskedMemory { if (line.startsWith("mask")) { return { (mem) -> Pair(mem, parseMask(line)) } } return { mem -> val (address, value) = parseMemoryWrite(line) decoder(mem, address, value) } }) .fold(Pair(initialMemory, initialMask), { mem, instruction -> instruction(mem) }) return finalMemory.map { (_, value) -> value } .sum() } fun valueBitMaskDecoder(maskedMemory: MaskedMemory, address: Long, value: Long): MaskedMemory { val (mem, mask) = maskedMemory return Pair(mem + Pair(address, applyMask(value, mask)), mask) } fun memoryAddressDecoder(maskedMemory: MaskedMemory, address: Long, value: Long): MaskedMemory { val (mem, mask) = maskedMemory val maskedAddr = toBinaryString(address or onesMask(mask)) .padStart(mask.length, '0') .mapIndexed { index, character -> if (mask[index] == 'X') 'X' else character } .joinToString("") fun generateAddresses(value: String): List<String> { if (!value.contains('X')) { return listOf(value) } return generateAddresses(value.replaceFirst('X', '0')) + generateAddresses(value.replaceFirst('X', '1')) } val newMemory = mem + generateAddresses(maskedAddr) .map { Pair(parseLong(it, 2), value) } return Pair(newMemory, mask) } fun applyMask(value: Long, mask: String): Long = value or onesMask(mask) and zerosMask(mask) private fun zerosMask(mask: String) = mask.map { character -> when (character) { '0' -> '1' else -> '0' } } .joinToBinaryLong() .inv() private fun onesMask(mask: String): Long = mask.map { character -> when (character) { '1' -> '1' else -> '0' } } .joinToBinaryLong() private fun <T> Iterable<T>.joinToBinaryLong(): Long { return parseLong(joinToString(""), 2) } private fun parseMask(line: String): String = line.split("=")[1].trim() private fun parseMemoryWrite(line: String): Pair<Long, Long> { val (addressTokens, value) = line.split("=") val re = Regex("[^0-9]") val address = re.replace(addressTokens.trim(), "").toLong() return Pair(address, value.trim().toLong()) }
0
Kotlin
0
0
a721c8f26738fe31190911d96896f781afb795e1
3,139
advent-of-code-2020
MIT License
src/Utils.kt
arhor
572,349,244
false
{"Kotlin": 36845}
import java.io.File import kotlin.math.absoluteValue fun readInput(ref: () -> Unit): List<String> { return ref.javaClass.name.substringBefore("Kt$").let { File("src", "$it.txt") }.readLines() } fun <T> flattenTree(item: T, children: T.() -> Sequence<T>): Sequence<T> { return sequenceOf(item) + item.children().flatMap { flattenTree(it, children) } } inline fun <T> Iterable<T>.countUntil(isValid: (T) -> Boolean): Int { var count = 0 for (item in this) { count++ if (!isValid(item)) break } return count } fun <T> List<T>.split(separator: T): List<List<T>> = fold(initial = mutableListOf(ArrayList<T>())) { result, element -> result.also { if (element == separator) { it.add(ArrayList()) } else { it.last().add(element) } } } tailrec fun gcd(a: Int, b: Int): Int = if (b == 0) a else gcd(b, a % b) fun gcd(arr: IntArray): Int = arr.reduce { a, b -> gcd(a, b) } fun lcm(a: Int, b: Int): Int = (a * b).absoluteValue / gcd(a, b) fun lcm(arr: IntArray): Int = arr.reduce { a, b -> lcm(a, b) } const val ALPHABET = " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" inline fun StringBuilder.extractTo(consumer: (String) -> Unit) { if (this.isNotEmpty()) { val value = this.toString() consumer(value) this.clear() } } fun IntRange.overlaps(other: IntRange) = maxOf(first, other.first) <= minOf(last, other.last) + 1 fun IntRange.merge(other: IntRange) = minOf(first, other.first)..maxOf(last, other.last)
0
Kotlin
0
0
047d4bdac687fd6719796eb69eab2dd8ebb5ba2f
1,581
aoc-2022-in-kotlin
Apache License 2.0
src/Day02.kt
Allagash
572,736,443
false
{"Kotlin": 101198}
// Day 02, Advent of Code 2022, Rock Paper Scissors fun main() { fun getScore(input: Char) = when (input) { 'A' -> 1 'B' -> 2 'C' -> 3 'X' -> 1 'Y' -> 2 'Z' -> 3 else -> -100000 } fun part1(input: List<String>): Long { var total = 0L input.forEach { val oppScore = getScore(it[0]) val myScore = getScore(it[2]) check(oppScore > 0 && myScore > 0) total += myScore total += when { myScore == 1 && oppScore == 3 -> 6 // my rock beats their scissors myScore == 3 && oppScore == 1 -> 0 // their rock beats my scissors myScore > oppScore -> 6 myScore < oppScore -> 0 else -> 3 // draw } } return total } fun part2(input: List<String>): Long { val moves = mutableListOf<String>() val oppToMyLookup = mapOf('A' to 'X', 'B' to 'Y', 'C' to 'Z') input.forEach { val oppMove = it[0] val myStrat = it[2] check(myStrat in 'X'..'Z') val newInc = when(it[2]) { 'X' -> -1 'Y' -> 0 'Z' -> 1 else -> { check(false) -10000 } } var myMove = oppToMyLookup[oppMove]?.plus(newInc)!! if (myMove < 'X') myMove = 'Z' if (myMove > 'Z') myMove = 'X' val round = it[0] + " " + myMove moves.add(round) } check(moves.size == input.size) return part1(moves) } // test if implementation meets criteria from the description, like: val testInput = readInput("Day02_test") check(part1(testInput) == 15L) check(part2(testInput) == 12L) val input = readInput("Day02") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
8d5fc0b93f6d600878ac0d47128140e70d7fc5d9
2,003
AdventOfCode2022
Apache License 2.0
src/Day11.kt
catcutecat
572,816,768
false
{"Kotlin": 53001}
import kotlin.system.measureTimeMillis fun main() { measureTimeMillis { Day11.run { solve1(10605L) // 58322L solve2(2713310158L) // 13937702909L } }.let { println("Total: $it ms") } } object Day11 : Day.GroupInput<List<Day11.Monkey>, Long>("11") { data class Monkey(val items: MutableList<Long>, val operation: (Long) -> Long, val next: (Long) -> Int, val div: Long) { var inspectedItems = 0L } override fun parse(input: List<List<String>>) = input.map { rawMonkey -> val items = rawMonkey[1].split(": ").last() .split(", ") .map(String::toLong) .let { ArrayDeque<Long>().apply { addAll(it) } } val (op, num) = rawMonkey[2].split(" ").takeLast(2) val operation: (Long) -> Long = when { op == "*" && num == "old" -> { { it * it } } op == "*" -> { { it * num.toLong() } } num == "old" -> { { it + it } } else -> { { it + num.toLong() } } } val div = rawMonkey[3].split(" ").last().toLong() val testTrue = rawMonkey[4].split(" ").last().toInt() val testFalse = rawMonkey[5].split(" ").last().toInt() val next: (Long) -> Int = { if (it % div == 0L) testTrue else testFalse } Monkey(items, operation, next, div) } private fun throwItems(data: List<Monkey>, round: Int, divide: Boolean): Long { val monkeys = data.map { it.copy(items = it.items.toMutableList()) } val mod = monkeys.fold(1L) { acc, monkey -> acc * monkey.div } repeat(round) { for (monkey in monkeys) monkey.apply { inspectedItems += items.size for (item in items) { val worryLevel = operation(item).let { if (divide) it / 3 else it % mod } val nextMonkey = next(worryLevel) monkeys[nextMonkey].items.add(worryLevel) } items.clear() } } return monkeys.map { it.inspectedItems }.sorted().takeLast(2).let { (a, b) -> a * b } } override fun part1(data: List<Monkey>) = throwItems(data, 20, true) override fun part2(data: List<Monkey>) = throwItems(data, 10000, false) }
0
Kotlin
0
2
fd771ff0fddeb9dcd1f04611559c7f87ac048721
2,268
AdventOfCode2022
Apache License 2.0
src/Day07.kt
leeturner
572,659,397
false
{"Kotlin": 13839}
fun main() { class Dir(val parent: Dir?, val name: String, val children: MutableList<Dir> = mutableListOf()) { var size: Long = 0 val totalSize: Long get() = size + children.sumOf { it.totalSize } override fun toString(): String { return "Dir($name) { size=$size, totalSize=$totalSize }" } } fun List<String>.parseDirectories(): List<Dir> { val root = Dir(null, "/") val directories = mutableListOf(root) var currentDir: Dir = root this.drop(1).forEach { cliOutput -> when { cliOutput == "$ cd .." -> currentDir = currentDir.parent ?: error("Parent not available") cliOutput.startsWith("$ cd") -> { val newDir = Dir(currentDir, cliOutput.substringAfterLast(" ")) currentDir.children.add(newDir) directories.add(newDir) currentDir = newDir } cliOutput[0].isDigit() -> currentDir.size += cliOutput.substringBefore(" ").toLong() } } return directories } fun part1(input: List<String>): Long { return input.parseDirectories().filter { it.totalSize <= 100000 }.sumOf { it.totalSize } } fun part2(input: List<String>): Long { val totalDiskSpace = 70000000 val diskSpaceRequired = 30000000 val directories = input.parseDirectories() val totalSpaceUsed = directories.first().totalSize val missing = diskSpaceRequired - (totalDiskSpace - totalSpaceUsed) return directories.filter { it.totalSize >= missing }.minOf { it.totalSize } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day07_test") check(part1(testInput) == 95437L) check(part2(testInput) == 24933642L) val input = readInput("Day07") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
8da94b6a0de98c984b2302b2565e696257fbb464
1,784
advent-of-code-2022
Apache License 2.0
src/day-8/part-2/solution-day-8-part-2.kts
d3ns0n
572,960,768
false
{"Kotlin": 31665}
import java.io.File val treeGrid = mutableListOf<String>() File("../input.txt").readLines().forEach { treeGrid.add(it) } val treeGridWidth = treeGrid.first().length val treeGridHeight = treeGrid.size fun viewingDistanceLeft(x: Int, y: Int): Int { val height = treeGrid[y][x].code for ((index, value) in treeGrid[y].substring(0, x).reversed().withIndex()) { if (value.code >= height) { return index + 1 } } return x } fun viewingDistanceRight(x: Int, y: Int): Int { val height = treeGrid[y][x].code for ((index, value) in treeGrid[y].substring(x + 1, treeGrid[y].length).withIndex()) { if (value.code >= height) { return index + 1 } } return treeGridWidth - 1 - x } fun viewingDistanceTop(x: Int, y: Int): Int { val height = treeGrid[y][x].code for (i in (y - 1 downTo 0)) { if (treeGrid[i][x].code >= height) { return y - i } } return y } fun viewingDistanceBottom(x: Int, y: Int): Int { val height = treeGrid[y][x].code for (i in (y + 1 until treeGridHeight)) { if (treeGrid[i][x].code >= height) { return i - y } } return treeGridHeight - 1 - y } fun findHighestScenicScore(treeGrid: List<String>): Int { var highestScenicScore = 0 for (y in treeGrid.indices) { for (x in 0 until treeGrid[y].length) { val scenicScore = viewingDistanceLeft(x, y) * viewingDistanceTop(x, y) * viewingDistanceRight(x, y) * viewingDistanceBottom(x, y) if (scenicScore > highestScenicScore) { highestScenicScore = scenicScore } } } return highestScenicScore } val highestScenicScore = findHighestScenicScore(treeGrid) println(highestScenicScore) assert(highestScenicScore == 268800)
0
Kotlin
0
0
8e8851403a44af233d00a53b03cf45c72f252045
1,893
advent-of-code-22
MIT License
src/day15/Code.kt
fcolasuonno
162,470,286
false
null
package day15 import java.io.File import kotlin.math.max fun main(args: Array<String>) { 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 Ingredient( val name: String, val score: Score ) data class Score( val capacity: Int = 0, val durability: Int = 0, val flavor: Int = 0, val texture: Int = 0, val calories: Int ) { val part1 = max(0, capacity) * max(0, texture) * max(0, flavor) * max(0, durability) operator fun times(quantity: Int) = copy(capacity * quantity, durability * quantity, flavor * quantity, texture * quantity, calories * quantity) operator fun plus(other: Score) = copy( capacity + other.capacity, durability + other.durability, flavor + other.flavor, texture + other.texture, calories + other.calories ) } private val List<Pair<Ingredient, Int>>.score: Score get() = map { (ingredient, quantity) -> ingredient.score * quantity }.reduce { acc, score -> acc + score } private val lineStructure = """(\w+): capacity (-?\d+), durability (-?\d+), flavor (-?\d+), texture (-?\d+), calories (-?\d+)""".toRegex() fun parse(input: List<String>) = input.map { lineStructure.matchEntire(it)?.destructured?.let { operator fun List<String>.component6() = this[5] val (name, capacity, durability, flavor, texture, calories) = it.toList() Ingredient(name, Score(capacity.toInt(), durability.toInt(), flavor.toInt(), texture.toInt(), calories.toInt())) } }.requireNoNulls() fun part1(input: List<Ingredient>): Any? = 100.possibleSums(input.size).map { input.zip(it).score.part1 }.max() fun part2(input: List<Ingredient>): Any? = 100.possibleSums(input.size).map { input.zip(it).score }.filter { it.calories == 500 }.map { it.part1 }.max() private fun Int.possibleSums(size: Int): List<List<Int>> = when { size == 1 -> listOf(listOf(this)) else -> (0..this).flatMap { curr -> (this - curr).possibleSums(size - 1).map { listOf(curr) + it } } }
0
Kotlin
0
0
24f54bf7be4b5d2a91a82a6998f633f353b2afb6
2,264
AOC2015
MIT License
advent-of-code-2020/src/main/kotlin/eu/janvdb/aoc2020/day07/Day07.kt
janvdbergh
318,992,922
false
{"Java": 1000798, "Kotlin": 284065, "Shell": 452, "C": 335}
package eu.janvdb.aoc2020.day07 import eu.janvdb.aocutil.kotlin.readLines val SHINY_GOLD = "shiny gold" fun main() { val bags = readLines(2020, "input07.txt") .map(::Bag) .map { Pair(it.name, it) } .toMap() val results = bags.values.filter { bag -> bag.canContain(SHINY_GOLD, bags) } .map(Bag::name) println(results.size) val shinyGoldBag = bags.get(SHINY_GOLD) if (shinyGoldBag != null) { println(shinyGoldBag.countIncludingNestedBags(bags) - 1) } } val LINE_REGEX = Regex("^(.*) contain (.*)\\.$") val CONTENTS_DELIMITER_REGEX = Regex("\\s*,\\s*") class Bag(description: String) { val name: String val contents: List<BagDescription> init { val matchResult = LINE_REGEX.matchEntire(description) if (matchResult == null) { throw IllegalArgumentException(description) } this.name = removeBagsFromName(matchResult.groupValues[1]) val contents = matchResult.groupValues[2] if (contents == "no other bags") this.contents = listOf() else this.contents = contents.split(CONTENTS_DELIMITER_REGEX).map(::BagDescription) } override fun toString(): String { return "$name contains $contents" } fun canContain(bagToFind: String, bags: Map<String, Bag>): Boolean { for (content in contents) { if (content.name == bagToFind) return true val nestedBag = bags[content.name] if (nestedBag != null && nestedBag.canContain(bagToFind, bags)) return true } return false } fun countIncludingNestedBags(bags: Map<String, Bag>): Int { var count = 1 for (content in contents) { val nestedBag = bags[content.name] if (nestedBag != null) count += content.number * nestedBag.countIncludingNestedBags(bags) } return count } } val BAG_DESCRIPTION_REGEX = Regex("^(\\d+) (.*)$") class BagDescription(description: String) { val number: Int val name: String init { val matchResult = BAG_DESCRIPTION_REGEX.matchEntire(description) if (matchResult == null) { throw IllegalArgumentException(description) } this.number = matchResult.groupValues[1].toInt() this.name = removeBagsFromName(matchResult.groupValues[2]) } override fun toString(): String { return "$number $name" } } val BAGS_REGEX = Regex(" bags?$") fun removeBagsFromName(input: String): String { return input.replace(BAGS_REGEX, "") }
0
Java
0
0
78ce266dbc41d1821342edca484768167f261752
2,286
advent-of-code
Apache License 2.0
src/Day24.kt
jvmusin
572,685,421
false
{"Kotlin": 86453}
import java.util.* fun main() { val dx = intArrayOf(0, 1, 0, -1) val dy = intArrayOf(1, 0, -1, 0) val dirs = ">v<^" data class Wind(val p: Pair<Int, Int>, val d: Int) fun solve(input: List<String>, needCycle: Int): Any { val n = input.size val m = input[0].length fun inside(p: Pair<Int, Int>): Boolean { val (x, y) = p return x in 0 until n && y in 0 until m && input[x][y] != '#' } fun move(w: Wind): Wind { val (x, y) = w.p var nx = x + dx[w.d] var ny = y + dy[w.d] if (!inside(nx to ny)) { if (w.d % 2 == 0) { ny = if (y == 1) m - 2 else 1 } else { nx = if (x == 1) n - 2 else 1 } } return Wind(nx to ny, w.d) } data class State(val p: Pair<Int, Int>, val cycle: Int) val startPos = 0 to 1 val endPos = n - 1 to m - 2 val canBe = buildSet { add(State(startPos, 0)) }.toHashSet() var activeWinds = buildSet { for (i in input.indices) { for (j in input[i].indices) { val dir = dirs.indexOf(input[i][j]) if (dir == -1) continue add(Wind(i to j, dir)) } } } var time = 0 val endState = State(endPos, needCycle) while (true) { if (endState in canBe) return time val nextWinds = activeWinds.map { move(it) } val nextWindsPositions = nextWinds.map { it.p }.toSet() val nextCanBe = canBe.flatMap { cur -> val (x, y) = cur.p (0 until 4).map { d -> val nx = x + dx[d] val ny = y + dy[d] State(nx to ny, cur.cycle) }.filter { created -> inside(created.p) }.flatMap { created -> val newCycle = when { created.cycle == 0 && created.p == endPos -> 1 created.cycle == 1 && created.p == startPos -> 2 else -> created.cycle } setOf(created, created.copy(cycle = newCycle)) } } canBe += nextCanBe canBe.removeIf { it.p in nextWindsPositions } activeWinds = nextWinds.toSet() time++ } } fun part1(input: List<String>): Any { return solve(input, 0) } fun part2(input: List<String>): Any { return solve(input, 2) } @Suppress("DuplicatedCode") run { val day = String.format("%02d", 24) val testInput = readInput("Day${day}_test") val input = readInput("Day$day") println("Part 1 test - " + part1(testInput)) println("Part 1 real - " + part1(input)) println("---") println("Part 2 test - " + part2(testInput)) println("Part 2 real - " + part2(input)) } }
1
Kotlin
0
0
4dd83724103617aa0e77eb145744bc3e8c988959
3,127
advent-of-code-2022
Apache License 2.0
src/main/kotlin/de/tek/adventofcode/y2022/day15/BeaconExclusionZone.kt
Thumas
576,671,911
false
{"Kotlin": 192328}
package de.tek.adventofcode.y2022.day15 import de.tek.adventofcode.y2022.util.math.Norm import de.tek.adventofcode.y2022.util.math.OneNorm import de.tek.adventofcode.y2022.util.math.Point import de.tek.adventofcode.y2022.util.readInputLines import kotlin.math.abs class SensorAndBeacon(val sensor: Point, private val beacon: Point) { fun getSensorRadius(): Int = with(OneNorm) { sensor distanceTo beacon } operator fun component1(): Point = sensor operator fun component2(): Point = beacon } fun main() { val input = readInputLines(SensorAndBeacon::class) println("In the row where y=2000000, ${part1(input)} positions cannot contain a beacon.") println("The tuning frequency of the distress beacon is ${part2(input)}.") } fun part1(input: List<String>): Int { val lineHeight = 2000000 val sensorBeaconPairs = input.map(::parsePointsFromLine) val linePointsInSensorRadius = linePointsInSensorRadius(sensorBeaconPairs, lineHeight) val beaconsOnLine = sensorBeaconPairs.map { (_, beacon) -> beacon }.filter { it.y == lineHeight }.toSet() return (linePointsInSensorRadius - beaconsOnLine).size } private val sensorRegex = Regex("""Sensor at x=([^,]+?), y=([^:]+?): closest beacon is at x=([^,]+?), y=([^,]+)""") fun parsePointsFromLine(line: String): SensorAndBeacon { val sensorRegexMatches = sensorRegex.matchEntire(line) if (sensorRegexMatches != null) { val (sensorX, sensorY, beaconX, beaconY) = sensorRegexMatches.destructured return SensorAndBeacon(Point(sensorX.toInt(), sensorY.toInt()), Point(beaconX.toInt(), beaconY.toInt())) } throw IllegalArgumentException("Input line does not match the expected format: '$line' does not match '$sensorRegex'.") } fun linePointsInSensorRadius(sensorBeaconPairs: List<SensorAndBeacon>, lineHeight: Int): Set<Point> = sensorBeaconPairs .asSequence() .map { it.sensor to it.getSensorRadius() } .filter { (sensor, radius) -> abs(sensor.y - lineHeight) <= radius } .flatMap { (sensor, radius) -> linePointsInSensorRadius(radius, sensor, lineHeight) } .toSet() fun linePointsInSensorRadius(radius: Int, sensor: Point, lineHeight: Int): List<Point> { val maxDeltaX = radius - abs(sensor.y - lineHeight) println("Sensor is at $sensor, radius is $radius, so the interval at y=$lineHeight is [${sensor.x - maxDeltaX},${sensor.x + maxDeltaX}].") return (-maxDeltaX..maxDeltaX).map { deltaX -> Point(sensor.x + deltaX, lineHeight) } } fun part2(input: List<String>, searchSpaceSize: Int = 4000000): Long { val sensorWithRadius = input.map(::parsePointsFromLine).map { OneNorm.Ball(it.sensor, it.getSensorRadius()) } for (x in 0..searchSpaceSize) { var point = Point(x, 0) val sensorBallsToConsider = sensorWithRadius.toMutableList() while (point.y <= searchSpaceSize) { val sensorBall = sensorBallsToConsider.firstOrNull { it contains point } ?: return calculateTuningFrequency(point) sensorBallsToConsider.remove(sensorBall) point = getNextPointOnVerticalLineOutsideOfBall(point, sensorBall) } } throw NoSuchElementException("The whole search space is covered by the sensors.") } private fun getNextPointOnVerticalLineOutsideOfBall(point: Point, sensorBall: Norm.Ball): Point { val distanceToSphere = sensorBall.distanceToSphere(point) val verticalDistanceToSensor = abs(point.y - sensorBall.point.y) return if (sensorBall.point.y > point.y) { // reflect point on the horizontal line through the sensor and go further down until you leave the sphere // of the detection ball around the sensor Point(point.x, point.y + 2 * verticalDistanceToSensor + distanceToSphere + 1) } else { // go further down until you leave the sphere of the detection ball around the sensor Point(point.x, point.y + distanceToSphere + 1) } } fun calculateTuningFrequency(beacon: Point) = with(beacon) { x * 4000000L + y }
0
Kotlin
0
0
551069a21a45690c80c8d96bce3bb095b5982bf0
4,046
advent-of-code-2022
Apache License 2.0
src/main/kotlin/Problem11.kt
jimmymorales
496,703,114
false
{"Kotlin": 67323}
/** * Largest product in a grid * * In the 20×20 grid below, four numbers along a diagonal line have been marked in red. * * 08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08 * 49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00 * 81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65 * 52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91 * 22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80 * 24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50 * 32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70 * 67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21 * 24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72 * 21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95 * 78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92 * 16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57 * 86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58 * 19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40 * 04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66 * 88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69 * 04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36 * 20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16 * 20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54 * 01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48 * * The product of these numbers is 26 × 63 × 78 × 14 = 1788696. * * What is the greatest product of four adjacent numbers in the same direction (up, down, left, right, or diagonally) in * the 20×20 grid? */ fun main() { println(largestProduct(grid, 4)) } fun largestProduct(matrix: Array<Array<Int>>, n: Int): Long { var maxP = 0L for (i in matrix.indices) { for (j in matrix[i].indices) { if (matrix[i][j] == 0) continue if (matrix.size - i >= n) { val pv = (0 until n).fold(initial = 1L) { acc, offset -> acc * matrix[i + offset][j] } if (pv > maxP) { maxP = pv } } if (matrix[i].size - j >= n) { val ph = (0 until n).fold(initial = 1L) { acc, offset -> acc * matrix[i][j + offset] } if (ph > maxP) { maxP = ph } } if (matrix.size - i >= n && matrix[i].size - j >= n) { val pdr = (0 until n).fold(initial = 1L) { acc, offset -> acc * matrix[i + offset][j + offset] } if (pdr > maxP) { maxP = pdr } } if (matrix.size - i >= n && j >= n - 1) { val pdl = (0 until n).fold(initial = 1L) { acc, offset -> acc * matrix[i + offset][j - offset] } if (pdl > maxP) { maxP = pdl } } } } return maxP } private val grid = arrayOf( arrayOf(8, 2, 22, 97, 38, 15, 0, 40, 0, 75, 4, 5, 7, 78, 52, 12, 50, 77, 91, 8), arrayOf(49, 49, 99, 40, 17, 81, 18, 57, 60, 87, 17, 40, 98, 43, 69, 48, 4, 56, 62, 0), arrayOf(81, 49, 31, 73, 55, 79, 14, 29, 93, 71, 40, 67, 53, 88, 30, 3, 49, 13, 36, 65), arrayOf(52, 70, 95, 23, 4, 60, 11, 42, 69, 24, 68, 56, 1, 32, 56, 71, 37, 2, 36, 91), arrayOf(22, 31, 16, 71, 51, 67, 63, 89, 41, 92, 36, 54, 22, 40, 40, 28, 66, 33, 13, 80), arrayOf(24, 47, 32, 60, 99, 3, 45, 2, 44, 75, 33, 53, 78, 36, 84, 20, 35, 17, 12, 50), arrayOf(32, 98, 81, 28, 64, 23, 67, 10, 26, 38, 40, 67, 59, 54, 70, 66, 18, 38, 64, 70), arrayOf(67, 26, 20, 68, 2, 62, 12, 20, 95, 63, 94, 39, 63, 8, 40, 91, 66, 49, 94, 21), arrayOf(24, 55, 58, 5, 66, 73, 99, 26, 97, 17, 78, 78, 96, 83, 14, 88, 34, 89, 63, 72), arrayOf(21, 36, 23, 9, 75, 0, 76, 44, 20, 45, 35, 14, 0, 61, 33, 97, 34, 31, 33, 95), arrayOf(78, 17, 53, 28, 22, 75, 31, 67, 15, 94, 3, 80, 4, 62, 16, 14, 9, 53, 56, 92), arrayOf(16, 39, 5, 42, 96, 35, 31, 47, 55, 58, 88, 24, 0, 17, 54, 24, 36, 29, 85, 57), arrayOf(86, 56, 0, 48, 35, 71, 89, 7, 5, 44, 44, 37, 44, 60, 21, 58, 51, 54, 17, 58), arrayOf(19, 80, 81, 68, 5, 94, 47, 69, 28, 73, 92, 13, 86, 52, 17, 77, 4, 89, 55, 40), arrayOf(4, 52, 8, 83, 97, 35, 99, 16, 7, 97, 57, 32, 16, 26, 26, 79, 33, 27, 98, 66), arrayOf(88, 36, 68, 87, 57, 62, 20, 72, 3, 46, 33, 67, 46, 55, 12, 32, 63, 93, 53, 69), arrayOf(4, 42, 16, 73, 38, 25, 39, 11, 24, 94, 72, 18, 8, 46, 29, 32, 40, 62, 76, 36), arrayOf(20, 69, 36, 41, 72, 30, 23, 88, 34, 62, 99, 69, 82, 67, 59, 85, 74, 4, 36, 16), arrayOf(20, 73, 35, 29, 78, 31, 90, 1, 74, 31, 49, 71, 48, 86, 81, 16, 23, 57, 5, 54), arrayOf(1, 70, 54, 71, 83, 51, 54, 69, 16, 92, 33, 48, 61, 43, 52, 1, 89, 19, 67, 48), )
0
Kotlin
0
0
e881cadf85377374e544af0a75cb073c6b496998
4,756
project-euler
MIT License
src/day24/Day24.kt
gautemo
317,316,447
false
null
package day24 import shared.getLines import kotlin.math.abs val commands = listOf("e", "se", "sw", "w", "nw", "ne") fun turnedTiles(input: List<String>, days: Int = 0): Int{ val tiles = mutableMapOf<PointDouble, Boolean>() for(path in input){ var x = 0.0 var y = 0.0 var pathLeft = path while(pathLeft.isNotEmpty()){ for(c in commands){ val removed = pathLeft.removePrefix(c) if(removed != pathLeft){ pathLeft = removed when(c){ "e" -> x++ "se" -> x += 0.5.also { y += 1 } "sw" -> x -= 0.5.also { y += 1 } "w" -> x-- "nw" -> x -= 0.5.also { y -= 1 } "ne" -> x += 0.5.also { y -= 1 } } break } } } tiles[(PointDouble(x, y))] = !(tiles[(PointDouble(x, y))] ?: false) } var mapForDay = TileMap(tiles) repeat(days){ mapForDay = TileMap(mapForDay.blackTilesNextDay()) } return mapForDay.tiles.count { it.value } } data class PointDouble(val x: Double, val y: Double) class TileMap(val tiles: MutableMap<PointDouble, Boolean>){ private fun countAdjacent(x: Double, y: Double): Int{ return tiles.count { (point, black) -> !(point.x == x && point.y == y) && abs(point.x - x) <= 1 && abs(point.y - y) <= 1 && black } } private fun pointsToCheck(): List<PointDouble>{ val points = mutableListOf<PointDouble>() var y = tiles.minBy { it.key.y }!!.key.y - 1 while(y <= tiles.maxBy { it.key.y }!!.key.y + 1){ var x = (tiles.minBy { it.key.x }!!.key.x - 1).toInt().toDouble() if(y % 2 != 0.0){ x += 0.5 } while(x <= tiles.maxBy { it.key.x }!!.key.x + 1){ points.add(PointDouble(x, y)) x++ } y++ } return points } fun blackTilesNextDay(): MutableMap<PointDouble, Boolean>{ val copy = tiles.toMutableMap() val check = pointsToCheck() for(p in check){ val adjacents = countAdjacent(p.x, p.y) if(tiles[p] == true && (adjacents == 0 || adjacents > 2)){ copy[p] = false } if(tiles[p] != true && adjacents == 2){ copy[p] = true } } return copy } } fun main(){ val input = getLines("day24.txt") val blackTiles = turnedTiles(input) println(blackTiles) val blackTiles100Days = turnedTiles(input, 100) println(blackTiles100Days) }
0
Kotlin
0
0
ce25b091366574a130fa3d6abd3e538a414cdc3b
2,795
AdventOfCode2020
MIT License
src/main/kotlin/utils/dijkstra.kt
komu
113,825,414
false
{"Kotlin": 395919}
package utils import java.util.* fun <T> shortestPath(from: T, isTarget: (T) -> Boolean, edges: (T) -> List<T>): List<T>? = shortestPathWithCost(from, isTarget) { n -> edges(n).map { it to 1 } }?.first fun <T> shortestPathBetween(from: T, to : T, edges: (T) -> List<T>): List<T>? = shortestPath(from, { it == to }, edges) fun <T> shortestPathWithCost(from: T, isTarget: (T) -> Boolean, edges: (T) -> List<Pair<T, Int>>): Pair<List<T>, Int>? { val initial = PathNode(from, null, 0) val nodes = mutableMapOf(from to initial) val queue = PriorityQueue(setOf(initial)) val targets = mutableSetOf<T>() while (queue.isNotEmpty()) { val u = queue.remove() for ((v, cost) in edges(u.point)) { if (isTarget(v)) targets += v val newDistance = u.distance + cost val previousNode = nodes[v] if (previousNode == null || newDistance < previousNode.distance) { val newNode = PathNode(v, u, newDistance) nodes[v] = newNode queue += newNode } } } val targetNode = targets.map { nodes[it]!! }.minByOrNull { it.distance } if (targetNode != null) { val result = mutableListOf<T>() var node: PathNode<T>? = targetNode while (node?.previous != null) { result += node.point node = node.previous } return result.asReversed() to targetNode.distance } return null } private class PathNode<T>(val point: T, val previous: PathNode<T>?, val distance: Int) : Comparable<PathNode<T>> { override fun compareTo(other: PathNode<T>) = distance.compareTo(other.distance) }
0
Kotlin
0
0
8e135f80d65d15dbbee5d2749cccbe098a1bc5d8
1,710
advent-of-code
MIT License
src/main/kotlin/se/saidaspen/aoc/aoc2016/Day04.kt
saidaspen
354,930,478
false
{"Kotlin": 301372, "CSS": 530}
package se.saidaspen.aoc.aoc2016 import se.saidaspen.aoc.util.* fun main() = Day04.run() object Day04 : Day(2016, 4) { private var memo = mutableMapOf<P<String, Int>, String>() class Room(val letters: String, val checksum: String, val sector: Int) override fun part1(): Any { val rooms = toRooms(input) return rooms.filter { checksum(it) == it.checksum }.map { it.sector }.sum() } override fun part2(): Any { val decrypted = toRooms(input) .filter { checksum(it) == it.checksum } .map { P(decrypt(it), it.sector) }.toList() return decrypted.filter { it.first.startsWith("north") }.toList()[0].second } private fun toRooms(input: String): MutableList<Room> { val rooms = mutableListOf<Room>() for (line in input.lines()) { val m = Regex("(.+)-(\\d+)\\[(.+)]").find(line)!! rooms.add(Room(m.groupValues[1], m.groupValues[3], m.groupValues[2].toInt())) } return rooms } private fun checksum(t: Room): String { val frequencies = freqMap(t.letters.replace("-", "")) return frequencies.entries .sortedWith(compareBy<Map.Entry<Char, Int>> { it.value }.thenByDescending { it.key }) .reversed().take(5).map { it.key }.joinToString("") } private fun decrypt(room: Room) : String { val words = room.letters.split("-") return words.joinToString(" ") { decryptWord(it, room.sector) } } private fun decryptWord(it: String, times: Int): String { if (memo.containsKey(P(it, times))) return memo[P(it, times)]!! var output = it for (i in 0 until times) { var newWord = "" for (c in output.chars()) newWord += if (c == 'z'.toInt()) 'a' else (c + 1).toChar() output = newWord } return output } }
0
Kotlin
0
1
be120257fbce5eda9b51d3d7b63b121824c6e877
1,916
adventofkotlin
MIT License
src/Day03.kt
gylee2011
573,544,473
false
{"Kotlin": 9419}
fun main() { fun part1(input: List<String>): Int = input .map { it.chunked(it.length / 2) } .map { (first, second) -> first.toSet() to second.toSet() } .map { (first, second) -> first.intersect(second).first() } .sumOf { it.priority } fun part2(input: List<String>): Int = input .chunked(3) .map { it.commonChar() } .sumOf { it.priority } // test if implementation meets criteria from the description, like: val testInput = readInput("Day03_test") check(part1(testInput) == 157) check(part2(testInput) == 70) val input = readInput("Day03") println(part1(input)) println(part2(input)) } val Char.priority: Int get() = if (isLowerCase()) { (this.code - 'a'.code + 1) } else { (this.code - 'A'.code + 27) } fun commonCharOf(list: List<String>): Char { return list.map { it.toSet().toMutableSet() } .reduce { acc, set -> acc.apply { retainAll(set) } } .first() } fun List<String>.commonChar(): Char = map { it.toSet() } .let { (first, second, third) -> first intersect second intersect third } .first()
0
Kotlin
0
0
339e0895fd2484b7f712b966a0dae8a4cfebc2fa
1,154
aoc2022-kotlin
Apache License 2.0
src/day11/Solution.kt
abhabongse
576,594,038
false
{"Kotlin": 63915}
/* Solution to Day 11: Monkey in the Middle * https://adventofcode.com/2022/day/11 */ package day11 import utils.MathUtil import utils.largest import utils.otherwiseThrow import utils.splitAt import java.io.File fun main() { val fileName = // "day11_sample.txt" "day11_input.txt" val (monkeyAlgorithms, itemQueues) = readInput(fileName) // Part 1: simulate 20 rounds, with discount rate of worry level = 3 run { val itemQueues = itemQueues.clone() repeat(20) { simulateRound(monkeyAlgorithms, itemQueues, 3L) } val p1MonkeyBusinessLevel = itemQueues .asSequence() .map { it.popFrontCount } .largest(2) .let { (fst, snd) -> fst * snd } println("Part 1: $p1MonkeyBusinessLevel") } // Part 2: simulate 10_000 rounds, no discount rate of worry level run { val itemQueues = itemQueues.clone() val modulus = monkeyAlgorithms.map { it.throwAction.testDivisibleBy }.let(MathUtil::lcm) repeat(10_000) { simulateRound(monkeyAlgorithms, itemQueues) itemQueues.forEach { it.resetMod(modulus) } } val p2MonkeyBusinessLevel = itemQueues .asSequence() .map { it.popFrontCount } .largest(2) .let { (fst, snd) -> fst.toLong() * snd.toLong() } println("Part 2: $p2MonkeyBusinessLevel") } } /** Reads and parses input data according to the problem statement. */ fun readInput(fileName: String): Pair<List<MonkeyAlgorithm>, List<ItemQueue>> { val monkeyAlgorithms: ArrayList<MonkeyAlgorithm> = arrayListOf() val itemQueues: ArrayList<ItemQueue> = arrayListOf() val lineGroups = File("inputs", fileName) .readLines() .asSequence() .map { it.trim() } .splitAt { it.isEmpty() } // Process each monkey information for ((monkeyNo, lines) in lineGroups.withIndex()) { (monkeyNo == parseMonkeyNo(lines[0])) .otherwiseThrow { IllegalArgumentException("unmatched monkey number") } val initialItemQueue = ItemQueue from lines[1] val modifyAction = ModifyAction from lines[2] val throwAction = ThrowAction.from(lines[3], lines[4], lines[5]) val monkeyAlgorithm = MonkeyAlgorithm(modifyAction, throwAction) monkeyAlgorithms.add(monkeyAlgorithm) itemQueues.add(initialItemQueue) } return Pair(monkeyAlgorithms, itemQueues) } private val monkeyNoPattern = """Monkey (\d+):""".toRegex() /** * Parses an input line representing the initial item queue for a monkey. */ fun parseMonkeyNo(string: String): Int { val (monkeyNo) = monkeyNoPattern .matchEntire(string) ?.destructured ?: throw IllegalArgumentException("invalid monkey number format: $string") return monkeyNo.toInt() } /** * Simulates a round of monkey throwing items around. * The variable [itemQueues] will be modified in-place. */ fun simulateRound(monkeyAlgorithms: List<MonkeyAlgorithm>, itemQueues: List<ItemQueue>, discountRatio: Long = 1) { for ((monkeyNo, itemQueue) in itemQueues.withIndex()) { while (itemQueue.isNotEmpty()) { val item = itemQueue.popFront() val (modifiedItem, nextMonkeyNo) = monkeyAlgorithms[monkeyNo].apply(item, discountRatio) itemQueues[nextMonkeyNo].pushBack(modifiedItem) } } }
0
Kotlin
0
0
8a0aaa3b3c8974f7dab1e0ad4874cd3c38fe12eb
3,421
aoc2022-kotlin
Apache License 2.0
src/Day03.kt
p357k4
573,068,508
false
{"Kotlin": 59696}
fun main() { fun score(repeated: Char): Int = when (repeated) { in 'a'..'z' -> 1 + (repeated - 'a') in 'A'..'Z' -> 27 + (repeated - 'A') else -> 0 } fun part1(input: List<String>): Int { val result = input.sumOf { line -> val half = line.length / 2 val first = line.substring(0, half) val second = line.substring(half, line.length) val common = first.toSet().intersect(second.toSet()) val repeated = common.first() score(repeated) } return result } fun part2(input: List<String>): Int { val result = input .windowed(3, 3) .sumOf { lines -> val common = lines .map(String::toSet) .reduce { a, b -> a.intersect(b) } val repeated = common.first() score(repeated) } return result } // test if implementation meets criteria from the description, like: val testInput = readInput("Day03_test") check(part1(testInput) == 7691) check(part2(testInput) == 2508) }
0
Kotlin
0
0
b9047b77d37de53be4243478749e9ee3af5b0fac
1,158
aoc-2022-in-kotlin
Apache License 2.0
src/main/kotlin/algorithmic_toolbox/week6/PlacingParentheses.kt
eniltonangelim
369,331,780
false
null
package algorithmic_toolbox.week6 import java.util.* import kotlin.math.max import kotlin.math.min fun getMaximValue(exp: String): Long { val n = exp.length / 2 + 1 var min = Array(n){ LongArray(n) } var max = Array(n){ LongArray(n) } for (i in 0 until n) { min[i][i] = (exp[i * 2] - '0').toLong() max[i][i] = (exp[i * 2] - '0').toLong() } for (s in 1 until n ) { for (z in 0 .. n -1 -s) { val j = s + z val minAndMax = getMinAndMax(exp, z, j, min, max) min[z][j] = minAndMax[0] max[z][j] = minAndMax[1] } } return max[0][n - 1] } fun getMinAndMax(exp: String, i: Int, j: Int, w: Array<LongArray>, W: Array<LongArray> ): LongArray { var minAndMax = longArrayOf(Long.MAX_VALUE, Long.MIN_VALUE) for (k in i until j) { val op = exp[k * 2 + 1] val a = eval(w[i][k], w[k+1][j], op) val b = eval(w[i][k], W[k+1][j], op) val c = eval(W[i][k], w[k+1][j], op) val d = eval(W[i][k], W[k+1][j], op) minAndMax[0] = min(a, min(b, min(c, min(d, minAndMax[0])))) minAndMax[1] = max(a, max(b, max(c, max(d, minAndMax[1])))) } return minAndMax } fun eval(a: Long, b: Long, op: Char): Long = when (op) { '+' -> a + b '-' -> a - b '*' -> a * b else -> { assert(false) 0 } } fun main(args: Array<String>) { val scanner = Scanner(System.`in`) val exp = scanner.next() println(getMaximValue(exp)) }
0
Kotlin
0
0
031bccb323339bec05e8973af7832edc99426bc1
1,536
AlgorithmicToolbox
MIT License
src/main/kotlin/Day04.kt
robfletcher
724,814,488
false
{"Kotlin": 18682}
class Day04 : Puzzle { override fun test() { val input = """ Card 1: 41 48 83 86 17 | 83 86 6 31 17 9 48 53 Card 2: 13 32 20 16 61 | 61 30 68 82 17 32 24 19 Card 3: 1 21 53 59 44 | 69 82 63 72 16 21 14 1 Card 4: 41 92 73 84 69 | 59 84 76 51 58 5 54 83 Card 5: 87 83 26 28 32 | 88 30 70 12 93 22 82 36 Card 6: 31 18 13 56 72 | 74 77 10 23 35 67 36 11""".trimIndent() assert(part1(input.lineSequence()) == 13) assert(part2(input.lineSequence()) == 30) } override fun part1(input: Sequence<String>) = input.sumOf { line -> when (val n = line.parse().winCount) { 0 -> 0 else -> (2..n).fold(1) { sum, _ -> sum * 2 } as Int } } override fun part2(input: Sequence<String>): Any { val cards = input.map { it.parse() }.toList() val counts = cards.associate { it.number to 1 }.toMutableMap() cards.forEach { card -> card.won.forEach { n -> counts[n] = counts.getValue(n) + counts.getValue(card.number) } } return counts.values.sum() } data class Card( val number: Int, val winCount: Int ) { val won: List<Int> get() = ((number + 1)..(number + winCount)).toList() } fun String.parse() = Card( checkNotNull(Regex("""Card\s+(\d+):""").find(this)).groupValues.last().toInt(), Regex("""\d+""").run { val winners = findAll(substringAfter(':').substringBefore('|')).map { it.value.toInt() } findAll(substringAfter('|')).map { it.value.toInt() }.filter { it in winners }.toList() }.size ) }
0
Kotlin
0
0
cf10b596c00322ea004712e34e6a0793ba1029ed
1,585
aoc2023
The Unlicense
advent/src/test/kotlin/org/elwaxoro/advent/y2021/Dec21.kt
elwaxoro
328,044,882
false
{"Kotlin": 376774}
package org.elwaxoro.advent.y2021 import org.elwaxoro.advent.PuzzleDayTester /** * <NAME> */ class Dec21 : PuzzleDayTester(21, 2021) { override fun part1(): Any = GameV1(listOf(Player(1, 6), Player(2, 8))).let { game -> while (!game.hasWinner()) { game.players.forEach { player -> if (!game.hasWinner()) { player.position = (player.position + List(3) { game.roll() }.sum() - 1) % 10 + 1 player.score += player.position } } } game.players.minOf { it.score } * game.dice } override fun part2(): Any = findAllTheGames(mapOf(GameV2(listOf(Player(1, 6), Player(2, 8))) to 1L)) .entries.groupBy { it.key.getWinner() } .map { it.value.sumOf { it.value } }.maxOf { it } /** * Recursively find all games without a winner by rolling each of 1,2,3 for the current player and expanding the games */ private fun findAllTheGames(games: Map<GameV2, Long>): Map<GameV2, Long> = if (games.all { it.key.hasWinner() }) { games } else { findAllTheGames(games.flatMap { (game, count) -> if (game.hasWinner()) { listOf(game to count) } else { game.roll().map { it to count } } }.groupBy { it.first }.map { it.key to it.value.sumOf { it.second } }.toMap()) } private data class Player(val name: Int, var position: Long, var score: Long = 0) { fun roll(roll: Long): Player = Player(name, (position + roll - 1) % 10 + 1, score) fun score(): Player = Player(name, position, score + position) fun rollScore(roll: Long, score: Boolean): Player = roll(roll).takeUnless { score } ?: roll(roll).score() } private data class GameV1(val players: List<Player>) { var dice = 0L fun roll(): Long = (dice++ % 100L) + 1 fun hasWinner(): Boolean = players.any { it.score >= 1000L } } private data class GameV2(var players: List<Player>) { private var rolls = 0L // each player gets 3 rolls before it's the other players turn fun hasWinner(): Boolean = getWinner() != null fun getWinner(): Int? = players.singleOrNull { it.score >= 21 }?.name fun swapPlayers() { players = players.reversed() } fun endTurn(newRolls: Long) { rolls = newRolls if (newRolls == 3L) { rolls = 0 swapPlayers() } } fun roll(): List<GameV2> = (1L..3L).map { GameV2(listOf(players.first().rollScore(it, rolls + 1 == 3L), players.last())).also { it.endTurn(rolls + 1) } } } }
0
Kotlin
4
0
1718f2d675f637b97c54631cb869165167bc713c
2,820
advent-of-code
MIT License
src/Day14.kt
Allagash
572,736,443
false
{"Kotlin": 101198}
import java.io.File import kotlin.math.min import kotlin.math.max // Advent of Code 2022, Day 14, Regolith Reservoir fun main() { fun readInputAsOneLine(name: String) = File("src", "$name.txt").readText().trim() fun Array<CharArray>.print() { for (y in this[0].indices) { for (element in this) { val c = element[y] print(c) } println() } } fun part1(input: String) : Int { val inputLines = input.split("\n").map { it.split(" -> ") } val drawLines = mutableListOf<Pair<Pair<Int, Int>, Pair<Int, Int>>>() var max = Pair(Int.MIN_VALUE, Int.MIN_VALUE) var min = Pair(Int.MAX_VALUE, Int.MAX_VALUE) inputLines.forEach { for (i in 0 until it.lastIndex) { val firstPt = it[i].split(",").map{it.toInt()}//.map{it[0].toInt() to it[1].toInt()} val secondPt = it[i+1].split(",").map{it.toInt()} val firstPair = firstPt[0] to firstPt[1] val secondPair = secondPt[0] to secondPt[1] max = Pair(maxOf(max.first, firstPair.first, secondPair.first), maxOf(max.second, firstPair.second, secondPair.second)) min = Pair(minOf(min.first, firstPair.first, secondPair.first), minOf(min.second, firstPair.second, secondPair.second)) drawLines.add(Pair(firstPair, secondPair)) } // val chunked = it.chunked(2).filter { it.size == 2 } // val pairs = chunked.map{ it.split(",")} } // println("max is $max, min is $min") max = Pair(max.first + 1, max.second + 1) // enlarge the grid min = Pair(min.first - 1, min.second - 1 - 5) // will start piling up, need more vertical space val xSize = max.first - min.first + 1 val ySize = max.second - min.second + 1 val graph = Array(xSize) {CharArray(ySize){'.'} } drawLines.forEach { val x1 = it.first.first - min.first val y1 = it.first.second - min.second val x2 = it.second.first - min.first val y2 = it.second.second - min.second if (x1 == x2) { for (y in min(y1, y2)..max(y1, y2) ) { graph[x1][y] = '#' } } else { for (x in min(x1, x2)..max(x1, x2) ) { graph[x][y1] = '#' } } } var done = false var count = 0 while(!done) { count++ var sand = Pair(500 - min.first, 0) check(graph[sand.first][sand.second] == '.') { "count is $count" } while (sand.second != ySize - 1 && (graph[sand.first][sand.second + 1] == '.' || graph[sand.first-1][sand.second + 1] == '.' || graph[sand.first+1][sand.second + 1] == '.') ) { if (graph[sand.first][sand.second + 1] == '.') { // can optimize - first in array not . sand = Pair(sand.first, sand.second + 1) continue } if (graph[sand.first-1][sand.second + 1] == '.') { sand = Pair(sand.first-1, sand.second + 1) continue } if (graph[sand.first+1][sand.second + 1] == '.') { sand = Pair(sand.first+1, sand.second + 1) continue } } if (sand.second == ySize - 1) done = true graph[sand.first][sand.second] = 'o' } //graph.print() return count - 1 // don't count last one which fell through } fun part2(input: String) : Int { val inputLines = input.split("\n").map { it.split(" -> ") } val drawLines = mutableListOf<Pair<Pair<Int, Int>, Pair<Int, Int>>>() var max = Pair(Int.MIN_VALUE, Int.MIN_VALUE) var min = Pair(Int.MAX_VALUE, Int.MAX_VALUE) inputLines.forEach { for (i in 0 until it.lastIndex) { val firstPt = it[i].split(",").map{it.toInt()}//.map{it[0].toInt() to it[1].toInt()} val secondPt = it[i+1].split(",").map{it.toInt()} val firstPair = firstPt[0] to firstPt[1] val secondPair = secondPt[0] to secondPt[1] max = Pair(maxOf(max.first, firstPair.first, secondPair.first), maxOf(max.second, firstPair.second, secondPair.second)) min = Pair(minOf(min.first, firstPair.first, secondPair.first), minOf(min.second, firstPair.second, secondPair.second)) drawLines.add(Pair(firstPair, secondPair)) } // val chunked = it.chunked(2).filter { it.size == 2 } // val pairs = chunked.map{ it.split(",")} } //println("max is $max, min is $min") val left = max(500 - min.first, max.second) val right = max( max.first- 500, max.second) //println("left is $left, right is $right") max = Pair(500 + right + 7, max.second + 1) // enlarge the grid min = Pair(500 - left - 5, 0) // will start piling up, need more vertical space //println("max is now $max, min is $min") val xSize = max.first - min.first + 1 val ySize = max.second - min.second + 1 val graph = Array(xSize) {CharArray(ySize){'.'} } drawLines.forEach { val x1 = it.first.first - min.first val y1 = it.first.second - min.second val x2 = it.second.first - min.first val y2 = it.second.second - min.second if (x1 == x2) { for (y in min(y1, y2)..max(y1, y2) ) { graph[x1][y] = '#' } } else { for (x in min(x1, x2)..max(x1, x2) ) { graph[x][y1] = '#' } } } // printGraph(graph) // print("\n\n") var done = false var count = 0 while(!done) { if (graph[500-min.first][0]=='o') { done = true continue } count++ var sand = Pair(500 - min.first, 0) check(graph[sand.first][sand.second] == '.') { "count is $count" } while (sand.second != ySize - 1 && (graph[sand.first][sand.second + 1] == '.' || graph[sand.first-1][sand.second + 1] == '.' || graph[sand.first+1][sand.second + 1] == '.') ) { if (graph[sand.first][sand.second + 1] == '.') { // can optimize - first in array not . sand = Pair(sand.first, sand.second + 1) continue } if (graph[sand.first-1][sand.second + 1] == '.') { sand = Pair(sand.first-1, sand.second + 1) continue } if (graph[sand.first+1][sand.second + 1] == '.') { sand = Pair(sand.first+1, sand.second + 1) continue } } graph[sand.first][sand.second] = 'o' } // printGraph(graph) return count } val testInput = readInputAsOneLine("Day14_test") check(part1(testInput) == 24) check(part2(testInput) == 93) val input = readInputAsOneLine("Day14") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
8d5fc0b93f6d600878ac0d47128140e70d7fc5d9
7,513
AdventOfCode2022
Apache License 2.0
src/Day07.kt
alfr1903
573,468,312
false
{"Kotlin": 9628}
import java.util.ArrayDeque import java.util.Deque fun main() { fun part1(input: List<String>): Int { return solve(input) } fun part2(comingSoon: Any): Int { TODO() } print(part1(testInput.lines())); println(" 48381165") val input = readInputAsList("Day07Input") println(part1(input)) println(part2(input)) } private fun String.isCdBackCommand() = this == "$ cd .." private fun String.isCdCommand() = this.startsWith("$ cd") private fun String.isLsCommand() = this.startsWith("$ cd") private fun String.isDir() = this.startsWith("dir") private fun String.isFile() = this.first().isDigit() private fun String.getDir() = this.substringAfterLast(" ") private fun String.getFileSize():Int = this.substringBefore(" ").toInt() private fun solve(input: List<String>): Int { val currentDir: Deque<String> = ArrayDeque() val map = mutableMapOf<String, Int>() val visited = emptySet<String>().toMutableSet() for (line in input) { when { line.isCdBackCommand() -> { visited += currentDir.first val prevCurrent = currentDir.first currentDir.removeFirst() map[currentDir.first] = map[currentDir.first]!! + map[prevCurrent]!! } line.isCdCommand() -> { if (visited.isNotEmpty()) visited += currentDir.first currentDir.addFirst(line.getDir()) if (currentDir.first !in visited) map[currentDir.first] = 0 } line.isFile() && currentDir.first !in visited -> map[currentDir.first] = map[currentDir.first]!! + line.getFileSize() } } return map.values.sum() } val testInput = """${'$'} cd / ${'$'} ls dir a 14848514 b.txt 8504156 c.dat dir d ${'$'} cd a ${'$'} ls dir e 29116 f 2557 g 62596 h.lst ${'$'} cd e ${'$'} ls 584 i ${'$'} cd .. ${'$'} cd .. ${'$'} cd d ${'$'} ls 4060174 j 8033020 d.log 5626152 d.ext 7214296 k"""
0
Kotlin
0
0
c1d1fbf030ac82c643fa5aea4d9f7c302051c38c
1,990
advent-of-code-2022
Apache License 2.0
src/y2022/day07.kt
sapuglha
573,238,440
false
{"Kotlin": 33695}
package y2022 import readFileAsLines enum class EntryType { DIRECTORY, FILE, } sealed interface Entry { val type: EntryType val name: String data class FileEntry( val size: Int, override val name: String, override val type: EntryType = EntryType.FILE ) : Entry data class DirectoryEntry( override val name: String, override val type: EntryType = EntryType.DIRECTORY ) : Entry } class TreeNode( val parent: TreeNode? = null, val value: Entry, ) { val children: MutableList<TreeNode> = mutableListOf() fun getChild(name: String): TreeNode { val entry = children.first { it.value.name == name } return entry } fun addChild(child: TreeNode) { children.add(child) } fun prettyString(): String { val stringBuilder = StringBuilder() print(stringBuilder, "", "") return stringBuilder.toString() } private fun print(stringBuilder: StringBuilder, prefix: String, childrenPrefix: String) { stringBuilder.append(prefix) stringBuilder.append(value) stringBuilder.append('\n') val childIterator = children.iterator() while (childIterator.hasNext()) { val node = childIterator.next() if (childIterator.hasNext()) { node.print(stringBuilder, "$childrenPrefix├── ", "$childrenPrefix│ ") } else { node.print(stringBuilder, "$childrenPrefix└── ", "$childrenPrefix ") } } } } data class ToBeSummed( val path: String, val size: Int, ) fun TreeNode.part1(currentPath: String, list: MutableList<ToBeSummed>): Int { if (value.type == EntryType.FILE) return (value as Entry.FileEntry).size val total = children .map { it.part1(currentPath + "/${it.value.name}", list) } .sumOf { it } if (total <= 100_000) { list.add(ToBeSummed(currentPath, total)) } return total } fun TreeNode.part2(currentPath: String, list: MutableList<ToBeSummed>): Int { when (value.type) { EntryType.FILE -> { // println("File name: $currentPath, size: ${(value as Entry.FileEntry).size})") return (value as Entry.FileEntry).size } else -> Unit //println("Directory name: $currentPath") } val total = children .map { it.part2(currentPath + "/${it.value.name}", list) } .sumOf { it } list.add(ToBeSummed(currentPath, total)) return total } fun main() { fun populateTree(input: List<String>, currentNode: TreeNode) { var currentNode1 = currentNode input.forEach { line -> val splitLine = line.split(" ") if (splitLine.first() == "$") { val splitLine = line.split(" ") val prompt = splitLine.first() // $ val command = splitLine[1] val directory = if (command == "cd") splitLine[2] else "" if (command == "cd") { if (directory == "..") currentNode1 = currentNode1.parent!! // YAY!!! else if (directory == "/") // nothing else currentNode1 = currentNode1.getChild(directory) } } else { if (splitLine.first() == "dir") { // add a new DIRECTORY node val directoryName = splitLine.last() currentNode1.addChild( TreeNode( parent = currentNode1, value = Entry.DirectoryEntry(name = directoryName), ) ) } else { currentNode1.addChild( TreeNode( parent = currentNode1, value = Entry.FileEntry( size = splitLine.first().toInt(), name = splitLine.last() ) ) ) } } } } fun part1(input: List<String>): Int { val tree = TreeNode(value = Entry.DirectoryEntry("/")) populateTree(input, tree) println(tree.prettyString()) val listDirectoriesLessThanSize = mutableListOf<ToBeSummed>() tree.part1("", listDirectoriesLessThanSize) return listDirectoriesLessThanSize.sumOf { it.size } } fun part2(input: List<String>): Int { val tree = TreeNode(value = Entry.DirectoryEntry("/")) populateTree(input, tree) val allDirectories = mutableListOf<ToBeSummed>() tree.part2("", allDirectories) val usedSpace = allDirectories.find { it.path.isEmpty() }?.size ?: 0 val neededSpace = 70_000_000 - usedSpace allDirectories.remove(allDirectories.find { it.path.isEmpty() }) val duplicateDirectories = mutableListOf<ToBeSummed>() allDirectories.sortBy { it.path.length } allDirectories .forEachIndexed { itemIndex, item -> allDirectories .filterIndexed { filterIndex, filterItem -> item.path.contains(filterItem.path) && itemIndex != filterIndex } .onEach { duplicate -> if (duplicate.size == item.size) { allDirectories .find { it == duplicate } ?.let { duplicateDirectories.add(it) } } } } duplicateDirectories.forEach { allDirectories.remove(it) } allDirectories.sortByDescending { it.size } val item = allDirectories .filter { (it.size + neededSpace) > 30_000_000 } .reversed() .first() return item.size } "y2022/data/day07_test".readFileAsLines().let { input -> check(part1(input) == 95437) check(part2(input) == 24933642) } "y2022/data/day07".readFileAsLines().let { input -> println("part1: ${part1(input)}") println("part2: ${part2(input)}") } }
0
Kotlin
0
0
82a96ccc8dcf38ae4974e6726e27ddcc164e4b54
6,452
adventOfCode2022
Apache License 2.0
src/main/kotlin/aoc/year2022/Day02.kt
SackCastellon
573,157,155
false
{"Kotlin": 62581}
package aoc.year2022 import aoc.Puzzle /** * [Day 2 - Advent of Code 2022](https://adventofcode.com/2022/day/2) */ object Day02 : Puzzle<Int, Int> { override fun solvePartOne(input: String): Int = input.lines().sumOf { val (shape, response) = it.split(" ").map(String::toShape) (shape vs response).score + response.score } override fun solvePartTwo(input: String): Int = input.lines().sumOf { val (left, right) = it.split(" ") val result = right.toResult() val shape = left.toShape() (shape responseFor result).score + result.score } } private fun String.toShape(): Shape = when (this) { "A", "X" -> Shape.Rock "B", "Y" -> Shape.Paper "C", "Z" -> Shape.Scissors else -> throw IllegalArgumentException("Unexpected shape: $this") } private fun String.toResult(): Result = when (this) { "X" -> Result.Lose "Y" -> Result.Draw "Z" -> Result.Win else -> throw IllegalArgumentException("Unexpected shape: $this") } private enum class Shape(val score: Int, defeatedByGetter: () -> Shape, defeatsGetter: () -> Shape) { Rock(1, { Paper }, { Scissors }), Paper(2, { Scissors }, { Rock }), Scissors(3, { Rock }, { Paper }); private val defeatedBy by lazy(defeatedByGetter) private val defeats by lazy(defeatsGetter) infix fun vs(shape: Shape): Result = when (shape) { defeats -> Result.Lose this -> Result.Draw else -> Result.Win } infix fun responseFor(result: Result): Shape = when (result) { Result.Lose -> this.defeats Result.Draw -> this Result.Win -> this.defeatedBy } } private enum class Result(val score: Int) { Lose(0), Draw(3), Win(6) }
0
Kotlin
0
0
75b0430f14d62bb99c7251a642db61f3c6874a9e
1,780
advent-of-code
Apache License 2.0
src/main/kotlin/day3/Solution.kt
krazyglitch
573,086,664
false
{"Kotlin": 31494}
package day3 import util.Utils import java.time.Duration import java.time.LocalDateTime class Solution { private val offsetLower = 'a'.code private val offsetUpper = 'A'.code private val priorityMap: Map<Char, Int> init { priorityMap = HashMap() ('a'..'z').forEach { priorityMap.put(it, it.code - offsetLower + 1) } ('A'..'Z').forEach { priorityMap.put(it, it.code - offsetUpper + 27) } } class Rucksack(val input: String) { private val first: String private val second: String init { val midPoint = (input.length / 2) first = input.substring(0, midPoint) second = input.substring(midPoint) } fun getCommonCharacter(): Char { val firstSet = first.toHashSet() val secondSet = second.toHashSet() firstSet.forEach { c -> if (secondSet.contains(c)) return c } return ' ' } } class Group(private val rucksacks: Triple<Rucksack, Rucksack, Rucksack>) { fun getCommonCharacter(): Char { val firstSet = rucksacks.first.input val secondSet = rucksacks.second.input val thirdSet = rucksacks.third.input return firstSet.filter { c -> secondSet.contains(c) }.first { c -> thirdSet.contains(c) } } } fun part1(data: List<String>): Int { val rucksacks = data.map { s -> Rucksack(s) } return rucksacks.sumOf { r -> val commonCharacter = r.getCommonCharacter() priorityMap[commonCharacter] ?: 0 } } fun part2(data: List<String>): Int { val rucksacks = data.map { s -> Rucksack(s) } val groups = (0..data.size-2 step 3).map{ Group(Triple(rucksacks[it], rucksacks[it+1], rucksacks[it+2])) } return groups.sumOf { g -> val commonCharacter = g.getCommonCharacter() priorityMap[commonCharacter] ?: 0 } } } fun main() { val runner = Solution() val input = Utils.readLines(runner, "input.txt", runner.javaClass.packageName) println("Solving first part of day 3") var start = LocalDateTime.now() println("The priority sum is: ${input?.let { runner.part1(it) }}") var end = LocalDateTime.now() println("Solved first part of day 3") var milliseconds = Duration.between(start, end).toMillis() println("Took $milliseconds ms to solve first part of day 3") println() println("Solving second part of day 3") start = LocalDateTime.now() println("The badge priority sum is: ${input?.let { runner.part2(it) }}") end = LocalDateTime.now() println("Solved second part of day 3") milliseconds = Duration.between(start, end).toMillis() println("Took $milliseconds ms to solve second part of day 3") }
0
Kotlin
0
0
db6b25f7668532f24d2737bc680feffc71342491
2,848
advent-of-code2022
MIT License
src/Day04.kt
hoppjan
433,705,171
false
{"Kotlin": 29015, "Shell": 338}
typealias BingoBoard = List<List<Int>> fun main() { fun part1(numbers: List<Int>, bingoBoards: List<BingoBoard>): Int { val drawnNumbers = mutableListOf<Int>() numbers.forEach { number -> drawnNumbers.add(number) bingoBoards.firstOrNull { it.hasBingo(drawnNumbers) }?.run { return number * unmarkedFieldSum(drawnNumbers) } } throw Exception("Better luck next time!") } fun part2(numbers: List<Int>, bingoBoards: List<BingoBoard>): Int { var boards = bingoBoards val drawnNumbers = mutableListOf<Int>() numbers.forEach { number -> drawnNumbers.add(number) val board = boards.first() if (boards.onlyOneRemaining() && board.hasBingo(drawnNumbers)) return number * board.unmarkedFieldSum(drawnNumbers) else boards = boards.filter { it.hasBingo(drawnNumbers).not() } } throw Exception("Better luck next time!") } // test if implementation meets criteria from the description val (testNumbers, testBingoBoards) = BingoBoardInputReader.read("Day04_test") // testing part 1 val testSolution1 = 4512 val testOutput1 = part1(testNumbers, testBingoBoards) printTestResult(1, testOutput1, testSolution1) check(testOutput1 == testSolution1) // testing part 2 val testSolution2 = 1924 val testOutput2 = part2(testNumbers, testBingoBoards) printTestResult(2, testOutput2, testSolution2) check(testOutput2 == testSolution2) // using the actual input for val (numbers, boards) = BingoBoardInputReader.read("Day04") printResult(1, part1(numbers, boards)) printResult(2, part2(numbers, boards)) } fun List<*>.onlyOneRemaining() = size == 1 fun BingoBoard.unmarkedFieldSum(drawnNumbers: List<Int>) = sumOf { numbers -> numbers.filterNot { drawnNumbers.contains(it) }.sum() } fun BingoBoard.hasBingo(drawnNumbers: List<Int>) = any { drawnNumbers.checkRowForBingo(it) } or rotate().any { drawnNumbers.checkRowForBingo(it) } fun List<Int>.checkRowForBingo(row: List<Int>) = containsAll(row) fun BingoBoard.rotate() = indices.map { index -> map { it[index] } }
0
Kotlin
0
0
04f10e8add373884083af2a6de91e9776f9f17b8
2,387
advent-of-code-2021
Apache License 2.0
src/main/kotlin/com/github/ferinagy/adventOfCode/aoc2021/2021-14.kt
ferinagy
432,170,488
false
{"Kotlin": 787586}
package com.github.ferinagy.adventOfCode.aoc2021 import com.github.ferinagy.adventOfCode.println import com.github.ferinagy.adventOfCode.readInputText fun main() { val input = readInputText(2021, "14-input") val test1 = readInputText(2021, "14-test1") println("Part1:") part1(test1).println() part1(input).println() println() println("Part2:") part2(test1).println() part2(input).println() } private fun part1(input: String): Long { return doPairInsertion(input, 10) } private fun part2(input: String): Long { return doPairInsertion(input, 40) } private fun doPairInsertion(input: String, count: Int): Long { val (initial, temp) = input.split("\n\n") val templates: Map<String, String> = temp.lines().associate { val (from, to) = it.split(" -> ") from to to + from[1] } val letterMap = mutableMapOf<Char, Long>() val cache = mutableMapOf<Pair<String, Int>, Map<Char, Long>>() for (i in 0 until initial.lastIndex) { val subLetters = letterMap(initial.substring(i .. i + 1), count, templates, cache) letterMap.add(subLetters) } val first = letterMap[initial.first()]!! letterMap[initial.first()] = first + 1 val sorted = letterMap.map { it.value }.sorted() return sorted.last() - sorted.first() } private fun MutableMap<Char, Long>.add(other: Map<Char, Long>) { other.forEach { val count = getOrDefault(it.key, 0) put(it.key, count + it.value) } } private fun letterMap( key: String, depth: Int, templates: Map<String, String>, cache: MutableMap<Pair<String, Int>, Map<Char, Long>> ): Map<Char, Long> { val existing = cache[key to depth] if (existing != null) return existing if (depth == 1) { return templates[key]!!.toCharArray().letterMap().also { cache[key to depth] = it } } val result = mutableMapOf<Char, Long>() val sub = templates[key]!! for (i in 1..sub.lastIndex) { val subLetters = letterMap(sub.substring(i - 1..i), depth - 1, templates, cache) result.add(subLetters) } val subLetters = letterMap("${key[0]}${sub[0]}", depth - 1, templates, cache) result.add(subLetters) return result.also { cache[key to depth] = it } } private fun CharArray.letterMap() = groupBy { it }.mapValues { it.value.size.toLong() }
0
Kotlin
0
1
f4890c25841c78784b308db0c814d88cf2de384b
2,366
advent-of-code
MIT License
2015/Day15/src/main/kotlin/Main.kt
mcrispim
658,165,735
false
null
import java.io.File import java.lang.Thread.yield data class Ingredient( val name: String, val capacity: Int, val durability: Int, val flavor: Int, val texture: Int, val calories: Int ) fun recipeFactory(ingredients: List<Ingredient>, amount: Int): Sequence<List<Pair<Ingredient, Int>>> { fun sumArray(array: IntArray, lastIndex: Int): Int { var sum = 0 for (i in 0..lastIndex) { sum += array[i] } return sum } return sequence { if (ingredients.size == 1) { yield(listOf(ingredients[0] to amount)) } val n = ingredients.size val quantities = IntArray(n) var counterIndex = n - 2 while (counterIndex >= 0) { quantities[n - 1] = amount - sumArray(quantities, n - 2) val recipe = ingredients.mapIndexed { index, ingredient -> Pair(ingredient, quantities[index]) } yield(recipe) counterIndex = n - 2 quantities[counterIndex]++ while (counterIndex >= 0 && quantities[counterIndex] > amount) { quantities[counterIndex] = 0 counterIndex-- if (counterIndex >= 0) { quantities[counterIndex]++ } } } } } fun main() { fun getIngredients(input: List<String>): List<Ingredient> { val parser = Regex("""(\w+): capacity (-?\d+), durability (-?\d+), flavor (-?\d+), texture (-?\d+), calories (-?\d+)""") val ingredients = input.map { line -> (parser.matchEntire(line) ?: error("Invalid input: $line")).destructured.let { val (name, capacity, durability, flavor, texture, calories) = it Ingredient( name, capacity.toInt(), durability.toInt(), flavor.toInt(), texture.toInt(), calories.toInt() ) } } return ingredients } fun calculatePoints(recipe: List<Pair<Ingredient, Int>>): Int { var capacityPoints = 0 var durabilityPoints = 0 var flavorPoints = 0 var texturePoints = 0 recipe.forEach { val (ingredient, spoons) = it capacityPoints += spoons * ingredient.capacity durabilityPoints += spoons * ingredient.durability flavorPoints += spoons * ingredient.flavor texturePoints += spoons * ingredient.texture } if (capacityPoints < 0 || durabilityPoints < 0 || flavorPoints < 0 || texturePoints < 0) { return 0 } return capacityPoints * durabilityPoints * flavorPoints * texturePoints } fun calculateCalories(recipe: List<Pair<Ingredient, Int>>): Int { var caloriesPoints = 0 recipe.forEach { val (ingredient, spoons) = it caloriesPoints += spoons * ingredient.calories } if (caloriesPoints < 0) { return 0 } return caloriesPoints } fun part1(input: List<String>) = recipeFactory(getIngredients(input), 100) .map { calculatePoints(it) } .maxOrNull()!! fun part2(input: List<String>) = recipeFactory(getIngredients(input), 100) .filter { calculateCalories(it) == 500 } .map { calculatePoints(it) } .maxOrNull()!! // test if implementation meets criteria from the description, like: val testInput = readInput("Day15_test") check(part1(testInput) == 62842880) check(part2(testInput) == 57600000) val input = readInput("Day15_data") println("Part 1 answer: ${part1(input)}") println("Part 2 answer: ${part2(input)}") } /** * Reads lines from the given input txt file. */ fun readInput(name: String) = File("src", "$name.txt") .readLines()
0
Kotlin
0
0
2f4be35e78a8a56fd1e078858f4965886dfcd7fd
3,921
AdventOfCode
MIT License
src/main/kotlin/year_2022/Day11.kt
krllus
572,617,904
false
{"Kotlin": 97314}
package year_2022 import utils.readInputAsText fun main() { fun getMonkeys(monkeysStr: List<String>): Map<Int, Monkey> { return buildMap { monkeysStr.forEachIndexed { index, s -> // split by line and remove first "Monkey n" val lines = s.split("\n").drop(1) val items = lines[0].split(":").last() .split(",") .map { BagItem(it.trim().toLong()) } val itemsStack = ArrayDeque<BagItem>() itemsStack.addAll(items) val operation = lines[1].split("new = old ").last() val test = lines[2].split("by ").last().toInt() val monkeySuccess = lines[3].takeLast(1).toInt() val monkeyFailure = lines[4].takeLast(1).toInt() val monkey = Monkey( id = index, bagItems = itemsStack, operation = operation, test = test, testSuccessMonkeyId = monkeySuccess, testFailureMonkeyId = monkeyFailure ) put(index, monkey) } } } fun part1(input: String): Int { val monkeysStr = input.split("\n\n") val monkeys: Map<Int, Monkey> = getMonkeys(monkeysStr) repeat(20) { monkeys.values.forEach { monkey -> val monkeySuccess = monkeys[monkey.testSuccessMonkeyId] ?: error("monkey success[${monkey.testSuccessMonkeyId} not found") val monkeyFailure = monkeys[monkey.testFailureMonkeyId] ?: error("monkey failure[${monkey.testFailureMonkeyId} not found") monkey.inspectItems(monkeySuccess, monkeyFailure) } monkeys.values.forEach { println(it) } println() } val monkeysItemCount = monkeys.values.map { it.inspectedItem }.sortedDescending().take(2) return monkeysItemCount.reduce { acc, i -> acc * i } } fun part2(input: String): Long { val monkeysStr = input.split("\n\n") val monkeys: Map<Int, Monkey> = getMonkeys(monkeysStr) repeat(10000) { monkeys.values.forEach { monkey -> val monkeySuccess = monkeys[monkey.testSuccessMonkeyId] ?: error("monkey success[${monkey.testSuccessMonkeyId} not found") val monkeyFailure = monkeys[monkey.testFailureMonkeyId] ?: error("monkey failure[${monkey.testFailureMonkeyId} not found") monkey.inspectItems(monkeySuccess, monkeyFailure) monkeys.values.forEach { println(it) } println() } } val monkeysItemCount = monkeys.values.map { it.inspectedItem }.sortedDescending().take(2) return monkeysItemCount[0].toLong() * monkeysItemCount[1].toLong() } // test if implementation meets criteria from the description, like: val testInput = readInputAsText("Day11_test") // check(part1(testInput) == 10605) // check(part2(testInput) == 2713310158) val input = readInputAsText("Day11") // println(part1(input)) println(part2(input)) } data class Monkey( val id: Int, var inspectedItem: Int = 0, val bagItems: ArrayDeque<BagItem>, val operation: String, val test: Int, val testSuccessMonkeyId: Int, val testFailureMonkeyId: Int ) { fun inspectItems(monkeySuccess: Monkey, monkeyFailure: Monkey) { while (bagItems.isNotEmpty()) { inspectedItem++ val currentItem = bagItems.removeFirst().copy() currentItem.worry(this.operation) currentItem.relief() if (testItem(currentItem.copy())) { monkeySuccess.receiveItem(currentItem) } else { monkeyFailure.receiveItem(currentItem) } } } private fun testItem(item: BagItem): Boolean { return item.value % test.toLong() == 0L } private fun receiveItem(bagItem: BagItem) { this.bagItems.addLast(bagItem) } override fun toString(): String { return "Monkey $id: ${bagItems.joinToString(separator = ",") { it.value.toString() }}" } } data class BagItem( var value: Long, ) { fun relief() { this.value = this.value % 9699690L } fun worry(operation: String) { val op = operation.split(" ").first() val operationValue = operation.split(" ").last().toLongOrNull() this.value = when (op) { "+" -> { if (operationValue == null) { this.value + this.value } else { this.value + operationValue } } "*" -> { if (operationValue == null) { this.value * this.value } else { this.value * operationValue } } else -> error("operation ($op) not parsable") } } }
0
Kotlin
0
0
b5280f3592ba3a0fbe04da72d4b77fcc9754597e
5,194
advent-of-code
Apache License 2.0