path stringlengths 5 169 | owner stringlengths 2 34 | repo_id int64 1.49M 755M | is_fork bool 2
classes | languages_distribution stringlengths 16 1.68k ⌀ | content stringlengths 446 72k | issues float64 0 1.84k | main_language stringclasses 37
values | forks int64 0 5.77k | stars int64 0 46.8k | commit_sha stringlengths 40 40 | size int64 446 72.6k | name stringlengths 2 64 | license stringclasses 15
values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
src/main/kotlin/de/nosswald/aoc/days/Day11.kt | 7rebux | 722,943,964 | false | {"Kotlin": 34890} | package de.nosswald.aoc.days
import de.nosswald.aoc.Day
// https://adventofcode.com/2023/day/11
object Day11 : Day<Long>(11, "Cosmic Expansion") {
private const val GALAXY = '#'
private const val EXPANDED = 'x'
private data class Galaxy(val x: Int, val y: Int)
private fun List<String>.expand(): List<String> {
return this.map { line ->
if (line.none { it == GALAXY })
EXPANDED.toString().repeat(line.length)
else {
line
.mapIndexed { i, old -> if (this.none { it[i] == GALAXY }) EXPANDED else old }
.joinToString("")
}
}
}
private fun combined(input: List<String>, expansionSize: Long): Long {
val space = input.expand()
val galaxies = space.flatMapIndexed { y, line ->
line.mapIndexedNotNull { x, c ->
if (c == GALAXY) Galaxy(x, y) else null
}
}
return galaxies
.flatMapIndexed { i, a ->
galaxies
.drop(i)
.map { b -> countSteps(space, a, b, expansionSize) }
}
.sum()
}
private fun countSteps(space: List<String>, a: Galaxy, b: Galaxy, expansionSize: Long): Long {
val xIndices = if (a.x > b.x) a.x - 1 downTo b.x else a.x until b.x
val yIndices = if (a.y > b.y) a.y - 1 downTo b.y else a.y until b.y
val xSteps = xIndices.sumOf { x -> if (space[a.y][x] == EXPANDED) expansionSize else 1 }
val ySteps = yIndices.sumOf { y -> if (space[y][a.x] == EXPANDED) expansionSize else 1 }
return xSteps + ySteps
}
override fun partOne(input: List<String>): Long =
combined(input, expansionSize = 2)
override fun partTwo(input: List<String>): Long =
combined(input, expansionSize = 1_000_000)
override val partOneTestExamples: Map<List<String>, Long> = mapOf(
listOf(
"...#......",
".......#..",
"#.........",
"..........",
"......#...",
".#........",
".........#",
"..........",
".......#..",
"#...#.....",
) to 374
)
// I adjusted the output since there is only a test provided for expansionSize=100
override val partTwoTestExamples: Map<List<String>, Long> = mapOf(
listOf(
"...#......",
".......#..",
"#.........",
"..........",
"......#...",
".#........",
".........#",
"..........",
".......#..",
"#...#.....",
) to 82000210
)
}
| 0 | Kotlin | 0 | 1 | 398fb9873cceecb2496c79c7adf792bb41ea85d7 | 2,718 | advent-of-code-2023 | MIT License |
src/Day10.kt | ShuffleZZZ | 572,630,279 | false | {"Kotlin": 29686} | private const val SCREEN_WIDTH = 40
private const val SCREEN_SIZE = 6 * SCREEN_WIDTH
private const val SIGNAL_STRENGTH = SCREEN_WIDTH / 2
private fun cycleSignals(input: List<String>): List<Int> {
val signals = MutableList(2 * input.size + 1) { 1 }
var cycle = 0
for (i in input.indices) {
signals[cycle + 1] = signals[cycle]
val instruction = input[i].split(" ")
if (instruction.first() == "addx") {
signals[++cycle + 1] = signals[cycle] + instruction.last().toInt()
}
cycle++
}
return signals
}
fun main() {
fun part1(input: List<String>): Int {
val signals = cycleSignals(input)
return (SIGNAL_STRENGTH..SCREEN_SIZE - SIGNAL_STRENGTH step SCREEN_WIDTH).sumOf { it * signals[it - 1] }
}
fun part2(input: List<String>): String {
val signals = cycleSignals(input).take(SCREEN_SIZE)
return signals.chunked(SCREEN_WIDTH) { line ->
line.mapIndexed { ind, signal -> if (signal in ind - 1..ind + 1) '#' else '.' }.joinToString("")
}.joinToString("\n")
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day10_test")
check(part1(testInput) == 13_140)
println(part2(testInput))
val input = readInput("Day10")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 5a3cff1b7cfb1497a65bdfb41a2fe384ae4cf82e | 1,374 | advent-of-code-kotlin | Apache License 2.0 |
src/main/kotlin/Day19.kt | clechasseur | 267,632,210 | false | null | object Day19 {
private const val input = 3004953
fun part1(): Int = generateSequence(State((1..input).toList())) {
it.next()
}.dropWhile {
it.elves.size > 1
}.first().elves.single()
fun part2(): Int = generateSequence(State2((1..input).toList())) {
it.next()
}.dropWhile {
it.elves.size > 1
}.first().elves.single()
private data class State(val elves: List<Int>) {
fun next(): State {
var copyLast = false
val nextElves = elves.asSequence().chunked(2).mapNotNull {
copyLast = it.size == 1
if (copyLast) null else it[0]
}.toList()
return State(if (copyLast) listOf(elves.last()) + nextElves else nextElves)
}
}
private data class State2(val elves: List<Int>) {
fun next(): State2 {
val firstHalf = elves.subList(0, elves.size / 2)
val secondHalf = elves.subList(elves.size / 2, elves.size)
val indexesToSkip = generateSequence(0 to if (elves.size % 2 == 0) 1 else 2) { (i, s) ->
i + s to if (s == 1) 2 else 1
}.takeWhile { it.first in secondHalf.indices }.map { it.first }.toSet()
val filteredSecondHalf = secondHalf.filterIndexed { i, _ -> !indexesToSkip.contains(i) }
val newElves = firstHalf.drop(indexesToSkip.size) + filteredSecondHalf + firstHalf.take(indexesToSkip.size)
return State2(newElves)
}
}
}
| 0 | Kotlin | 0 | 0 | 120795d90c47e80bfa2346bd6ab19ab6b7054167 | 1,499 | adventofcode2016 | MIT License |
2023/src/main/kotlin/de/skyrising/aoc2023/day2/solution.kt | skyrising | 317,830,992 | false | {"Kotlin": 411565} | package de.skyrising.aoc2023.day2
import de.skyrising.aoc.*
val test = TestInput("""
Game 1: 3 blue, 4 red; 1 red, 2 green, 6 blue; 2 green
Game 2: 1 blue, 2 green; 3 green, 4 blue, 1 red; 1 green, 1 blue
Game 3: 8 green, 6 blue, 20 red; 5 blue, 4 red, 13 green; 5 green, 1 red
Game 4: 1 green, 3 red, 6 blue; 3 green, 6 red; 3 green, 15 blue, 14 red
Game 5: 6 red, 1 blue, 3 green; 2 blue, 1 red, 2 green
""")
data class Round(val red: Int, val green: Int, val blue: Int)
data class Game(val num: Int, val rounds: List<Round>)
fun parse(game: String): Game {
val (gameNum, gameData) = game.split(": ")
return Game(gameNum.split(" ")[1].toInt(), gameData.split("; ").map {
var red = 0
var green = 0
var blue = 0
for (reveal in it.split(", ")) {
val (count, color) = reveal.split(" ")
when (color) {
"red" -> red += count.toInt()
"green" -> green += count.toInt()
"blue" -> blue += count.toInt()
else -> error("Invalid color: $color")
}
}
Round(red, green, blue)
})
}
@PuzzleName("Cube Conundrum")
fun PuzzleInput.part1() = lines.map(::parse).sumOf {
if (it.rounds.all { round -> round.red <= 12 && round.green <= 13 && round.blue <= 14 }) it.num else 0
}
fun PuzzleInput.part2() = lines.map(::parse).sumOf {
it.rounds.maxOf(Round::red) * it.rounds.maxOf(Round::green) * it.rounds.maxOf(Round::blue)
}
| 0 | Kotlin | 0 | 0 | 19599c1204f6994226d31bce27d8f01440322f39 | 1,502 | aoc | MIT License |
2021/src/main/kotlin/Day17.kt | eduellery | 433,983,584 | false | {"Kotlin": 97092} | class Day17(val input: String) {
private fun String.prepareInput(): List<Int> =
"target area: x=([-\\d]+)..([-\\d]+), y=([-\\d]+)..([-\\d]+)".toRegex()
.matchEntire(this)!!.destructured.toList().map { it.toInt() }
private val area = input.prepareInput()
private var minY = minOf(area[2], area[3])
private var maxY = -minY - 1
private val minX = (1..area[0]).first { it.sequenceSum() >= area[0] }
private val maxX = area[1]
private fun isInRange(point: Pair<Int, Int>): Boolean {
return point.first in area[0]..area[1] && point.second in area[2]..area[3]
}
private fun isInRange(x: Int, y: Int): Boolean {
val seqX = generateSequence(0 to x) { (posX, velX) -> posX + velX to maxOf(0, velX - 1) }
val seqY = generateSequence(0 to y) { (posY, velY) -> posY + velY to velY - 1 }
val validX = seqX.takeWhile { (posX, _) -> posX <= maxX }.map { it.first }
val validY = seqY.takeWhile { (posY, _) -> posY >= minY }.map { it.first }
return (validX zip validY).any { isInRange(it) }
}
fun solve1(): Int {
return minY.sequenceSum()
}
fun solve2(): Int {
return (minX..maxX).sumOf { x ->
(minY..maxY).count { y ->
isInRange(x, y)
}
}
}
}
| 0 | Kotlin | 0 | 1 | 3e279dd04bbcaa9fd4b3c226d39700ef70b031fc | 1,322 | adventofcode-2021-2025 | MIT License |
y2021/src/main/kotlin/adventofcode/y2021/Day24.kt | Ruud-Wiegers | 434,225,587 | false | {"Kotlin": 503769} | package adventofcode.y2021
import adventofcode.io.AdventSolution
import adventofcode.util.algorithm.transpose
import java.util.*
object Day24 : AdventSolution(2021, 24, "Arithmetic Logic Unit") {
override fun solvePartOne(input: String) = "36969794979199"
override fun solvePartTwo(input: String) = "11419161313147"
data class Instruction(val op: String, val target: Char, val source: (memory: Map<Char, Long>) -> Long)
fun parse(input: String) = input.lines().map { it.split(' ') }.map {
val op = it[0]
val target = it[1][0]
val readSource = it.getOrNull(2)
Instruction(op, target, when {
readSource == null -> { _ -> throw IllegalStateException() }
readSource.toLongOrNull() == null -> { m -> m.getValue(readSource[0]) }
else -> { _ -> readSource.toLong() }
})
}
fun verify(program: List<Instruction>, input: Iterator<Int>): Boolean {
val memory = mutableMapOf('w' to 0L, 'x' to 0L, 'y' to 0L, 'z' to 0L)
program.forEach { (op, target, source) ->
when (op) {
"inp" -> memory[target] = input.next().toLong()
"add" -> memory[target] = memory.getValue(target) + source(memory)
"mul" -> memory[target] = memory.getValue(target) * source(memory)
"div" -> memory[target] = memory.getValue(target) / source(memory)
"mod" -> memory[target] = memory.getValue(target) % source(memory)
"eql" -> memory[target] = if (memory.getValue(target) == source(memory)) 1 else 0
}
}
return memory['z'] == 0L
}
//Each input is processed in a block of instructions, that differs in only 3 places
fun parseDifferences(input: String) = input
.split("\ninp w\n", "inp w\n")
.filter { it.isNotBlank() }
.map(String::lines)
.transpose()
.filterNot { it.distinct().size == 1 }
.transpose()
.map { it.map { it.substringAfterLast(' ').toInt() } }
}
//hand-decompiled behavior of program
fun solveDecompiled(program: List<List<Int>>, inputs: List<Int>): Boolean {
val z = Stack<Int>()
program.zip(inputs).forEach { (v, input) ->
val a = v[1] + when {
z.isEmpty() -> 0
v[0] == 1 -> z.peek()
else -> z.pop()
}
if (a != input) z.push(input + v[2])
}
return z.isEmpty()
}
/*
further analysis: 7 pushes, 7 pops, 7 conditional pushes. z == 0 -> stack is empty
so conditional pushes must not occur.
the conditions compare values of previously stored digits. Further analysis yields:
S2 = S3 + 3
S4 = S11 + 8
S6 = S7 + 5
S8 = S9 + 2
S10 = S5 + 2
S12 = S1 + 3
S13 = S0 + 6
For part 1, we maximize the right side (9's)
For part 2, we minimize the left side (1's)
*/ | 0 | Kotlin | 0 | 3 | fc35e6d5feeabdc18c86aba428abcf23d880c450 | 2,845 | advent-of-code | MIT License |
src/Day04.kt | robotfooder | 573,164,789 | false | {"Kotlin": 25811} | fun main() {
fun isFullyOverLapping(it: Pair<IntRange, IntRange>): Boolean =
it.first.toSet().containsAll(it.second.toSet()) || it.second.toSet().containsAll(it.first.toSet())
fun isOverLapping(it: Pair<IntRange, IntRange>): Boolean =
(it.first.toSet() intersect it.second.toSet()).isNotEmpty()
fun part1(input: List<String>): Int = input
.map { it.split(",") }
.map { it.first().ranges() to it.last().ranges() }
.count { isFullyOverLapping(it) }
fun part2(input: List<String>): Int = input
.map { it.split(",") }
.map { it.first().ranges() to it.last().ranges() }
.count { isOverLapping(it) }
fun runTest(expected: Int, day: String, testFunction: (List<String>) -> Int) {
val actual = testFunction(readTestInput(day))
check(expected == actual)
{
"Failing for day $day, ${testFunction}. " +
"Expected $expected but got $actual"
}
}
val day = "04"
// test if implementation meets criteria from the description, like:
runTest(2, day, ::part1)
runTest(4, day, ::part2)
val input = readInput(day)
println(part1(input))
println(part2(input))
}
fun String.ranges(): IntRange {
return this.split("-")
.map { it.toInt() }
.zipWithNext { a, b -> IntRange(a, b) }
.first()
}
| 0 | Kotlin | 0 | 0 | 9876a52ef9288353d64685f294a899a58b2de9b5 | 1,387 | aoc2022 | Apache License 2.0 |
src/Day01.kt | purdyk | 572,817,231 | false | {"Kotlin": 19066} | fun main() {
fun part1(input: List<String>): Int {
val groups = input.fold(mutableListOf(mutableListOf<Int>())) { acc, it ->
if (it.isEmpty()) {
acc.add(mutableListOf())
} else {
acc.last().add(it.toInt())
}
acc
}
val totaled = groups.map { it.sum() to it }
val topIdx = totaled.maxBy { it.first }.let { max -> totaled.indexOfFirst { it.first == max.first } }
return totaled[topIdx].first
}
fun part2(input: List<String>): Int {
val groups = input.fold(mutableListOf(mutableListOf<Int>())) { acc, it ->
if (it.isEmpty()) {
acc.add(mutableListOf())
} else {
acc.last().add(it.toInt())
}
acc
}
val totaled = groups.map { it.sum() to it }
return totaled.sortedByDescending { it.first }.take(3).sumOf { it.first }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day01_test").split("\n")
check(part1(testInput) == 24000)
check(part2(testInput) == 45000)
println("Test: ")
println(part1(testInput))
println(part2(testInput))
val input = readInput("Day01").split("\n")
println("\nProblem: ")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 02ac9118326b1deec7dcfbcc59db8c268d9df096 | 1,384 | aoc2022 | Apache License 2.0 |
src/main/kotlin/be/seppevolkaerts/day5/Day5.kt | Cybermaxke | 727,453,020 | false | {"Kotlin": 35118} | package be.seppevolkaerts.day5
import be.seppevolkaerts.splitLongs
import kotlin.math.max
import kotlin.math.min
class Data(
val seeds: List<Long>,
val maps: RangeMaps,
)
data class RangeMaps(
val maps: List<RangeMap>
) {
private val mapsByInputType = maps.associateBy { it.inputType }
fun mapper(inputType: String, outputType: String): (input: Long) -> Long {
return { input ->
var output = input
var type = inputType
while (type != outputType) {
val map = mapsByInputType[type]!!
output = map[output]
type = map.outputType
}
output
}
}
fun rangeMapper(inputType: String, outputType: String): (input: LongRange) -> List<LongRange> {
return { input ->
var output = listOf(input)
var type = inputType
while (type != outputType) {
val map = mapsByInputType[type]!!
output = output.flatMap { map[it] }
type = map.outputType
}
output
}
}
}
data class RangeMap(
val inputType: String,
val outputType: String,
private val entries: List<Entry>,
) {
operator fun get(input: Long): Long {
entries.forEach { entry ->
if (input in entry.inputRange) {
return input + entry.outputOffset
}
}
return input
}
operator fun get(input: LongRange): List<LongRange> {
// assumes that the ranges in the entries don't overlap and are ordered
val ranges = ArrayList<LongRange>()
var lastEnd = -1L
for (entry in entries) {
if (entry.inputRange.first > input.last) {
break
}
if (entry.inputRange.last < input.first) {
continue
}
// coerce entry range within input range
val range = max(entry.inputRange.first, input.first)..min(entry.inputRange.last, input.last)
val gapStart = if (lastEnd == -1L) input.first else lastEnd + 1
if (gapStart != range.first) {
ranges.add(gapStart..<range.first)
} else {
ranges.add((range.first + entry.outputOffset)..(range.last + entry.outputOffset))
}
lastEnd = range.last
}
if (lastEnd < input.last) {
ranges.add((if (lastEnd == -1L) input.first else lastEnd + 1)..input.last)
}
return ranges
}
data class Entry(
val inputRange: LongRange,
val outputOffset: Long,
)
}
fun parseData(iterable: Iterable<String>): Data {
var seeds = emptyList<Long>()
val maps = ArrayList<RangeMap>()
val mapHeaderRegex = "([a-z]+)-to-([a-z]+) map:".toRegex()
var currentMapEntries = mutableListOf<RangeMap.Entry>()
var currentMapInputType = ""
var currentMapOutputType = ""
fun addCurrentMap() {
if (currentMapEntries.isNotEmpty()) {
maps += RangeMap(currentMapInputType, currentMapOutputType, currentMapEntries.sortedBy { it.inputRange.first })
}
}
iterable.forEach { line ->
if (line.startsWith("seeds:")) {
seeds = line.substringAfter(':').splitLongs()
} else {
val result = mapHeaderRegex.find(line)
if (result != null) {
addCurrentMap()
currentMapEntries = ArrayList()
currentMapInputType = result.groupValues[1]
currentMapOutputType = result.groupValues[2]
} else if (line.isNotBlank()) {
val destSourceLength = line.splitLongs()
currentMapEntries += RangeMap.Entry(
inputRange = destSourceLength[1]..<(destSourceLength[1] + destSourceLength[2]),
outputOffset = destSourceLength[0] - destSourceLength[1],
)
}
}
}
addCurrentMap()
return Data(seeds, RangeMaps(maps))
}
fun lowestSeedLocationNumber(iterable: Iterable<String>): Long {
val data = parseData(iterable)
val map = data.maps.mapper("seed", "location")
return data.seeds.minOf { seed -> map(seed) }
}
fun lowestSeedRangeLocationNumber(iterable: Iterable<String>): Long {
val data = parseData(iterable)
val seedRanges = data.seeds.chunked(2) { it[0]..<(it[0] + it[1]) }
val map = data.maps.rangeMapper("seed", "location")
return seedRanges.flatMap(map).minOf { it.first }
}
| 0 | Kotlin | 0 | 1 | 56ed086f8493b9f5ff1b688e2f128c69e3e1962c | 4,045 | advent-2023 | MIT License |
src/Day04.kt | allisonjoycarter | 574,207,005 | false | {"Kotlin": 22303} |
fun main() {
fun getRangeFromText(input: String): IntRange {
return input.split("-").first().toInt().rangeTo(
input.split("-").last().toInt()
)
}
fun part1(input: List<String>): Int {
val contained = input.count { line ->
val firstStart = line.split(",").first()
val secondStart = line.split(",").last()
val firstRange = getRangeFromText(firstStart)
val secondRange = getRangeFromText(secondStart)
(firstRange.first <= secondRange.first && firstRange.last >= secondRange.last) ||
(secondRange.first <= firstRange.first && secondRange.last >= firstRange.last)
}
return contained
}
fun part2(input: List<String>): Int {
val contained = input.count { line ->
val firstStart = line.split(",").first()
val secondStart = line.split(",").last()
val firstRange = getRangeFromText(firstStart)
val secondRange = getRangeFromText(secondStart)
firstRange.intersect(secondRange).isNotEmpty()
}
return contained
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day04_test")
check(part1(testInput) == 2)
check(part2(testInput) == 4)
val input = readInput("Day04")
println("Part 1:")
println(part1(input))
println("Part 2:")
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 86306ee6f4e90c1cab7c2743eb437fa86d4238e5 | 1,469 | adventofcode2022 | Apache License 2.0 |
src/Day14.kt | mathijs81 | 572,837,783 | false | {"Kotlin": 167658, "Python": 725, "Shell": 57} | private const val EXPECTED_1 = 136
private const val EXPECTED_2 = 64
private class Day14(isTest: Boolean) : Solver(isTest) {
fun part1(): Any {
val field = readAsLines()
var sum = 0
fun add(row: Int, count: Int) {
for (i in 0 until count) {
sum += field.size - row - i
}
}
for (x in 0 until field[0].length) {
var rockCount = 0
for (y in field.size - 1 downTo 0) {
if (field[y][x] == 'O') {
rockCount++
}
if (field[y][x] == '#') {
add(y + 1, rockCount)
rockCount = 0
}
}
add(0, rockCount)
}
return sum
}
fun load(field: List<CharArray>): Int {
var sum = 0
for (y in field.indices) {
for (x in field[0].indices) {
if (field[y][x] == 'O') {
sum += field.size - y
}
}
}
return sum
}
fun part2(): Any {
var field = readAsLines().map { it.toCharArray() }
fun add(row: Int, count: Int, field: List<CharArray>, x: Int) {
for (i in 0 until count) {
field[row + i][x] = 'O'
}
}
fun rotate(field: List<CharArray>): List<CharArray> {
val res = List(field[0].size) { CharArray(field.size) }
for (y in res.indices) {
for (x in res[0].indices) {
res[y][x] = field[field[0].size - x - 1][y]
}
}
return res
}
val seen = mutableMapOf<String, Long>()
var roundsLeft = 1000000000L
while (roundsLeft > 0) {
repeat(4) {
for (x in 0 until field[0].size) {
var rockCount = 0
for (y in field.size - 1 downTo 0) {
if (field[y][x] == 'O') {
rockCount++
field[y][x] = '.'
}
if (field[y][x] == '#') {
add(y + 1, rockCount, field, x)
rockCount = 0
}
}
add(0, rockCount, field, x)
}
field = rotate(field)
}
roundsLeft--
val key = field.map { it.joinToString("") }.joinToString("")
val lastIndex = seen[key]
if (lastIndex != null) {
val add = lastIndex - roundsLeft
if (roundsLeft >= add) {
roundsLeft %= add
}
}
seen[key] = roundsLeft
}
return load(field)
}
}
fun main() {
val testInstance = Day14(true)
val instance = Day14(false)
testInstance.part1().let { check(it == EXPECTED_1) { "part1: $it != $EXPECTED_1" } }
println("part1 ANSWER: ${instance.part1()}")
testInstance.part2().let {
check(it == EXPECTED_2) { "part2: $it != $EXPECTED_2" }
println("part2 ANSWER: ${instance.part2()}")
}
}
| 0 | Kotlin | 0 | 2 | 92f2e803b83c3d9303d853b6c68291ac1568a2ba | 3,234 | advent-of-code-2022 | Apache License 2.0 |
src/day10/Code.kt | fcolasuonno | 225,219,560 | false | null | package day10
import isDebug
import java.io.File
import kotlin.math.abs
fun main() {
val name = if (isDebug()) "test.txt" else "input.txt"
System.err.println(name)
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)}")
}
fun parse(input: List<String>) =
input.mapIndexed { j, s -> s.mapIndexedNotNull { i, c -> if (c == '#') (i to j) else null } }.flatten().toSet()
fun part1(input: Set<Pair<Int, Int>>): Any? = input.map { a ->
(input - a).map { (it.first - a.first) to (it.second - a.second) }.partition { it.second > 0 }
.let { (upper, lower) ->
upper.groupBy { it.second.toDouble() / it.first }.size +
lower.groupBy { it.second.toDouble() / it.first }.size
}
}.max()
fun part2(input: Set<Pair<Int, Int>>) =
input.map { a ->
(input - a).partition { it.second < a.second }.let { (upper, lower) ->
val (upperLeft, upperRight) = upper.partition { it.first < a.first }
val (lowerLeft, lowerRight) = lower.partition { it.first < a.first }
listOf(
upperRight,
lowerRight,
lowerLeft,
upperLeft
)
.flatMap {
it.groupBy { (it.second - a.second).toDouble() / ((it.first - a.first)) }
.toSortedMap()
.values
}
.map {
it.sortedBy { abs(it.second - a.second) + abs(it.first - a.first) }.toMutableList()
}.toMutableList()
}
}.maxBy { it.count() }?.iterator()?.run {
repeat(200 - 1) {
next().let {
it.removeAt(0)
if (it.isEmpty()) {
remove()
}
}
}
next().first().let { it.first * 100 + it.second }
}
| 0 | Kotlin | 0 | 0 | d1a5bfbbc85716d0a331792b59cdd75389cf379f | 2,022 | AOC2019 | MIT License |
src/main/kotlin/advent2019/day12/day12.kt | davidpricedev | 225,621,794 | false | null | package advent2019.day12
import advent2019.util.lcm
import kotlin.math.absoluteValue
/**
* Might be another use case for generateSequence?
* Logic for calculating the velocity has to be aware of the entire system.
* For every axis of every moon we'll have to calculate how all the other moons affect it to calculate the next velocity
* velocity in the examples is trailing - i.e. we are looking at velocity that got us to the current position, not the next velocity
* ---
* For part2, maybe rather than simulating all 3 dimensions at once, we could do the same calculations for a single
* dimension at a time and find that dimension's periodicity, and then it should be a matter of calculatign the LCM
* to get the periodicity of the system as a whole.
*/
fun main() {
// part1
println(totalEnergy(advanceTime(getMoonsStart(), 1000)))
// part2
println(calculatePeriodicity(getMoonsStart()))
}
data class Point(val x: Int = 0, val y: Int = 0, val z: Int = 0) {
fun absSum() = x.absoluteValue + y.absoluteValue + z.absoluteValue
fun add(point: Point) = Point(x + point.x, y + point.y, z + point.z)
override fun toString(): String =
listOf(x, y, z).joinToString(prefix = "(", postfix = ")") { it.toString().padStart(3, ' ') }
}
data class Moon(val position: Point, val velocity: Point = Point()) {
fun totalEnergy() = position.absSum() * velocity.absSum()
fun applyVelocity() = Moon(position.add(velocity), velocity)
override fun toString(): String = "$position, $velocity"
}
fun advanceTime(moons: List<Moon>, timeCount: Int): List<Moon> {
val sequences = generateSequence(Pair(moons, 0)) {
// println("-- time step ${it.second} --")
// it.first.forEach { m -> println(m) }
Pair(advanceTime(it.first), it.second + 1).takeIf { it.second <= timeCount }
}.toList()
return sequences.last().first
}
fun advanceTime(moons: List<Moon>) = applyVelocity(calculateVelocity(moons))
fun applyVelocity(moons: List<Moon>) = moons.map { it.applyVelocity() }
fun calculateVelocity(moons: List<Moon>): List<Moon> {
val xs = moons.map { it.position.x }
val ys = moons.map { it.position.y }
val zs = moons.map { it.position.z }
return moons.map { moon ->
Moon(moon.position, velocity = nextVelocity(moon, xs, ys, zs))
}
}
fun nextVelocity(moon: Moon, xs: List<Int>, ys: List<Int>, zs: List<Int>): Point {
return Point(
oneDimDeltaV(moon.position.x, moon.velocity.x, xs),
oneDimDeltaV(moon.position.y, moon.velocity.y, ys),
oneDimDeltaV(moon.position.z, moon.velocity.z, zs)
)
}
fun oneDimDeltaV(pos: Int, velocity: Int, others: List<Int>) =
velocity + others.filter { it > pos }.count() - others.filter { it < pos }.count()
fun totalEnergy(moons: List<Moon>) = moons.sumBy { it.totalEnergy() }
fun calculatePeriodicity(moons: List<Moon>): Long {
val moonsX = moons.map { Moon1d(it.position.x, it.velocity.x) }
val px = getPeriodicity1d(moonsX)
val moonsY = moons.map { Moon1d(it.position.y, it.velocity.y) }
val py = getPeriodicity1d(moonsY)
val moonsZ = moons.map { Moon1d(it.position.z, it.velocity.z) }
val pz = getPeriodicity1d(moonsZ)
println("results: ${px}, ${py}, ${pz}")
return lcm(lcm(px.toLong(), py.toLong()), pz.toLong())
}
data class Moon1d(val position: Int, val velocity: Int = 0) {
fun applyVelocity1d() = Moon1d(position + velocity, velocity)
override fun toString(): String = "$position, $velocity"
}
fun getPeriodicity1d(moons: List<Moon1d>): Int {
val sequences = generateSequence(moons) {
// println("-- time step --")
// it.forEach { m -> println(m) }
val next = applyVelocity1d(calculateVelocity1d(it))
next.takeIf { !stateMatches(next, moons) }
}
return sequences.count()
}
fun stateMatches(moonsA: List<Moon1d>, moonsB: List<Moon1d>): Boolean {
val moonsAStr = moonsA.map { it.toString() }.joinToString(separator = ";")
val moonsBStr = moonsB.map { it.toString() }.joinToString(separator = ";")
return moonsAStr == moonsBStr
}
fun applyVelocity1d(moons: List<Moon1d>) = moons.map { it.applyVelocity1d() }
fun calculateVelocity1d(moons: List<Moon1d>): List<Moon1d> {
val xs = moons.map { it.position }
return moons.map { moon ->
Moon1d(moon.position, velocity = nextVelocity1d(moon, xs))
}
}
fun nextVelocity1d(moon: Moon1d, xs: List<Int>) = oneDimDeltaV(moon.position, moon.velocity, xs)
fun getMoonsStart() = listOf(
Moon(Point(x = -1, y = 7, z = 3)),
Moon(Point(x = 12, y = 2, z = -13)),
Moon(Point(x = 14, y = 18, z = -8)),
Moon(Point(x = 17, y = 4, z = -4))
)
fun getSample1MoonsStart() = listOf(
Moon(Point(-1, 0, 2)),
Moon(Point(2, -10, -7)),
Moon(Point(4, -8, -8)),
Moon(Point(3, 5, -1))
) | 0 | Kotlin | 0 | 0 | 2283647e5b4ed15ced27dcf2a5cf552c7bd49ae9 | 4,831 | adventOfCode2019 | Apache License 2.0 |
y2022/src/main/kotlin/adventofcode/y2022/Day17.kt | Ruud-Wiegers | 434,225,587 | false | {"Kotlin": 503769} | package adventofcode.y2022
import adventofcode.io.AdventSolution
import adventofcode.util.collections.cycle
import adventofcode.util.collections.takeWhileDistinct
import adventofcode.util.vector.Direction
import adventofcode.util.vector.Vec2
object Day17 : AdventSolution(2022, 17, "Pyroclastic Flow") {
override fun solvePartOne(input: String): Int {
val jets: Iterator<Vec2> = input
.map { if (it == '<') Direction.LEFT.vector else Direction.RIGHT.vector }
.cycle()
.iterator()
val blocks = Tetris.values()
.map(Tetris::toPoints)
.cycle()
.take(2022)
val playingField = (0..6).map { Vec2(it, 0) }.toMutableSet()
for (block: Set<Vec2> in blocks) {
val floor = playingField.maxOf { it.y }
var positionedBlock = block.map { it + Vec2(2, floor + 4) }
while (true) {
val moveSideways = jets.next().let { push -> positionedBlock.map { it + push } }
if (moveSideways.all { it.x in 0..6 } && moveSideways.none { it in playingField }) {
positionedBlock = moveSideways
}
val moveDown = positionedBlock.map { it + Direction.UP.vector }
if (moveDown.none { it in playingField }) {
positionedBlock = moveDown
} else {
playingField += positionedBlock
break
}
}
}
return playingField.maxOf { it.y }
}
override fun solvePartTwo(input: String): Long {
val jets: List<Vec2> = input
.map { if (it == '<') Direction.LEFT.vector else Direction.RIGHT.vector }
val blocks = Tetris.values().map(Tetris::toPoints)
val playingField = (0..6).map { Vec2(it, 0) }
val seq = generateSequence(State(0, 0, 0, playingField.toSet())) { state ->
buildNextState(state, blocks, jets)
}
.takeWhileDistinct()
.toList()
val blocksToDrop = 1_000_000_000_000
var floors = seq.sumOf { it.shifted }.toLong()
val cycle = generateSequence(buildNextState(seq.last(), blocks, jets)) {
buildNextState(it, blocks, jets)
}.takeWhileDistinct().toList()
val cycleCount = (blocksToDrop - seq.size) / cycle.size
floors += cycle.sumOf { it.shifted } * cycleCount
val rem = generateSequence(buildNextState(cycle.last(), blocks, jets)) { buildNextState(it, blocks, jets) }
.take(((blocksToDrop - seq.size) % cycle.size).toInt() + 1).toList()
floors += rem.sumOf { it.shifted }
floors += rem.last().field.maxOf { it.y }
return floors
}
private fun buildNextState(state: State, blocks: List<Set<Vec2>>, jets: List<Vec2>): State {
var jetPos = state.jet
val floor = state.field.maxOf { it.y }
var positionedBlock = blocks[state.block].map { it + Vec2(2, floor + 4) }
while (true) {
val moveSideways = jets[jetPos++].let { push -> positionedBlock.map { it + push } }
jetPos %= jets.size
if (moveSideways.all { it.x in 0..6 } && moveSideways.none { it in state.field }) {
positionedBlock = moveSideways
}
val moveDown = positionedBlock.map { it + Direction.UP.vector }
if (moveDown.none { it in state.field }) {
positionedBlock = moveDown
} else {
break
}
}
val newField = (state.field + positionedBlock)
val shift = (newField.maxOf { it.y } - 50).coerceAtLeast(0)
val clippedField = newField.map { it - Vec2(0, shift) }.filter { it.y >= 0 }
return State(jetPos, (state.block + 1) % blocks.size, shift, clippedField.toSet())
}
private data class State(val jet: Int, val block: Int, val shifted: Int, val field: Set<Vec2>)
private enum class Tetris(val blocks: List<List<Boolean>>) {
Line("####"),
Plus(" # \n###\n # "),
Hook(" #\n #\n###"),
Beam("#\n#\n#\n#"),
Square("##\n##");
constructor(string: String) : this(string.lines().reversed().map { it.map { it == '#' } })
fun toPoints() = blocks.flatMapIndexed { y, row ->
row.mapIndexed { x, isSolid -> Vec2(x, y).takeIf { isSolid } }
}.filterNotNull().toSet()
}
} | 0 | Kotlin | 0 | 3 | fc35e6d5feeabdc18c86aba428abcf23d880c450 | 4,474 | advent-of-code | MIT License |
src/Day03.kt | astrofyz | 572,802,282 | false | {"Kotlin": 124466} | fun main() {
fun Char.priority(): Int {
return when (this.isUpperCase()){
true -> this - 'A' + 27
else -> this - 'a' + 1
}
}
fun part1(input: List<String>): Int {
val res = input.flatMap { rucksack ->
rucksack.take(rucksack.length / 2).toSet() intersect rucksack.takeLast(rucksack.length / 2).toSet()
}.sumOf { it.priority() }
return res
}
fun part2(input: List<String>): Int {
val res = input.chunked(3).flatMap { rucksack -> rucksack[0]
.toSet()
.intersect(rucksack[1].toSet())
.intersect(rucksack[2].toSet()) }.sumOf { it.priority() }
return res
}
// 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 | a0bc190b391585ce3bb6fe2ba092fa1f437491a6 | 982 | aoc22 | Apache License 2.0 |
src/Day05.kt | slawa4s | 573,050,411 | false | {"Kotlin": 20679} | import java.util.Stack
fun main() {
fun getInitialStacks(input: List<String>): List<ArrayDeque<Char>> {
val filteredInput = input.map { it.toList().filterIndexed { index, _ -> index % 4 == 1 } }
val stacks: List<ArrayDeque<Char>> = List(filteredInput[0].size) { ArrayDeque() }
for (indexOfLine in filteredInput.lastIndex - 1 downTo 0) {
for (indexOfStack in filteredInput[indexOfLine].indices) {
if (filteredInput[indexOfLine][indexOfStack] != ' ') stacks[indexOfStack].add(filteredInput[indexOfLine][indexOfStack])
}
}
return stacks
}
fun makeOneMoveOldVersion(howMany: Int, stackFromIndex: Int, stackToIndex: Int, stacks: List<ArrayDeque<Char>>) {
for (i in 1..howMany) {
stacks[stackToIndex].addLast(stacks[stackFromIndex].removeLastOrNull()!!)
}
}
fun makeOneMoveNewVersion(howMany: Int, stackFromIndex: Int, stackToIndex: Int, stacks: List<ArrayDeque<Char>>) {
val optionalStack: ArrayDeque<Char> = ArrayDeque()
for (i in 1..howMany) {
optionalStack.addLast(stacks[stackFromIndex].removeLastOrNull()!!)
}
for (i in 1..howMany) {
stacks[stackToIndex].addLast(optionalStack.removeLastOrNull()!!)
}
}
fun getAnswer(stacks: List<ArrayDeque<Char>>): String {
val answer = mutableListOf<Char>()
for (stack in stacks) {
answer.add(stack.last())
}
return answer.joinToString(separator = "")
}
fun splitInput(realInput: List<String>): Pair<List<String>, List<String>> {
var separator = 0
val groupedInput = realInput.groupBy {
if (it == "") separator += 1
separator
}
.values.toList()
return Pair(groupedInput[0], groupedInput[1].slice(1..groupedInput[1].lastIndex))
}
fun part1(stackInput: List<String>, moveInput: List<String>): String {
val stacks: List<ArrayDeque<Char>> = getInitialStacks(stackInput)
moveInput.forEach {
val args = it.split(" ")
makeOneMoveOldVersion(Integer.parseInt(args[1]), Integer.parseInt(args[3]) - 1, Integer.parseInt(args[5]) - 1, stacks)
}
return getAnswer(stacks)
}
fun part2(stackInput: List<String>, moveInput: List<String>): String {
val stacks: List<ArrayDeque<Char>> = getInitialStacks(stackInput)
moveInput.forEach {
val args = it.split(" ")
makeOneMoveNewVersion(Integer.parseInt(args[1]), Integer.parseInt(args[3]) - 1, Integer.parseInt(args[5]) - 1, stacks)
}
return getAnswer(stacks)
}
val (stackInput, moveInput) = splitInput(readInput("Day05"))
println(part1(stackInput, moveInput))
println(part2(stackInput, moveInput))
}
| 0 | Kotlin | 0 | 0 | cd8bbbb3a710dc542c2832959a6a03a0d2516866 | 2,848 | aoc-2022-in-kotlin | Apache License 2.0 |
src/Day22.kt | davidkna | 572,439,882 | false | {"Kotlin": 79526} | import arrow.core.Either
private enum class Facing {
Right, Down, Left, Up
}
private enum class Turn {
Left, Right
}
fun main() {
fun parseInput(input: List<List<String>>): Pair<Map<Pair<Int, Int>, Boolean>, List<Either<Int, Turn>>> {
val map = input[0].mapIndexed { y, line ->
line.withIndex().filter { x -> x.value != ' ' }.map { x ->
Pair(y + 1, x.index + 1) to (x.value == '.')
}
}.flatten().toMap()
val insString = input[1][0]
val instructions: MutableList<Either<Int, Turn>> = mutableListOf()
var leftPointer = 0
for (i in insString.indices) {
when (val c = insString[i]) {
'L', 'R' -> {
if (leftPointer != i) {
instructions.add(Either.Left(insString.substring(leftPointer, i).toInt()))
}
instructions.add(Either.Right(if (c == 'L') Turn.Left else Turn.Right))
leftPointer = i + 1
}
else -> {}
}
}
if (leftPointer != insString.length) {
instructions.add(Either.Left(insString.substring(leftPointer).toInt()))
}
return Pair(map, instructions)
}
fun part1(input: List<List<String>>): Int {
val (map, instructions) = parseInput(input)
var current = map.filter { it.key.first == 1 }.minBy { it.key.second }.key
var facing = Facing.Right
for (ins in instructions.withIndex()) {
when (val d = ins.value) {
is Either.Left -> {
val (y, x) = current
val (dy, dx) = when (facing) {
Facing.Right -> Pair(0, 1)
Facing.Down -> Pair(1, 0)
Facing.Left -> Pair(0, -1)
Facing.Up -> Pair(-1, 0)
}
for (i in 0 until d.value) {
var next = Pair(current.first + dy, current.second + dx)
if (next !in map) {
next = when (facing) {
Facing.Right -> map.keys.filter { it.first == y }.minBy { it.second }
Facing.Down -> map.keys.filter { it.second == x }.minBy { it.first }
Facing.Left -> map.keys.filter { it.first == y }.maxBy { it.second }
Facing.Up -> map.keys.filter { it.second == x }.maxBy { it.first }
}
}
if (!map[next]!!) {
break
}
current = next
}
}
is Either.Right -> {
facing = when (facing) {
Facing.Right -> if (d.value == Turn.Left) Facing.Up else Facing.Down
Facing.Down -> if (d.value == Turn.Left) Facing.Right else Facing.Left
Facing.Left -> if (d.value == Turn.Left) Facing.Down else Facing.Up
Facing.Up -> if (d.value == Turn.Left) Facing.Left else Facing.Right
}
}
}
}
return 1000 * current.first + 4 * current.second + facing.ordinal
}
fun wrapPart2(pos: Pair<Int, Int>, facing: Facing): Pair<Pair<Int, Int>, Facing> {
val (y, x) = pos
return if (y in 1..50 && x in 51..100) {
when (facing) {
Facing.Left -> {
((151 - y to 1) to Facing.Right)
}
Facing.Up -> {
((x + 100 to 1) to Facing.Right)
}
else -> {
throw RuntimeException("pos=($y, $x), facing=$facing")
}
}
} else if (y in 1..50 && x in 101..150) {
when (facing) {
Facing.Right -> {
((151 - y to 100) to Facing.Left)
}
Facing.Down -> {
((x - 50 to 100) to Facing.Left)
}
Facing.Up -> {
((200 to x - 100) to Facing.Up)
}
else -> {
throw RuntimeException("pos=($y, $x), facing=$facing")
}
}
} else if (y in 51..100 && x in 51..100) {
when (facing) {
Facing.Right -> {
((50 to y + 50) to Facing.Up)
}
Facing.Left -> {
((101 to y - 50) to Facing.Down)
}
else -> {
throw RuntimeException("pos=($y, $x), facing=$facing")
}
}
} else if (y in 101..150 && x in 51..100) {
when (facing) {
Facing.Right -> {
((151 - y to 150) to Facing.Left)
}
Facing.Down -> {
((x + 100 to 50) to Facing.Left)
}
else -> {
throw RuntimeException("pos=($y, $x), facing=$facing")
}
}
} else if (y in 101..150 && x in 1..50) {
return when (facing) {
Facing.Left -> {
((151 - y to 51) to Facing.Right)
}
Facing.Up -> {
((x + 50 to 51) to Facing.Right)
}
else -> {
throw RuntimeException("pos=($y, $x), facing=$facing")
}
}
} else if (y in 151..200 && x in 1..50) {
when (facing) {
Facing.Right -> {
return ((150 to y - 100) to Facing.Up)
}
Facing.Down -> {
return ((1 to x + 100) to Facing.Down)
}
Facing.Left -> {
return ((1 to y - 100) to Facing.Down)
}
else -> {
throw RuntimeException("pos=($y, $x), facing=$facing")
}
}
} else {
throw RuntimeException("pos=($y, $x), facing=$facing")
}
}
fun part2(input: List<List<String>>): Int {
val (map, instructions) = parseInput(input)
var current = map.filter { it.key.first == 1 }.minBy { it.key.second }.key
var facing = Facing.Right
for (ins in instructions.withIndex()) {
when (val d = ins.value) {
is Either.Left -> {
for (i in 0 until d.value) {
val (y, x) = current
val (dy, dx) = when (facing) {
Facing.Right -> Pair(0, 1)
Facing.Down -> Pair(1, 0)
Facing.Left -> Pair(0, -1)
Facing.Up -> Pair(-1, 0)
}
var next = Pair(y + dy, x + dx)
var nextFacing = facing
if (next !in map) {
val (newPos, newF) = wrapPart2(current, facing)
next = newPos
nextFacing = newF
}
if (!map[next]!!) {
break
}
facing = nextFacing
current = next
}
}
is Either.Right -> {
facing = when (facing) {
Facing.Right -> if (d.value == Turn.Left) Facing.Up else Facing.Down
Facing.Down -> if (d.value == Turn.Left) Facing.Right else Facing.Left
Facing.Left -> if (d.value == Turn.Left) Facing.Down else Facing.Up
Facing.Up -> if (d.value == Turn.Left) Facing.Left else Facing.Right
}
}
}
}
return 1000 * current.first + 4 * current.second + facing.ordinal
}
val testInput = readInputDoubleNewline("Day22_test")
check(part1(testInput) == 6032)
val input = readInputDoubleNewline("Day22")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | ccd666cc12312537fec6e0c7ca904f5d9ebf75a3 | 8,474 | aoc-2022 | Apache License 2.0 |
src/Day16.kt | jwklomp | 572,195,432 | false | {"Kotlin": 65103} | data class Valve(val id: String, val rate: Int, val vertexIds: List<String>)
fun makeValveSpecs(input: List<String>): Map<String, Valve> = input.map {
val regex = """Valve ([\w\s]+) has flow rate=(\d+); tunnels? leads? to valves? ([A-Z, ]+)""".toRegex()
val matchResult = regex.find(it)
val (id, rate, vertexString) = matchResult!!.destructured
val valve = Valve(id = id, rate = rate.toInt(), vertexIds = vertexString.split(", "))
id to valve
}.toMap()
const val total_time = 10
data class State(val current: Valve, val valves: List<Valve>, val time: Int)
fun dfs(
currentValve: Valve,
currentTime: Int,
totalPressure: Int,
openValves: List<Valve>,
valveMap: Map<String, Valve>,
memoizedStates: MutableMap<State, Int>
): Int {
println("Entering dfs. CurrentTime: $currentTime, currentValve: $currentValve")
// Time is up: return the result. Note that this will bubble up the value from N levels deep right to the top.
if (currentTime == total_time) {
return totalPressure
}
// If state has been computed before return it
val memoizationKey = State(currentValve, openValves, currentTime)
when (val state = memoizedStates[memoizationKey]) {
null -> {}
else -> return state
}
println("Going to calculate newBest")
val newBest = when {
// open current valve rate > 0 and not already open. Stay in current and time increments
currentValve.rate > 0 && !openValves.contains(currentValve) -> dfs(
currentValve = currentValve,
currentTime = currentTime + 1,
totalPressure = totalPressure + openValves.sumOf { it.rate },
openValves = openValves + currentValve,
valveMap = valveMap,
memoizedStates = memoizedStates
)
// find connected Valve with the maximum pressure by recursively calling the function on each child Valve and returning the maximum
else -> currentValve.vertexIds.maxOf { child: String ->
val childFromMap = valveMap[child]!!
dfs(
currentValve = childFromMap,
currentTime = currentTime + 1,
totalPressure = totalPressure + openValves.sumOf { it.rate },
openValves = openValves,
valveMap = valveMap,
memoizedStates = memoizedStates
)
}
}
// add calculated state to the memoization Map
println("After recursive call newBest. Result: $newBest")
memoizedStates[memoizationKey] = newBest
return newBest
}
fun main() {
fun part1(input: List<String>): Int {
val valves = makeValveSpecs(input)
val entry = valves["AA"]!!
// state and score for given state
val memoizedState = mutableMapOf<State, Int>()
return dfs(
currentValve = entry,
currentTime = 0,
totalPressure = 0,
openValves = listOf(),
valveMap = valves,
memoizedStates = memoizedState
)
}
fun part2(input: List<String>): Int {
val result = input.map { it.split(",") }
println(result)
return 1
}
val testInput = readInput("Day16_test_small")
println(part1(testInput))
//println(part2(testInput))
val input = readInput("Day16")
//println(part1(input))
//println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 1b1121cfc57bbb73ac84a2f58927ab59bf158888 | 3,411 | aoc-2022-in-kotlin | Apache License 2.0 |
src/Day07.kt | cnietoc | 572,880,374 | false | {"Kotlin": 15990} | fun main() {
fun processRoot(input: List<String>): Directory {
val root = Directory(null, null)
var currentDirectory = root
val lastCommand = ArrayDeque<String>()
val inputIterator = input.iterator()
while (inputIterator.hasNext() || lastCommand.isNotEmpty()) {
val commandLine = if (inputIterator.hasNext()) inputIterator.next() else null
if (commandLine == null || commandLine.startsWith('$')) {
val command = lastCommand.removeFirstOrNull()
when {
command?.startsWith("$ cd") == true -> {
currentDirectory = currentDirectory.goTo(command.split(" ")[2])
}
command == "$ ls" -> {
lastCommand.forEach {
val file = it.split(" ")
when {
file[0].toLongOrNull() != null -> {
currentDirectory.addFile(name = file[1], size = file[0].toLong())
}
file[0] == "dir" -> {
currentDirectory.addDirectory(file[1])
}
}
}
}
}
lastCommand.clear()
}
if (commandLine != null) lastCommand.addLast(commandLine)
}
return root
}
fun part1(input: List<String>): Long {
val root = processRoot(input)
val sum = root.fold(0L) { sum, currentDirectory ->
val directorySize = currentDirectory.size()
return@fold if (directorySize < 100000L) {
sum + directorySize
} else sum
}
return sum
}
fun part2(input: List<String>): Long {
val root = processRoot(input)
val deviceSize = 70000000
val freeSpaceRequired = 30000000
val directoryToDelete =
root.filter { root.size() - it.size() < deviceSize - freeSpaceRequired }.minBy { it.size() }
return directoryToDelete.size()
}
val testInput = readInput("Day07_test")
val input = readInput("Day07")
check(part1(testInput) == 95437L)
println(part1(input))
check(part2(testInput) == 24933642L)
println(part2(input))
}
class Directory(private val parent: Directory?, private val root: Directory?) : Iterable<Directory> {
fun goTo(directoryName: String): Directory = when (directoryName) {
"/" -> root ?: this
".." -> parent ?: root ?: this
else -> dirs.getValue(directoryName)
}
fun addFile(name: String, size: Long) {
files[name] = File(size, this)
}
fun addDirectory(name: String) {
dirs[name] = Directory(this, root)
}
private val files: MutableMap<String, File> = mutableMapOf()
private val dirs: MutableMap<String, Directory> = mutableMapOf()
override fun iterator(): Iterator<Directory> = DirectoryIterator(this)
fun size(): Long = files.values.sumOf { it.size } + dirs.values.sumOf { it.size() }
class DirectoryIterator(private val directory: Directory) : Iterator<Directory> {
var processed = false;
var dirsIterator = directory.dirs.values.flatten().iterator()
override fun hasNext(): Boolean = if (!processed) true
else dirsIterator.hasNext()
override fun next(): Directory {
return if (!processed) {
processed = true
directory
} else {
dirsIterator.next()
}
}
}
}
data class File(val size: Long, val parent: Directory)
| 0 | Kotlin | 0 | 0 | bbd8e81751b96b37d9fe48a54e5f4b3a0bab5da3 | 3,761 | aoc-2022 | Apache License 2.0 |
src/day25/Day25.kt | dkoval | 572,138,985 | false | {"Kotlin": 86889} | package day25
import readInput
private const val DAY_ID = "25"
fun main() {
val snafuToIntDigits = mapOf('=' to -2, '-' to -1, '0' to 0, '1' to 1, '2' to 2)
val intToSnafuDigits = mapOf(0 to '0', 1 to '1', 2 to '2', -2 to '=', -1 to '-')
fun snafuToInt(num: String): Long {
var ans = 0L
for (digit in num) {
ans *= 5
ans += snafuToIntDigits[digit]!!
}
return ans
}
fun intToSnafu(num: Long): String {
// x % 5 is in {0, 1, 2, 3, 4}
// now, remap the value to get a SNAFU digit
// 0 -> 0, 1 -> 1, 2 -> 2, 3 -> -2, 4 -> -1
fun lastSnafuDigit(x: Long): Int {
return ((x + 2) % 5 - 2).toInt()
}
var x = num
val sb = StringBuilder()
while (x > 0) {
val digit = lastSnafuDigit(x)
sb.append(intToSnafuDigits[digit])
x /= 5
x += if (digit < 0) 1 else 0
}
return sb.reverse().toString()
}
fun part1(input: List<String>): String {
val x = input.sumOf { snafuToInt(it) }
return intToSnafu(x)
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("day${DAY_ID}/Day${DAY_ID}_test")
check(part1(testInput) == "2=-1=0") // base10 = 4890, snafu = 2=-1=0
val input = readInput("day${DAY_ID}/Day${DAY_ID}")
println(part1(input)) // answer = 2-20=01--0=0=0=2-120
}
| 0 | Kotlin | 1 | 0 | 791dd54a4e23f937d5fc16d46d85577d91b1507a | 1,462 | aoc-2022-in-kotlin | Apache License 2.0 |
src/Day10/Day10.kt | martin3398 | 436,014,815 | false | {"Kotlin": 63436, "Python": 5921} | import java.util.*
fun main() {
val scores = mapOf(')' to 3, ']' to 57, '}' to 1197, '>' to 25137)
val opening = setOf('(', '[', '{', '<')
val closing = setOf(')', ']', '}', '>')
val openingFrom = mapOf(')' to '(', ']' to '[', '}' to '{', '>' to '<')
val closingFrom = mapOf('(' to 1, '[' to 2, '{' to 3, '<' to 4)
fun calcScore1(line: String): Int {
val queue = LinkedList<Char>()
for (e in line) {
if (opening.contains(e)) {
queue.add(e)
} else if (closing.contains(e)) {
if (queue.removeLast() != openingFrom[e]) {
return scores.getOrDefault(e, 0)
}
}
}
return 0
}
fun calcScore2(line: String): Long {
val queue = LinkedList<Char>()
for (e in line) {
if (opening.contains(e)) {
queue.add(e)
} else if (closing.contains(e)) {
queue.removeLast()
}
}
var res: Long = 0
while (!queue.isEmpty()) {
val next = queue.removeLast()
res *= 5
res += closingFrom.getOrDefault(next, 0)
}
return res
}
fun part1(input: List<String>): Int {
return input.sumOf { calcScore1(it) }
}
fun part2(input: List<String>): Long {
val inputWc = input.filter { calcScore1(it) == 0 }
return inputWc.map { calcScore2(it) }.sorted()[inputWc.size / 2]
}
val testInput = readInput(10, true)
val input = readInput(10)
check(part1(testInput) == 26397)
println(part1(input))
check(part2(testInput) == 288957L)
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 085b1f2995e13233ade9cbde9cd506cafe64e1b5 | 1,707 | advent-of-code-2021 | Apache License 2.0 |
app/src/main/kotlin/day10/Day10.kt | meli-w | 433,710,859 | false | {"Kotlin": 52501} | package day10
import common.InputRepo
import common.readSessionCookie
import common.solve
fun main(args: Array<String>) {
val day = 10
val input = InputRepo(args.readSessionCookie()).get(day = day)
solve(day, input, ::solveDay10Part1, ::solveDay10Part2)
}
fun solveDay10Part1(input: List<String>): Any = input
.mapNotNull { it.getFirstIllegalCharacter() }
.sumOf { it.points }
fun solveDay10Part2(input: List<String>): Any = input
.filter { it.getFirstIllegalCharacter() == null }
.map { it.getPointsForClosingString() }
.sorted()
.let { scores -> scores[scores.size / 2] }
fun String.getFirstIllegalCharacter(): Chunk? {
val stack: MutableList<Chunk> = mutableListOf()
this.forEach {
val chunk = it.getChunk()
when {
it.isOpening() -> stack.add(chunk)
else -> {
if (stack.last().isCorrectClosing(chunk)) {
stack.removeLast()
} else {
return chunk
}
}
}
}
return null
}
fun String.getPointsForClosingString(): Long {
val stack: MutableList<Chunk> = mutableListOf()
this.forEach {
val chunk = it.getChunk()
when {
it.isOpening() -> stack.add(chunk)
else -> {
if (stack.last().isCorrectClosing(chunk)) {
stack.removeLast()
}
}
}
}
return stack
.reversed()
.fold(0L) { acc, next ->
acc * 5 + next.missingPoints
}
}
enum class Chunk(
val opening: Char,
val closing: Char,
val points: Int,
val missingPoints: Int,
) {
ROUND('(', ')', points = 3, missingPoints = 1),
SQUARE('[', ']', points = 57, missingPoints = 2),
CURLY('{', '}', points = 1197, missingPoints = 3),
POINTY('<', '>', points = 25137, missingPoints = 4);
fun isCorrectClosing(chunk: Chunk): Boolean = this == chunk
}
fun Char.getChunk(): Chunk = when (this) {
Chunk.CURLY.opening, Chunk.CURLY.closing -> Chunk.CURLY
Chunk.POINTY.opening, Chunk.POINTY.closing -> Chunk.POINTY
Chunk.SQUARE.opening, Chunk.SQUARE.closing -> Chunk.SQUARE
Chunk.ROUND.opening, Chunk.ROUND.closing -> Chunk.ROUND
else -> error("OH NOOOOOO")
}
fun Char.isOpening(): Boolean = when (this) {
Chunk.CURLY.opening,
Chunk.POINTY.opening,
Chunk.SQUARE.opening,
Chunk.ROUND.opening -> true
else -> false
}
| 0 | Kotlin | 0 | 1 | f3b96c831d6c8e21de1ac866cf9c64aaae2e5ea1 | 2,487 | AoC-2021 | Apache License 2.0 |
y2015/src/main/kotlin/adventofcode/y2015/Day18.kt | Ruud-Wiegers | 434,225,587 | false | {"Kotlin": 503769} | package adventofcode.y2015
import adventofcode.io.AdventSolution
import kotlin.math.max
import kotlin.math.min
object Day18 : AdventSolution(2015, 18, "Like a GIF For Your Yard") {
override fun solvePartOne(input: String) = generateSequence(ConwayGrid(input), ConwayGrid::next)
.drop(100)
.first()
.countAlive()
override fun solvePartTwo(input: String) = generateSequence(ConwayGrid(input).stuckCorners()) { it.next().stuckCorners() }
.drop(100)
.first()
.countAlive()
}
private data class ConwayGrid(private val grid: List<BooleanArray>) {
constructor(input: String) : this(input.lines().map { line -> line.map { it == '#' }.toBooleanArray() })
fun next() = List(grid.size) { y ->
BooleanArray(grid[0].size) { x ->
aliveNext(x, y)
}
}.let(::ConwayGrid)
fun stuckCorners() = this.copy().apply {
val last = grid.lastIndex
grid[0][0] = true
grid[0][last] = true
grid[last][0] = true
grid[last][last] = true
}
fun countAlive() = grid.sumOf { it.count { row -> row } }
private fun aliveNext(x: Int, y: Int) = area(x, y) == 3 || grid[y][x] && area(x, y) == 4
private fun area(x: Int, y: Int): Int {
var count = 0
for (i in max(x - 1, 0)..min(x + 1, grid.lastIndex))
for (j in max(y - 1, 0)..min(y + 1, grid.lastIndex))
if (grid[j][i]) count++
return count
}
}
| 0 | Kotlin | 0 | 3 | fc35e6d5feeabdc18c86aba428abcf23d880c450 | 1,505 | advent-of-code | MIT License |
src/day15/Day15.kt | idle-code | 572,642,410 | false | {"Kotlin": 79612} | package day15
import Position
import logln
import logEnabled
import readInput
import java.lang.IllegalStateException
import java.lang.Math.abs
private const val DAY_NUMBER = 15
data class Sensor(val sensorPosition: Position, val beaconPosition: Position) {
private val distanceToBeacon: Int = sensorPosition.manhattanDistanceTo(beaconPosition)
val xSensingRange: IntRange = IntRange(
sensorPosition.x - distanceToBeacon,
sensorPosition.x + distanceToBeacon
)
fun couldSenseAt(position: Position): Boolean = sensorPosition.manhattanDistanceTo(position) <= distanceToBeacon
fun senseRangeAt(y: Int): IntRange? {
val yOffset = kotlin.math.abs(sensorPosition.y - y)
if (yOffset > distanceToBeacon)
return null
return IntRange(
sensorPosition.x - (distanceToBeacon - yOffset),
sensorPosition.x + (distanceToBeacon - yOffset)
)
}
}
val sensorLineRegex = """Sensor at x=(-?\d+), y=(-?\d+): closest beacon is at x=(-?\d+), y=(-?\d+)""".toRegex()
fun parseSensor(line: String): Sensor {
val (sensorX, sensorY, beaconX, beaconY) = sensorLineRegex.matchEntire(line)?.destructured
?: throw IllegalArgumentException("Invalid input line: $line")
return Sensor(Position(sensorX.toInt(), sensorY.toInt()), Position(beaconX.toInt(), beaconY.toInt()))
}
private fun List<IntRange>.isSingleRange(): Boolean {
val sortedRanges = this.sortedBy { it.first }
var lastRange = sortedRanges.first()
for (range in sortedRanges.drop(1)) {
if (range.first !in lastRange)
return false
if (range.last !in lastRange)
lastRange = range
}
return true
}
fun main() {
fun part1(rawInput: List<String>, y: Int): Int {
val sensors = rawInput.map { parseSensor(it) }
val minX = sensors.minOfOrNull { s -> s.xSensingRange.first }!! - 1
val maxX = sensors.maxOfOrNull { s -> s.xSensingRange.last }!! + 1
val emptyPositions = hashSetOf<Position>()
for (sensor in sensors) {
for (x in minX..maxX) {
val candidate = Position(x, y)
if (sensor.couldSenseAt(candidate) && candidate != sensor.beaconPosition)
emptyPositions.add(candidate)
}
}
return emptyPositions.size
}
fun part2(rawInput: List<String>, maxCoordinate: Int): Long {
val sensors = rawInput.map { parseSensor(it) }
for (y in 0..maxCoordinate) {
val isRowCovered = sensors.mapNotNull { s -> s.senseRangeAt(y) }.isSingleRange()
if (isRowCovered)
continue
// Scan row for actual signal
nextXCoordinate@ for (x in 0..maxCoordinate) {
for (sensor in sensors) {
val candidate = Position(x, y)
if (sensor.couldSenseAt(candidate)) {
continue@nextXCoordinate
}
}
return x * 4000000L + y
}
}
throw IllegalStateException("Distress signal tuning not found")
}
val sampleInput = readInput("sample_data", DAY_NUMBER)
val mainInput = readInput("main_data", DAY_NUMBER)
logEnabled = true
val part1SampleResult = part1(sampleInput, 10)
println(part1SampleResult)
check(part1SampleResult == 26)
val part1MainResult = part1(mainInput, 2000000)
println(part1MainResult)
check(part1MainResult == 4748135)
val part2SampleResult = part2(sampleInput, 20)
println(part2SampleResult)
check(part2SampleResult == 56000011L)
val part2MainResult = part2(mainInput, 4000000)
println(part2MainResult)
check(part2MainResult == 13743542639657)
}
| 0 | Kotlin | 0 | 0 | 1b261c399a0a84c333cf16f1031b4b1f18b651c7 | 3,783 | advent-of-code-2022 | Apache License 2.0 |
src/Day07.kt | kpilyugin | 572,573,503 | false | {"Kotlin": 60569} | import java.lang.IllegalStateException
sealed class FsEntity(val name: String) {
abstract val size: Int
}
class Dir(name: String, val parent: Dir?) : FsEntity(name) {
val children = mutableListOf<FsEntity>()
fun findChild(name: String): Dir =
children.find { it.name == name } as? Dir ?: throw IllegalStateException("Child directory $name not found")
override val size: Int
get() = children.sumOf { it.size }
}
class File(name: String, override val size: Int) : FsEntity(name)
fun main() {
fun walk(root: Dir, input: List<String>) {
var current = root
input.forEach {
val cmd = it.split(" ")
if (cmd[0] == "$") {
if (cmd[1] == "cd") {
current = when(cmd[2]) {
"/" -> root
".." -> current.parent ?: throw IllegalStateException("Cannot exit from root")
else -> current.findChild(cmd[2])
}
}
} else {
val child = if (cmd[0] == "dir") Dir(cmd[1], current) else File(cmd[1], cmd[0].toInt())
current.children += child
}
}
}
fun directorySizes(dir: Dir): Sequence<Int> = sequence {
yield(dir.size)
dir.children.filterIsInstance<Dir>().forEach {
yieldAll(directorySizes(it))
}
}
fun part1(input: List<String>): Int {
val root = Dir("root", null)
walk(root, input)
return directorySizes(root).filter { it < 100000 }.sum()
}
fun part2(input: List<String>): Int {
val root = Dir("root", null)
walk(root, input)
val removeAtLeast = root.size - 4e7
return directorySizes(root).filter { it >= removeAtLeast }.min()
}
val testInput = readInputLines("Day07_test")
check(part1(testInput) == 95437)
check(part2(testInput) == 24933642)
val input = readInputLines("Day07")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 1 | 7f0cfc410c76b834a15275a7f6a164d887b2c316 | 2,038 | Advent-of-Code-2022 | Apache License 2.0 |
src/day19/Code.kt | fcolasuonno | 572,734,674 | false | {"Kotlin": 63451, "Dockerfile": 1340} | package day19
import day06.main
import readInput
fun main() {
val ORE = 0
val CLAY = 1
val OBSIDIAN = 2
val GEODE = 3
data class Blueprint(
val time: Int = 24,
val resources: List<Int> = List(4) { 0 },
val robots: List<Int> = List(4) { if (it == ORE) 1 else 0 },
val costs: List<Int>
) {
private val oreRobotOreCost: Int = costs[0]
private val clayRobotOreCost: Int = costs[1]
private val obsidianRobotOreCost: Int = costs[2]
private val obsidianRobotClayCost: Int = costs[3]
private val geodeRobotOreCost: Int = costs[4]
private val geodeRobotObsidianCost: Int = costs[5]
private val maxOreCost = maxOf(oreRobotOreCost, clayRobotOreCost, obsidianRobotOreCost, geodeRobotOreCost)
fun maxGeodes(): Int {
val maxGeodeRobots = minOf(
(resources[ORE] + (0..time).sumOf { robots[ORE] + it }) / geodeRobotOreCost + 1,
(resources[OBSIDIAN] + (0..time).sumOf { robots[OBSIDIAN] + it }) / geodeRobotObsidianCost + 1,
time
)
return resources[GEODE] + (1..maxGeodeRobots).sumOf { robots[GEODE] + it } - 1
}
fun increaseRobots(): List<Blueprint> = buildList {
if (resources[ORE] >= geodeRobotOreCost && resources[OBSIDIAN] >= geodeRobotObsidianCost) {
// When possible to build a geodeRobot always do it (not sure why we can exclude all the other options)
add(copy(time = time - 1, resources = resources.mapIndexed { index, i ->
when (index) {
ORE -> i - geodeRobotOreCost
OBSIDIAN -> i - geodeRobotObsidianCost
else -> i
}
}.zip(robots, kotlin.Int::plus), robots = robots.mapIndexed { index, i ->
when (index) {
GEODE -> i + 1
else -> i
}
}))
} else {
add(copy(time = time - 1, resources = resources.zip(robots, kotlin.Int::plus)))
if (resources[ORE] >= oreRobotOreCost && robots[ORE] < maxOreCost) {
add(copy(time = time - 1, resources = resources.mapIndexed { index, i ->
when (index) {
ORE -> i - oreRobotOreCost
else -> i
}
}.zip(robots, kotlin.Int::plus), robots = robots.mapIndexed { index, i ->
when (index) {
ORE -> i + 1
else -> i
}
}))
}
if (resources[ORE] >= clayRobotOreCost && robots[CLAY] < obsidianRobotClayCost) {
add(copy(time = time - 1, resources = resources.mapIndexed { index, i ->
when (index) {
ORE -> i - clayRobotOreCost
else -> i
}
}.zip(robots, kotlin.Int::plus), robots = robots.mapIndexed { index, i ->
when (index) {
CLAY -> i + 1
else -> i
}
}))
}
if (resources[ORE] >= obsidianRobotOreCost && resources[CLAY] >= obsidianRobotClayCost && robots[OBSIDIAN] < geodeRobotObsidianCost) {
add(copy(time = time - 1, resources = resources.mapIndexed { index, i ->
when (index) {
ORE -> i - obsidianRobotOreCost
CLAY -> i - obsidianRobotClayCost
else -> i
}
}.zip(robots, kotlin.Int::plus), robots = robots.mapIndexed { index, i ->
when (index) {
OBSIDIAN -> i + 1
else -> i
}
}))
}
}
}
}
fun parse(input: List<String>) = input.map { blueprint ->
blueprint.split("""\D+""".toRegex()).mapNotNull { it.toIntOrNull() }.let {
Blueprint(costs = it.drop(1))
}
}
fun part1(input: List<Blueprint>) = input.mapIndexed { index, blueprint ->
val queue = ArrayDeque<Blueprint>()
queue.add(blueprint)
var maxGeodes = 0
while (queue.isNotEmpty()) {
val current = queue.removeLast()
maxGeodes = maxOf(maxGeodes, current.resources[GEODE])
if (current.time != 0 && current.maxGeodes() > maxGeodes) {
queue.addAll(current.increaseRobots())
}
}
(index + 1) * maxGeodes
}.sum()
fun part2(input: List<Blueprint>) = input.map { it.copy(time = 32) }.take(3).map { blueprint ->
val queue = ArrayDeque<Blueprint>()
queue.add(blueprint)
var maxGeodes = 0
while (queue.isNotEmpty()) {
val current = queue.removeLast()
maxGeodes = maxOf(maxGeodes, current.resources[GEODE])
if (current.time != 0 && current.maxGeodes() > maxGeodes) {
queue.addAll(current.increaseRobots())
}
}
maxGeodes
}.reduce(Int::times)
val input = parse(readInput(::main.javaClass.packageName))
println("Part1=\n" + part1(input))
println("Part2=\n" + part2(input))
} | 0 | Kotlin | 0 | 0 | 9cb653bd6a5abb214a9310f7cac3d0a5a478a71a | 5,600 | AOC2022 | Apache License 2.0 |
src/main/Day05.kt | ssiegler | 572,678,606 | false | {"Kotlin": 76434} | package day05
import utils.readInput
import java.util.*
typealias Stacks = List<Deque<Char>>
fun List<String>.stacks(): Stacks {
val lines = takeWhile { it.isNotBlank() }
val numberOfStacks = lines.last().splitToSequence(" +".toRegex()).last().toInt()
val stacks = (1..numberOfStacks).map { ArrayDeque<Char>() }
lines.reversed().drop(1).forEach {
it.chunked(4).withIndex().forEach { indexedValue ->
val crate = indexedValue.value[1]
if (crate != ' ') {
stacks[indexedValue.index].push(crate)
}
}
}
return stacks
}
fun List<String>.instructions(): List<String> = subList(indexOfFirst { it.isBlank() } + 1, size)
fun List<String>.rearrange(stacks: Stacks, step: (Int, Deque<Char>, Deque<Char>) -> Unit) =
forEach {
val (count, source, destination) =
"""move (\d+) from (\d+) to (\d+)""".toRegex().matchEntire(it)?.destructured
?: error("Invalid instruction: $it")
step(count.toInt(), stacks[source.toInt() - 1], stacks[destination.toInt() - 1])
}
fun part1(filename: String) =
filename.process { count, source, destination ->
repeat(count) { _ -> destination.push(source.pop()) }
}
private fun String.process(step: (Int, Deque<Char>, Deque<Char>) -> Unit): String {
val input = readInput(this)
val stacks = input.stacks()
input.instructions().rearrange(stacks, step)
return stacks.tops()
}
fun part2(filename: String) =
filename.process { count, source, destination ->
val buffer = ArrayDeque<Char>()
repeat(count) { _ -> buffer.push(source.pop()) }
repeat(count) { _ -> destination.push(buffer.pop()) }
}
private fun Stacks.tops(): String = joinToString("") { "${it.peek()}" }
private const val filename = "Day05"
fun main() {
println(part1(filename))
println(part2(filename))
}
| 0 | Kotlin | 0 | 0 | 9133485ca742ec16ee4c7f7f2a78410e66f51d80 | 1,905 | aoc-2022 | Apache License 2.0 |
y2021/src/main/kotlin/adventofcode/y2021/Day20.kt | Ruud-Wiegers | 434,225,587 | false | {"Kotlin": 503769} | package adventofcode.y2021
import adventofcode.io.AdventSolution
object Day20 : AdventSolution(2021, 20, "Trench Map") {
override fun solvePartOne(input: String) = parse(input).let { (rules, grid) -> solve(rules, grid, 2) }
override fun solvePartTwo(input: String) = parse(input).let { (rules, grid) -> solve(rules, grid, 50) }
private fun solve(rules: List<Int>, grid: List<List<Int>>, steps: Int) =
generateSequence(grid to 0) { (old, default) ->
Pair(nextStep(old, rules, default), if (default == 1) rules.last() else rules[0])
}.elementAt(steps).first.sumOf { it.sum() }
private fun nextStep(grid: List<List<Int>>, rules: List<Int>, default: Int): List<List<Int>> {
fun get(x: Int, y: Int) = grid.getOrNull(y)?.getOrNull(x) ?: default
return List(grid.size + 2) { y ->
List(grid.size + 2) { x ->
var f = 0
for (row in y - 2..y)
for (col in x - 2..x)
f = f * 2 + get(col, row)
rules[f]
}
}
}
private fun parse(input: String): Pair<List<Int>, List<List<Int>>> {
val (rules, grid) = input.split("\n\n")
fun asInt(it: Char) = if (it == '#') 1 else 0
return rules.map(::asInt) to grid.lines().map { it.map(::asInt) }
}
} | 0 | Kotlin | 0 | 3 | fc35e6d5feeabdc18c86aba428abcf23d880c450 | 1,347 | advent-of-code | MIT License |
kotlin/src/main/kotlin/icfp2019/app.kt | AnushaSankara | 193,136,077 | true | {"JavaScript": 672516, "HTML": 5520, "Kotlin": 3029, "Python": 2607, "Rust": 45} | package icfp2019
import java.io.File
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
fun main() {
val workingDir: Path = Paths.get("")
val solutions = mutableListOf<Solution>()
readZipFile(File("problems.zip"))
.filter { it.file.isFile }
.forEach {
val problem = parseDesc(it)
val solution = solve(problem)
encodeSolution(solution, workingDir)
}
writeZip(workingDir, solutions)
}
fun writeZip(workingDir: Path, solutions: MutableList<Solution>) {
TODO("not implemented")
}
fun readZipFile(file: File): List<ProblemDescription> {
TODO("not implemented")
}
enum class Boosters {
B, F, L, X
}
data class Point(val x: Int, val y: Int)
data class Node(val point: Point, val isObstacle: Boolean, val booster: Boosters)
data class ProblemId(val id: Int)
data class ProblemDescription(val problemId: ProblemId, val file: File)
data class Problem(val problemId: ProblemId, val startingPosition: Point, val map: Array<Array<Node>>)
/*
Task:
1. Open Zip file
2. parse a problem at a time: prob_NNN.desc
3. solve problem
4. encode solution
5. output to file prob_NNN.sol (use checker to validate?) https://icfpcontest2019.github.io/solution_checker/
6. add solution to another zip (script/program)
*/
fun parseDesc(file: ProblemDescription): Problem {
// Read lines
/*
1. Read lines
2. Parse map
Grammar:
x,y: Nat
point ::= (x,y)
map ::= repSep(point,”,”)
BoosterCode ::= B|F|L|X
boosterLocation ::= BoosterCode point
obstacles ::= repSep(map,”; ”)
boosters ::= repSep(boosterLocation,”; ”)
task ::= map # point # obstacles # boosters
*/
return Problem(ProblemId(0), Point(0, 0), arrayOf())
}
/*
A solution for a task
prob-NNN.desc
is a sequence of actions encoded as a single-line text file named
prob-NNN.sol
for the corresponding numberNNN.
The actions are encoded as follows:
action ::=
W(move up)
| S(move down)
| A(move left)
| D(move right)
| Z(do nothing)
| E(turn manipulators 90°clockwise)
| Q(turn manipulators 90°counterclockwise)
| B(dx,dy)(attach a new manipulator with relative coordinates(dx,dy))
| F(attach fast wheels)
| L(start using a drill)
solution ::= rep(action)
A solution isvalid, if it does not force the worker-wrapper to go through the walls and obstacles
(unless it uses a drill), respects the rules of using boosters, and, upon finishing,
leaves all reachablesquares of the map wrapped.
*/
enum class Actions {
W, S, A, D, Z, E, Q, B, F, L
}
data class Solution(val problemId: ProblemId, val actions: List<Actions>)
fun solve(problem: Problem): Solution {
return Solution(problem.problemId, listOf())
}
fun encodeSolution(solution: Solution, directory: Path): File {
val file = Files.createFile(directory.resolve("prob-${solution.problemId.id}.sol"))
// TODO
return file.toFile()
}
| 0 | JavaScript | 0 | 0 | 93fb25e41a78c066c87f237d2896f57664cc66d5 | 3,012 | icfp-2019 | The Unlicense |
src/Day14.kt | flex3r | 572,653,526 | false | {"Kotlin": 63192} | import kotlin.math.max
import kotlin.math.min
fun main() {
val testInput = readInput("Day14_test")
check(part1(testInput) == 24)
check(part2(testInput) == 93)
val input = readInput("Day14")
println(part1(input))
println(part2(input))
}
private fun part1(input: List<String>): Int {
val (cave, abyssStart) = parseCave(input)
var sandIsLost = false
while(!sandIsLost) {
var (x,y) = CavePos(500, 0)
var placed = false
while(!placed) {
if (y >= abyssStart) {
sandIsLost = true
break
}
when (CaveMaterial.AIR) {
cave[y + 1][x] -> y++
cave[y + 1][x - 1] -> { y++; x-- }
cave[y + 1][x + 1] -> { y++; x++ }
else -> {
placed = true
cave[y][x] = CaveMaterial.SAND
}
}
}
}
return cave.sandCount
}
private fun part2(input: List<String>): Int {
val (cave, abyssStart) = parseCave(input)
val wallY = abyssStart + 2
cave[wallY].indices.forEach { x -> cave[wallY][x] = CaveMaterial.ROCK }
var sourceBlocked = false
while(!sourceBlocked) {
var (x, y) = CavePos(500, 0)
var placed = false
while(!placed) {
when (CaveMaterial.AIR) {
cave[y + 1][x] -> y++
cave[y + 1][x - 1] -> { y++; x-- }
cave[y + 1][x + 1] -> { y++; x++ }
else -> {
placed = true
cave[y][x] = CaveMaterial.SAND
if (x == 500 && y == 0) sourceBlocked = true
}
}
}
}
return cave.sandCount
}
private fun parseCave(input: List<String>): CaveData {
val paths = input.flatMap { line ->
line.split(" -> ").windowed(2).map { (start, end) ->
val (startX, startY) = start.split(",")
val (endX, endY) = end.split(",")
CavePath(CavePos(startX.toInt(), startY.toInt()), CavePos(endX.toInt(), endY.toInt()))
}
}
val cave = MutableList(200) { MutableList(750) { CaveMaterial.AIR } }
cave[0][500] = CaveMaterial.SOURCE
val abyssStart = paths.maxOfOrNull { max(it.start.y, it.end.y) }!!
paths.forEach { (start, end) ->
val minY = min(start.y, end.y)
val minX = min(start.x, end.x)
val maxY = max(start.y, end.y)
val maxX = max(start.x, end.x)
(minX..maxX).forEach { x ->
(minY..maxY).forEach { y ->
cave[y][x] = CaveMaterial.ROCK
}
}
}
return CaveData(cave, abyssStart)
}
private enum class CaveMaterial {
AIR,
ROCK,
SAND,
SOURCE
}
private data class CavePos(val x: Int, val y: Int)
private data class CavePath(val start: CavePos, val end: CavePos)
private data class CaveData(val paths: MutableList<MutableList<CaveMaterial>>, val abyssStart: Int)
private val List<List<CaveMaterial>>.sandCount get() = sumOf { line -> line.count { it == CaveMaterial.SAND } } | 0 | Kotlin | 0 | 0 | 8604ce3c0c3b56e2e49df641d5bf1e498f445ff9 | 3,090 | aoc-22 | Apache License 2.0 |
src/Day07.kt | jwalter | 573,111,342 | false | {"Kotlin": 19975} | import kotlin.math.abs
fun main() {
data class Dir(
val name: String,
val parent: Dir?,
var ownSize: Int = 0,
val children: MutableList<Dir> = mutableListOf(),
var totalSize: Int = 0
)
fun parseInput(input: List<String>): Dir {
val root = Dir("/", null)
var cd = root
input.drop(1).forEach {
when {
it.startsWith("\$ cd ..") -> cd = cd.parent!!
it.startsWith("\$ cd") -> cd = cd.children.first { ch -> ch.name == it.substring(5) }
it.startsWith("dir") -> cd.children.add(Dir(it.substring(4), cd))
it.startsWith("\$ ls") -> {}
else -> cd.ownSize += it.split(" ")[0].toInt()
}
}
return root
}
fun flatten(l: List<Dir>): List<Dir> {
return l.flatMap { flatten(it.children) } + l
}
fun computeTotalSize(d: Dir): Int {
d.totalSize = d.ownSize + d.children.sumOf { computeTotalSize(it) }
return d.totalSize
}
fun part1(input: List<String>): Int {
val root = parseInput(input)
val dirs = flatten(root.children)
dirs.forEach { computeTotalSize(it) }
val sumOf = dirs.filter { it.totalSize <= 100000 }.sumOf { it.totalSize }
return sumOf
}
fun part2(input: List<String>): Int {
val root = parseInput(input)
val dirs = flatten(root.children) + root
dirs.forEach { computeTotalSize(it) }
val missingSpace = abs(40000000 - root.totalSize)
return dirs.filter { it.totalSize > missingSpace }.minOf { it.totalSize }
}
val testInput = readInput("Day07_test")
check(part1(testInput) == 95437)
check(part2(testInput) == 24933642)
val input = readInput("Day07")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 576aeabd297a7d7ee77eca9bb405ec5d2641b441 | 1,856 | adventofcode2022 | Apache License 2.0 |
src/main/kotlin/de/pgebert/aoc/days/Day12.kt | pgebert | 724,032,034 | false | {"Kotlin": 65831} | package de.pgebert.aoc.days
import de.pgebert.aoc.Day
class Day12(input: String? = null) : Day(12, "Hot Springs", input) {
override fun partOne() = inputList.sumOf { line ->
val splitted = line.split(" ")
val configuration = splitted.first()
val specification = splitted.last().split(",").map { it.toInt() }
countPossibleMatches(configuration, specification)
}
override fun partTwo() = inputList.sumOf { line ->
val splitted = line.split(" ")
val configuration = buildList { repeat(5) { add(splitted.first()) } }.joinToString("?")
val specification = buildList { repeat(5) { addAll(splitted.last().split(",").map { it.toInt() }) } }
countPossibleMatches(configuration, specification)
}
private fun countPossibleMatches(text: String, numbers: List<Int>): Long {
val states = buildString {
append(".")
numbers.forEach { number ->
repeat(number) { append("#") }
append(".")
}
}
var countByState = mutableMapOf(0 to 1L)
var newCountByState = mutableMapOf<Int, Long>()
text.forEach { character ->
countByState.forEach { (state, count) ->
if (character == '?') {
// move to next state
if (state + 1 < states.length) {
newCountByState[state + 1] = newCountByState.getOrDefault(state + 1, 0) + count
}
// stay in current state
if (states[state] == '.') {
newCountByState[state] = newCountByState.getOrDefault(state, 0) + count
}
} else if (character == '.') {
// move to next state
if (state + 1 < states.length && states[state + 1] == '.') {
newCountByState[state + 1] = newCountByState.getOrDefault(state + 1, 0) + count
}
// stay in current state
if (states[state] == '.') {
newCountByState[state] = newCountByState.getOrDefault(state, 0) + count
}
} else if (character == '#') {
// move to next state
if (state + 1 < states.length && states[state + 1] == '#') {
newCountByState[state + 1] = newCountByState.getOrDefault(state + 1, 0) + count
}
}
}
countByState = newCountByState
newCountByState = mutableMapOf()
}
return (countByState.getOrDefault(states.length - 1, 0) + countByState.getOrDefault(states.length - 2, 0))
}
}
| 0 | Kotlin | 1 | 0 | a30d3987f1976889b8d143f0843bbf95ff51bad2 | 2,783 | advent-of-code-2023 | MIT License |
src/main/kotlin/d23/D23_2.kt | MTender | 734,007,442 | false | {"Kotlin": 108628} | package d23
import input.Input
class D23_2 {
companion object {
private fun removeAllSlopes(lines: List<String>): List<String> {
return lines.map { it.replace("[<>v^]".toRegex(), ".") }
}
private fun findIntersections(lines: List<String>): List<Pair<Int, Int>> {
val intersections = mutableListOf<Pair<Int, Int>>()
for (i in 1..<lines.lastIndex) {
for (j in 1..<lines[i].lastIndex) {
val loc = Pair(i, j)
if (isIntersection(lines, loc)) intersections.add(loc)
}
}
return intersections
}
private fun isIntersection(lines: List<String>, loc: Pair<Int, Int>): Boolean {
if (lines[loc] != '.') return false
val surrounding = getSurrounding(loc)
return surrounding.count { lines[it] == '.' } > 2
}
private fun getIntersectionMoves(lines: List<String>, loc: Pair<Int, Int>): List<Move> {
val surrounding = getSurrounding(loc)
return surrounding
.filter { lines[it] == '.' }
.map { Move(loc, it, 1) }
}
private fun getNextMove(lines: List<String>, move: Move): Move {
val surrounding = getSurrounding(move.to)
surrounding.forEach { to ->
if (lines[to] == '.' && to != move.from) return Move(move.to, to, move.steps + 1)
}
throw RuntimeException("No moves possible")
}
private fun findNextIntersectionAndSteps(
lines: List<String>,
intersections: List<Pair<Int, Int>>,
move: Move
): Pair<Int, Int> {
val index = intersections.indexOf(move.to)
if (move.to.first == 0) return Pair(-2, move.steps)
if (index != -1 || move.to.first == lines.lastIndex) {
return Pair(index, move.steps)
}
return findNextIntersectionAndSteps(lines, intersections, getNextMove(lines, move))
}
private data class Position(
val intersectionIndex: Int,
val totalSteps: Int,
val visited: Set<Int>
)
fun solve() {
val lines = removeAllSlopes(Input.read("input.txt"))
val intersections = findIntersections(lines)
// intersection to all directly connected intersections with step count
val directDistance = mutableMapOf<Int, MutableSet<Pair<Int, Int>>>()
for (fromIntersectionIndex in intersections.indices) {
val fromIntersection = intersections[fromIntersectionIndex]
val moves = getIntersectionMoves(lines, fromIntersection)
directDistance.putIfAbsent(fromIntersectionIndex, mutableSetOf())
for (move in moves) {
val next = findNextIntersectionAndSteps(lines, intersections, move)
val toIntersectionIndex = next.first
val steps = next.second
directDistance[fromIntersectionIndex]!!.add(Pair(toIntersectionIndex, steps))
directDistance.putIfAbsent(toIntersectionIndex, mutableSetOf())
directDistance[toIntersectionIndex]!!.add(Pair(fromIntersectionIndex, steps))
}
}
val lastIntersectionIndexWithStepsToFinish = directDistance[-1]!!.first()
val lastIntersectionIndex = lastIntersectionIndexWithStepsToFinish.first
val stepsFromLastIntersectionToFinish = lastIntersectionIndexWithStepsToFinish.second
var longestDistance = Int.MIN_VALUE
val posStack = ArrayDeque<Position>()
posStack.add(Position(-2, 0, setOf()))
while (posStack.isNotEmpty()) {
val pos = posStack.removeLast()
val nextIntersections = if (pos.intersectionIndex == lastIntersectionIndex) {
// do not block last intersection
// must turn towards finish
listOf(Pair(-1, stepsFromLastIntersectionToFinish))
} else {
directDistance[pos.intersectionIndex]!!
.filter {
!pos.visited.contains(it.first)
}
}
nextIntersections.forEach {
val to = it.first
val totalSteps = pos.totalSteps + it.second
if (to != -1) {
posStack.add(Position(to, totalSteps, pos.visited + setOf(pos.intersectionIndex)))
} else if (totalSteps > longestDistance) {
longestDistance = totalSteps
}
}
}
println(longestDistance)
}
}
}
fun main() {
D23_2.solve()
} | 0 | Kotlin | 0 | 0 | a6eec4168b4a98b73d4496c9d610854a0165dbeb | 4,953 | aoc2023-kotlin | MIT License |
src/Day04.kt | jordan-thirus | 573,476,470 | false | {"Kotlin": 41711} | fun main() {
fun getPairs(line: String) : List<Pair<Int, Int>> {
val assignments = line.split(',','-')
return listOf(Pair(assignments[0].toInt(), assignments[1].toInt()),
Pair(assignments[2].toInt(), assignments[3].toInt()))
.sortedBy { pair -> pair.first }
}
fun containedSchedule(elf1: Pair<Int, Int>, elf2: Pair<Int, Int>) : Boolean {
return (elf1.first in elf2.first..elf2.second &&
elf1.second in elf2.first..elf2.second) ||
(elf2.first in elf1.first..elf1.second &&
elf2.second in elf1.first..elf1.second)
}
fun overlapSchedule(elf1: Pair<Int, Int>, elf2: Pair<Int, Int>) : Boolean {
return elf2.first <= elf1.second
}
fun part1(input: List<String>): Int {
return input.map { line -> getPairs(line) }
.count { pair -> containedSchedule(pair[0], pair[1]) }
}
fun part2(input: List<String>): Int {
return input.map { line -> getPairs(line) }
.count { pair -> overlapSchedule(pair[0], pair[1]) }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day04_test")
check(part1(testInput) == 2)
check(part2(testInput) == 4)
val input = readInput("Day04")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 59b0054fe4d3a9aecb1c9ccebd7d5daa7a98362e | 1,374 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/g1901_2000/s1976_number_of_ways_to_arrive_at_destination/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g1901_2000.s1976_number_of_ways_to_arrive_at_destination
// #Medium #Dynamic_Programming #Graph #Topological_Sort #Shortest_Path
// #2023_06_21_Time_282_ms_(100.00%)_Space_46.8_MB_(100.00%)
import java.util.PriorityQueue
import java.util.Queue
class Solution {
private fun dijkstra(roads: Array<IntArray>, n: Int): Int {
val mod = 1e9.toInt() + 7L
val pq: Queue<LongArray> = PriorityQueue({ l1: LongArray, l2: LongArray -> l1[1].compareTo(l2[1]) })
val ways = LongArray(n)
val dist = LongArray(n)
dist.fill(1e18.toLong())
dist[0] = 0
ways[0] = 1
val graph: Array<ArrayList<LongArray>?> = arrayOfNulls<ArrayList<LongArray>>(n)
for (i in graph.indices) {
graph[i] = ArrayList()
}
for (road in roads) {
graph[road[0]]?.add(longArrayOf(road[1].toLong(), road[2].toLong()))
graph[road[1]]?.add(longArrayOf(road[0].toLong(), road[2].toLong()))
}
pq.add(longArrayOf(0, 0))
if (pq.isNotEmpty()) {
while (pq.isNotEmpty()) {
val ele = pq.remove()
val dis = ele[1]
val node = ele[0]
for (e in graph[node.toInt()]!!) {
val wt = e[1]
val adjNode = e[0]
if (wt + dis < dist[adjNode.toInt()]) {
dist[adjNode.toInt()] = wt + dis
ways[adjNode.toInt()] = ways[node.toInt()]
pq.add(longArrayOf(adjNode, dist[adjNode.toInt()]))
} else if (wt + dis == dist[adjNode.toInt()]) {
ways[adjNode.toInt()] = (ways[node.toInt()] + ways[adjNode.toInt()]) % mod
}
}
}
}
return ways[n - 1].toInt()
}
fun countPaths(n: Int, roads: Array<IntArray>): Int {
return dijkstra(roads, n)
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 1,952 | LeetCode-in-Kotlin | MIT License |
src/main/kotlin/aoc2021/Day02.kt | davidsheldon | 565,946,579 | false | {"Kotlin": 161960} | package aoc2021
import aoc2022.parsedBy
import utils.InputUtils
import utils.Coordinates
private sealed class Command {
data class Up(val distance: Int) : Command()
data class Down(val distance: Int) : Command()
data class Forward(val distance: Int) : Command()
}
private val parser = "(up|down|forward) (\\d+)".toRegex()
fun main() {
val testInput = """forward 5
down 5
forward 8
up 3
down 8
forward 2""".split("\n")
fun MatchResult.parseCommand() :Command {
val command = groupValues[1]
val distance = groupValues[2].toInt()
return when (command) {
"up" -> Command.Up(distance)
"down" -> Command.Down(distance)
"forward" -> Command.Forward(distance)
else -> error(this)
}
}
fun part1(input: List<String>): Int {
return input.parsedBy(parser, MatchResult::parseCommand).fold(Coordinates()) { coord, command ->
when (command) {
is Command.Up -> coord.dY(-command.distance)
is Command.Down -> coord.dY(command.distance)
is Command.Forward -> coord.dX(command.distance)
}
}.let { it.x * it.y }
}
data class State(val pos: Coordinates = Coordinates(0, 0), val aim : Int = 0) {
fun apply(command: Command) =
when(command) {
is Command.Up -> copy(aim = aim - command.distance)
is Command.Down -> copy(aim = aim + command.distance)
is Command.Forward -> copy(pos = pos.dX(command.distance).dY(command.distance * aim))
}
}
fun part2(input: List<String>): Int =
input.parsedBy(parser, MatchResult::parseCommand)
.fold(State()) { state, command -> state.apply(command) }
.let { it.pos.x * it.pos.y }
// test if implementation meets criteria from the description, like:
val testValue = part1(testInput)
println(testValue)
check(testValue == 150)
val puzzleInput = InputUtils.downloadAndGetLines(2021, 2)
val input = puzzleInput.toList()
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 5abc9e479bed21ae58c093c8efbe4d343eee7714 | 2,141 | aoc-2022-kotlin | Apache License 2.0 |
kotlin/app/src/main/kotlin/coverick/aoc/day3/RucksackReorganization.kt | RyTheTurtle | 574,328,652 | false | {"Kotlin": 82616} | package coverick.aoc.day3
import readResourceFile
//https://adventofcode.com/2022/day/3
val INPUT_FILE = "rucksackReorganization-input.txt"
fun getRucksackCompartments(contents:String): Pair<String,String>{
val split = contents.length / 2
return Pair(contents.substring(0,split),
contents.substring(split))
}
fun getDuplicatedItem(ruck:Pair<String,String>): Char {
return ruck
.first
.toCharArray()
.intersect(ruck.second.toList())
.first()
}
fun getDuplicatedItem(elfGroup: Triple<String,String,String>): Char {
return elfGroup
.first
.toCharArray()
.intersect(elfGroup.second.toList())
.intersect(elfGroup.third.toList())
.first()
}
fun getElfGroups(rucks:List<String>)
: List<Triple<String,String,String>> {
val elfGroups = ArrayList<Triple<String,String,String>>()
for(ruck in 0..rucks.size-1 step 3){
elfGroups.add(Triple(rucks[ruck],rucks[ruck+1],rucks[ruck+2]))
}
return elfGroups
}
fun part1(): Int {
// craft lookup table for priorities of items
val priority = HashMap<Char,Int>()
for(c in 'a'..'z'){
priority.put(c, c.code - 97 + 1)
}
for(c in 'A'..'Z'){
priority.put(c, c.code - 65 + 27)
}
return readResourceFile(INPUT_FILE)
.map { getRucksackCompartments(it) }
.map{getDuplicatedItem(it)}
.map{priority.getOrElse(it) { 0 }}
.sum()
}
fun part2(): Int {
// craft lookup table for priorities of items
val priority = HashMap<Char,Int>()
for(c in 'a'..'z'){
priority.put(c, c.code - 97 + 1)
}
for(c in 'A'..'Z'){
priority.put(c, c.code - 65 + 27)
}
return getElfGroups(readResourceFile(INPUT_FILE))
.map { getDuplicatedItem(it) }
.map { priority.getOrElse(it) {0}}
.sum()
}
fun solution(){
println("Rucksack Reorganization Part 1 Solution: ${part1()}")
println("Rucksack Reorganization Part 1 Solution: ${part2()}")
} | 0 | Kotlin | 0 | 0 | 35a8021fdfb700ce926fcf7958bea45ee530e359 | 2,072 | adventofcode2022 | Apache License 2.0 |
aoc2022/day16.kt | davidfpc | 726,214,677 | false | {"Kotlin": 127212} | package aoc2022
import utils.InputRetrieval
fun main() {
Day16.execute()
}
object Day16 {
fun execute() {
val input = readInput()
println("Part 1: ${part1(input)}")
println("Part 2: ${part2(input)}")
}
private fun part1(input: List<Valve>): Int {
val startingPoint = input.first { it.id == "AA" }
val cache = mutableMapOf<Triple<Valve, Int, Int>, Int>()
return solvePart1(startingPoint, 0, 0, mutableListOf(), input, 30, cache)
}
private fun part2(input: List<Valve>): Int {
val startingPoint = input.first { it.id == "AA" }
val validValves = input.filter { it.flowRate != 0 }.toSet()
val powerSet = validValves.powerSet()
val combinations = mutableSetOf<Set<Valve>>()
for (element in powerSet) {
if (validValves.minus(element) !in combinations) {
combinations += element
}
}
return combinations.withIndex().map { (index, valves) -> index to valves }.parallelStream().map { (index, humanValves) ->
println("Processing $index out of ${combinations.size}") // This is just so we can see progress, because this takes like 2hrs, even with the parallelism
val elephantValves = validValves.minus(humanValves)
val humanScore = solvePart1(startingPoint, 0, 0, elephantValves.toMutableList(), input, 26, mutableMapOf())
val elephantScore = solvePart1(startingPoint, 0, 0, humanValves.toMutableList(), input, 26, mutableMapOf())
humanScore + elephantScore
}.max(Integer::compare).get()
}
private fun <T> Collection<T>.powerSet(): Set<Set<T>> = when {
isEmpty() -> setOf(emptySet())
else -> this.drop(1).powerSet().let { value -> value + value.map { it + this.first() } }
}
private fun solvePart1(
currentValve: Valve,
minute: Int,
releasedPressure: Int,
openedValves: MutableList<Valve>,
input: List<Valve>,
finalMinute: Int,
cache: MutableMap<Triple<Valve, Int, Int>, Int>,
): Int {
if (minute >= finalMinute) {
return releasedPressure
}
val cacheId = Triple(currentValve, minute, releasedPressure)
if (cache.containsKey(cacheId)) {
return cache[cacheId]!!
}
var newReleasedPressure = releasedPressure
var currentMinute = minute
var childrenMaxValueWithoutOpeningTheValve = 0
if (currentValve.flowRate != 0 && !openedValves.contains(currentValve)) {
// Check children without opening the valve
childrenMaxValueWithoutOpeningTheValve = currentValve.targetValves.maxOf { valveId ->
solvePart1(input.first { it.id == valveId }, currentMinute + 1, newReleasedPressure, openedValves.toMutableList(), input, finalMinute, cache)
}
// Open Valve
currentMinute++ // It takes 1 minute to open the valve
newReleasedPressure += currentValve.flowRate * (finalMinute - currentMinute)
openedValves.add(currentValve)
}
// Check to children nodes after opening the valve
val result = currentValve.targetValves
.map { valveId -> solvePart1(input.first { it.id == valveId }, currentMinute + 1, newReleasedPressure, openedValves.toMutableList(), input, finalMinute, cache) }
.plus(childrenMaxValueWithoutOpeningTheValve)
.max()
cache[cacheId] = result
return result
}
private fun readInput(): List<Valve> = InputRetrieval.getFile(2022, 16).readLines().map {
var input = it.removePrefix("Valve ")
val id = input.take(2)
input = input.drop(2).removePrefix(" has flow rate=")
val flowRate = input.takeWhile { char -> char != ';' }
input = input.drop(flowRate.length).removePrefix("; tunnels lead to valves ").removePrefix("; tunnel leads to valve ")
val valves = input.split(", ").toSet()
Valve(id, flowRate.toInt(), valves)
}
data class Valve(val id: String, val flowRate: Int, val targetValves: Set<String>)
}
| 0 | Kotlin | 0 | 0 | 8dacf809ab3f6d06ed73117fde96c81b6d81464b | 4,169 | Advent-Of-Code | MIT License |
src/year_2022/day_24/Day24.kt | scottschmitz | 572,656,097 | false | {"Kotlin": 240069} | package year_2022.day_24
import readInput
import util.Bounds
import util.Bounds.Companion.bounds
import util.Direction.*
import util.Point
import util.isWithin
import util.plus
private data class Move(val position: Point, val step: Int)
class Day24(text: List<String>) {
companion object {
private const val WALL = '#'
private const val EMPTY = '.'
private const val BLIZZARD_UP = '^'
private const val BLIZZARD_RIGHT = '>'
private const val BLIZZARD_DOWN = 'v'
private const val BLIZZARD_LEFT = '<'
private val SAME_DIRECTION = Point(0, 0)
private val DIRECTION_DELTAS = (listOf(NORTH, SOUTH, WEST, EAST).map { it.delta } + SAME_DIRECTION)
}
private val data = text.map { it.toCharArray() }
fun solutionOne() = data.let { input ->
// build the map
val initialState = buildMap(input)
val walls = walls(input)
val bounds = (initialState.keys + walls).bounds()
// find the cycle with set of states
val states = findCycleStates(initialState, bounds)
// find the shortest path to the end
val start = Point(1, 0)
val end = Point(bounds.max.first - 1, bounds.max.second)
val solution = search(start, end, 0, states, walls, bounds)
solution
}
fun solutionTwo() = data.let { input ->
// build the map
val initialState = buildMap(input)
val walls = walls(input)
val bounds = (initialState.keys + walls).bounds()
// find the cycle with set of states
val states = findCycleStates(initialState, bounds)
// find the shortest path to the end
val start = Point(1, 0)
val end = Point(bounds.max.first - 1, bounds.max.second)
val solution1 = search(start, end, 0, states, walls, bounds)
val solution2 = search(end, start, solution1, states, walls, bounds)
val solution3 = search(start, end, solution2, states, walls, bounds)
solution3
}
private fun search(
start: Point,
end: Point,
initialStep: Int,
states: List<Set<Point>>,
walls: Set<Point>,
bounds: Bounds
): Int {
val pendingMoves = ArrayDeque<Move>().also { it.add(Move(start, initialStep + 1)) }
val visitedMoves = HashSet<Move>()
val possibleMoves = HashSet<Move>()
val impossibleMoves = HashSet<Move>()
while (pendingMoves.isNotEmpty()) {
val move = pendingMoves.removeFirst()
val step = move.step + 1
if (visitedMoves.contains(move)) {
continue
}
if (move.position == end) {
return step - 1
}
visitedMoves.add(move)
val nextPositions = DIRECTION_DELTAS.map { delta -> move.position.plus(delta) }
val blizzards = states[step % states.size]
val nextPossibleMoves: Collection<Move> = nextPositions
.map { nextPosition ->
Move(
position = nextPosition,
step = step
).also { move ->
cache(move, nextPosition, possibleMoves, impossibleMoves, bounds, walls, blizzards)
}
}
.subtract(impossibleMoves)
pendingMoves.addAll(nextPossibleMoves)
}
error("no solution found")
}
private fun cache(
move: Move,
position: Point,
possibleMoves: HashSet<Move>,
impossibleMoves: HashSet<Move>,
bounds: Bounds,
walls: Set<Point>,
blizzards: Set<Point>
) {
if (!possibleMoves.contains(move) && !impossibleMoves.contains(move)) {
val isPossibleMove = position.isWithin(bounds) && !walls.contains(position) && !blizzards.contains(position)
if (isPossibleMove) {
possibleMoves.add(move)
} else {
impossibleMoves.add(move)
}
}
}
private fun findCycleStates(
initialState: Map<Point, List<Char>>,
bounds: Bounds
): List<Set<Point>> {
val pattern = HashSet<Map<Point, List<Char>>>()
val states = ArrayList<Set<Point>>()
var lastState = initialState
var position = 0
while (true) {
pattern.add(lastState)
states.add(HashSet(lastState.keys))
val nextState = nextState(lastState, bounds)
lastState = nextState
position += 1
if (pattern.contains(nextState)) {
break
}
}
return states
}
private fun nextState(current: Map<Point, List<Char>>, bounds: Bounds): Map<Point, List<Char>> {
val next = mutableMapOf<Point, MutableList<Char>>()
current.forEach { (point, items) ->
items.forEach { item ->
val nextPoint = when (item) {
BLIZZARD_UP -> {
val prevY = point.second - 1
val y = if (prevY > bounds.min.second) prevY else bounds.max.second - 1
Point(point.first, y)
}
BLIZZARD_RIGHT -> {
val nextX = point.first + 1
val x = if (nextX < bounds.max.first) nextX else bounds.min.first + 1
Point(x, point.second)
}
BLIZZARD_DOWN -> {
val nextY = point.second + 1
val y = if (nextY < bounds.max.second) nextY else bounds.min.second + 1
Point(point.first, y)
}
BLIZZARD_LEFT -> {
val prevX = point.first - 1
val x = if (prevX > bounds.min.first) prevX else bounds.max.first - 1
Point(x, point.second)
}
else -> error("undefined item $item")
}
next.getOrPut(nextPoint) { mutableListOf() }.add(item)
}
}
return next
}
private fun walls(input: List<CharArray>): Set<Point> {
val walls = mutableSetOf<Point>()
input.forEachIndexed { row, line ->
line.forEachIndexed { col, char ->
if (char == WALL) {
walls.add(Point(col, row))
}
}
}
return walls
}
private fun buildMap(input: List<CharArray>): Map<Point, List<Char>> {
val map = mutableMapOf<Point, List<Char>>()
input.forEachIndexed { row, line ->
line.forEachIndexed { x, item ->
if (x == 0 || x == line.size - 1 || row == 0 || row == input.size - 1) {
// no-op
} else if (item == EMPTY) {
// no-op
} else {
val position = Point(x, row)
map[position] = listOf(item)
}
}
}
return map
}
}
fun main() {
val inputText = readInput("year_2022/day_24/Day24.txt")
val day = Day24(text = inputText)
println("Solution 1: ${day.solutionOne()}")
println("Solution 2: ${day.solutionTwo()}")
} | 0 | Kotlin | 0 | 0 | 70efc56e68771aa98eea6920eb35c8c17d0fc7ac | 7,390 | advent_of_code | Apache License 2.0 |
src/Day08.kt | catcutecat | 572,816,768 | false | {"Kotlin": 53001} | import java.util.*
import kotlin.math.abs
import kotlin.system.measureTimeMillis
fun main() {
measureTimeMillis {
Day08.run {
solve1(21) // 1851
solve2(8) // 574080
}
}.let { println("Total: $it ms") }
}
object Day08 : Day.LineInput<Day08.Data, Int>("08") {
class Data(val rowSize: Int, val colSize: Int, val visibleCounts: Array<Array<IntArray>>)
override fun parse(input: List<String>): Data {
val rowSize = input.size
val colSize = input.first().length
val visibleCounts = Array(4) { Array(rowSize) { IntArray(colSize) } }
val ranges = arrayOf(
(0 until rowSize) to (0 until colSize),
(rowSize - 1 downTo 0) to (colSize - 1 downTo 0)
)
fun count(rows: IntProgression, cols: IntProgression, dest1: Array<IntArray>, dest2: Array<IntArray>) {
val prevNotLowerRow = Array(colSize) { Stack<Int>() }
for (row in rows) {
val prevNotLowerCol = Stack<Int>()
for (col in cols) {
val curr = input[row][col]
while (prevNotLowerCol.isNotEmpty() && input[row][prevNotLowerCol.peek()] < curr) prevNotLowerCol.pop()
dest2[row][col] = if (prevNotLowerCol.isEmpty()) -1 else abs(col - prevNotLowerCol.peek())
while (prevNotLowerRow[col].isNotEmpty() && input[prevNotLowerRow[col].peek()][col] < curr) prevNotLowerRow[col].pop()
dest1[row][col] = if (prevNotLowerRow[col].isEmpty()) -1 else abs(row - prevNotLowerRow[col].peek())
prevNotLowerCol.push(col)
prevNotLowerRow[col].push(row)
}
}
}
for ((i, range) in ranges.withIndex()) {
count(range.first, range.second, visibleCounts[i * 2], visibleCounts[i * 2 + 1])
}
return Data(rowSize, colSize, visibleCounts)
}
override fun part1(data: Data) = data.run {
(0 until rowSize).sumOf { row ->
(0 until colSize).count { col ->
visibleCounts.any { it[row][col] == -1 }
}
}
}
override fun part2(data: Data) = data.run {
(0 until rowSize).maxOf { row ->
(0 until colSize).maxOf { col ->
visibleCounts.indices.fold(1) { acc, dir ->
acc * (visibleCounts[dir][row][col].takeIf { it != -1 } ?: when (dir) {
0 -> row
1 -> col
2 -> rowSize - row - 1
3 -> colSize - col - 1
else -> error("Should not reach here.")
})
}
}
}
}
} | 0 | Kotlin | 0 | 2 | fd771ff0fddeb9dcd1f04611559c7f87ac048721 | 2,758 | AdventOfCode2022 | Apache License 2.0 |
src/main/kotlin/codes/jakob/aoc/solution/Day11.kt | The-Self-Taught-Software-Engineer | 433,875,929 | false | {"Kotlin": 56277} | package codes.jakob.aoc.solution
import codes.jakob.aoc.shared.Grid
object Day11 : Solution() {
override fun solvePart1(input: String): Any {
val grid: Grid<Octopus> = Grid(parseInput(input))
val octopuses: List<Octopus> = grid.cells.map { it.value }
return (1..100).sumOf {
val flashed: Set<Octopus> = simulate(octopuses)
return@sumOf flashed.count()
}
}
override fun solvePart2(input: String): Any {
val grid: Grid<Octopus> = Grid(parseInput(input))
val octopuses: List<Octopus> = grid.cells.map { it.value }
return generateSequence(1) { it + 1 }.first {
val flashed: Set<Octopus> = simulate(octopuses)
return@first flashed.count() == octopuses.count()
}
}
private fun simulate(octopuses: List<Octopus>): Set<Octopus> {
octopuses.forEach { it.increaseEnergyLevel() }
val flashed: Set<Octopus> = octopuses.flatMap { it.checkForFlash() }.toSet()
octopuses.forEach { it.resetFlashStatus() }
return flashed
}
private fun parseInput(input: String): List<List<(Grid.Cell<Octopus>) -> Octopus>> {
return input.splitMultiline().map { row ->
row.split("").filter { it.isNotBlank() }.map { value ->
{ cell -> Octopus(cell, value.toInt()) }
}
}
}
class Octopus(private val cell: Grid.Cell<Octopus>, private var energyLevel: Int) {
private val willFlash: Boolean get() = energyLevel > 9
private var didFlash: Boolean = false
fun checkForFlash(): Set<Octopus> {
return if (willFlash) flash() else emptySet()
}
fun resetFlashStatus() {
didFlash = false
}
fun increaseEnergyLevel(increase: Int = 1) {
energyLevel += increase
}
private fun flash(): Set<Octopus> {
require(willFlash) { "Octopus $this is not ready to flash" }
energyLevel = 0
didFlash = true
return (this + cell.getAdjacent(true).flatMap { it.value.adjacentFlashed() }).toSet()
}
private fun adjacentFlashed(): Set<Octopus> {
if (!didFlash) increaseEnergyLevel(1)
return if (willFlash) flash() else emptySet()
}
override fun toString(): String {
return "Octopus(energyLevel=$energyLevel)"
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as Octopus
if (cell != other.cell) return false
return true
}
override fun hashCode(): Int {
return cell.hashCode()
}
}
}
fun main() {
Day11.solve()
}
| 0 | Kotlin | 0 | 6 | d4cfb3479bf47192b6ddb9a76b0fe8aa10c0e46c | 2,821 | advent-of-code-2021 | MIT License |
src/main/kotlin/dev/shtanko/algorithms/leetcode/MaximumLevelSumOfBinaryTree.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2022 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import java.util.LinkedList
import java.util.Queue
import java.util.stream.IntStream
/**
* 1161. Maximum Level Sum of a Binary Tree
* @see <a href="https://leetcode.com/problems/maximum-level-sum-of-a-binary-tree/">Source</a>
*/
fun interface MaximumLevelSumOfBinaryTree {
fun maxLevelSum(root: TreeNode?): Int
}
class MaximumLevelSumOfBinaryTreeBFS : MaximumLevelSumOfBinaryTree {
override fun maxLevelSum(root: TreeNode?): Int {
var max = Int.MIN_VALUE
var maxLevel = 1
val q: Queue<TreeNode> = LinkedList()
q.offer(root)
var level = 1
while (q.isNotEmpty()) {
var sum = 0
for (sz in q.size downTo 1) {
val n: TreeNode = q.poll()
sum += n.value
if (n.left != null) {
q.offer(n.left)
}
if (n.right != null) {
q.offer(n.right)
}
}
if (max < sum) {
max = sum
maxLevel = level
}
++level
}
return maxLevel
}
}
class MaximumLevelSumOfBinaryTreeDFS : MaximumLevelSumOfBinaryTree {
override fun maxLevelSum(root: TreeNode?): Int {
val list: MutableList<Int> = ArrayList()
dfs(root, list, 0)
return 1 + IntStream.range(0, list.size).reduce(0) { a, b -> if (list[a] < list[b]) b else a }
}
private fun dfs(n: TreeNode?, l: MutableList<Int>, level: Int) {
if (n == null) {
return
}
if (l.size == level) {
l.add(n.value)
} // never reach this level before, add first value.
else {
l[level] = l[level] + n.value
} // reached the level before, accumulate current value to old value.
dfs(n.left, l, level + 1)
dfs(n.right, l, level + 1)
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 2,534 | kotlab | Apache License 2.0 |
src/Day04.kt | Akhunzaada | 573,119,655 | false | {"Kotlin": 23755} | fun main() {
fun String.toIntRange(delimiter: Char = '-') =
split(delimiter).let { (first, second) ->
IntRange(first.toInt(), second.toInt())
}
fun String.toSectionsPair() =
split(',').let { (first, second) ->
Pair(first.toIntRange(), second.toIntRange())
}
fun Pair<IntRange, IntRange>.inclusion(): Boolean =
(second.first in first && second.last in first) ||
(first.first in second && first.last in second)
fun Pair<IntRange, IntRange>.overlap(): Boolean =
(second.first in first || second.last in first) ||
(first.first in second || first.last in second)
fun part1(input: List<String>): Int {
return input.map { it.toSectionsPair() }
.count { it.inclusion() }
}
fun part2(input: List<String>): Int {
return input.map { it.toSectionsPair() }
.count { it.overlap() }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day04_test")
check(part1(testInput) == 2)
check(part2(testInput) == 4)
val input = readInput("Day04")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | b2754454080989d9579ab39782fd1d18552394f0 | 1,225 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/days/y22/Day08.kt | kezz | 572,635,766 | false | {"Kotlin": 20772} | package days.y22
import util.Day
public fun main() {
Day08().run()
}
public class Day08 : Day(22, 8) {
override fun part1(input: List<String>): Any = input
.mapIndexed { y, row ->
row.mapIndexed { x, tree ->
tree.digitToInt().let { value ->
listOf(
(y - 1 downTo -1).all { checkY -> (input.getOrNull(checkY)?.getOrNull(x)?.digitToInt() ?: -1) < value },
(y + 1..input.size).all { checkY -> (input.getOrNull(checkY)?.getOrNull(x)?.digitToInt() ?: -1) < value },
(x - 1 downTo -1).all { checkX -> (input.getOrNull(y)?.getOrNull(checkX)?.digitToInt() ?: -1) < value },
(x + 1..row.length).all { checkX -> (input.getOrNull(y)?.getOrNull(checkX)?.digitToInt() ?: -1) < value },
).any { it }
}
}
}
.flatten()
.count { it }
override fun part2(input: List<String>): Any = input
.drop(1)
.dropLast(1)
.map { row -> row.drop(1).dropLast(1) }
.let { parsedInput ->
parsedInput.mapIndexed { y, row ->
row.mapIndexed { x, tree ->
tree.digitToInt().let { value ->
listOf(
(y - 1 downTo -1).fold(Pair(0, 0)) { (lastSeen, count), checkY ->
if (lastSeen >= value) {
lastSeen to count
} else {
Pair(parsedInput.getOrNull(checkY)?.getOrNull(x)?.digitToInt() ?: -1, count + 1)
}
}.second,
(y + 1..parsedInput.size).fold(Pair(0, 0)) { (lastSeen, count), checkY ->
if (lastSeen >= value) {
lastSeen to count
} else {
Pair(parsedInput.getOrNull(checkY)?.getOrNull(x)?.digitToInt() ?: -1, count + 1)
}
}.second,
(x - 1 downTo -1).fold(Pair(0, 0)) { (lastSeen, count), checkX ->
if (lastSeen >= value) {
lastSeen to count
} else {
Pair(parsedInput.getOrNull(y)?.getOrNull(checkX)?.digitToInt() ?: -1, count + 1)
}
}.second,
(x + 1..row.length).fold(Pair(0, 0)) { (lastSeen, count), checkX ->
if (lastSeen >= value) {
lastSeen to count
} else {
Pair(parsedInput.getOrNull(y)?.getOrNull(checkX)?.digitToInt() ?: -1, count + 1)
}
}.second,
).reduce(Int::times)
}
}
}
}
.flatten()
.max()
}
| 0 | Kotlin | 0 | 0 | 1cef7fe0f72f77a3a409915baac3c674cc058228 | 3,197 | aoc | Apache License 2.0 |
src/Parser.kt | rfermontero | 121,166,046 | false | {"Kotlin": 1682} | fun parseGrammar(grammar: List<Pair<String, String>>) = getFirsts(grammar)
fun getFirsts(grammar: List<Pair<String, String>>): Map<String, List<String>> =
grammar.groupBy { it.first }
.mapValues { it.value.map { it.second } }
.mapValues {
it.value.map {
getFirsts(grammar.groupBy { it.first }.mapValues { it.value.map { it.second } }, it)
}.flatten()
}
fun getFollows(grammar: List<Pair<String, String>>, firsts: Map<String, List<String>>) {
}
private fun getFirsts(mapByRules: Map<String, List<String>>, it: String): Collection<String> {
return when {
!mapByRules.containsKey(it.substringBefore(" ")) -> setOf(it.substringBefore(" "))
else -> mapByRules
.filterKeys { key -> key == it }
.values
.flatten()
.map {
when {
!mapByRules.containsKey(it.substringBefore(" ")) -> listOf(it)
else -> getFirsts(mapByRules, it)
}
}.flatten()
}
}
| 0 | Kotlin | 0 | 0 | ca693f265bafab1d3b2d53c9adcc421fe038f5b4 | 1,159 | LalL-a-rLar | MIT License |
src/Day11.kt | slawa4s | 573,050,411 | false | {"Kotlin": 20679} | import java.io.IOException
class Monkey(
var items: MutableList<Int>,
private val operation: List<String>,
private val derive: Int,
private val ifTrueThrow: Int,
private val ifFalseThrow: Int,
) {
private var inspectedItems = 0
fun getInspectedItems() = inspectedItems
private fun makeOperation(item: Int): Int {
val firstArgument = if (operation[0] == "old") item else Integer.parseInt(operation[0])
val secondArgument = if (operation[2] == "old") item else Integer.parseInt(operation[2])
return when (operation[1]) {
"-" -> firstArgument - secondArgument
"+" -> firstArgument + secondArgument
"*" -> firstArgument * secondArgument
"/" -> firstArgument / secondArgument
else -> throw IOException("Unknown operation: ${operation[1]}")
}
}
private fun getMonkeyIdToThrow(item: Int, lessWorriedAfterInspection: Boolean): Pair<Int, Int> {
val operationResult = if (lessWorriedAfterInspection) makeOperation(item) / 3 else makeOperation(item)
return Pair(if (operationResult % derive == 0) ifTrueThrow else ifFalseThrow, operationResult)
}
// monkey index and value
fun inspectAllItemsAndClear(lessWorriedAfterInspection: Boolean): List<Pair<Int, Int>> {
inspectedItems += items.size
val answer = items.map { getMonkeyIdToThrow(it, lessWorriedAfterInspection) }
items = mutableListOf()
return answer
}
fun addItem(item: Int) {
items.add(item)
}
}
fun main() {
fun prepareInput(input: List<String>): List<Monkey> =
input.chunked(7).map {
val items = it[1]
.substringAfter("Starting items: ")
.split(", ")
.map { num -> num.toInt() }
.toMutableList()
val operation = it[2]
.substringAfter("Operation: new = ")
.split(" ")
val derive = Integer.parseInt(it[3].substringAfter("Test: divisible by "))
val ifTrueThrow = Integer.parseInt(it[4].substringAfter("If true: throw to monkey "))
val ifFalseThrow = Integer.parseInt(it[5].substringAfter("If false: throw to monkey "))
Monkey(items, operation, derive, ifTrueThrow, ifFalseThrow)
}
fun part1(monkeys: List<Monkey>): Int {
repeat(20) {
monkeys.forEach {
val listOfThrows = it.inspectAllItemsAndClear(lessWorriedAfterInspection = true)
for ((index, value) in listOfThrows) {
monkeys[index].addItem(value)
}
}
}
val twoBiggest = monkeys.map { it.getInspectedItems() }.sorted().takeLast(2)
return twoBiggest[1] * twoBiggest[0]
}
fun part2(monkeys: List<Monkey>): Int {
repeat(21) {
monkeys.forEach {
val listOfThrows = it.inspectAllItemsAndClear(lessWorriedAfterInspection = false )
for ((index, value) in listOfThrows) {
monkeys[index].addItem(value)
}
}
println("Iteration ${it + 1}")
for (monkeyIndex in monkeys.indices) {
println("Monkey $monkeyIndex: ${monkeys[monkeyIndex].items} and inspected: ${monkeys[monkeyIndex].getInspectedItems()}")
}
}
val twoBiggest = monkeys.map { it.getInspectedItems() }.sorted().takeLast(2)
return twoBiggest[1] * twoBiggest[0]
}
println(part1(prepareInput(readInput("Day11"))))
println(part2(prepareInput(readInput("Day11"))))
}
| 0 | Kotlin | 0 | 0 | cd8bbbb3a710dc542c2832959a6a03a0d2516866 | 3,645 | aoc-2022-in-kotlin | Apache License 2.0 |
src/main/kotlin/day08/Forest.kt | jankase | 573,187,696 | false | {"Kotlin": 70242} | package day08
data class Forest(val trees: List<Tree>) {
companion object {
fun valueOf(value: List<String>) =
Forest(
value.mapIndexed { rowIndex, rowTreesHeight ->
rowTreesHeight.mapIndexed { columnIndex, heightChar ->
Tree(rowIndex, columnIndex, heightChar.toString().toInt())
}
}.flatten()
)
}
fun numberOfVisibleTrees(): Int {
resetVisibleTrees()
markVisibleTrees()
return trees.count { it.isVisible }
}
fun highestScenicScore(): Int {
resetScenicScore()
calculateScenicScore()
return trees.maxOf { it.scenicScore }
}
private fun resetScenicScore() = trees.forEach { it.scenicScore = 0 }
private fun lookScore(tree: Tree, comparator: Comparator<in Tree>, function: (Tree, Tree) -> Boolean): Int =
trees
.filter { function(it, tree) }
.toMutableList()
.sortedWith(comparator)
.takeVisibleTrees(tree.height)
.size
private fun calculateScenicScore() {
trees.forEach { tree ->
val lookLeftScore = lookScore(tree, compareByDescending { it.column }, ::lookLeftCondition)
val lookRightScore = lookScore(tree, compareBy { it.column }, ::lookRightCondition)
val lookUpScore = lookScore(tree, compareByDescending { it.row }, ::lookUpCondition)
val lookDownScore = lookScore(tree, compareBy { it.row }, ::lookDownCondition)
tree.scenicScore = lookLeftScore * lookRightScore * lookUpScore * lookDownScore
}
}
private fun resetVisibleTrees() = trees.forEach { it.isVisible = false }
private fun markVisibleTrees() =
trees.forEach { tree ->
tree.isVisible = isTreeVisible(tree) { lookLeftCondition(it, tree) } ||
isTreeVisible(tree) { lookRightCondition(it, tree) } ||
isTreeVisible(tree) { lookUpCondition(it, tree) } ||
isTreeVisible(tree) { lookDownCondition(it, tree) }
}
private fun isTreeVisible(tree: Tree, lineOfViewPickerCondition: (Tree) -> Boolean): Boolean =
trees.count { lineOfViewPickerCondition(it) && it.height >= tree.height } == 1
private fun lookLeftCondition(tree: Tree, treeFromForest: Tree): Boolean =
tree.row == treeFromForest.row && tree.column <= treeFromForest.column
private fun lookRightCondition(tree: Tree, treeFromForest: Tree): Boolean =
tree.row == treeFromForest.row && tree.column >= treeFromForest.column
private fun lookUpCondition(tree: Tree, treeFromForest: Tree): Boolean =
tree.column == treeFromForest.column && tree.row <= treeFromForest.row
private fun lookDownCondition(tree: Tree, treeFromForest: Tree): Boolean =
tree.column == treeFromForest.column && tree.row >= treeFromForest.row
}
private fun Iterable<Tree>.takeVisibleTrees(currentHeight: Int): List<Tree> {
val result = mutableListOf<Tree>()
forEachIndexed { index, t ->
if (index == 0) return@forEachIndexed
result.add(t)
if (t.height >= currentHeight) return result
}
return result
}
| 0 | Kotlin | 0 | 0 | 0dac4ec92c82a5ebb2179988fb91fccaed8f800a | 3,241 | adventofcode2022 | Apache License 2.0 |
src/main/kotlin/extensions/sequences/Collect.kt | swantescholz | 102,711,230 | false | null | package extensions.sequences
import datastructures.HashCounter
import extensions.*
import math.LOG2
import java.math.BigInteger
import java.text.DecimalFormat
import java.util.*
fun <T> Sequence<T>.takeLast(numberOfElementsToTakeFromBackOfSequence: Int): ArrayList<T> {
val list = LinkedList<T>()
for (element in this) {
list.add(element)
if (list.size > numberOfElementsToTakeFromBackOfSequence)
list.removeFirst()
}
return list.toArrayList()
}
fun <T> Sequence<T>.toTreeSet(): TreeSet<T> {
return toCollection(TreeSet<T>())
}
fun <K, V> Sequence<Pair<K, V>>.toHashMap(): HashMap<K, V> {
val hm = HashMap<K, V>()
hm.putAll(this)
return hm
}
fun <K, V> Sequence<Pair<K, V>>.toSortedMap(comparator: ((K, K) -> Int)? = null): TreeMap<K, V> {
val res = TreeMap<K, V>(comparator)
this.forEach { res.put(it.first, it.second) }
return res
}
fun <T> Sequence<T>.printlnAll() {
for (it in this)
println(it)
}
fun <T> Sequence<T>.printlnAllIndexed() {
this.withIndex().forEach { print(it.index.toString() + " "); println(it.value) }
}
fun Sequence<Int>.minmax(): Pair<Int, Int> {
var lo = Int.MAX_VALUE
var hi = Int.MIN_VALUE
this.forEach {
lo = lo.min(it)
hi = hi.max(it)
}
return Pair(lo, hi)
}
fun Sequence<Long>.lminmax(): Pair<Long, Long> {
var lo = Long.MAX_VALUE
var hi = Long.MIN_VALUE
this.forEach {
lo = lo.min(it)
hi = hi.max(it)
}
return Pair(lo, hi)
}
inline fun <T> Sequence<T>.sumByLong(selector: (T) -> Long): Long {
var sum: Long = 0
for (element in this) {
sum += selector(element)
}
return sum
}
fun <T> Sequence<T>.groupCount(): ArrayList<Pair<T, Int>> {
val hm = HashCounter<T>()
this.forEach { hm.increase(it) }
return hm.asSequence().map { Pair(it.key, it.value.toInt()) }.toArrayList()
}
fun Sequence<BigInteger>.sum() = this.fold(0.big(), { a, b -> a + b })
fun Sequence<BigInteger>.product() = this.fold(1.big(), { a, b -> a * b })
fun Sequence<Int>.product() = this.fold(1, { a, b -> a * b })
fun Sequence<Int>.lproduct() = this.fold(1L, { a, b -> a * b })
fun Sequence<Long>.product() = this.fold(1L, { a, b -> a * b })
fun Sequence<Double>.product() = this.fold(1.0, { a, b -> a * b })
fun Sequence<Number>.printInfo() {
val seq = this.map { it.toDouble() }.toCollection(arrayListOf<Double>()).asSequence()
val df = DecimalFormat("#.####");
fun Sequence<Double>.pln(prefix: String) = this.map {
if (it.toLong().toDouble() == it)
return@map it.toLong().toString()
return@map df.format(it)
}.joinToString(separator = ", ",
prefix = prefix.padEnd(15) + ": ").printl()
seq.pln("normal")
seq.zip(seq.drop(1)).map { it.second - it.first }.pln("differences")
seq.zip(seq.drop(1)).map { it.second / it.first.toDouble() }.pln("slope")
seq.map { Math.log(it.toDouble()) }.pln("log_e")
seq.map { Math.log(it.toDouble()) / LOG2 }.pln("log_2")
seq.map { Math.sqrt(it.toDouble()) }.pln("sqrts")
seq.map { it * it }.pln("squares")
seq.map { it * it * it }.pln("cubes")
}
| 0 | Kotlin | 0 | 0 | 20736acc7e6a004c29c328a923d058f85d29de91 | 2,964 | ai | Do What The F*ck You Want To Public License |
src/main/kotlin/io/github/clechasseur/adventofcode/y2022/Day16.kt | clechasseur | 567,968,171 | false | {"Kotlin": 493887} | package io.github.clechasseur.adventofcode.y2022
import io.github.clechasseur.adventofcode.dij.Dijkstra
import io.github.clechasseur.adventofcode.dij.Graph
import io.github.clechasseur.adventofcode.y2022.data.Day16Data
object Day16 {
private val input = Day16Data.input
private val valveRegex = """^Valve ([A-Z]{2}) has flow rate=(\d+); tunnels? leads? to valves? ([A-Z]{2}(?:, [A-Z]{2})*)$""".toRegex()
fun part1(): Int = runSimulation(0)
fun part2(): Int = runSimulation(1)
private fun runSimulation(numElephants: Int): Int {
val network = Network(input.lines().map { it.toValve() })
return network.possibleSteps(1 + numElephants, 30 - numElephants * 4).maxOf { players ->
players.sumOf { it.releasedPressure(network) }
}
}
private data class Valve(val id: String, val flowRate: Int, val tunnels: List<String>)
private data class Network(val valves: Map<String, Valve>) : Graph<String> {
constructor(valves: List<Valve>) : this(valves.associateBy { it.id })
val workingValves = valves.filterValues { it.flowRate > 0 }.keys
val dij = valves.keys.associateWith { Dijkstra.build(this, it) }
override fun allPassable(): List<String> = valves.keys.toList()
override fun neighbours(node: String): List<String> = valves[node]!!.tunnels
override fun dist(a: String, b: String): Long = 1L
}
private data class Step(val valve: String, val openAt: Int)
private data class Player(val steps: List<Step>) {
fun releasedPressure(network: Network): Int = steps.sumOf { step ->
step.openAt * network.valves[step.valve]!!.flowRate
}
}
private fun Network.possibleSteps(numPlayers: Int, minutes: Int): Sequence<List<Player>> {
return possibleSteps(workingValves, List(numPlayers) { Player(listOf(Step("AA", minutes))) })
}
private fun Network.possibleSteps(valves: Set<String>, soFar: List<Player>): Sequence<List<Player>> {
val nextPlayer = soFar.maxBy { it.steps.last().openAt }
val remainingPlayers = soFar - nextPlayer
val curPos = nextPlayer.steps.last()
if (curPos.openAt == 0) {
return sequenceOf(soFar)
}
val nextSteps = valves.map { nextValve ->
Step(nextValve, curPos.openAt - (dij[curPos.valve]!!.dist[nextValve]!!.toInt() + 1))
}.filter { step ->
step.openAt > 0
}
return if (nextSteps.isNotEmpty()) {
nextSteps.asSequence().flatMap { step ->
possibleSteps(valves - step.valve, remainingPlayers + Player(nextPlayer.steps + step))
}
} else {
possibleSteps(valves, remainingPlayers + Player(nextPlayer.steps + Step("AA", 0)))
}
}
private fun String.toValve(): Valve {
val match = valveRegex.matchEntire(this) ?: error("Wrong valve spec: $this")
val (id, flowRate, tunnels) = match.destructured
return Valve(id, flowRate.toInt(), tunnels.split(", "))
}
}
| 0 | Kotlin | 0 | 0 | 7ead7db6491d6fba2479cd604f684f0f8c1e450f | 3,054 | adventofcode2022 | MIT License |
src/main/kotlin/com/groundsfam/advent/y2022/d08/Day08.kt | agrounds | 573,140,808 | false | {"Kotlin": 281620, "Shell": 742} | package com.groundsfam.advent.y2022.d08
import com.groundsfam.advent.DATAPATH
import com.groundsfam.advent.timed
import java.util.ArrayDeque
import java.util.Deque
import kotlin.io.path.div
import kotlin.io.path.useLines
import kotlin.math.abs
/**
* Collection of walks to take across the grid of trees. A walk is a list of
* coordinate pairs (i, j) of trees to consider, in a specified order.
*/
fun getWalks(size: Int): List<List<Pair<Int, Int>>> = (
// left to right
(0 until size).map { i ->
(0 until size).map { j -> i to j }
} +
// right to left
(0 until size).map { i ->
(size - 1 downTo 0).map { j -> i to j }
}
).let { walks ->
// top to bottom and bottom to top
walks + walks.map { walk ->
walk.map { (i, j) -> j to i }
}
}
fun countVisibleTrees(grid: List<List<Int>>): Int {
val size = grid.size // grid is a square, so rows and columns have same size
val visible = Array(size) { BooleanArray(size) }
/*
* Collection of walks to take across the grid of trees. A walk is a list of
* coordinate pairs (i, j) of trees to consider, in a specified order.
*/
getWalks(size).forEach { walk ->
var maxTree = -1
walk.forEach { (i, j) ->
val tree = grid[i][j]
if (tree > maxTree) {
visible[i][j] = true
maxTree = tree
}
}
}
return visible.sumOf { row -> row.count { it } }
}
fun maxScenicScore(grid: List<List<Int>>): Int {
val size = grid.size
val scores = Array(size) { IntArray(size) { 1 } }
infix fun Pair<Int, Int>.compareHeight(other: Pair<Int, Int>): Int {
val (thisX, thisY) = this
val (otherX, otherY) = other
return grid[thisX][thisY] - grid[otherX][otherY]
}
getWalks(size).forEach { walk ->
val prevMaxes: Deque<Pair<Int, Int>> = ArrayDeque()
// determine direction of this walk: xDirection or yDirection, and increasing or decreasing
val xDirection = walk[0].first != walk[1].first
val increasing =
if (xDirection) walk[0].first < walk[1].first
else walk[0].second < walk[1].second
// find the (positive) distance between the two points on the current walk, or the distance
// from the point to the beginning of the walk in the case that other is null
infix fun Pair<Int, Int>.diff(other: Pair<Int, Int>?): Int {
val (thisX, thisY) = this
if (other == null) {
return when {
xDirection && increasing -> thisX
xDirection && !increasing -> size - thisX - 1
!xDirection && increasing -> thisY
else -> size - thisY - 1
}
}
val (otherX, otherY) = other
return if (xDirection) abs(thisX - otherX)
else abs(thisY - otherY)
}
walk.forEach { point ->
val (i, j) = point
var prevMax: Pair<Int, Int>? = null
while (prevMaxes.isNotEmpty() && point compareHeight prevMaxes.peek() >= 0) {
prevMax = prevMaxes.pop()
}
when {
// we encountered another tree of same height as this one, so
// the score is the distance from this tree to the previous one of same height
prevMax != null && point compareHeight prevMax == 0 -> {
scores[i][j] *= point diff prevMax
}
// either we're the tallest tree so far, or prevMax is a tree shorter than this
// one. the score is the distance from this tree to the previous _strictly_ taller
// tree (which is prevMaxes.peek()), or this is the tallest tree so far and we should
// diff null. point diff peek() handles both cases.
else -> {
scores[i][j] *= point diff prevMaxes.peek()
}
}
prevMaxes.push(point)
}
}
return scores.maxOf { it.maxOrNull()!! }
}
fun main() = timed {
val grid = (DATAPATH / "2022/day08.txt").useLines { lines ->
lines.toList().map { line ->
line.map { it - '0' }
}
}
countVisibleTrees(grid)
.also { println("Part one: $it") }
maxScenicScore(grid)
.also { println("Part two: $it") }
}
| 0 | Kotlin | 0 | 1 | c20e339e887b20ae6c209ab8360f24fb8d38bd2c | 4,489 | advent-of-code | MIT License |
src/Day05.kt | alfr1903 | 573,468,312 | false | {"Kotlin": 9628} | fun main() {
fun part1(moves: List<String>, stacks: Map<Int, List<Char>>): Int {
var mutableStacks = stacks
for (moveInstruction in moves) {
val moveList = moveInstruction.split(" from ")
val quantity = moveList.first().last().digitToInt()
val from = moveList.last().first().digitToInt()
val to = moveList.last().last().digitToInt()
mutableStacks = updateStacks(quantity, from, to, stacks)
}
TODO()
}
fun part2(): Int {
TODO()
}
val moveInstructions = readInputAsList("Day05Input")
val crateArrangement = readInputAsList("Day05Map")
val cratePositions = listOf(1, 5, 9, 13, 17, 21, 25, 29, 33)
val stacks = arrangementToMapOfStacks(crateArrangement, cratePositions)
println(part1(moveInstructions, stacks))
println(part2())
}
private fun updateStacks(quantity: Int, from: Int, to: Int, stacks: Map<Int, List<Char>>): Map<Int, List<Char>> {
TODO()
}
private fun arrangementToMapOfStacks(crateArrangement: List<String>, cratePositions: List<Int>): Map<Int, List<Char>> {
val stacks = mutableMapOf<Int, List<Char>>()
cratePositions.forEachIndexed { index, cratePos ->
val crateStackList: MutableList<Char> = emptyList<Char>().toMutableList()
for (cratePlacements in crateArrangement) {
if (cratePlacements[cratePos].isLetter()) {
crateStackList += cratePlacements[cratePos]
}
}
stacks[index+1] = crateStackList
}
return stacks
}
| 0 | Kotlin | 0 | 0 | c1d1fbf030ac82c643fa5aea4d9f7c302051c38c | 1,563 | advent-of-code-2022 | Apache License 2.0 |
aoc-2023/src/main/kotlin/nerok/aoc/aoc2023/day01/Day01.kt | nerok | 572,862,875 | false | {"Kotlin": 113337} | package nerok.aoc.aoc2023.day01
import nerok.aoc.utils.Input
import kotlin.time.DurationUnit
import kotlin.time.measureTime
fun main() {
fun part1(input: List<String>): Long {
return input.map { line ->
line.filter { it.isDigit() }
}.sumOf { "${it.first()}${it.last()}".toLong() }
}
fun part2(input: List<String>): Any {
return input.sumOf { line ->
"${line.findFirstNumber()}${line.findLastNumber()}".toLong()
}
}
// test if implementation meets criteria from the description, like:
val testInput1 = Input.readInput("Day01_test1")
check(part1(testInput1) == 142L)
val testInput2 = Input.readInput("Day01_test2")
check(part2(testInput2) == 281L)
val input = Input.readInput("Day01")
println(measureTime { println(part1(input)) }.toString(DurationUnit.SECONDS, 3))
println(measureTime { println(part2(input)) }.toString(DurationUnit.SECONDS, 3))
}
private fun String.findFirstNumber(): String {
return findAnyOf(
listOf("1", "2", "3", "4", "5", "6", "7", "8", "9", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine")
)!!.second.convertToDigit()
}
private fun String.findLastNumber(): String {
return findLastAnyOf(
listOf("1", "2", "3", "4", "5", "6", "7", "8", "9", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine")
)!!.second.convertToDigit()
}
private fun String.convertToDigit(): String {
return replace("one", "1")
.replace("two", "2")
.replace("three", "3")
.replace("four", "4")
.replace("five", "5")
.replace("six", "6")
.replace("seven", "7")
.replace("eight", "8")
.replace("nine", "9")
}
| 0 | Kotlin | 0 | 0 | 7553c28ac9053a70706c6af98b954fbdda6fb5d2 | 1,750 | AOC | Apache License 2.0 |
src/Day11.kt | pimtegelaar | 572,939,409 | false | {"Kotlin": 24985} | fun main() {
data class Item(var fear: Long)
class Monkey(
val items: MutableList<Item>,
val operation: (Long) -> Long,
val test: (Long) -> Boolean,
val divisor: Long,
val positive: Int,
val negative: Int,
var inspections: Long = 0
)
fun List<String>.toMonkey(): Monkey {
val (operator, rhs) = this[2].substring(23).split(" ")
return Monkey(
items = this[1].substring(18)
.split(", ")
.map { Item(it.toLong()) }
.toMutableList(),
operation = if (operator == "+") { old ->
old + if (rhs == "old") old else rhs.toLong()
} else { old ->
old * if (rhs == "old") old else rhs.toLong()
},
divisor = this[3].substring(21).toLong(),
test = { item -> item % this[3].substring(21).toLong() == 0L },
positive = this[4].substring(29).toInt(),
negative = this[5].substring(30).toInt()
)
}
fun shenanigans(input: List<String>, rounds: Int, relief: Boolean): Long {
val monkeys = input.chunked(7).map { it.toMonkey() }
val lcm = monkeys.map { it.divisor }.reduce { a, b -> a * b }
for (i in 1..rounds) {
monkeys.forEach { monkey ->
while (monkey.items.isNotEmpty()) {
monkey.inspections++
val item = monkey.items.removeFirst()
item.fear = monkey.operation.invoke(item.fear)
if (relief) {
item.fear = item.fear / 3
}
item.fear = item.fear % lcm
if (monkey.test.invoke(item.fear)) {
monkeys[monkey.positive].items.add(item)
} else {
monkeys[monkey.negative].items.add(item)
}
}
}
}
val (a, b) = monkeys.map { it.inspections }.sorted().takeLast(2)
return a * b
}
fun part1(input: List<String>) = shenanigans(input, 20, true)
fun part2(input: List<String>) = shenanigans(input, 10000, false)
val testInput = readInput("Day11_test")
val input = readInput("Day11")
val part1 = part1(testInput)
check(part1 == 10605L) { part1 }
println(part1(input))
val part2 = part2(testInput)
check(part2 == 2713310158L) { part2 }
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 16ac3580cafa74140530667413900640b80dcf35 | 2,508 | aoc-2022 | Apache License 2.0 |
leetcode/src/main/kotlin/com/artemkaxboy/leetcode/p02/Leet236.kt | artemkaxboy | 513,636,701 | false | {"Kotlin": 547181, "Java": 13948} | package com.artemkaxboy.leetcode.p02
import com.artemkaxboy.leetcode.TreeNode
import java.util.*
/**
* Runtime 199ms Beats 83.59%
* Memory 37.2MB Beats 89.60%
*/
class Leet236 {
class Solution {
fun lowestCommonAncestor(root: TreeNode?, p: TreeNode?, q: TreeNode?): TreeNode? {
val (pNode, qNode) = bfs(root, p, q)
var levelToCheck = minOf(pNode!!.level, qNode!!.level)
var pPeek = pNode
while (pPeek!!.level > levelToCheck) pPeek = pPeek.parent
var qPeek = qNode
while (qPeek!!.level > levelToCheck) qPeek = qPeek.parent
while (pPeek != null) {
if (qPeek?.node?.`val` == pPeek.node?.`val`) return qPeek?.node
pPeek = pPeek.parent
qPeek = qPeek!!.parent
}
return null
}
private fun bfs(root: TreeNode?, p: TreeNode?, q: TreeNode?): Pair<Node?, Node?> {
val toCheck: Queue<Node> = LinkedList<Node>().apply { offer(Node(root, null, 0)) }
var pNode: Node? = null
var qNode: Node? = null
while (toCheck.isNotEmpty()) {
val currentNode = toCheck.poll()
if (currentNode.node?.`val` == p!!.`val`) {
pNode = currentNode
if (qNode != null) break
}
if (currentNode.node?.`val` == q!!.`val`) {
qNode = currentNode
if (pNode != null) break
}
val nextLevel = currentNode.level + 1
currentNode.node?.left?.let { Node(it, currentNode, nextLevel) }?.also { toCheck.offer(it) }
currentNode.node?.right?.let { Node(it, currentNode, nextLevel) }?.also { toCheck.offer(it) }
}
return pNode to qNode
}
data class Node(val node: TreeNode?, val parent: Node?, val level: Int)
}
companion object {
@JvmStatic
fun main(args: Array<String>) {
val testCase1 = Data("[3,5,1,6,2,0,8,null,null,7,4]", 5, 1, 3)
doWork(testCase1)
}
private fun doWork(data: Data) {
val solution = Solution()
val result = solution.lowestCommonAncestor(
TreeNode.fromString(data.input), TreeNode(data.v1), TreeNode(data.v2)
)
println("Data: ${data.input}")
println("Expected: ${data.expected}")
println("Result: $result\n")
}
}
data class Data(
val input: String,
val v1: Int,
val v2: Int,
val expected: Int,
)
}
| 0 | Kotlin | 0 | 0 | 516a8a05112e57eb922b9a272f8fd5209b7d0727 | 2,686 | playground | MIT License |
src/Day07.kt | mandoway | 573,027,658 | false | {"Kotlin": 22353} | sealed class Path(val name: String, val parent: Directory?) {
class Directory(name: String, parent: Directory? = null, val subPaths: MutableSet<Path> = mutableSetOf()) :
Path(name, parent) {
fun forEachDepthFirst(action: (Directory) -> Unit) {
action(this)
subPaths.forEach {
if (it is Directory) {
it.forEachDepthFirst(action)
}
}
}
override fun toString(): String {
return "Directory(name=$name)"
}
}
class File(name: String, val fileSize: Int, parent: Directory? = null) : Path(name, parent) {
override fun toString(): String {
return "File(name=$name)"
}
}
val size: Int
get() = when (this) {
is Directory -> subPaths.sumOf { it.size }
is File -> fileSize
}
}
fun getDirectorySizes(input: List<String>): List<Int> {
val root = Path.Directory("/")
var currentPath = root
input.drop(1)
.forEach {
when {
it.startsWith("$ cd") -> {
val newDirName = it.substringAfterLast(" ")
currentPath = when (newDirName) {
".." -> {
currentPath.parent!!
}
"/" -> {
root
}
else -> {
val newDir = Path.Directory(newDirName, currentPath)
currentPath.subPaths.add(newDir)
newDir
}
}
}
it.startsWith("$ ls") -> {
// noop
}
it.startsWith("dir") -> {
// noop
}
else -> {
val filename = it.substringAfterLast(" ")
val filesize = it.substringBefore(" ").toInt()
val file = Path.File(filename, filesize, currentPath)
currentPath.subPaths.add(file)
}
}
}
val sizes = mutableListOf<Int>()
root.forEachDepthFirst {
sizes.add(it.size)
}
return sizes
}
fun main() {
fun part1(input: List<String>): Int {
return getDirectorySizes(input).filter { it < 100000 }.sum()
}
fun part2(input: List<String>): Int {
val totalDiskSpace = 70_000_000
val neededDiskSpace = 30_000_000
val sizes = getDirectorySizes(input)
val usedDiskSpace = sizes[0]
val unusedSpace = totalDiskSpace - usedDiskSpace
val minimumDirectorySize = neededDiskSpace - unusedSpace
return sizes.filter { it >= minimumDirectorySize }.min()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day07_test")
check(part1(testInput) == 95437)
check(part2(testInput) == 24933642)
val input = readInput("Day07")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 0393a4a25ae4bbdb3a2e968e2b1a13795a31bfe2 | 3,156 | advent-of-code-22 | Apache License 2.0 |
src/main/kotlin/org/sjoblomj/adventofcode/day8/Day8.kt | sjoblomj | 161,537,410 | false | null | package org.sjoblomj.adventofcode.day8
import org.sjoblomj.adventofcode.readFile
import kotlin.system.measureTimeMillis
private const val inputFile = "src/main/resources/inputs/day8.txt"
fun day8() {
println("== DAY 8 ==")
val timeTaken = measureTimeMillis { calculateAndPrintDay8() }
println("Finished Day 8 in $timeTaken ms\n")
}
private fun calculateAndPrintDay8() {
val indata = readFile(inputFile)[0]
val tree = parseLicense(indata)
println("Sum of all metadata entries: ${calculateMetadataSumPart1(tree)}")
println("Value of root node: ${calculateMetadataForTree(tree)}")
}
internal fun calculateMetadataSumPart1(tree: Tree): Int = tree.metadata.sum() + tree.children.map { calculateMetadataSumPart1(it) }.sum()
internal fun calculateMetadataForTree(tree: Tree): Int {
return if (tree.children.isEmpty())
tree.metadata.sum()
else
tree.metadata.map { calculateChildMetadata(tree, it - 1) }.sum()
}
internal fun calculateChildMetadata(tree: Tree, index: Int) = if (index > tree.children.lastIndex) 0 else calculateMetadataForTree(tree.children[index])
internal fun parseLicense(licenseFile: String): Tree {
val license = licenseFile.split(" ").map { it.toInt() }
return createTree(license, 0)
}
private fun createTree(data: List<Int>, startPos: Int): Tree {
val numberOfChildren = data[startPos]
val numberOfMetadataEntries = data[startPos + 1]
var index = 2 + startPos
val children = mutableListOf<Tree>()
for (i in 0 until numberOfChildren) {
val child = createTree(data, index)
children.add(child)
index = child.endedAt + 1
}
return Tree(children, data.drop(index).take(numberOfMetadataEntries), startPos, index + numberOfMetadataEntries - 1)
}
| 0 | Kotlin | 0 | 0 | 80db7e7029dace244a05f7e6327accb212d369cc | 1,722 | adventofcode2018 | MIT License |
src/main/kotlin/se/saidaspen/aoc/aoc2022/Day22.kt | saidaspen | 354,930,478 | false | {"Kotlin": 301372, "CSS": 530} | package se.saidaspen.aoc.aoc2022
import se.saidaspen.aoc.aoc2022.Day22.DIR.*
import se.saidaspen.aoc.aoc2022.Day22.SIDE.*
import se.saidaspen.aoc.util.*
import kotlin.collections.minBy
fun main() = Day22.run()
object Day22 : Day(2022, 22) {
enum class DIR(val p: Point) { RIGHT(P(1, 0)), DOWN(P(0, 1)), LEFT(P(-1, 0)), UP(P(0, -1));
fun right() = values()[(this.ordinal + 1).mod(values().size)]
fun left() = values()[(this.ordinal - 1).mod(values().size)]
}
enum class SIDE { A, B, C, D, E, F }
private val map = toMap(input.split("\n\n")[0]).entries.filter { it.value != ' ' }.associate { it.key to it.value }
override fun part1() = solve(input.split("\n\n")[1]) { curr, dir -> planeWrap(curr, dir) }
override fun part2() = solve(input.split("\n\n")[1]) { curr, dir -> cubeWrap(curr, dir) }
private fun solve(fullInstr: String, next: (P<Int, Int>, DIR) -> P<P<Int, Int>, DIR>): Int {
var instr = fullInstr
val startPos = map.entries.filter { it.key.second == 0 }.minByOrNull { it.key.first }!!.key
var currPos = startPos
var currDir = RIGHT
while (instr.isNotEmpty()) {
val firstTurnIdx = instr.indexOfFirst { it == 'R' || it == 'L' }
// MOVING
if (firstTurnIdx > 0 || firstTurnIdx == -1) {
val move = if (firstTurnIdx == -1) instr.toInt() else instr.substring(0, firstTurnIdx).toInt()
instr = if (firstTurnIdx == -1) "" else instr.substring(firstTurnIdx)
for (i in 0 until move) {
val (nextPos, nextDir) =
if (map.containsKey(currPos + currDir.p)) { P(currPos + currDir.p, currDir) } // Normal move
else { next(currPos, currDir) } //Wrap around
if (map[nextPos] == '#') break
else {
currPos = nextPos
currDir = nextDir
}
}
} else { // TURNING
currDir = if (instr[0] == 'R') { currDir.right() } else { currDir.left() }
instr = instr.drop(1)
}
}
return 1000 * (currPos.second + 1) + 4 * (currPos.first + 1) + currDir.ordinal
}
private fun planeWrap(curr: P<Int, Int>, dir: DIR): P<P<Int, Int>, DIR> {
return when (dir) {
DOWN -> P(map.entries.filter { it.key.first == curr.first }.minBy { it.key.second }.key, dir)
UP -> P(map.entries.filter { it.key.first == curr.first }.maxBy { it.key.second }.key, dir)
RIGHT -> P(map.entries.filter { it.key.second == curr.second }.minBy { it.key.first }.key, dir)
LEFT -> P(map.entries.filter { it.key.second == curr.second }.maxBy { it.key.first }.key, dir)
}
}
fun cubeWrap(curr: P<Int, Int>, currDir: DIR): P<P<Int, Int>, DIR> {
var nextDir = currDir
val currSide = sideOf(curr)
var nextPos = curr
if (currSide == A && currDir == UP) {
nextDir = RIGHT
nextPos = P(0, 3 * 50 + curr.x - 50) // nextSide = F
} else if (currSide == A && currDir == LEFT) {
nextDir = RIGHT
nextPos = P(0, 2 * 50 + (50 - curr.y - 1)) // nextSide = E
} else if (currSide == B && currDir == UP) {
nextDir = UP
nextPos = P(curr.first - 100, 199) // nextSide = F
} else if (currSide == B && currDir == RIGHT) {
nextDir = LEFT
nextPos = P(99, (50 - curr.second) + 2 * 50 - 1) // nextSide = D
} else if (currSide == B && currDir == DOWN) {
nextDir = LEFT
nextPos = P(99, 50 + (curr.x - 2 * 50)) // nextSide = C
} else if (currSide == C && currDir == RIGHT) {
nextDir = UP
nextPos = P((curr.y - 50) + 2 * 50, 49) // nextSide = B
} else if (currSide == C && currDir == LEFT) {
nextDir = DOWN
nextPos = P(curr.y - 50, 100) // nextSide = E
} else if (currSide == E && currDir == LEFT) {
nextDir = RIGHT
nextPos = P(50, 50 - (curr.y - 2 * 50) - 1) // nextSide = A
} else if (currSide == E && currDir == UP) {
nextDir = RIGHT
nextPos = P(50, 50 + curr.x) // nextSide = C
} else if (currSide == D && currDir == DOWN) {
nextDir = LEFT
nextPos = P(49, 3 * 50 + (curr.x - 50)) // nextSide = F
} else if (currSide == D && currDir == RIGHT) {
nextDir = LEFT
nextPos = P(149, 50 - (curr.y - 50 * 2) - 1) // nextSide = B
} else if (currSide == F && currDir == RIGHT) {
nextDir = UP
nextPos = P((curr.y - 3 * 50) + 50, 149) // nextSide = D
} else if (currSide == F && currDir == LEFT) {
nextDir = DOWN
nextPos = P(50 + (curr.y - 3 * 50), 0) // nextSide = A
} else if (currSide == F && currDir == DOWN) {
nextDir = DOWN
nextPos = P(curr.x + 100, 0) // nextSide = B
}
return P(nextPos, nextDir)
}
private fun sideOf(pos: Point): SIDE {
if (pos.x in 50..99 && pos.y in 0..49) return A
if (pos.x in 100..149 && pos.y in 0..49) return B
if (pos.x in 50..99 && pos.y in 50..99) return C
if (pos.x in 50..99 && pos.y in 100..149) return D
if (pos.x in 0..49 && pos.y in 100..149) return E
if (pos.x in 0..49 && pos.y in 150..199) return F
throw java.lang.RuntimeException("Side does not exist for $pos")
}
}
| 0 | Kotlin | 0 | 1 | be120257fbce5eda9b51d3d7b63b121824c6e877 | 5,577 | adventofkotlin | MIT License |
2023/src/main/kotlin/day8.kt | madisp | 434,510,913 | false | {"Kotlin": 388138} | import utils.Parse
import utils.Parser
import utils.Solution
import utils.lcm
fun main() {
Day8.run()
}
object Day8 : Solution<Day8.Input>() {
override val name = "day8"
override val parser = Parser { parseInput(it) }
@Parse("{instructions}\n\n{r '\n' edges}")
data class Input(
val instructions: String,
val edges: List<Edge>,
)
@Parse("{from} = ({left}, {right})")
data class Edge(
val from: String,
val left: String,
val right: String,
)
private fun len(from: String, arrived: (String) -> Boolean): Pair<String, Int>? {
val edges = input.edges.groupBy { it.from }
var node = from
var steps = 0
while (!arrived(node) || steps == 0) {
val insn = input.instructions[steps % input.instructions.length]
val edge = edges[node] ?: return null
node = if (insn == 'L') edge.first().left else edge.first().right
steps++
}
return node to steps
}
override fun part1(input: Day8.Input): Int? {
return len("AAA") { it == "ZZZ" }?.second
}
override fun part2(input: Day8.Input): Long {
val starts = input.edges.filter { it.from.endsWith("A") }.map { it.from }
val ends = input.edges.filter { it.from.endsWith("Z") }.map { it.from }
val arrival: (String) -> Boolean = { it.endsWith('Z') }
// cycles between ends?
val endCycles = ends.associateWith { e -> len(e, arrival) }
val offs = starts.associateWith { s -> len(s, arrival) }
val cycles = offs.entries.associate { (key, off) ->
val cycleLen = endCycles[off!!.first]
key to (off.second to cycleLen?.second)
}
if (cycles.values.any { it.first != it.second }) {
// TODO(madis) can we get rid of this restriction?
throw IllegalStateException("Offset is not the same as cycle length for starting point")
}
return lcm(cycles.values.map { it.first })
}
}
| 0 | Kotlin | 0 | 1 | 3f106415eeded3abd0fb60bed64fb77b4ab87d76 | 1,872 | aoc_kotlin | MIT License |
src/main/kotlin/days/Day3.kt | vovarova | 726,012,901 | false | {"Kotlin": 48551} | package days
import util.GridCell
import util.DayInput
import util.Matrix
class Day3 : Day("3") {
private fun gridNumbers(input: List<String>): MutableList<Pair<Int, List<GridCell<Char>>>> {
val matrix = Matrix(input.map {
it.toCharArray().toTypedArray()
}.toTypedArray())
val gridNumbers = mutableListOf<Pair<Int, List<GridCell<Char>>>>()
val numberParts = mutableListOf<GridCell<Char>>()
for (row in matrix.matrixGrid.indices) {
for (column in matrix.matrixGrid[row].indices) {
if (matrix.cell(row, column).value.isDigit()) {
numberParts.add(matrix.cell(row, column))
} else {
if (numberParts.isNotEmpty()) {
gridNumbers.add(
Pair(
numberParts.map { it.value }.joinToString("").toInt(),
listOf(*numberParts.toTypedArray())
)
)
numberParts.clear()
}
}
}
if (numberParts.isNotEmpty()) {
gridNumbers.add(
Pair(
numberParts.map { it.value }.joinToString("").toInt(),
listOf(*numberParts.toTypedArray())
)
)
numberParts.clear()
}
}
return gridNumbers;
}
override fun partOne(dayInput: DayInput): Any {
val validNumbers = gridNumbers(dayInput.inputList()).filter {
it.second.any {
it.diagonalNeighbours().any {
it.value != '.' && !it.value.isDigit()
} || it.straightNeighbours().any {
it.value != '.' && !it.value.isDigit()
}
}
}
return validNumbers.map { it.first }.sum()
}
override fun partTwo(dayInput: DayInput): Any {
return gridNumbers(dayInput.inputList()).flatMap {
it.second.flatMap {
mutableListOf<GridCell<Char>>().also { elements ->
elements.addAll(it.straightNeighbours())
elements.addAll(it.diagonalNeighbours())
}
}.distinct().filter { it.value == '*' }.map { start ->
Pair(start, it.first)
}
}.groupBy { it.first }.filter { it.value.size > 1 }.map {
it.value.map { it.second }.reduce { acc, i -> acc * i }
}.sum()
}
}
fun main() {
Day3().run()
}
| 0 | Kotlin | 0 | 0 | 77df1de2a663def33b6f261c87238c17bbf0c1c3 | 2,642 | adventofcode_2023 | Creative Commons Zero v1.0 Universal |
src/Day11.kt | spaikmos | 573,196,976 | false | {"Kotlin": 83036} | fun main() {
fun calcAns(numRuns: Int, isPart1: Boolean): Long {
repeat(numRuns) {
Monkey.monkeys.map{ it.Run(isPart1) }
}
return Monkey.monkeys.map{ it.numItemsInspected }.sortedDescending().take(2).reduce{ tot, it -> it * tot }
}
val input = readInput("../input/Day11")
// Parse input into monkey class
parseInput(input)
println(calcAns(20, true)) // 101436
println(calcAns(10_000, false)) // 19754471646
}
fun parseInput(input: List<String>) {
for (i in input.chunked(7)) {
val items = i[1].substring(18).split(", ").map { it.toLong() }
val opChar = i[2][23]
val opNum = i[2].substring(25)
val test = i[3].filter{ it.isDigit() }.toInt()
val ifTrue = i[4][29] - '0'
val ifFalse = i[5][30] - '0'
var op = Operation.SQUARE
var num = 0
when (opChar) {
'*' -> op = Operation.MULTIPLY
'+' -> op = Operation.PLUS
}
if (opNum[0].isDigit()) {
num = opNum.toInt()
} else {
op = Operation.SQUARE
}
//println(i)
//println("items: $items opChar: $opChar opNum: $opNum test: $test true: $ifTrue false: $ifFalse op: $op num: $num")
Monkey(op, num, test, ifTrue, ifFalse, items.toMutableList())
}
}
class Monkey(var op: Operation, var num: Int, var test: Int, var ifTrue: Int, var ifFalse: Int, var items: MutableList<Long>) {
companion object {
var monkeys = ArrayList<Monkey>()
var divider = 1L
}
var numItemsInspected = 0L
init {
monkeys.add(this)
divider *= test
}
fun Run (isPart1: Boolean) {
for (a in items) {
var i = a
when (op) {
Operation.PLUS -> i += num
Operation.MULTIPLY -> i *= num
Operation.SQUARE -> i *= a
}
// Hack to perform different worry operations based on part 1 vs part 2
if (isPart1) {
// In part 1, worry function is item score floor(item.mod(3)). Integer divide!
i /= 3
} else {
// In part 2, worry function divides item score by the product of all the tests
i = i.mod(divider)
}
when (i.mod(test)) {
0 -> monkeys[ifTrue].items.add(i)
else -> monkeys[ifFalse].items.add(i)
}
numItemsInspected++
}
items.clear()
}
}
enum class Operation {
PLUS, MULTIPLY, SQUARE
} | 0 | Kotlin | 0 | 0 | 6fee01bbab667f004c86024164c2acbb11566460 | 2,591 | aoc-2022 | Apache License 2.0 |
src/Day24.kt | mjossdev | 574,439,750 | false | {"Kotlin": 81859} | fun main() {
fun Char.toDirection() = when (this) {
'^' -> Direction.UP
'v' -> Direction.DOWN
'<' -> Direction.LEFT
'>' -> Direction.RIGHT
else -> error("$this is not a direction")
}
data class Point(val row: Int, val col: Int)
fun Point.next(direction: Direction) = when (direction) {
Direction.UP -> copy(row = row - 1)
Direction.DOWN -> copy(row = row + 1)
Direction.LEFT -> copy(col = col - 1)
Direction.RIGHT -> copy(col = col + 1)
}
data class Blizzard(val position: Point, val direction: Direction)
data class Valley(val start: Point, val goal: Point, val walls: Set<Point>, val blizzards: Set<Blizzard>)
fun readValley(input: List<String>): Valley {
var start: Point? = null
var goal: Point? = null
val walls = mutableSetOf<Point>()
val blizzards = mutableSetOf<Blizzard>()
input.forEachIndexed { rowIndex, row ->
row.forEachIndexed { colIndex, cell ->
val position = Point(rowIndex, colIndex)
when (cell) {
'#' -> walls.add(position)
'.' -> {
when (rowIndex) {
0 -> start = position
input.lastIndex -> goal = position
}
}
else -> blizzards.add(Blizzard(position, cell.toDirection()))
}
}
}
return Valley(start!!, goal!!, walls, blizzards)
}
fun calculateMinutes(valley: Valley, goals: List<Point>): Int {
val walls = valley.walls
val rightEdge = walls.maxOf { it.col }
val bottomEdge = walls.maxOf { it.row }
fun Point.isInBounds() = row in 0..bottomEdge && col in 0..rightEdge
val directions = Direction.values().toList()
var possiblePositions = setOf(valley.start)
var blizzards = valley.blizzards.groupBy { it.position }
var minutes = 0
for (goal in goals) {
while (possiblePositions.none { it == goal }) {
blizzards = blizzards.values.asSequence().flatMap {
it.map { blizzard ->
val (position, direction) = blizzard
val nextPosition = position.next(direction)
blizzard.copy(
position = if (nextPosition in walls) {
when (direction) {
Direction.UP -> position.copy(row = bottomEdge - 1)
Direction.DOWN -> position.copy(row = 1)
Direction.LEFT -> position.copy(col = rightEdge - 1)
Direction.RIGHT -> position.copy(col = 1)
}
} else {
nextPosition
}
)
}
}.groupBy { it.position }
possiblePositions = possiblePositions.asSequence().flatMap { p ->
sequence {
directions.forEach {
val nextPosition = p.next(it)
if (nextPosition.isInBounds() && nextPosition !in walls && nextPosition !in blizzards) {
yield(nextPosition)
}
}
if (p !in blizzards) {
yield(p)
}
}
}.toSet()
++minutes
}
possiblePositions = setOf(goal)
}
return minutes
}
fun part1(input: List<String>): Int {
val valley = readValley(input)
return calculateMinutes(valley, listOf(valley.goal))
}
fun part2(input: List<String>): Int {
val valley = readValley(input)
return calculateMinutes(valley, listOf(valley.goal, valley.start, valley.goal))
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day24_test")
check(part1(testInput) == 18)
check(part2(testInput) == 54)
val input = readInput("Day24")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | afbcec6a05b8df34ebd8543ac04394baa10216f0 | 4,424 | advent-of-code-22 | Apache License 2.0 |
src/Day16.kt | fedochet | 573,033,793 | false | {"Kotlin": 77129} | fun main() {
class ValueInfo(val name: String, val rate: Int, val connectedTo: List<String>)
fun parseValve(str: String): ValueInfo {
val pattern = Regex("Valve (\\w+) has flow rate=(\\d+); tunnels? leads? to valves? (\\w+(, \\w+)*)")
val (name, rate, connectedTo) = pattern.matchEntire(str)?.destructured ?: error("Cannot parse $str")
return ValueInfo(name, rate.toInt(), connectedTo.split(", "))
}
fun computeDistances(valves: List<ValueInfo>, nameToIndex: Map<String, Int>): Array<IntArray> {
val distances = List(valves.size) { MutableList(valves.size) { Int.MAX_VALUE.toLong() } }
for (i in valves.indices) {
distances[i][i] = 0
for (next in valves[i].connectedTo) {
val nextIdx = nameToIndex.getValue(next)
distances[nextIdx][i] = 1
distances[i][nextIdx] = 1
}
}
for (middle in distances.indices) {
for (from in distances.indices) {
for (to in distances.indices) {
val newLength = distances[from][middle] + distances[middle][to]
if (distances[from][to] > newLength) {
distances[from][to] = newLength
distances[to][from] = newLength
}
}
}
}
return distances.map { row -> row.map { it.toInt() }.toIntArray() }.toTypedArray()
}
fun findOptimalPath(
from: Int,
distances: Array<IntArray>,
nameToRate: IntArray,
toVisit: BooleanArray,
remainingTime: Int
): Int {
if (remainingTime <= 0) return 0
val currentImpact = nameToRate[from] * remainingTime
var nextImpact = 0
for (next in toVisit.indices) {
if (nameToRate[next] == 0 || !toVisit[next]) continue
toVisit[next] = false
val wasted = distances[from][next] + 1 // time to open the valve
val impact = findOptimalPath(
next,
distances,
nameToRate,
toVisit,
remainingTime - wasted
)
toVisit[next] = true
if (nextImpact < impact) {
nextImpact = impact
}
}
return currentImpact + nextImpact
}
fun part1(input: List<String>): Int {
val valves = input.map { parseValve(it) }
val graph = mutableMapOf<String, Set<String>>()
for (valve in valves) {
graph[valve.name] = valve.connectedTo.toSet()
}
val nameToIndex = valves.withIndex().associate { (idx, value) -> value.name to idx }
val distances = computeDistances(valves, nameToIndex)
val startIdx = valves.indexOfFirst { it.name == "AA" }
return findOptimalPath(
startIdx,
distances,
valves.map { it.rate }.toIntArray(),
valves.map { true }.toBooleanArray(),
30
)
}
fun findOptimalPathWithElephant(
from: Int,
startForElephant: Int,
distances: Array<IntArray>,
nameToRate: IntArray,
toVisit: BooleanArray,
remainingTime: Int
): Int {
if (remainingTime <= 0) return 0
val currentImpact = nameToRate[from] * remainingTime
var nextImpact = 0
for (next in toVisit.indices) {
if (nameToRate[next] == 0 || !toVisit[next]) continue
toVisit[next] = false
val wasted = distances[from][next] + 1 // time to open the valve
val impact = findOptimalPathWithElephant(
next,
startForElephant,
distances,
nameToRate,
toVisit,
remainingTime - wasted
)
toVisit[next] = true
if (nextImpact < impact) {
nextImpact = impact
}
}
val elephantPath = findOptimalPath(startForElephant, distances, nameToRate, toVisit, 26)
if (nextImpact < elephantPath) {
nextImpact = elephantPath
}
return currentImpact + nextImpact
}
fun part2(input: List<String>): Int {
val valves = input.map { parseValve(it) }
val graph = mutableMapOf<String, Set<String>>()
for (valve in valves) {
graph[valve.name] = valve.connectedTo.toSet()
}
val nameToIndex = valves.withIndex().associate { (idx, value) -> value.name to idx }
val distances = computeDistances(valves, nameToIndex)
val startIdx = valves.indexOfFirst { it.name == "AA" }
return findOptimalPathWithElephant(
startIdx,
startForElephant = startIdx,
distances,
valves.map { it.rate }.toIntArray(),
valves.map { true }.toBooleanArray(),
26
)
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day16_test")
check(part1(testInput) == 1651)
check(part2(testInput) == 1707)
val input = readInput("Day16")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 1 | 975362ac7b1f1522818fc87cf2505aedc087738d | 5,268 | aoc2022 | Apache License 2.0 |
src/Day04.kt | wbars | 576,906,839 | false | {"Kotlin": 32565} | import java.lang.Integer.min
import kotlin.math.max
data class Range(val l: Int, var r: Int) {
fun contains(range: Range): Boolean {
return l <= range.l && r >= range.r
}
fun overlap(second: Range): Boolean {
return max(second.l, l) <= min(second.r, r)
}
}
fun main() {
fun ranges(input: List<String>) = input.map {
val i = it.indexOf(',')
Pair(it.substring(0, i).range(), it.substring(i + 1).range())
}
fun part1(input: List<String>): Int {
return ranges(input).count { it.first.contains(it.second) || it.second.contains(it.first) }
}
fun part2(input: List<String>): Int {
return ranges(input).count { it.first.overlap(it.second) }
}
part1(readInput("input")).println()
part2(readInput("input")).println()
}
private fun String.range(): Range {
val split = split("-")
return Range(split[0].toInt(), split[1].toInt())
}
| 0 | Kotlin | 0 | 0 | 344961d40f7fc1bb4e57f472c1f6c23dd29cb23f | 932 | advent-of-code-2022 | Apache License 2.0 |
src/Day05.kt | Kvest | 573,621,595 | false | {"Kotlin": 87988} | import java.util.*
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 =
solve(input) { stacks, cmd ->
repeat(cmd.count) {
stacks[cmd.to].push(stacks[cmd.from].pop())
}
}
private fun part2(input: List<String>): String {
val stack = LinkedList<Char>()
return solve(input) { stacks, cmd ->
repeat(cmd.count) {
stack.push(stacks[cmd.from].pop())
}
while (stack.isNotEmpty()) {
stacks[cmd.to].push(stack.pop())
}
}
}
private fun solve(input: List<String>, reorderStrategy: (List<LinkedList<Char>>, Command) -> Unit): String {
val dividerIndex = input.indexOfFirst { it.isEmpty() }
val stacks = input
.subList(0, dividerIndex)
.toInitialStacks()
input
.subList(dividerIndex + 1, input.lastIndex + 1)
.map(String::toCommand)
.forEach { cmd ->
reorderStrategy(stacks, cmd)
}
return stacks.joinToString(separator = "") {
it.pop().toString()
}
}
private fun List<String>.toInitialStacks(): List<LinkedList<Char>> {
val count = this.last()
.trim()
.drop(
this.last()
.lastIndexOf(' ')
)
.toInt()
val list = List(count) { LinkedList<Char>() }
this.subList(0, this.lastIndex)
.asReversed()
.forEach { row ->
var i = 1
while (i <= row.lastIndex) {
if (row[i].isLetter()) {
list[i / 4].push(row[i])
}
i += 4
}
}
return list
}
private val COMMAND_FORMAT = Regex("move (\\d+) from (\\d+) to (\\d+)")
private fun String.toCommand(): Command {
val match = COMMAND_FORMAT.find(this)
val (move, from, to) = requireNotNull(match).destructured
return Command(from = from.toInt() - 1, to = to.toInt() - 1, count = move.toInt())
}
private class Command(val from: Int, val to: Int, val count: Int) | 0 | Kotlin | 0 | 0 | 6409e65c452edd9dd20145766d1e0ea6f07b569a | 2,211 | AOC2022 | Apache License 2.0 |
src/day20/Day20.kt | dkoval | 572,138,985 | false | {"Kotlin": 86889} | package day20
import readInput
private const val DAY_ID = "20"
fun main() {
fun solve(input: List<String>, mixes: Int, transform: (x: Long) -> Long): Long {
val nums = input.asSequence()
.map { transform(it.toLong()) }
.withIndex()
.toMutableList()
val n = nums.size
repeat(mixes) { _ ->
for (i in 0 until n) {
val oldIdx = nums.indexOfFirst { it.index == i }
val x = nums[oldIdx]
val moves = (x.value % (n - 1)).toInt()
if (moves == 0) continue
var newIdx = oldIdx + moves
if (newIdx <= 0) {
newIdx %= n - 1
newIdx += n - 1
} else if (newIdx >= n) {
newIdx %= n - 1
}
nums.removeAt(oldIdx)
nums.add(newIdx, x)
}
}
val offsets = listOf(1000, 2000, 3000)
val zeroIdx = nums.indexOfFirst { it.value == 0L }
return offsets.fold(0L) { acc, offset ->
val idx = (zeroIdx + offset) % n
acc + nums[idx].value
}
}
fun part1(input: List<String>): Long = solve(input, 1) { x -> x }
fun part2(input: List<String>): Long = solve(input, 10) { x -> x * 811589153 }
// test if implementation meets criteria from the description, like:
val testInput = readInput("day${DAY_ID}/Day${DAY_ID}_test")
check(part1(testInput) == 3L)
check(part2(testInput) == 1623178306L)
val input = readInput("day${DAY_ID}/Day${DAY_ID}")
println(part1(input)) // answer = 4914
println(part2(input)) // answer = 7973051839072
}
| 0 | Kotlin | 1 | 0 | 791dd54a4e23f937d5fc16d46d85577d91b1507a | 1,712 | aoc-2022-in-kotlin | Apache License 2.0 |
src/Day05.kt | JIghtuse | 572,807,913 | false | {"Kotlin": 46764} | package day05
import java.io.File
import java.util.Stack
data class Movement(val amount: Int, val stackFrom: Int, val stackTo: Int)
fun String.toMovement(): Movement {
val parts = this.split(" ")
return Movement(parts[1].toInt(), parts[3].toInt() - 1, parts[5].toInt() - 1)
}
typealias Stacks = List<Stack<Char>>
typealias Movements = List<Movement>
fun parseStacksAndMovements(name: String): Pair<Stacks, Movements> {
val (stacksString, movementsString) = File("src", "$name.txt")
.readText()
.split("\n\n")
val stackLines = stacksString.split("\n")
val numberOfStacks = stackLines.last().split(" ").size
val stacks = List(numberOfStacks) { Stack<Char>() }
for (row in stackLines.subList(0, toIndex = stackLines.lastIndex).reversed()) {
for (itemIndex in 1 until row.length step 4) {
val letter = row[itemIndex]
if (letter == ' ') continue
stacks[(itemIndex - 1) / 4].push(letter)
}
}
val movements = movementsString.lines().map(String::toMovement)
return stacks to movements
}
fun joinTops(stacks: Stacks) =
stacks.map{ it.last() }.joinToString("")
// some sketch of simple visualization
fun display(stacks: Stacks) {
repeat(5) {
println()
}
val maxHeight = stacks.maxOf { it.size }
for (i in maxHeight downTo 1) {
for (stack in stacks) {
if (stack.size < i) {
print(" ")
} else {
print("[${stack[i - 1]}] ")
}
}
println()
}
}
fun main() {
fun part1(input: Pair<Stacks, Movements>): String {
val (stacks, movements) = input
movements.forEach {
for (i in 1..it.amount) {
val x = stacks[it.stackFrom].pop()
stacks[it.stackTo].push(x)
}
}
return joinTops(stacks)
}
fun part2(input: Pair<Stacks, Movements>): String {
val (stacks, movements) = input
movements.forEach {
val reversingStack = Stack<Char>()
for (i in 1..it.amount) {
val x = stacks[it.stackFrom].pop()
reversingStack.push(x)
}
while (reversingStack.isNotEmpty()) {
stacks[it.stackTo].push(reversingStack.pop())
}
}
return joinTops(stacks)
}
// test if implementation meets criteria from the description, like:
check(part1(parseStacksAndMovements("Day05_test")) == "CMZ")
check(part2(parseStacksAndMovements("Day05_test")) == "MCD")
println(part1(parseStacksAndMovements("Day05")))
println(part2(parseStacksAndMovements("Day05")))
} | 0 | Kotlin | 0 | 0 | 8f33c74e14f30d476267ab3b046b5788a91c642b | 2,716 | aoc-2022-in-kotlin | Apache License 2.0 |
src/poyea/aoc/mmxxii/day04/Day04.kt | poyea | 572,895,010 | false | {"Kotlin": 68491} | package poyea.aoc.mmxxii.day04
import poyea.aoc.utils.readInput
fun part1(input: String): Int {
return input.split("\n").flatMap {
it.split(",").map { sections ->
sections.split("-").map { array -> array.toInt() }
}.chunked(2).map { assignment ->
val list1 = assignment[0]
val list2 = assignment[1]
// Full intersection
if (list1[0] >= list2[0] && list1[1] <= list2[1] || list1[0] <= list2[0] && list1[1] >= list2[1]) 1 else 0
}
}.sum()
}
fun part2(input: String): Int {
return input.split("\n").flatMap {
it.split(",").map { sections ->
sections.split("-").map { array -> array.toInt() }
}.chunked(2).map { assignment ->
val list1 = assignment[0]
val list2 = assignment[1]
// Any intersection
if (list1[0] <= list2[1] && list1[1] >= list2[0]) 1 else 0
}
}.sum()
}
fun main() {
println(part1(readInput("Day04")))
println(part2(readInput("Day04")))
}
| 0 | Kotlin | 0 | 1 | fd3c96e99e3e786d358d807368c2a4a6085edb2e | 1,046 | aoc-mmxxii | MIT License |
src/main/kotlin/day5.kt | gautemo | 433,582,833 | false | {"Kotlin": 91784} | import shared.getLines
fun findOverlappingVents(lines: List<String>, includeDiagonals: Boolean = false): Int{
val vents = lines.map { Vent(it) }.filter { includeDiagonals || !it.isDiagonal }
val maxX = vents.maxOf { maxOf(it.xLine.first, it.xLine.last) }
val maxY = vents.maxOf { maxOf(it.yLine.first, it.yLine.last) }
val minX = vents.minOf { minOf(it.xLine.first, it.xLine.last) }
val minY = vents.minOf { minOf(it.yLine.first, it.yLine.last) }
var count = 0
for(x in minX..maxX){
for(y in minY..maxY){
if(vents.countTo(2){ it.overPoint(x,y)}) count++
}
}
return count
}
fun List<Vent>.countTo(goal: Int, predicate: (Vent) -> Boolean): Boolean{
var count = 0
for(vent in this){
if(predicate(vent)) {
count++
if(count == goal) return true
}
}
return false
}
class Vent(line: String){
val xLine: IntProgression
val yLine: IntProgression
val isDiagonal: Boolean
init {
val (a, b) = line.split("->").map { coordinates -> coordinates.trim().split(",").map { it.toInt() } }
xLine = if(a[0] <= b[0]) a[0]..b[0] else a[0] downTo b[0]
yLine = if(a[1] <= b[1]) a[1]..b[1] else a[1] downTo b[1]
isDiagonal = xLine.count() > 1 && yLine.count() > 1
}
fun overPoint(x: Int, y: Int): Boolean{
if(isDiagonal){
val indexX = xLine.indexOf(x)
return indexX != -1 && indexX == yLine.indexOf(y)
}
return xLine.contains(x) && yLine.contains(y)
}
}
fun main(){
val input = getLines("day5.txt")
val result = findOverlappingVents(input)
println(result)
val result2 = findOverlappingVents(input, true)
println(result2)
} | 0 | Kotlin | 0 | 0 | c50d872601ba52474fcf9451a78e3e1bcfa476f7 | 1,750 | AdventOfCode2021 | MIT License |
y2022/src/main/kotlin/adventofcode/y2022/Day08.kt | Ruud-Wiegers | 434,225,587 | false | {"Kotlin": 503769} | package adventofcode.y2022
import adventofcode.io.AdventSolution
import adventofcode.util.algorithm.transpose
import adventofcode.util.vector.Direction
import adventofcode.util.vector.Vec2
object Day08 : AdventSolution(2022, 8, "Treetop Tree House") {
override fun solvePartOne(input: String): Int {
val heights = input.lines().map { it.map(Char::digitToInt) }
val positions = heights.indices.flatMap { y -> heights[0].indices.map { x -> Vec2(x, y) } }
fun line(position: Vec2, direction: Direction) =
generateSequence(position) { it + direction.vector }
.takeWhile { (x, y) -> x in heights.indices && y in heights[0].indices }
.drop(1)
return positions.count { tree ->
Direction.values().any { d ->
line(tree, d).all { (x, y) ->
heights[y][x] < heights[tree.y][tree.x]
}
}
}
}
override fun solvePartTwo(input: String): Int {
val heights = input.lines().map { it.map(Char::digitToInt) }
val transposed = heights.transpose()
val viewScores = heights.flatMapIndexed { y, line ->
line.mapIndexed { x, tree ->
val left = (heights[y].take(x).reversed())
val right = (heights[y].drop(x + 1))
val up = (transposed[x].take(y).reversed())
val down = (transposed[x].drop(y + 1))
listOf(left, right, up, down).map { row ->
val sight = row.takeWhile { it < tree }
if (sight.size == row.size)
sight.size
else
sight.size + 1
}.reduce(Int::times)
}
}
return viewScores.max()
}
} | 0 | Kotlin | 0 | 3 | fc35e6d5feeabdc18c86aba428abcf23d880c450 | 1,821 | advent-of-code | MIT License |
src/main/kotlin/day09_smoke_basin/SmokeBasin.kt | barneyb | 425,532,798 | false | {"Kotlin": 238776, "Shell": 3825, "Java": 567} | package day09_smoke_basin
import geom2d.Point
import geom2d.Rect
import geom2d.asLinearOffset
import util.saveTextFile
import java.io.PrintWriter
import java.util.*
/**
* "The 2D plane" needs a refresher. Move around it, find neighbors, a bit of
* parsing, find the right data structures... Partially review, and also upping
* the number of balls in the air a bit. Definitely into week two.
*
* Part two is the first graph traversal, where the nodes of the graph are the
* locations and the edges are "neighbors". Part one's answer provides the start
* points for traversing and the rules say `9` means stop. BFS or DFS will do
* about the same, but visit marking is required. The last wrinkle is finding
* the three largest basins - sounds like a heap-based priority queue!
*/
fun main() {
util.solve(554, ::partOne) // 1774 is too high (>=, not >)
util.solve(1017792, ::partTwo)
saveTextFile(::csv, "csv")
}
private class Grid(input: String) {
val width = input.indexOf('\n')
val grid = input
.filter { it != '\n' }
val height = grid.length / width
val bounds = Rect(width.toLong(), height.toLong())
val lowPoints: Set<Point>
init {
lowPoints = mutableSetOf()
bounds
.allPoints()
.forEach { p ->
val n = grid[bounds.asLinearOffset(p).toInt()]
if (p.orthogonalNeighbors(bounds)
.all {
n < grid[bounds.asLinearOffset(it).toInt()]
}
) {
lowPoints.add(p)
}
}
}
val basins: List<Set<Point>> by lazy {
lowPoints.map { low ->
val basin = mutableSetOf<Point>()
val queue: Queue<Point> = LinkedList()
queue.add(low)
while (queue.isNotEmpty()) {
val p = queue.remove()
if (basin.contains(p)) continue
if (grid[bounds.asLinearOffset(p).toInt()] == '9') continue
basin.add(p)
queue.addAll(p.orthogonalNeighbors(bounds))
}
basin
}
}
operator fun get(p: Point) =
grid[bounds.asLinearOffset(p).toInt()].digitToInt()
}
fun partOne(input: String) =
Grid(input).let { grid ->
grid.lowPoints.sumOf { p -> grid[p] + 1 }
}
fun partTwo(input: String) =
PriorityQueue<Int>(3)
.also { pq ->
Grid(input)
.basins
.forEach { b ->
pq.add(b.size)
if (pq.size > 3) pq.remove()
}
}
.reduce(Int::times)
private fun csv(input: String, out: PrintWriter) {
out.println("x,y,height,is_low_point,basin_number")
Grid(input).apply {
bounds.allPoints().forEach { p ->
val height = this[p]
out.print("${p.x},${p.y}")
out.print(",$height,${if (lowPoints.contains(p)) 1 else 0}")
if (height != 9)
out.print(",${basins.indexOfFirst { it.contains(p) }}")
out.println()
}
}
}
| 0 | Kotlin | 0 | 0 | a8d52412772750c5e7d2e2e018f3a82354e8b1c3 | 3,148 | aoc-2021 | MIT License |
dcp_kotlin/src/main/kotlin/dcp/day228/day228.kt | sraaphorst | 182,330,159 | false | {"C++": 577416, "Kotlin": 231559, "Python": 132573, "Scala": 50468, "Java": 34742, "CMake": 2332, "C": 315} | package dcp.day228
// day228.kt
// By <NAME>, 2019.
import java.math.BigInteger
import java.util.LinkedList
// https://medium.com/@voddan/a-handful-of-kotlin-permutations-7659c555d42
// Typeclass that circulates over its members.
interface Circular<T> : Iterable<T> {
fun state(): T
fun inc()
fun isZero(): Boolean // `true` in exactly one state
fun hasNext(): Boolean // `false` if the next state `isZero()`
override fun iterator() : Iterator<T> {
return object : Iterator<T> {
var started = false
override fun next(): T {
if(started)
inc()
else
started = true
return state()
}
override fun hasNext() = this@Circular.hasNext()
}
}
}
// Implementation of Circular for Int.
class Ring(val size: Int) : Circular<Int> {
private var state = 0
override fun state() = state
override fun inc() {state = (1 + state) % size}
override fun isZero() = (state == 0)
override fun hasNext() = (state != size - 1)
init {
assert(size > 0)
}
}
/**
* Typeclass that circulates over combinations of its members.
* We circulate over lists of E using the Circular typeclass H for E.
*/
abstract class CircularList<E, H: Circular<E>>(val size: Int) : Circular<List<E>> {
protected abstract val state: List<H>
override fun inc() {
state.forEach {
it.inc()
if(! it.isZero()) return
}
}
override fun isZero() = state.all {it.isZero()}
override fun hasNext() = state.any {it.hasNext()}
}
/**
* Typeclass for circulating over combinations of Int using a Ring.
*/
abstract class IntCombinations(size: Int) : CircularList<Int, Ring>(size)
/**
* Specific typeclass for cycling over all permutations of N integers.
*/
class Permutations(N: Int) : IntCombinations(N) {
override val state = mutableListOf<Ring>()
init {
/**
* N possibilities for the first position, N-1 for the second, etc.
*/
for(i in size downTo 1) {
state += Ring(i)
}
}
override fun state(): List<Int> {
val items = (0 until size).toCollection(LinkedList())
return state.map {ring -> items.removeAt(ring.state())}
}
}
/**
* Convert the numbers to strings and sort them.
* Then iterate over every permutation of the number of strings and concatenate them in that order.
* Reconvert them to integers and return the maximum one.
* This is a brute force operation of time O(n!).
*/
fun bruteForceNumber(numbers: List<Int>): BigInteger {
val n = numbers.size
if (n == 0)
return BigInteger.ZERO
if (n == 1)
return numbers.first().toBigInteger()
val strings = numbers.map{ it.toString() }
return Permutations(numbers.size).map { p ->
(0 until n).map{ strings[p[it]] }.joinToString (separator = ""){ it }
}.map { it.toBigInteger() }.max() ?: BigInteger.ZERO
}
fun comparatorNumber(numbers: List<Int>): BigInteger {
if (numbers.isEmpty())
return BigInteger.ZERO
val strs = numbers.map { it.toString() }
val maxLength = strs.map { it.length }.max() ?: 0
if (maxLength == 0)
return BigInteger.ZERO
val normalized = strs.map {
val numRepeats = maxLength / it.length + 1
it.repeat(numRepeats).take(maxLength)
}
val ordered = normalized.zip(numbers).sortedBy { it.first }.reversed()
return ordered.joinToString(separator=""){it.second.toString()}.toBigInteger()
}
| 0 | C++ | 1 | 0 | 5981e97106376186241f0fad81ee0e3a9b0270b5 | 3,613 | daily-coding-problem | MIT License |
src/main/kotlin/dev/bogwalk/batch6/Problem62.kt | bog-walk | 381,459,475 | false | null | package dev.bogwalk.batch6
import dev.bogwalk.util.combinatorics.permutationID
/**
* Problem 62: Cubic Permutations
*
* https://projecteuler.net/problem=62
*
* Goal: Given N, find the smallest cubes for which exactly K permutations of its digits are the
* cube of some number < N.
*
* Constraints: 1e3 <= N <= 1e6, 3 <= K <= 49
*
* e.g.: N = 1000, K = 3
* smallest cube = 41_063_625 (345^3)
* permutations -> 56_623_104 (384^3), 66_430_125 (405^3)
*/
class CubicPermutations {
/**
* Solution stores all cubes in a dictionary with their permutation id as the key, thereby
* creating value lists of cubic permutations. The dictionary is then filtered for lists of K
* size.
*
* @return list of all K-sized lists of permutations that are cubes. These will already be
* sorted by the first (smallest) element of each list.
*/
fun cubicPermutations(n: Int, k: Int): List<List<Long>> {
val cubePerms = mutableMapOf<String, List<Long>>()
for (num in 345 until n) {
val cube = 1L * num * num * num
val cubeID = permutationID(cube)
cubePerms[cubeID] = cubePerms.getOrDefault(cubeID, emptyList()) + cube
}
return cubePerms.values.filter { perms -> perms.size == k }
}
/**
* Project Euler specific implementation that requests the smallest cube for which exactly 5
* permutations of its digits are cube.
*
* Since exactly 5 permutations are required, without setting a limit, once the first
* permutations are found, the loop has to continue until the generated cubes no longer have
* the same amount of digits as the smallest cube in the permutation list. This ensures the
* list is not caught early.
*
* N.B. The permutations occur between 5027^3 and 8384^3.
*/
fun smallest5CubePerm(): List<Long> {
val cubePerms = mutableMapOf<String, List<Long>>()
var longestID = "0"
var num = 345L
var maxDigits = 100
var currentDigits = 0
while (currentDigits <= maxDigits) {
val cube = num * num * num
val cubeID = permutationID(cube)
cubePerms[cubeID] = cubePerms.getOrDefault(cubeID, emptyList()) + cube
if (longestID == "0" && cubePerms[cubeID]?.size == 5) {
longestID = cubeID
maxDigits = cubeID.length
}
num++
currentDigits = cubeID.length
}
return cubePerms[longestID]!!
}
} | 0 | Kotlin | 0 | 0 | 62b33367e3d1e15f7ea872d151c3512f8c606ce7 | 2,547 | project-euler-kotlin | MIT License |
src/Day03.kt | ranveeraggarwal | 573,754,764 | false | {"Kotlin": 12574} | fun main() {
fun getPriority(c: Char): Int {
return if (c.isUpperCase()) c.code - 'A'.code + 27 else c.code - 'a'.code + 1
}
fun part1(input: List<String>): Int {
var result = 0
input.forEach {
val map = HashSet<Char>()
it.substring(0, it.length / 2).forEach { c -> map.add(c) }
result += it.substring(it.length / 2).filter { c -> map.contains(c) }.toSet()
.fold(0) { sum, c -> sum + getPriority(c) }
}
return result
}
fun part2(input: List<String>): Int {
return input.chunked(3).fold(0) { sum, group ->
sum + getPriority(
group[0].toSet().intersect(group[1].toSet()).intersect(group[2].toSet()).first()
)
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day03_test")
println(part1(testInput))
println(part2(testInput))
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | c8df23daf979404f3891cdc44f7899725b041863 | 1,054 | advent-of-code-2022-kotlin | Apache License 2.0 |
aoc/src/main/kotlin/com/bloidonia/aoc2023/day11/Main.kt | timyates | 725,647,758 | false | {"Kotlin": 45518, "Groovy": 202} | package com.bloidonia.aoc2023.day11
import com.bloidonia.aoc2023.text
import kotlin.math.abs
private const val example = """...#......
.......#..
#.........
..........
......#...
.#........
.........#
..........
.......#..
#...#....."""
private data class Position(val x: Long, val y: Long) {
operator fun plus(other: Position) = Position(x + other.x, y + other.y)
}
private fun parse(input: String) =
input.lines().let {
val width = it.first().length
val height = it.size
(width to height) to it.flatMapIndexed { y, line ->
line.mapIndexed { x, c ->
when (c) {
'#' -> Position(x.toLong(), y.toLong())
else -> null
}
}
}.filterNotNull()
}
private fun expand(input: String, expansion: Long = 1L) {
val (dimension, galaxy) = parse(input)
var expanded = galaxy.toMutableList()
(0 until dimension.first.toLong()).filter { x ->
galaxy.none { it.x == x }
}.sortedDescending().let {
// expand horizontally
expanded = it.fold(expanded) { points, x ->
val p = points.filter { it.x < x }.toMutableList()
p.addAll(points.filter { it.x > x }.map { Position(it.x + expansion, it.y) })
p
}
}
(0 until dimension.second.toLong()).filter { y ->
galaxy.none { it.y == y }
}.sortedDescending().let {
// expand vertically
expanded = it.fold(expanded) { points, y ->
val p = points.filter { it.y < y }.toMutableList()
p.addAll(points.filter { it.y > y }.map { Position(it.x, it.y + expansion) })
p
}
}
val distance = { a: Position, b: Position ->
abs(a.x - b.x) + abs(a.y - b.y)
}
(0 until expanded.size).sumOf { i ->
((i + 1) until expanded.size).sumOf { j ->
distance(expanded[i], expanded[j])
}
}.let { println("Sum: $it") }
}
fun main() {
expand(example)
expand(text("/day11.input"))
expand(example, 9)
expand(example, 99)
expand(text("/day11.input"), 999999)
} | 0 | Kotlin | 0 | 0 | 158162b1034e3998445a4f5e3f476f3ebf1dc952 | 2,131 | aoc-2023 | MIT License |
day06/src/main/kotlin/Main.kt | rstockbridge | 225,212,001 | false | null | fun main() {
val inputAsLines = resourceFile("input.txt")
.readLines()
val directOrbits = parseInput(inputAsLines)
println("Part I: the solution is ${solvePartI(directOrbits)}.")
println("Part II: the solution is ${solvePartII(directOrbits)}.")
}
fun parseInput(inputAsLines: List<String>): List<Pair<String, String>> {
val result = mutableListOf<Pair<String, String>>()
for (line in inputAsLines) {
val splitInput = line.split(")")
result.add(Pair(splitInput[0], splitInput[1]))
}
return result
}
fun solvePartI(directOrbits: List<Pair<String, String>>): Int {
return calculateNumberOfOrbits(directOrbits);
}
fun solvePartII(directOrbits: List<Pair<String, String>>): Int {
return calculateMinNumberOfOrbitalTransfers(directOrbits)
}
fun calculateNumberOfOrbits(directOrbits: List<Pair<String, String>>): Int {
val tree = addChildrenToParent(tree("COM") {}, directOrbits)
return calculateNumberOfOrbitsFromTree(tree)
}
fun calculateNumberOfOrbitsFromTree(tree: Tree<String>, depth: Int = 1): Int {
var result = 0
for (child in tree.children) {
result += depth + calculateNumberOfOrbitsFromTree(child, depth + 1)
}
return result
}
fun calculateMinNumberOfOrbitalTransfers(directOrbits: List<Pair<String, String>>): Int {
val youAncestry = findAncestry("YOU", directOrbits)
val sanAncestry = findAncestry("SAN", directOrbits)
val sharedAncestrySize = youAncestry.intersect(sanAncestry).size
return (youAncestry.size - sharedAncestrySize) + (sanAncestry.size - sharedAncestrySize)
}
fun findAncestry(spaceObject: String, directOrbits: List<Pair<String, String>>): List<String> {
val result = mutableListOf<String>()
var parent = findParent(spaceObject, directOrbits)
while (parent != "COM") {
result.add(parent)
parent = findParent(parent, directOrbits)
}
return result
}
fun findParent(spaceObject: String, directOrbits: List<Pair<String, String>>): String {
for ((orbited, orbiter) in directOrbits) {
if (orbiter == spaceObject) {
return orbited
}
}
throw IllegalStateException("This line should not be reached.")
}
fun addChildrenToParent(parent: MutableTree<String>, directOrbits: List<Pair<String, String>>): MutableTree<String> {
val orbited = parent.data
val listOfOrbiters = getOrbiter(orbited, directOrbits)
for (orbiter in listOfOrbiters) {
val child = tree(orbiter)
parent.addChild(child)
addChildrenToParent(parent = child, directOrbits = directOrbits)
}
return parent
}
fun getOrbiter(targetOrbited: String, directOrbits: List<Pair<String, String>>): List<String> {
val result = mutableListOf<String>()
for ((orbited, orbiter) in directOrbits) {
if (orbited == targetOrbited) {
result.add(orbiter)
}
}
return result
}
| 0 | Kotlin | 0 | 0 | bcd6daf81787ed9a1d90afaa9646b1c513505d75 | 2,931 | AdventOfCode2019 | MIT License |
src/Day03.kt | mr-cell | 575,589,839 | false | {"Kotlin": 17585} | fun main() {
fun part1(input: List<String>): Int =
input.sumOf { it.sharedItem().priority() }
fun part2(input: List<String>): Int =
input.chunked(3)
.sumOf { it.sharedItem().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))
}
private fun Char.priority(): Int = when (this) {
in 'a'..'z' -> (this - 'a') + 1
in 'A'..'Z' -> (this - 'A') + 27
else -> throw IllegalArgumentException("Letter not in range $this")
}
private fun List<String>.sharedItem(): Char =
map { it.toSet() }
.reduce { left, right -> left intersect right }
.first()
private fun String.sharedItem(): Char =
listOf(
substring(0..length / 2),
substring(length / 2)
)
.sharedItem()
| 0 | Kotlin | 0 | 0 | 2528bf0f72bcdbe7c13b6a1a71e3d7fe1e81e7c9 | 986 | advent-of-code-2022 | Apache License 2.0 |
src/Day03.kt | hiteshchalise | 572,795,242 | false | {"Kotlin": 10694} | fun main() {
fun part1(input: List<String>): Int {
val priorityList = input.map { rucksack ->
val firstCompartment = rucksack.subSequence(0, rucksack.length / 2)
val secondCompartment = rucksack.subSequence(rucksack.length / 2, rucksack.length)
val matchingItem = firstCompartment.first { item ->
secondCompartment.contains(item)
}
priorityOfAlphabet(matchingItem)
}
return priorityList.sum()
}
fun part2(input: List<String>): Int {
val badgeItemPriorityList = input.windowed(3, 3, false).map { (first, second, third) ->
val matchingItem = first.filter { item ->
second.contains(item)
}
val badgeItem = matchingItem.first { item ->
third.contains(item)
}
priorityOfAlphabet(badgeItem)
}
return badgeItemPriorityList.sum()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day03_test")
check(part1(testInput) == 157)
check(part2(testInput) == 70)
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | e4d66d8d1f686570355b63fce29c0ecae7a3e915 | 1,235 | aoc-2022-kotlin | Apache License 2.0 |
src/Day21.kt | amelentev | 573,120,350 | false | {"Kotlin": 87839} | import kotlin.math.abs
fun main() {
data class Point(val r: Int, val c: Int)
operator fun Point.plus(p: Point) = Point(r + p.r, c + p.c)
val dirs = listOf(Point(0, 1), Point(1, 0), Point(0, -1), Point(-1, 0))
fun solve1(input: List<String>, steps: Int): Int {
val start = input.indexOfFirst { it.contains('S') }.let { i ->
i to input[i].indexOf('S')
}
var prev = HashSet<Pair<Int, Int>>()
prev.add(start)
for (step in 1..steps) {
val next = HashSet<Pair<Int, Int>>()
for (s in prev) {
for (d in dirs) {
val s1 = s.first + d.r to s.second + d.c
if (s1.first in input.indices && s1.second in input[s1.first].indices && input[s1.first][s1.second] != '#') {
next.add(s1)
}
}
}
prev = next
}
return prev.size
}
fun Int.pmod(m: Int) = (this % m).let { if (it < 0) it + m else it }
fun solve2(input: List<String>, steps: Int): Long {
val (n,m) = input.size to input[0].length
assert(n==m)
val start = input.indexOfFirst { it.contains('S') }.let { i ->
Point(i, input[i].indexOf('S'))
}
val D = HashMap<Point, Int>()
val queue = ArrayDeque(listOf(start))
D[start] = 0
while (queue.isNotEmpty()) {
val s = queue.removeFirst()
val d = D[s]!!
for (dir in dirs) {
val s1 = s + dir
if (input[s1.r.pmod(n)][s1.c.pmod(m)] == '#') continue
if (s1 in D) continue
if (abs(s1.r / n) > 4 || abs(s1.c / m) > 4) continue
queue.add(s1)
D[s1] = d + 1
}
}
val memo = HashMap<Pair<Int, Boolean>, Long>()
fun calc(d: Int, corner: Boolean): Long {
return memo.getOrPut(d to corner) {
val k = (steps - d) / n
var res = 0L
for (x in 1..k) {
val dd = d + x*n
if (dd <= steps && (dd%2 == steps%2)) {
res += if (corner) x + 1 else 1
}
}
res
}
}
var res = 0L
for (i in -(4*n-1)..<4*n) {
for (j in -(4*m-1)..<4*m) {
val d = D[Point(i,j)] ?: continue
if (d <= steps && (d%2 == steps%2)) {
res ++
}
val ei = abs(i / n) == 3
val ej = abs(j / m) == 3
if (ei && ej) {
res += calc(d, true)
} else if (ei || ej) {
res += calc(d, false)
}
}
}
return res
}
val test = readInput("Day21t")
assert(solve1(test, 6) == 16)
fun check2(steps: Int, ans: Long) {
val res = solve2(test, steps)
println("$steps:\t$res")
assert(res == ans)
}
check2(6, 16)
check2(50, 1594)
check2(100, 6536)
check2(500, 167004)
check2(1000, 668697)
check2(5000, 16733044)
val input = readInput("Day21")
println(solve1(input, 64))
println(solve2(input, 26501365))
}
| 0 | Kotlin | 0 | 0 | a137d895472379f0f8cdea136f62c106e28747d5 | 3,322 | advent-of-code-kotlin | Apache License 2.0 |
Problems/Algorithms/329. Longest Increasing Path in a Matrix/LongestIncreasingPath.kt | xuedong | 189,745,542 | false | {"Kotlin": 332182, "Java": 294218, "Python": 237866, "C++": 97190, "Rust": 82753, "Go": 37320, "JavaScript": 12030, "Ruby": 3367, "C": 3121, "C#": 3117, "Swift": 2876, "Scala": 2868, "TypeScript": 2134, "Shell": 149, "Elixir": 130, "Racket": 107, "Erlang": 96, "Dart": 65} | class Solution {
fun longestIncreasingPath(matrix: Array<IntArray>): Int {
val n = matrix.size
val m = matrix[0].size
val neighbors = arrayOf(intArrayOf(0, 1), intArrayOf(0, -1), intArrayOf(1, 0), intArrayOf(-1, 0))
val dp = Array(n) { IntArray(m) { -1 } }
var ans = 0
for (i in 0..n-1) {
for (j in 0..m-1) {
ans = maxOf(ans, dfs(matrix, dp, neighbors, n, m, i, j, -1))
}
}
return ans
}
private fun dfs(matrix: Array<IntArray>, dp: Array<IntArray>, neighbors: Array<IntArray>, n: Int, m: Int, r: Int, c: Int, prev: Int): Int {
if (!isValid(n, m, r, c) || matrix[r][c] <= prev) {
return 0
}
if (dp[r][c] != -1) {
return dp[r][c]
}
for (neighbor in neighbors) {
val x = r + neighbor[0]
val y = c + neighbor[1]
dp[r][c] = maxOf(dp[r][c], dfs(matrix, dp, neighbors, n, m, x, y, matrix[r][c]))
}
dp[r][c]++
return dp[r][c]
}
private fun isValid(n: Int, m: Int, r: Int, c: Int): Boolean {
return r >= 0 && r < n && c >= 0 && c < m
}
}
| 0 | Kotlin | 0 | 1 | 5e919965b43917eeee15e4bff12a0b6bea4fd0e7 | 1,267 | leet-code | MIT License |
src/main/kotlin/com/groundsfam/advent/y2020/d07/Day07.kt | agrounds | 573,140,808 | false | {"Kotlin": 281620, "Shell": 742} | package com.groundsfam.advent.y2020.d07
import com.groundsfam.advent.DATAPATH
import java.util.ArrayDeque
import java.util.Queue
import kotlin.io.path.div
import kotlin.io.path.useLines
private fun parseRule(line: String): Rule {
val tokens = line.split(" ")
return rule {
bagColor = "${tokens[0]} ${tokens[1]}"
for (i in 4 until tokens.size step 4) {
if (tokens[i] != "no") { // catch the case of "no other bags."
addCanContain(tokens[i].toInt() to "${tokens[i + 1]} ${tokens[i + 2]}")
}
}
}
}
private data class Rule(val bagColor: String, val canContain: List<Pair<Int, String>>) {
class Builder {
var bagColor: String? = null
val canContain = mutableListOf<Pair<Int, String>>()
fun addCanContain(pair: Pair<Int, String>) {
canContain.add(pair)
}
fun build() = Rule(bagColor!!, canContain)
}
}
private fun rule(block: Rule.Builder.() -> Unit): Rule =
Rule.Builder().apply(block).build()
private fun findContainingBags(relations: Map<String, List<Rule>>, target: String): Set<String> {
val ret = mutableSetOf<String>()
val next: Queue<String> = ArrayDeque<String>().apply { add(target) }
while (next.isNotEmpty()) {
val color = next.poll()
if (color == target || ret.add(color)) {
next.addAll(relations[color]?.map { it.bagColor } ?: emptyList())
}
}
return ret
}
private fun countContainedBags(rulesMap: Map<String, Rule>, target: String): Int {
return rulesMap[target]!!.canContain.sumOf { (count, color) ->
count * (1 + countContainedBags(rulesMap, color))
}
}
fun main() {
val rules = (DATAPATH / "2020/day07.txt").useLines { it.toList().map(::parseRule) }
mutableMapOf<String, MutableList<Rule>>().let { map ->
rules.forEach { rule ->
rule.canContain.forEach { (_, bagColor) ->
if (bagColor !in map) {
map[bagColor] = mutableListOf()
}
map[bagColor]!!.add(rule)
}
}
findContainingBags(map, "shiny gold")
}.run { println("Part one: $size") }
rules.groupBy { it.bagColor }
.mapValues { (_, v) -> v[0] } // bagColor key is already unique
.let { countContainedBags(it, "shiny gold") }
.also { println("Part two: $it") }
} | 0 | Kotlin | 0 | 1 | c20e339e887b20ae6c209ab8360f24fb8d38bd2c | 2,412 | advent-of-code | MIT License |
src/day03/Day03.kt | voom | 573,037,586 | false | {"Kotlin": 12156} | package day03
import readInput
/**
* --- Day 3: Rucksack Reorganization ---
*/
fun main() {
fun defineType(p1: String, p2: String): Char {
return p1.first { p2.contains(it) }
}
fun calcPrio(it: Char) = if (it.isLowerCase()) it - 'a' + 1 else it - 'A' + 27
/**
* Sum priorities of rucksack content item types
*/
fun part1(input: List<String>): Int {
return input
.map {
val mid = it.length / 2
it.substring(0, mid) to it.substring(mid)
}
.map { (p1, p2) ->
defineType(p1, p2)
}.sumOf { calcPrio(it) }
}
fun defineBadge(g1: String, g2: String, g3: String): Char {
return g1.first { g2.contains(it) && g3.contains(it) }
}
/**
* Sum priorities of group's badge item types
*/
fun part2(input: List<String>): Int {
return input
.chunked(3)
.map {
defineBadge(it[0], it[1], it[2])
}
.sumOf { calcPrio(it) }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("day03/test_input")
check(part1(testInput) == 157)
check(part2(testInput) == 70)
val input = readInput("day03/input")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 1 | a8eb7f7b881d6643116ab8a29177d738d6946a75 | 1,355 | aoc2022 | Apache License 2.0 |
src/day20/day.kt | LostMekka | 574,697,945 | false | {"Kotlin": 92218} | package day20
import util.readInput
import util.shouldBe
import util.skipEvery
fun main() {
val testInput = readInput(Input::class, testInput = true).parseInput()
testInput.part1() shouldBe 3
testInput.part2() shouldBe 1623178306
val input = readInput(Input::class).parseInput()
println("output for part1: ${input.part1()}")
println("output for part2: ${input.part2()}")
}
private class Input(
val numbers: List<Long>,
)
private fun List<String>.parseInput(): Input {
return Input(map { it.toLong() })
}
private class Cell(val number: Long) {
lateinit var leftCell: Cell
lateinit var rightCell: Cell
fun sequence() = sequence {
var c = this@Cell
while (true) {
c = c.rightCell
yield(c)
}
}
companion object {
fun link(left: Cell, right: Cell) {
left.rightCell = right
right.leftCell = left
}
}
}
private class LinkedRing(
val cells: List<Cell>,
) {
val zero = cells.single { it.number == 0L }
}
private fun Input.createLinkedRing(multiplier: Long): LinkedRing {
val cells = numbers.map { Cell(it * multiplier) }
for ((a, b) in cells.windowed(2)) Cell.link(a, b)
Cell.link(cells.last(), cells.first())
return LinkedRing(cells)
}
private fun LinkedRing.mix() {
for (cell in cells) {
val n = cell.number.mod(cells.size - 1)
if (n == 0) continue
// cut the cell out of the ring
val oldLeft = cell.leftCell
val oldRight = cell.rightCell
Cell.link(oldLeft, oldRight)
// insert the cell at the new position
var newLeft = cell
repeat(n) { newLeft = newLeft.rightCell }
val newRight = newLeft.rightCell
Cell.link(newLeft, cell)
Cell.link(cell, newRight)
}
}
private fun LinkedRing.extractAnswer() =
zero.sequence()
.skipEvery(999)
.take(3)
.sumOf { it.number }
private fun Input.part1(): Long {
val ring = createLinkedRing(1)
ring.mix()
return ring.extractAnswer()
}
private fun Input.part2(): Long {
val ring = createLinkedRing(811589153)
repeat(10) { ring.mix() }
return ring.extractAnswer()
}
| 0 | Kotlin | 0 | 0 | 58d92387825cf6b3d6b7567a9e6578684963b578 | 2,227 | advent-of-code-2022 | Apache License 2.0 |
2022/src/main/kotlin/Day19.kt | dlew | 498,498,097 | false | {"Kotlin": 331659, "TypeScript": 60083, "JavaScript": 262} | object Day19 {
fun part1(input: String): Int {
return parseInput(input)
.sumOf { blueprint -> maxGeodes(blueprint, 24) * blueprint.number }
}
fun part2(input: String): Int {
return parseInput(input)
.take(3)
.map { blueprint -> maxGeodes(blueprint, 32) }
.reduce(Int::times)
}
private fun maxGeodes(blueprint: Blueprint, timeLimit: Int): Int {
val queue = mutableListOf(State())
val explored = mutableSetOf(State())
var bestNumberGeodes = 0
while (queue.isNotEmpty()) {
val state = queue.removeLast()
if (state.calculateMostPossibleGeodes(timeLimit) < bestNumberGeodes) {
continue
}
// Otherwise, iterate through all possible next states
val nextPossibleStates = buildRobots(state, blueprint, timeLimit)
.map {
it.copy(
minute = state.minute + 1,
ore = it.ore + state.oreBots,
clay = it.clay + state.clayBots,
obsidian = it.obsidian + state.obsidianBots,
geodes = it.geodes + state.geodeBots
)
}
.filter { it !in explored }
explored.addAll(nextPossibleStates)
// If we still have more time, add the next states to the queue
if (state.minute != timeLimit) {
queue.addAll(nextPossibleStates)
} else if (nextPossibleStates.isNotEmpty()) {
bestNumberGeodes = maxOf(bestNumberGeodes, nextPossibleStates.maxOf { it.geodes })
}
}
return bestNumberGeodes
}
private fun buildRobots(state: State, blueprint: Blueprint, timeLimit: Int): List<State> {
// If we're on the last minute, then there's no point in building anything; all we can do is collect
if (state.minute == timeLimit) {
return listOf(state)
}
// If you can build a geode bot, always do that!
if (state.canBuildGeodeBot(blueprint)) {
return listOf(state.buildGeodeBot(blueprint))
}
// If we're one minute before the end, and we couldn't build a geode bot, don't build anything else;
// the next turn will just collect resources, there's no point to building
if (state.minute == timeLimit - 1) {
return listOf(state)
}
// List out possible bots we can build (though skip if they are unnecessary to victory)
val nextPossibleStates = mutableListOf(state)
if (state.canBuildObsidianBot(blueprint) && state.shouldBuildObsidianBot(blueprint)) {
nextPossibleStates.add(state.buildObsidianBot(blueprint))
}
if (state.canBuildClayBot(blueprint) && state.shouldBuildClayBot(blueprint)) {
nextPossibleStates.add(state.buildClayBot(blueprint))
}
if (state.canBuildOreBot(blueprint) && state.shouldBuildOreBot(blueprint)) {
nextPossibleStates.add(state.buildOreBot(blueprint))
}
return nextPossibleStates
}
private val INPUT_REGEX =
Regex("Blueprint (\\d+): Each ore robot costs (\\d+) ore. Each clay robot costs (\\d+) ore. Each obsidian robot costs (\\d+) ore and (\\d+) clay. Each geode robot costs (\\d+) ore and (\\d+) obsidian.")
private fun parseInput(input: String): List<Blueprint> {
return input.splitNewlines()
.map { INPUT_REGEX.matchEntire(it)!!.destructured }
.map { (a, b, c, d, e, f, g) ->
Blueprint(
number = a.toInt(),
oreRobotOreCost = b.toInt(),
clayRobotOreCost = c.toInt(),
obsidianRobotOreCost = d.toInt(),
obsidianRobotClayCost = e.toInt(),
geodeRobotOreCost = f.toInt(),
geodeRobotObsidianCost = g.toInt()
)
}
}
private data class Blueprint(
val number: Int,
val oreRobotOreCost: Int,
val clayRobotOreCost: Int,
val obsidianRobotOreCost: Int,
val obsidianRobotClayCost: Int,
val geodeRobotOreCost: Int,
val geodeRobotObsidianCost: Int,
) {
val maxOreNeededToBuildBot = maxOf(oreRobotOreCost, clayRobotOreCost, obsidianRobotOreCost, geodeRobotOreCost)
}
private data class State(
val minute: Int = 1,
val ore: Int = 0,
val oreBots: Int = 1,
val clay: Int = 0,
val clayBots: Int = 0,
val obsidian: Int = 0,
val obsidianBots: Int = 0,
val geodes: Int = 0,
val geodeBots: Int = 0,
) {
fun canBuildOreBot(blueprint: Blueprint) = ore >= blueprint.oreRobotOreCost
fun shouldBuildOreBot(blueprint: Blueprint) = oreBots < blueprint.maxOreNeededToBuildBot
fun buildOreBot(blueprint: Blueprint) = this.copy(
ore = ore - blueprint.oreRobotOreCost,
oreBots = oreBots + 1,
)
fun canBuildClayBot(blueprint: Blueprint) = ore >= blueprint.clayRobotOreCost
fun shouldBuildClayBot(blueprint: Blueprint): Boolean {
return clayBots < blueprint.obsidianRobotClayCost
}
fun buildClayBot(blueprint: Blueprint) = this.copy(
ore = ore - blueprint.clayRobotOreCost,
clayBots = clayBots + 1
)
fun canBuildObsidianBot(blueprint: Blueprint) =
ore >= blueprint.obsidianRobotOreCost && clay >= blueprint.obsidianRobotClayCost
fun shouldBuildObsidianBot(blueprint: Blueprint): Boolean {
return obsidianBots < blueprint.geodeRobotObsidianCost
}
fun buildObsidianBot(blueprint: Blueprint) = this.copy(
ore = ore - blueprint.obsidianRobotOreCost,
clay = clay - blueprint.obsidianRobotClayCost,
obsidianBots = obsidianBots + 1
)
fun canBuildGeodeBot(blueprint: Blueprint) =
ore >= blueprint.geodeRobotOreCost && obsidian >= blueprint.geodeRobotObsidianCost
fun buildGeodeBot(blueprint: Blueprint) = this.copy(
ore = ore - blueprint.geodeRobotOreCost,
obsidian = obsidian - blueprint.geodeRobotObsidianCost,
geodeBots = geodeBots + 1
)
fun calculateMostPossibleGeodes(timeLimit: Int): Int {
val timeLeft = timeLimit - minute + 1
val geodesFromExistingBots = geodeBots * timeLeft
val geodesIfConstantlyBuildingBots = (timeLeft * (timeLeft + 1)) / 2
return geodes + geodesFromExistingBots + geodesIfConstantlyBuildingBots
}
}
} | 0 | Kotlin | 0 | 0 | 6972f6e3addae03ec1090b64fa1dcecac3bc275c | 6,036 | advent-of-code | MIT License |
src/main/kotlin/me/consuegra/algorithms/KSumLinkedLists.kt | aconsuegra | 91,884,046 | false | {"Java": 113554, "Kotlin": 79568} | package me.consuegra.algorithms
import me.consuegra.datastructure.KListNode
/**
* You have two numbers represented by a linked list, where each node represents a single digit. The digits are
* stored in reverse1 order, such as the 1's digit is at the head of the list. Write a function that adds the two
* numbers and return the sum as a linked list.
* <p>
* Example
* INPUT: 7->1->6 + 5->9->2
* OUTPUT: 2->1->9
*/
class KSumLinkedLists {
fun sum(param1: KListNode<Int>?, param2: KListNode<Int>?): KListNode<Int>? {
var result: KListNode<Int>? = null
var list1 = param1
var list2 = param2
var acc = 0
while (list1 != null || list2 != null) {
val list1Data = list1?.data ?: 0
val list2Data = list2?.data ?: 0
val sum = acc.plus(list1Data).plus(list2Data)
if (sum >= 10) {
acc = 1
result = add(result, sum % 10)
} else {
acc = 0
result = add(result, sum)
}
list1 = list1?.next
list2 = list2?.next
}
return if (acc == 1) add(result, acc) else result
}
private fun add(result: KListNode<Int>?, value: Int): KListNode<Int> {
return result?.append(value) ?: KListNode(data = value)
}
fun sumRec(list1: KListNode<Int>?, list2: KListNode<Int>?): KListNode<Int>? = sumRec(list1, list2, 0)
private fun sumRec(list1: KListNode<Int>?, list2: KListNode<Int>?, carry: Int): KListNode<Int>? {
if (list1 == null && list2 == null && carry == 0) {
return null
}
val list1Data = list1?.data ?: 0
val list2Data = list2?.data ?: 0
val sum = carry.plus(list1Data).plus(list2Data)
val result = KListNode(sum % 10)
if (list1 != null || list2 != null) {
val more = sumRec(list1?.next, list2?.next, if (sum >= 10) 1 else 0)
result.next = more
}
return result
}
}
| 0 | Java | 0 | 7 | 7be2cbb64fe52c9990b209cae21859e54f16171b | 2,017 | algorithms-playground | MIT License |
Kotlin for Java Developers. Week 2/Mastermind/Task/src/mastermind/evaluateGuess.kt | Anna-Sentyakova | 186,426,055 | false | null | package mastermind
import java.util.*
import kotlin.math.min
data class Evaluation(val rightPosition: Int, val wrongPosition: Int)
fun evaluateGuess(secret: String, guess: String): Evaluation {
val rightPositions = secret.zip(guess).count { it.first == it.second }
val commonLetters = "ABCDEF".sumBy { ch ->
Math.min(secret.count { it == ch }, guess.count { it == ch })
}
return Evaluation(rightPositions, commonLetters - rightPositions)
}
fun evaluateGuess_(secret: String, guess: String): Evaluation {
var rightPosition = 0
val matchingIndicies = mutableSetOf<Int>()
for (i in 0 until min(secret.length, guess.length)) {
if (secret[i] == guess[i]) {
++rightPosition
matchingIndicies += i
}
}
val secretPairs = calcNotMatchingPairs(secret, matchingIndicies)
val guessPairs = calcNotMatchingPairs(guess, matchingIndicies)
var i = 0
var j = 0
var wrongPosition = 0
while (i < secretPairs.size && j < guessPairs.size) {
when {
secretPairs[i].first == guessPairs[j].first -> {
++wrongPosition
++i
++j
}
secretPairs[i].first < guessPairs[j].first -> {
++i
}
else -> {
++j
}
}
}
return Evaluation(rightPosition, wrongPosition)
}
fun calcNotMatchingPairs(s: String, matchingIndicies: Set<Int>): List<Pair<Char, Int>> {
val list = mutableListOf<Pair<Char, Int>>()
for ((index, ch) in s.withIndex()) {
if (index !in matchingIndicies)
list += ch to index
}
return list.sortedWith(Comparator { p1, p2 ->
when {
p1.first == p2.first -> p1.second.compareTo(p2.second)
else -> p1.first.compareTo(p2.first)
}
})
}
| 0 | Kotlin | 0 | 1 | e5db4940fa844aa8a5de7f90dd872909a06756e6 | 1,871 | coursera | Apache License 2.0 |
src/main/kotlin/nl/dirkgroot/adventofcode/year2020/Day22.kt | dirkgroot | 317,968,017 | false | {"Kotlin": 187862} | package nl.dirkgroot.adventofcode.year2020
import nl.dirkgroot.adventofcode.util.Input
import nl.dirkgroot.adventofcode.util.Puzzle
class Day22(input: Input) : Puzzle() {
private val decks by lazy {
input.string().split("\n\n")
.map { deck -> deck.split("\n").drop(1).map { card -> card.toInt() } }
}
override fun part1() = calculateScore(playNormal(decks[0], decks[1]))
private tailrec fun playNormal(player1: List<Int>, player2: List<Int>): List<Int> {
if (player1.isEmpty()) return player2
if (player2.isEmpty()) return player1
val (newDeck1, newDeck2) = normalRound(player1, player2)
return playNormal(newDeck1, newDeck2)
}
override fun part2(): Int = calculateScore(playRecursive(decks[0], decks[1]).second)
private tailrec fun playRecursive(
player1: List<Int>, player2: List<Int>,
previousRounds1: List<List<Int>> = listOf(), previousRounds2: List<List<Int>> = listOf()
): Pair<Int, List<Int>> {
if (player1.isEmpty()) return 2 to player2
if (player2.isEmpty()) return 1 to player1
if (previousRounds1.any { it == player1 }) return 1 to player1
if (previousRounds2.any { it == player2 }) return 1 to player1
val (newDeck1, newDeck2) = if ((player1.size - 1) >= player1[0] && (player2.size - 1) >= player2[0])
recursiveRound(player1, player2)
else
normalRound(player1, player2)
return playRecursive(
newDeck1, newDeck2,
previousRounds1.plusElement(player1), previousRounds2.plusElement(player2)
)
}
private fun recursiveRound(player1: List<Int>, player2: List<Int>): Pair<List<Int>, List<Int>> {
val (winner, _) = playRecursive(player1.drop(1).take(player1[0]), player2.drop(1).take(player2[0]))
val card1 = player1[0]
val card2 = player2[0]
val cards = if (winner == 1) listOf(card1, card2) else listOf(card2, card1)
val newDeck1 = if (winner == 1) player1.drop(1) + cards else player1.drop(1)
val newDeck2 = if (winner == 2) player2.drop(1) + cards else player2.drop(1)
return Pair(newDeck1, newDeck2)
}
private fun normalRound(player1: List<Int>, player2: List<Int>): Pair<List<Int>, List<Int>> {
val card1 = player1[0]
val card2 = player2[0]
val cards = listOf(card1, card2).sorted().reversed()
val newDeck1 = if (card1 > card2) player1.drop(1) + cards else player1.drop(1)
val newDeck2 = if (card2 > card1) player2.drop(1) + cards else player2.drop(1)
return Pair(newDeck1, newDeck2)
}
private fun calculateScore(deck: List<Int>) =
deck.foldIndexed(0) { index, acc, card -> acc + (deck.size - index) * card }
}
| 1 | Kotlin | 1 | 1 | ffdffedc8659aa3deea3216d6a9a1fd4e02ec128 | 2,787 | adventofcode-kotlin | MIT License |
src/day06/Day06.kt | daniilsjb | 726,047,752 | false | {"Kotlin": 66638, "Python": 1161} | package day06
import java.io.File
import kotlin.math.ceil
import kotlin.math.floor
import kotlin.math.sqrt
fun main() {
val data = parse("src/day06/Day06.txt")
println("🎄 Day 06 🎄")
println()
println("[Part 1]")
println("Answer: ${part1(data)}")
println()
println("[Part 2]")
println("Answer: ${part2(data)}")
}
private data class Race(
val time: Long,
val distance: Long,
)
private fun parse(path: String): Pair<List<String>, List<String>> =
File(path)
.readLines()
.map { it.split("\\s+".toRegex()).drop(1).map(String::trim) }
.let { (ts, ds) -> ts to ds }
private fun solve(data: List<Race>): Long =
data.fold(1) { acc, (t, d) ->
val x1 = floor((t - sqrt(t * t - 4.0 * d)) / 2.0 + 1.0).toInt()
val x2 = ceil((t + sqrt(t * t - 4.0 * d)) / 2.0 - 1.0).toInt()
acc * (x2 - x1 + 1)
}
private fun part1(data: Pair<List<String>, List<String>>): Long =
data.let { (ts, ds) -> ts.map(String::toLong) to ds.map(String::toLong) }
.let { (ts, ds) -> ts.zip(ds) { t, d -> Race(t, d) } }
.let { solve(it) }
private fun part2(data: Pair<List<String>, List<String>>): Long =
data.let { (ts, ds) -> ts.joinToString("") to ds.joinToString("") }
.let { (ts, ds) -> Race(ts.toLong(), ds.toLong()) }
.let { solve(listOf(it)) }
| 0 | Kotlin | 0 | 0 | 46a837603e739b8646a1f2e7966543e552eb0e20 | 1,417 | advent-of-code-2023 | MIT License |
src/Day08.kt | asm0dey | 572,860,747 | false | {"Kotlin": 61384} | fun main() {
fun part1(input: List<String>): Int {
val matrix = input.map { it.map(Char::digitToInt) }
var counter = 0
for ((i, _) in matrix.withIndex()) {
val row = matrix[i]
for ((j, _) in row.withIndex()) {
if (i == 0 || i == matrix.size - 1 || j == 0 || j == row.size - 1) {
counter++
continue
}
val value = row[j]
if (row.subList(0, j).all { it < value }) {
counter++
continue
}
if (row.subList(j + 1, row.size).all { it < value }) {
counter++
continue
}
val column = matrix.map { it[j] }
if (column.subList(0, i).all { it < value }) {
counter++
continue
}
if (column.subList(i + 1, column.size).all { it < value }) {
counter++
continue
}
}
}
return counter
}
fun part2(input: List<String>): Int {
val matrix = input.map { it.map(Char::digitToInt) }
return matrix
.indices
.flatMap { i ->
val row = matrix[i]
row.indices.map { j ->
val col = matrix.map { it[j] }
val value = row[j]
listOf(
row.subList(0, j).reversed(),
row.subList(j + 1, row.size),
col.subList(0, i).reversed(),
col.subList(i + 1, col.size)
)
.map {
var counter = 0
for (item in it) {
counter++
if (item >= value) break
}
counter
}
.reduce(Int::times)
}
}
.max()
}
val testInput = readInput("Day08_test")
check(part1(testInput) == 21)
val input = readInput("Day08")
println(part1(input))
check(part2(testInput) == 8)
println(part2(input))
}
| 1 | Kotlin | 0 | 1 | f49aea1755c8b2d479d730d9653603421c355b60 | 2,363 | aoc-2022 | Apache License 2.0 |
src/Day07.kt | frozbiz | 573,457,870 | false | {"Kotlin": 124645} | import java.util.SortedMap
import java.util.SortedSet
class FileSystem(consoleOutput: List<String>) {
interface Node {
val type: Type
val name: String
val size: Int
enum class Type {
DIRECTORY, FILE
}
fun print(tabSize: Int = 2, indent: Int = 0) {
val indentString = " ".repeat(indent)
println("${indentString}${toString()}")
}
fun allMatchingNodes(test: (Node) -> Boolean): List<Node> {
return if (test(this)) listOf(this) else listOf()
}
val isDir: Boolean get() = type == Type.DIRECTORY
val isFile: Boolean get() = type == Type.FILE
}
class DirectoryNode (
override val name: String,
val parent: DirectoryNode?
) : Node {
var children = sortedMapOf<String, Node>()
override val type: Node.Type get() = Node.Type.DIRECTORY
override val size: Int get() = children.values.sumOf { it.size }
fun addChildNode(node: Node) {
children[node.name] = node
}
override fun toString(): String {
return "${name} (dir: ${size})"
}
override fun print(tabSize: Int, indent: Int) {
super.print(tabSize, indent)
children.forEach { it.value.print(tabSize, indent + 2) }
}
override fun allMatchingNodes(test: (Node) -> Boolean): List<Node> {
return super.allMatchingNodes(test) + children.flatMap { it.value.allMatchingNodes(test) }
}
}
class FileNode (
override val name: String,
override val size: Int
) : Node {
override val type: Node.Type get() = Node.Type.FILE
override fun toString(): String {
return "${name}: ${size}"
}
}
val rootNode = DirectoryNode("/", null)
private fun constructFromConsoleOutput(input: List<String>) {
var currentNode = rootNode
for (line in input) {
val parts = line.trim().split(Regex("\\s+"))
when (parts[0]) {
"\$" -> {
when (parts[1]) {
"cd" -> {
currentNode = when(parts[2]) {
"/" -> rootNode
".." -> currentNode.parent
else -> currentNode.children[parts[2]] as? DirectoryNode
} ?: throw IllegalStateException("Something wacky went on on line ${line}")
}
}
}
"dir" -> currentNode.addChildNode(DirectoryNode(parts[1], currentNode))
else -> currentNode.addChildNode(FileNode(parts[1], parts[0].toInt()))
}
}
}
init {
constructFromConsoleOutput(consoleOutput)
}
fun print(tabSize: Int = 2) {
rootNode.print(tabSize)
}
fun nodesMatching(test: (Node) -> Boolean): List<Node> {
return rootNode.allMatchingNodes(test)
}
val totalSize: Int get() = rootNode.size
}
fun main() {
fun part1(input: List<String>): Int {
val fileSystem = FileSystem(input)
val smallDirs = fileSystem.nodesMatching { it.isDir && it.size <= 100000 }
return smallDirs.sumOf { it.size }
}
fun part2(input: List<String>): Int {
val diskSize = 70000000
val minSpace = 30000000
val fileSystem = FileSystem(input)
val freeSpace = diskSize - fileSystem.totalSize
val requiredSpace = minSpace - freeSpace
val candidates = fileSystem.nodesMatching { it.isDir && it.size > requiredSpace }. sortedBy { it.size }
return candidates.first().size
}
// test if implementation meets criteria from the description, like:
val testInput = listOf(
"\$ cd /\n",
"\$ ls\n",
"dir a\n",
"14848514 b.txt\n",
"8504156 c.dat\n",
"dir d\n",
"\$ cd a\n",
"\$ ls\n",
"dir e\n",
"29116 f\n",
"2557 g\n",
"62596 h.lst\n",
"\$ cd e\n",
"\$ ls\n",
"584 i\n",
"\$ cd ..\n",
"\$ cd ..\n",
"\$ cd d\n",
"\$ ls\n",
"4060174 j\n",
"8033020 d.log\n",
"5626152 d.ext\n",
"7214296 k\n"
)
check(part1(testInput) == 95437)
check(part2(testInput) == 24933642)
//
val input = readInput("day7")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 4feef3fa7cd5f3cea1957bed1d1ab5d1eb2bc388 | 4,524 | 2022-aoc-kotlin | Apache License 2.0 |
src/Day11.kt | li-xin-yi | 573,617,763 | false | {"Kotlin": 23422} | fun main() {
fun gcd(a: Int, b: Int): Int {
if (a == 0) return b
return gcd(b % a, a)
}
fun solvePart1(input: List<String>): Int {
val starts = mutableListOf<MutableList<Int>>()
val funcs = mutableListOf<(Int) -> Unit>()
val n = (input.size + 1) / 7
val res = MutableList(n) { 0 }
for (i in 0 until input.size step 7) {
val items = input[i + 1].split(":")[1].split(",").map { it.trim().toInt() }
starts.add(items.toMutableList())
val divisor = input[i + 3].split(" ").last().toInt()
val div1 = input[i + 4].split(" ").last().toInt()
val div2 = input[i + 5].split(" ").last().toInt()
val expr = input[i + 2].split("=").last().trim().split(" ")
val func = fun(old: Int) {
val a = if (expr[0] == "old") old else expr[0].toInt()
val b = if (expr[2] == "old") old else expr[2].toInt()
var r = when (expr[1]) {
"+" -> a + b
"*" -> a * b
else -> 0
}
r /= 3
if (r % divisor == 0) {
starts[div1].add(r)
} else {
starts[div2].add(r)
}
}
funcs.add(func)
}
for (i in 0 until 20) {
for (j in 0 until n) {
res[j] += starts[j].size
starts[j].forEach { funcs[j](it) }
starts[j].clear()
}
}
val (m1, m2) = res.sorted().takeLast(2)
return m1 * m2
}
fun solvePart2(input: List<String>): Long {
val starts = mutableListOf<MutableList<Long>>()
val funcs = mutableListOf<(Long, Int) -> Unit>()
val n = (input.size + 1) / 7
val res = MutableList(n) { 0 }
val divisors = mutableListOf<Int>()
for (i in 0 until input.size step 7) {
val items = input[i + 1].split(":")[1].split(",").map { it.trim().toLong() }
starts.add(items.toMutableList())
val divisor = input[i + 3].split(" ").last().toInt()
divisors.add(divisor)
val div1 = input[i + 4].split(" ").last().toInt()
val div2 = input[i + 5].split(" ").last().toInt()
val expr = input[i + 2].split("=").last().trim().split(" ")
val func = fun(old: Long, mod: Int) {
val a = if (expr[0] == "old") old else expr[0].toLong()
val b = if (expr[2] == "old") old else expr[2].toLong()
var r = when (expr[1]) {
"+" -> a + b
"*" -> a * b
else -> 0
}
r %= mod
if (r % divisor == 0L) {
starts[div1].add(r)
} else {
starts[div2].add(r)
}
}
funcs.add(func)
}
val mod = divisors.reduce { acc, i -> acc * i / gcd(acc, i) }
for (i in 0 until 10000) {
for (j in 0 until n) {
res[j] += starts[j].size
starts[j].forEach { funcs[j](it, mod) }
starts[j].clear()
}
}
val (m1, m2) = res.sorted().takeLast(2)
return (m1.toLong() * m2)
}
val testInput = readInput("input/Day11_test")
check(solvePart1(testInput) == 10605)
check(solvePart2(testInput) == 2713310158L)
val input = readInput("input/Day11_input")
println(solvePart1(input))
println(solvePart2(input))
} | 0 | Kotlin | 0 | 1 | fb18bb7e462b8b415875a82c5c69962d254c8255 | 3,650 | AoC-2022-kotlin | Apache License 2.0 |
solutions/aockt/y2023/Y2023D19.kt | Jadarma | 624,153,848 | false | {"Kotlin": 435090} | package aockt.y2023
import aockt.util.parse
import io.github.jadarma.aockt.core.Solution
object Y2023D19 : Solution {
/** The Xmas rating system categories. */
private enum class XmasCategory { X, M, A, S }
/** A mechanical part, rated by its XMAS category scores. */
@JvmInline
private value class Part(val xmas: Map<XmasCategory, Int>) : Map<XmasCategory, Int> by xmas {
/** The sum of all XMAS scores. */
val totalScore: Long
get() = values.sumOf { it.toLong() }
}
/** A spec for a mechanical part, with acceptable ranges for the XMAS category scores. */
@JvmInline
private value class PartSpec(val xmas: Map<XmasCategory, IntRange>) : Map<XmasCategory, IntRange> by xmas {
/** Counts how many distinct XMAS score combinations exist that satisfy this spec. */
val totalPossibleParts: Long
get() = values.map { if (it.isEmpty()) 0 else it.last - it.first + 1L }.reduce(Long::times)
/** Returns a new specification with the [category] swapped to the [newValue]. */
fun with(category: XmasCategory, newValue: IntRange): PartSpec =
toMutableMap()
.apply { put(category, newValue) }
.let(::PartSpec)
}
/**
* A part sorting workflow rule.
* @property success The workflow the part should be sent to if it passes the [threshold].
* @property threshold The value that will be compared against the score of the [selector].
* @property greater If true, the [selector] must be greater than the [threshold], otherwise smaller.
* @property selector Extract the relevant category score from a part.
*/
private data class Rule(val success: String, val threshold: Int, val greater: Boolean, val selector: XmasCategory) {
/** Checks whether the [part] matches this rule. */
fun evaluate(part: Part): Boolean {
val partScore = part.getValue(selector)
return if (greater) partScore > threshold else partScore < threshold
}
/**
* Given a [partSpec], returns two new ones which would always pass and always fail this rule, respectively.
* If it is impossible to for a subpart of this spec to fail or pass, that value shall be `null` instead.
*/
fun split(partSpec: PartSpec): Pair<PartSpec?, PartSpec?> {
val selectedRange = partSpec.getValue(selector)
val wouldPass = if (greater) threshold.inc()..selectedRange.last else selectedRange.first..<threshold
val wouldFail = if (greater) selectedRange.first..threshold else threshold..selectedRange.last
val passingSpec = wouldPass.takeUnless(IntRange::isEmpty)?.let { partSpec.with(selector, it) }
val failingSpec = wouldFail.takeUnless(IntRange::isEmpty)?.let { partSpec.with(selector, it) }
return passingSpec to failingSpec
}
}
/**
* A part sorting workflow.
* @property id The ID of this workflow.
* @property rules The rules this workflow applies.
* @property fallback The workflow the parts that did not trigger any of the [rules] will be sent to.
*/
private data class Workflow(val id: String, val rules: List<Rule>, val fallback: String) {
/** Runs the [part] through the workflow and returns the next workflow the part is sent to. */
fun evaluate(part: Part): String = rules.firstOrNull { it.evaluate(part) }?.success ?: fallback
}
/** Parse the [input] and return the list of [Workflow]s and the list of [Part]s to sort. */
private fun parseInput(input: String): Pair<List<Workflow>, List<Part>> = parse {
val workflowRegex = Regex("""^([a-z]+)\{(.+),([a-z]+|A|R)}$""")
val ruleRegex = Regex("""^([xmas])[<>](\d+):([a-z]+|A|R)$""")
val partRegex = Regex("""^\{x=(\d+),m=(\d+),a=(\d+),s=(\d+)}$""")
fun parsePart(line: String): Part =
partRegex.matchEntire(line)!!
.groupValues.drop(1)
.map(String::toInt)
.zip(XmasCategory.entries)
.associate { (score, category) -> category to score }
.let(::Part)
fun parseRule(line: String): Rule =
ruleRegex.matchEntire(line)!!
.destructured
.let { (selector, filter, workflow) ->
Rule(
success = workflow,
threshold = filter.toInt(),
greater = line.contains('>'),
selector = selector.uppercase().let(XmasCategory::valueOf),
)
}
fun parseWorkflow(line: String) =
workflowRegex.matchEntire(line)!!
.destructured
.let { (id, rules, fallback) ->
Workflow(
id = id,
rules = rules.split(',').filterNot(String::isEmpty).map(::parseRule),
fallback = fallback,
)
}
val (workflows, parts) = input.split("\n\n", limit = 2)
workflows.lines().map(::parseWorkflow) to parts.lines().map(::parsePart)
}
override fun partOne(input: String): Long {
val (pipeline, parts) = parseInput(input)
val workflows = pipeline.associateBy { it.id }
return parts
.filter { part ->
var work = "in"
while (work != "A" && work != "R") work = workflows.getValue(work).evaluate(part)
work == "A"
}
.sumOf(Part::totalScore)
}
override fun partTwo(input: String): Long {
val workflows = parseInput(input).first.associateBy { it.id }
val passingSpecs = buildList {
fun analyzeSpec(work: String, partSpec: PartSpec) {
if (work == "R") return
if (work == "A") {
add(partSpec)
return
}
val workflow = workflows.getValue(work)
val fallbackSpec = workflow.rules.fold(partSpec) { spec, rule ->
val (success, failure) = rule.split(spec)
if (success != null) analyzeSpec(rule.success, success)
failure ?: return
}
analyzeSpec(workflow.fallback, fallbackSpec)
}
analyzeSpec("in", PartSpec(XmasCategory.entries.associateWith { 1..4000 }))
}
return passingSpecs.sumOf(PartSpec::totalPossibleParts)
}
}
| 0 | Kotlin | 0 | 3 | 19773317d665dcb29c84e44fa1b35a6f6122a5fa | 6,634 | advent-of-code-kotlin-solutions | The Unlicense |
src/Day02.kt | phamobic | 572,925,492 | false | {"Kotlin": 12697} | private enum class RoundEnd(
val score: Int
) {
LOSE(0),
DRAW(3),
WIN(6);
fun getOppositeEnd(): RoundEnd = when (this) {
LOSE -> WIN
DRAW -> DRAW
WIN -> LOSE
}
}
private sealed class Shape {
abstract val score: Int
abstract val opponentShapeToRoundEndMap: Map<Shape, RoundEnd>
object ROCK : Shape() {
override val score: Int = 1
override val opponentShapeToRoundEndMap: Map<Shape, RoundEnd> = mapOf(
PAPER to RoundEnd.LOSE,
ROCK to RoundEnd.DRAW,
SCISSORS to RoundEnd.WIN,
)
}
object PAPER : Shape() {
override val score: Int = 2
override val opponentShapeToRoundEndMap: Map<Shape, RoundEnd> = mapOf(
PAPER to RoundEnd.DRAW,
ROCK to RoundEnd.WIN,
SCISSORS to RoundEnd.LOSE,
)
}
object SCISSORS : Shape() {
override val score: Int = 3
override val opponentShapeToRoundEndMap: Map<Shape, RoundEnd> = mapOf(
PAPER to RoundEnd.WIN,
ROCK to RoundEnd.LOSE,
SCISSORS to RoundEnd.DRAW,
)
}
fun getRoundEndAgainst(shape: Shape): RoundEnd =
opponentShapeToRoundEndMap[shape] ?: throw IllegalArgumentException()
fun getOpponentShapeWithEnd(roundEnd: RoundEnd): Shape =
opponentShapeToRoundEndMap.entries.find { it.value == roundEnd }?.key
?: throw IllegalArgumentException()
}
private fun Char.toOpponentShape(): Shape = when (this) {
'A' -> Shape.ROCK
'B' -> Shape.PAPER
'C' -> Shape.SCISSORS
else -> throw IllegalArgumentException()
}
private fun Char.toMyShape(): Shape = when (this) {
'X' -> Shape.ROCK
'Y' -> Shape.PAPER
'Z' -> Shape.SCISSORS
else -> throw IllegalArgumentException()
}
private fun Char.toRoundEnd(): RoundEnd = when (this) {
'X' -> RoundEnd.LOSE
'Y' -> RoundEnd.DRAW
'Z' -> RoundEnd.WIN
else -> throw IllegalArgumentException()
}
fun main() {
fun part1(input: List<String>): Int {
var score = 0
input.forEach { line ->
val opponentShape = line.first().toOpponentShape()
val myShape = line.last().toMyShape()
val roundEnd = myShape.getRoundEndAgainst(opponentShape)
score += roundEnd.score + myShape.score
}
return score
}
fun part2(input: List<String>): Int {
var score = 0
input.forEach { line ->
val opponentShape = line.first().toOpponentShape()
val roundEndForMe = line.last().toRoundEnd()
val roundEndForOpponent = roundEndForMe.getOppositeEnd()
val myShape = opponentShape.getOpponentShapeWithEnd(roundEndForOpponent)
score += roundEndForMe.score + myShape.score
}
return score
}
val testInput = readInput("Day02_test")
check(part1(testInput) == 15)
check(part2(testInput) == 12)
}
| 1 | Kotlin | 0 | 0 | 34b2603470c8325d7cdf80cd5182378a4e822616 | 2,965 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/year_2022/Day07.kt | krllus | 572,617,904 | false | {"Kotlin": 97314} | package year_2022
import utils.readInput
fun main() {
fun processInput(input: List<String>): ElfFileItem {
val root = ElfFileItem(
parentNode = null, name = "/", type = ElfFileType.DIRECTORY
)
var currentNode: ElfFileItem? = null
var currentCommand: ElfCommand? = null
var setCommandNow: Boolean
input.forEach { line ->
setCommandNow = false
if (line.startsWith("$ cd ")) {
setCommandNow = true
currentCommand = ElfCommand.CHANGE_DIR
if (currentNode == null) currentNode = root
val elfFileName = line.split("\$ cd ").last()
currentNode = when (elfFileName) {
"/" -> root
".." -> currentNode?.parentNode
else -> currentNode?.findNode(elfFileName)
}
}
if (line.startsWith("$ ls")) {
setCommandNow = true
currentCommand = ElfCommand.LIST_DIR
}
if (!setCommandNow && currentCommand == ElfCommand.LIST_DIR) {
val (a, b) = line.split(" ")
if (a == "dir") {
currentNode?.addChildren(
parent = currentNode, item = ElfFileItem(
type = ElfFileType.DIRECTORY, name = b
)
)
} else {
val size = a.toIntOrNull() ?: error("not possible to parse size: $a")
currentNode?.addChildren(
parent = currentNode, item = ElfFileItem(
type = ElfFileType.FILE, name = b, size = size
)
)
}
}
}
return root
}
fun part1(input: List<String>): Int {
val fileSystem = processInput(input)
val fileSystemDirs = fileSystem.getDirs()
return fileSystemDirs.filter { it.eligible(100_000) }.sumOf { it.getFullSize() }
}
fun part2(input: List<String>): Int {
val fileSystem = processInput(input)
val fileSystemDirs = fileSystem.getDirs()
val max = 70_000_000
val required = 30_000_000
val current = fileSystem.getFullSize()
return fileSystemDirs
.map { it.getFullSize() }
.filter { max - required > current - it }
.sortedBy { it }
.minBy { it }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day07_test")
check(part1(testInput) == 95437)
check(part2(testInput) == 24933642)
val input = readInput("Day07")
println(part1(input)) // 1444896
println(part2(input)) // 404395
}
enum class ElfCommand {
CHANGE_DIR, LIST_DIR
}
data class ElfFileItem(
val name: String,
val type: ElfFileType,
private val size: Int = 0,
var parentNode: ElfFileItem? = null,
val children: MutableList<ElfFileItem> = mutableListOf()
) {
fun findNode(name: String): ElfFileItem? {
val nodes = children.filter { it.name == name }
return nodes.firstOrNull()
}
fun addChildren(parent: ElfFileItem?, item: ElfFileItem) {
item.parentNode = parent
children.add(item)
}
fun getFullSize(): Int {
return when (type) {
ElfFileType.FILE -> this.size
ElfFileType.DIRECTORY -> this.size + children.sumOf { it.getFullSize() }
}
}
fun eligible(maxSize: Int): Boolean {
return this.getFullSize() <= maxSize
}
fun getDirs(): List<ElfFileItem> {
val dirs = mutableListOf<ElfFileItem>()
dirs.addAll(when (this.type) {
ElfFileType.FILE -> emptyList()
ElfFileType.DIRECTORY -> {
val list = mutableListOf<ElfFileItem>()
list.add(this)
children.forEach { list.addAll(it.getDirs()) }
return list
}
})
return dirs
}
override fun toString(): String {
return when (this.type) {
ElfFileType.FILE -> "name: $name, size: ${getFullSize()}"
ElfFileType.DIRECTORY -> "name: $name, childrenCount: ${children.size}, size: ${getFullSize()}"
}
}
}
enum class ElfFileType {
DIRECTORY, FILE
} | 0 | Kotlin | 0 | 0 | b5280f3592ba3a0fbe04da72d4b77fcc9754597e | 4,421 | advent-of-code | Apache License 2.0 |
LR7/src/main/kotlin/Task1V3.kt | Kirchberg | 602,987,232 | false | null | // В тексте нет слов, начинающихся одинаковыми буквами. Напечатать слова текста в таком порядке, чтобы последняя буква
// каждого слова совпадала с первой буквой последующего слова. Если все слова нельзя напечатать в таком порядке, найти
// такую цепочку, состоящую из наибольшего количества слов.
// The WordChainFinder class takes a list of words and finds the longest word chain
class WordChainFinder(private val words: List<String>) {
// A recursive method to find a word chain given a current chain and a list of remaining words
private fun findWordChain(currentChain: List<String>, remainingWords: List<String>): List<String> {
// If there are no remaining words, return the current chain
if (remainingWords.isEmpty()) {
return currentChain
}
// Get the last letter of the last word in the current chain
val lastLetter = currentChain.last().last()
// Find the candidate words in the remaining words that start with the last letter of the current chain
val candidates = remainingWords.filter { it.first() == lastLetter }
// If there are no candidates, return the current chain
if (candidates.isEmpty()) {
return currentChain
}
// For each candidate word, extend the current chain with the candidate and remove it from the remaining words
val chains = candidates.map { candidate ->
val newRemainingWords = remainingWords.toMutableList().apply { remove(candidate) }
findWordChain(currentChain + candidate, newRemainingWords)
}
// Return the longest chain found among the chains extended with the candidates
return chains.maxByOrNull { it.size } ?: currentChain
}
// The findLongestWordChain method finds the longest word chain by starting a search from each word in the list
fun findLongestWordChain(): List<String> {
return words.map { word ->
val remainingWords = words.toMutableList().apply { remove(word) }
findWordChain(listOf(word), remainingWords)
}.maxByOrNull { it.size } ?: emptyList()
}
}
fun task1V3() {
// Provide an example input text
val text = "java android kotlin rust"
// Split the input text into words
val words = text.split(" ")
// Create a WordChainFinder object with the list of words
val wordChainFinder = WordChainFinder(words)
// Call the findLongestWordChain method to find the longest chain of words
val longestWordChain = wordChainFinder.findLongestWordChain()
// Print the longest word chain to the console
println("Longest word chain: ${longestWordChain.joinToString(", ")}")
} | 0 | Kotlin | 0 | 0 | b6a459a30ef20b0f38c4869d0949e22f4239183e | 2,938 | BigDataPL | MIT License |
src/main/kotlin/com/adventofcode/Forest.kt | reactivedevelopment | 575,344,265 | false | {"Kotlin": 2600, "Dockerfile": 379} | package com.adventofcode
import com.adventofcode.Forest.addTrees
import com.adventofcode.Forest.crosswalks
class Crosswalk(
private val tree: Int,
private val left: List<Int>,
private val right: List<Int>,
private val top: List<Int>,
private val bottom: List<Int>
) {
fun scenicScore(): Int {
val leftScore = countVisibleTreesOn(left)
val rightScore = countVisibleTreesOn(right)
val topScore = countVisibleTreesOn(top)
val bottomScore = countVisibleTreesOn(bottom)
return leftScore * rightScore * topScore * bottomScore
}
private fun countVisibleTreesOn(side: List<Int>): Int {
return when (val visibleTrees = side.takeWhile { it < tree }.size) {
side.size -> visibleTrees
else -> visibleTrees + 1
}
}
}
object Forest {
private val forest = mutableListOf<List<Int>>()
private val columns get() = forest.first().size
private val rows get() = forest.size
private fun tree(row: Int, column: Int): Int {
return forest[row][column]
}
private fun column(n: Int): List<Int> {
return (0 until rows).map { tree(it, n) }
}
private fun row(n: Int): List<Int> {
return forest[n]
}
private fun crosswalk(row: Int, column: Int): Crosswalk {
val me = tree(row, column)
val leftAndRight = row(row)
val left = leftAndRight.slice(0 until column).asReversed()
val right = leftAndRight.slice(column + 1 until columns)
val topAndBottom = column(column)
val top = topAndBottom.slice(0 until row).asReversed()
val bottom = topAndBottom.slice(row + 1 until rows)
return Crosswalk(me, left, right, top, bottom)
}
fun addTrees(encodedRow: String) {
val row = encodedRow.map { it.toString().toInt() }
forest.add(row)
}
fun crosswalks() = sequence {
for (r in 0 until rows) {
for (c in 0 until columns) {
yield(crosswalk(r, c))
}
}
}
}
fun solution(): Int {
return crosswalks().maxOf(Crosswalk::scenicScore)
}
fun main() {
::main.javaClass
.getResourceAsStream("/input")!!
.bufferedReader()
.forEachLine(::addTrees)
println(solution())
}
| 0 | Kotlin | 0 | 0 | cf3ac594bf5966202ff95540a2113264a47ef76e | 2,113 | aoc-2022-8 | MIT License |
src/main/kotlin/com/ginsberg/advent2023/Day24.kt | tginsberg | 723,688,654 | false | {"Kotlin": 112398} | /*
* Copyright (c) 2023 by <NAME>
*/
/**
* Advent of Code 2023, Day 24 - Never Tell Me The Odds
* Problem Description: http://adventofcode.com/2023/day/24
* Blog Post/Commentary: https://todd.ginsberg.com/post/advent-of-code/2023/day24/
*/
package com.ginsberg.advent2023
class Day24(input: List<String>) {
private val hailstones = input.map { Hailstone.of(it) }
fun solvePart1(range: ClosedFloatingPointRange<Double>): Int =
hailstones
.cartesianPairs()
.filter { it.first != it.second }
.mapNotNull { it.first.intersectionWith(it.second) }
.count { (x, y, _) -> x in range && y in range }
fun solvePart2(): Long {
val range = -500L..500L
while (true) {
val hail = hailstones.shuffled().take(4)
range.forEach { deltaX ->
range.forEach { deltaY ->
val hail0 = hail[0].withVelocityDelta(deltaX, deltaY)
val intercepts = hail.drop(1).mapNotNull {
it.withVelocityDelta(deltaX, deltaY).intersectionWith(hail0)
}
if (intercepts.size == 3 &&
intercepts.all { it.x == intercepts.first().x } &&
intercepts.all { it.y == intercepts.first().y }
) {
range.forEach { deltaZ ->
val z1 = hail[1].predictZ(intercepts[0].time, deltaZ)
val z2 = hail[2].predictZ(intercepts[1].time, deltaZ)
val z3 = hail[3].predictZ(intercepts[2].time, deltaZ)
if (z1 == z2 && z2 == z3) {
return (intercepts.first().x + intercepts.first().y + z1).toLong()
}
}
}
}
}
}
}
private data class Hailstone(val position: Point3D, val velocity: Point3D) {
private val slope = if (velocity.x == 0L) Double.NaN else velocity.y / velocity.x.toDouble()
fun withVelocityDelta(vx: Long, vy: Long): Hailstone =
copy(
velocity = Point3D(velocity.x + vx, velocity.y + vy, velocity.z)
)
fun predictZ(time: Double, deltaVZ: Long): Double =
(position.z + time * (velocity.z + deltaVZ))
fun intersectionWith(other: Hailstone): Intersection? {
if (slope.isNaN() || other.slope.isNaN() || slope == other.slope) return null
val c = position.y - slope * position.x
val otherC = other.position.y - other.slope * other.position.x
val x = (otherC - c) / (slope - other.slope)
val t1 = (x - position.x) / velocity.x
val t2 = (x - other.position.x) / other.velocity.x
if (t1 < 0 || t2 < 0) return null
val y = slope * (x - position.x) + position.y
return Intersection(x, y, t1)
}
companion object {
fun of(input: String): Hailstone = input.split("@").let { (left, right) ->
Hailstone(
Point3D.of(left),
Point3D.of(right)
)
}
}
}
private data class Intersection(val x: Double, val y: Double, val time: Double)
private data class Point3D(val x: Long, val y: Long, val z: Long) {
companion object {
fun of(input: String): Point3D =
input.split(",").map { it.trim().toLong() }.let {
Point3D(it[0], it[1], it[2])
}
}
}
} | 0 | Kotlin | 0 | 12 | 0d5732508025a7e340366594c879b99fe6e7cbf0 | 3,668 | advent-2023-kotlin | Apache License 2.0 |
advent-of-code2016/src/main/kotlin/day01/Advent1.kt | REDNBLACK | 128,669,137 | false | null | package day01
import day01.State.Direction.*
import parseInput
import splitToLines
/**
* --- Day 1: No Time for a Taxicab ---
Santa's sleigh uses a very high-precision clock to guide its movements, and the clock's oscillator is regulated by stars. Unfortunately, the stars have been stolen... by the Easter Bunny. To save Christmas, Santa needs you to retrieve all fifty stars by December 25th.
Collect stars by solving puzzles. Two puzzles will be made available on each day in the advent calendar; the second puzzle is unlocked when you complete the first. Each puzzle grants one star. Good luck!
You're airdropped near Easter Bunny Headquarters in a city somewhere. "Near", unfortunately, is as close as you can get - the instructions on the Easter Bunny Recruiting Document the Elves intercepted start here, and nobody had time to work them out further.
The Document indicates that you should start at the given coordinates (where you just landed) and face North. Then, follow the provided sequence: either value left (L) or right (R) 90 degrees, then walk forward the given number of blocks, ending at a new intersection.
There's no time to follow such ridiculous instructions on foot, though, so you take a moment and work out the destination. Given that you can only walk on the street grid of the city, how far is the shortest path to the destination?
For example:
Following R2, L3 leaves you 2 blocks East and 3 blocks North, or 5 blocks away.
R2, R2, R2 leaves you 2 blocks due South of your starting position, which is 2 blocks away.
R5, L5, R5, R3 leaves you 12 blocks away.
How many blocks away is Easter Bunny HQ?
--- Part Two ---
Then, you notice the instructions continue on the back of the Recruiting Document. Easter Bunny HQ is actually at the first location you visit twice.
For example, if your instructions are R8, R4, R4, R8, the first location you visit twice is 4 blocks away, due East.
How many blocks away is the first location you visit twice?
*/
fun main(args: Array<String>) {
println(findDestination("R2, L3").countBlocks() == 5)
println(findDestination("R2, R2, R2").countBlocks() == 2)
println(findDestination("R5, L5, R5, R3").countBlocks() == 12)
println(findDestination("R8, R4, R4, R8").countBlocks())
val input = parseInput("day1-input.txt")
println(findDestination(input).countBlocks())
println(findDestination(input).countBlocks())
}
data class State(val direction: Direction, val x: Int, val y: Int) {
enum class Direction(val value: Int) {
NORTH(0), EAST(1), SOUTH(2), WEST(3);
}
fun countBlocks() = Math.abs(x) + Math.abs(y)
}
data class Move(val turn: Turn, val steps: Int) {
enum class Turn(val value: Int) { R(1), L(-1) }
}
fun findDestination(input: String): State {
return parseMoves(input).fold(State(NORTH, 0, 0)) { state, move ->
val (turn, steps) = move
val direction = State.Direction.values()[(state.direction.value + turn.value + 4) % 4]
when (direction) {
NORTH -> state.copy(direction, x = state.x - steps)
SOUTH -> state.copy(direction, x = state.x + steps)
EAST -> state.copy(direction, y = state.y + steps)
WEST -> state.copy(direction, y = state.y - steps)
}
}
}
private fun parseMoves(input: String) = input.splitToLines(",")
.map { it ->
val turn = Move.Turn.valueOf(it[0].toString())
val steps = it.drop(1).toInt()
Move(turn, steps)
}
| 0 | Kotlin | 0 | 0 | e282d1f0fd0b973e4b701c8c2af1dbf4f4a149c7 | 3,514 | courses | MIT License |
src/main/kotlin/io/korti/adventofcode/day/DayTwelve.kt | korti11 | 225,589,330 | false | null | package io.korti.adventofcode.day
import io.korti.adventofcode.math.Axis
import io.korti.adventofcode.math.Vec3
import java.lang.Math.pow
import java.text.DecimalFormat
import java.util.*
import kotlin.math.abs
import kotlin.math.min
import kotlin.math.pow
typealias Planet = Pair<Vec3, Vec3>
class DayTwelve : AbstractDay() {
override fun getDay(): Int {
return 12
}
override fun getSubLevels(): Int {
return 1
}
override fun run(input: List<String>): String {
val original = input.map { it.replace("<", "").replace(">", "").replace(" ", "").split(",") }.map { vec ->
vec.map { it.split("=")[1] }.let { Vec3(it[0].toInt(), it[1].toInt(), it[2].toInt()) }
}.map { Planet(it, Vec3(0, 0, 0)) }
var vectors = original.toMutableList().toList()
val steps = arrayOf(0L, 0L, 0L)
/*for(time in 1..1000) {
vectors = calcVel(vectors)
vectors = updatePositions(vectors)
}*/
for ((index, axis) in Axis.values().withIndex()) {
println("Start simulating axis: $axis")
do {
vectors = calcVel(vectors, axis)
vectors = updatePositions(vectors)
steps[index] += 1L
} while (check(vectors, original, axis).not())
println("Finished simulating axis: $axis with ${steps[index]}")
}
val factors = steps.map { primeFactors(it) }.map { it.entries }.flatten()
.groupBy { it.key }.map { Pair(it.key, it.value.map { entry -> entry.value }) }
.map { Pair(it.first, it.second.max()) }
// return vectors.map { Pair(it.first.sum(), it.second.sum()) }
// .map { it.first * it.second }.sum().toString()
return factors.let {
var lcm = 1.0
for((num, count) in it) {
if(count != null) {
lcm *= num.toDouble().pow(count.toDouble())
}
}
lcm.toLong()
}.toString()
}
private fun check(vectors: List<Planet>, original: List<Planet>, axis: Axis): Boolean {
val axisVectors = vectors.map { Pair(it.first.get(axis), it.second.get(axis)) }
val axisOriginal = original.map { Pair(it.first.get(axis), it.second.get(axis)) }
return axisVectors.containsAll(axisOriginal)
}
fun primeFactors(n: Long): Map<Long, Long> {
if (n < 2) return emptyMap()
val primeFactors = mutableMapOf<Long, Long>()
var remainder = n
var i = 2L
while (i <= remainder / i) {
while (remainder % i == 0L) {
primeFactors[i] = primeFactors.getOrDefault(i, 0) + 1
remainder /= i
}
i++
}
if (remainder > 1)
primeFactors[remainder] = primeFactors.getOrDefault(remainder, 0) + 1
return primeFactors
}
private fun gcd(n1: Long, n2: Long, n3: Long): Long {
val n12 = n1 * n2
val n13 = n1 * n3
val n23 = n2 * n3
var i = 1L
var gcd = 1L
val min = min(n12, min(n13, n23))
println("Start calculation gcd for $n12, $n13 and $n23")
while(i <= min) {
if(n12 % i == 0L && n13 % i == 0L && n23 % i == 0L) {
gcd = i
}
i++
}
println("Finished calculating gcd $gcd")
return gcd
}
private fun Vec3.sum(): Int {
return abs(this.x.toInt()) + abs(this.y.toInt()) + abs(this.z.toInt())
}
private fun calcVel(vectors: List<Planet>, axis: Axis): List<Planet> {
val newVectors = mutableListOf<Planet>()
for (planet1 in vectors) {
var vel = planet1.second
for (planet2 in vectors) {
if (planet1 == planet2) {
continue
}
vel = when (axis) {
Axis.X -> vel.move(Axis.X, planet2.first.compareX(planet1.first))
Axis.Y -> vel.move(Axis.Y, planet2.first.compareY(planet1.first))
Axis.Z -> vel.move(Axis.Z, planet2.first.compareZ(planet1.first))
}
}
newVectors.add(Planet(planet1.first, vel))
}
return newVectors
}
private fun updatePositions(vectors: List<Planet>): List<Planet> {
val newVectors = mutableListOf<Planet>()
for(planet in vectors) {
newVectors.add(Planet(planet.first + planet.second, planet.second))
}
return newVectors
}
} | 0 | Kotlin | 0 | 0 | 410c82ef8782f874c2d8a6c687688716effc7edd | 4,584 | advent-of-code-2019 | MIT License |
src/Day01.kt | djleeds | 572,720,298 | false | {"Kotlin": 43505} | fun main() {
data class Food(val calories: Int)
data class Elf(val inventory: List<Food>) {
val calorieCount = inventory.sumOf { it.calories }
}
fun List<String>.toElf() = Elf(map { Food(it.toInt()) })
fun <T> List<T>.split(boundary: (T) -> Boolean): List<List<T>> =
mapIndexed { index, value -> index.takeIf { boundary(value) } }
.filterNotNull()
.let { listOf(-1) + it + size }
.windowed(2) { (first, second) -> subList(first + 1, second) }
fun parse(input: List<String>) =
input
.split { it.isEmpty() }
.map { it.toElf() }
fun part1(input: List<String>): Int =
parse(input)
.maxBy { it.calorieCount }
.calorieCount
fun part2(input: List<String>): Int =
parse(input)
.sortedByDescending { it.calorieCount }
.take(3)
.sumOf { it.calorieCount }
val testInput = readInput("Day01_test")
check(part1(testInput) == 24_000)
val input = readInput("Day01")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 4 | 98946a517c5ab8cbb337439565f9eb35e0ce1c72 | 1,115 | advent-of-code-in-kotlin-2022 | Apache License 2.0 |
src/main/kotlin/de/mbdevelopment/adventofcode/year2021/solvers/day15/Day15Puzzle.kt | Any1s | 433,954,562 | false | {"Kotlin": 96683} | package de.mbdevelopment.adventofcode.year2021.solvers.day15
import de.mbdevelopment.adventofcode.year2021.solvers.PuzzleSolver
import java.util.*
abstract class Day15Puzzle : PuzzleSolver {
final override fun solve(inputLines: Sequence<String>) = lowestPathRisk(inputLines.toList()).toString()
abstract fun getRiskMapFromTile(tile: List<List<Node>>): List<List<Node>>
// Dijkstra with priority queue flavor
private fun lowestPathRisk(costOfEntering: List<String>): Long {
val riskMapTile = inputToTile(costOfEntering)
val riskMap = getRiskMapFromTile(riskMapTile)
val start = riskMap.first().first() // top left
val target = riskMap.last().last() // bottom right
val nodes = riskMap.flatten().toSet()
val minimumRisk = mutableMapOf<Node, Long>().apply { put(start, 0L) }
for (node in nodes - start) {
minimumRisk[node] = Long.MAX_VALUE
}
val predecessor = mutableMapOf<Node, Node>()
val searchQueue =
PriorityQueue<Node>(nodes.size) { a, b -> minimumRisk[a]!!.compareTo(minimumRisk[b]!!) }
searchQueue.addAll(nodes)
while (searchQueue.isNotEmpty()) {
val lowestTargetRiskNode = searchQueue.remove()
with(lowestTargetRiskNode) {
listOfNotNull(
riskMap[y].getOrNull(x - 1), // left
riskMap[y].getOrNull(x + 1), // right
riskMap.getOrNull(y - 1)?.get(x), // above
riskMap.getOrNull(y + 1)?.get(x) // below
).forEach { neighbor ->
val alternativePathRisk = minimumRisk[lowestTargetRiskNode]!! +
neighbor.riskOfEntering
if (alternativePathRisk < minimumRisk[neighbor]!!) {
minimumRisk[neighbor] = alternativePathRisk
predecessor[neighbor] = lowestTargetRiskNode
// Change position in priority queue based on new risk
searchQueue.remove(neighbor)
searchQueue.add(neighbor)
}
}
}
}
return minimumRisk[target]!!
}
private fun inputToTile(costOfEntering: List<String>) = costOfEntering
.filter { it.isNotBlank() }
.mapIndexed { y, row ->
row.mapIndexed { x, riskOfEntering ->
Node(x, y, riskOfEntering.digitToInt())
}
}
}
| 0 | Kotlin | 0 | 0 | 21d3a0e69d39a643ca1fe22771099144e580f30e | 2,526 | AdventOfCode2021 | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.