path
stringlengths
5
169
owner
stringlengths
2
34
repo_id
int64
1.49M
755M
is_fork
bool
2 classes
languages_distribution
stringlengths
16
1.68k
content
stringlengths
446
72k
issues
float64
0
1.84k
main_language
stringclasses
37 values
forks
int64
0
5.77k
stars
int64
0
46.8k
commit_sha
stringlengths
40
40
size
int64
446
72.6k
name
stringlengths
2
64
license
stringclasses
15 values
src/Day03.kt
dannyrm
573,100,803
false
null
fun main() { fun part1(input: List<String>): Int { return input.map { findCommonItem(it) }.sumOf { calculatePriority(it) } } fun part2(input: List<String>): Int { return input.chunked(3).map { findBadge(Triple(it[0], it[1], it[2])) }.sumOf { calculatePriority(it) } } val input = readInput("Day03") println(part1(input)) println(part2(input)) } fun findCommonItem(rucksack: String) : Char { val compartments = rucksack.chunked(rucksack.length/2) // Should only be one type of item shared return compartments[0].filter { compartments[1].contains(it) }.toCharArray()[0] } fun findBadge(rucksacks: Triple<String, String, String>): Char { // Should only be one item (the "badge") shared by all three elves. return rucksacks.first.filter { rucksacks.second.contains(it) }.filter { rucksacks.third.contains(it) }.toCharArray()[0] } fun calculatePriority(theChar: Char): Int { if (theChar.isLowerCase()) { return theChar.code - ('a'.code-1) } else if (theChar.isUpperCase()) { return theChar.code - ('A'.code) + 27 } throw Exception("Unexpected input") }
0
Kotlin
0
0
9c89b27614acd268d0d620ac62245858b85ba92e
1,154
advent-of-code-2022
Apache License 2.0
src/main/java/io/deeplay/qlab/data/Utils.kt
oQaris
475,961,305
false
{"Jupyter Notebook": 766904, "Java": 47993, "Kotlin": 23299}
package io.deeplay.qlab.data import krangl.mean import kotlin.math.pow import kotlin.math.sqrt fun <T> splitData(data: List<T>, testFraq: Double, shuffle: Boolean = false): Pair<List<T>, List<T>> { require(testFraq in 0.0..1.0) { "Некорректный testFraq" } val dataCopy = if (shuffle) data.shuffled() else data val testSize = (dataCopy.size * testFraq).toInt() val trainData = dataCopy.take(data.size - testSize) val testData = dataCopy.takeLast(testSize) return trainData to testData } inline fun <T> Collection<T>.mean(selector: (T) -> Float) = this.sumOf { selector.invoke(it).toDouble() / this.size }.toFloat() inline fun <T> Collection<T>.median(selector: (T) -> Float): Float { if (this.isEmpty()) return 0f val sorted = this.map(selector).sorted() val n = this.size return if (n % 2 == 1) sorted[(n - 1) / 2] else (sorted[n / 2 - 1] + sorted[n / 2]) / 2 } inline fun <T> Collection<T>.standardDeviation(selector: (T) -> Float): Float { val mean = this.mean(selector) return sqrt(this.sumOf { (selector(it).toDouble() - mean).pow(2) / this.size }).toFloat() } inline fun <T> Collection<T>.quantile(alpha: Float, selector: (T) -> Float): Float { require(alpha in 0f..1f) if (this.isEmpty()) return 0f val sorted = this.map(selector).sorted() val floatIdx = (this.size - 1) * alpha val idxInt = floatIdx.toInt() val idxFrac = floatIdx - idxInt return if (idxFrac < 1e-5) sorted[idxInt] else sorted[idxInt] * (1 - idxFrac) + sorted[idxInt + 1] * idxFrac } fun r2Score(y: List<Double>, yPred: List<Double>): Double { val rss = y.mapIndexed { idx, gp -> (gp - yPred[idx]).pow(2) }.sum() val yMean = y.mean() val tss = y.sumOf { (it - yMean).pow(2) } return 1 - rss / tss }
0
Jupyter Notebook
0
0
5dd497b74a767c740386dc67e6841673b17b96fb
1,811
QLab
MIT License
src/main/kotlin/dev/bogwalk/batch3/Problem38.kt
bog-walk
381,459,475
false
null
package dev.bogwalk.batch3 import dev.bogwalk.util.strings.isPandigital /** * Problem 38: Pandigital Multiples * * https://projecteuler.net/problem=38 * * Goal: Find all multipliers M below N that provide a K-pandigital concatenated product when * used with a multiplicand starting with 1 onwards. * * Constraints: 100 <= N <= 1e5, K in {8, 9} and 1 < M * * e.g.: N = 100, K = 8 * multipliers = {18, 78}, since: * 18 * (1, 2, 3, 4) -> 18|36|54|72 * 78 * (1, 2, 3) -> 78|156|234 */ class PandigitalMultiples { /** * Since a 9-digit pandigital number is the limit, the multiplier will never be larger than 4 * digits (as a 5-digit number times 2 would produce another 5-digit number). * * N.B. The logic behind the inner loop breaks could all be replaced by the isPandigital() * helper function used in the PE implementation at the bottom. */ fun findPandigitalMultipliers(n: Int, k: Int): List<Int> { val multipliers = mutableListOf<Int>() for (num in 2..(minOf(n, 9876))) { var concat = "" var multiplicand = 1 while (concat.length < k) { val product = (num * multiplicand).toString() // ensure result only 1 to k pandigital if ( product.any { ch -> ch == '0' || ch > k.digitToChar() || ch in concat } ) break // avoid products that contain duplicate digits if (product.length != product.toSet().size) break concat += product multiplicand++ } if (concat.length == k) { multipliers.add(num) } } return multipliers } /** * Project Euler specific implementation that finds the largest 1 to 9 pandigital number that * can be formed as a concatenated product. * * Solution is based on the following: * * - Since the multiplier must at minimum be multiplied by both 1 & 2, it cannot be larger * than 4 digits to ensure product is only 9 digits. * * - The default largest would be M = 9 * (1, 2, 3, 4, 5) = 918_273_645, so M must begin * with the digit 9. * * - The 2-digit minimum (M = 91) would result in either an 8-/11-digit product once * multiplied by 3 and 4. The 3-digit minimum (M = 912) would result in either a 7-/11-digit * product once multiplied by 2 and 3. * * - So M must be a 4-digit number multiplied by 2 to get a 9-digit product and at minimum * will be 9182 (1st 4 digits of default) and at max 9876. * * - Multiplying 9xxx by 2 will at minimum result in 18xxx, always generating a new digit 1, * so M cannot itself contain the digit 1, setting the new minimum to 9234. * * - Lastly, multiplying [98xx, 95xx, -1] by 2 will at minimum result in 19xxx, always * generating another digit 9, so M's 2nd digit must be < 5, setting the new maximum to 9487. */ fun largest9Pandigital(): String { var largest = "" for (m in 9487 downTo 9234) { largest = "${m}${m * 2}" if (largest.isPandigital(9)) break } return largest } }
0
Kotlin
0
0
62b33367e3d1e15f7ea872d151c3512f8c606ce7
3,321
project-euler-kotlin
MIT License
src/main/kotlin/Day18.kt
clechasseur
318,029,920
false
null
import org.clechasseur.adventofcode2020.Day18Data object Day18 { private val input = Day18Data.input fun part1(): Long = input.lines().map { line -> line.withoutWhitespace.compute(advanced = false) }.sum() fun part2(): Long = input.lines().map { line -> line.withoutWhitespace.compute(advanced = true) }.sum() private interface Token private class ValueToken(val value: Long) : Token private class OperatorToken(val op: Char) : Token private val String.withoutWhitespace: String get() = "\\s".toRegex().replace(this, "") private fun String.compute(advanced: Boolean): Long { val tokens = mutableListOf<Token>() var (left, pos) = readValue(0, advanced) tokens.add(left) while (pos < length) { val op = OperatorToken(this[pos++]) tokens.add(op) val (right, newPos) = readValue(pos, advanced) tokens.add(right) pos = newPos } return if (advanced) { tokens.computeAdvanced() } else { tokens.computeBasic() } } private fun String.readValue(pos: Int, advanced: Boolean): Pair<Token, Int> = if (this[pos] == '(') { var lastPos = pos + 1 var depth = 1 while (depth > 0) { depth += when (this[lastPos]) { '(' -> 1 ')' -> -1 else -> 0 } lastPos++ } ValueToken(substring(pos + 1 until lastPos - 1).compute(advanced)) to lastPos } else { ValueToken(this[pos].toString().toLong()) to pos + 1 } private fun List<Token>.computeBasic(): Long { var value = (first() as ValueToken).value drop(1).chunked(2).forEach { (opToken, right) -> val rightValue = (right as ValueToken).value value = when (val op = (opToken as OperatorToken).op) { '+' -> value + rightValue '*' -> value * rightValue else -> error("Wrong operator: $op") } } return value } private fun List<Token>.computeAdvanced(): Long { val added = toMutableList() var i = 0 while (i < (added.size - 1)) { val left = added[i] val op = added[i + 1] val right = added[i + 2] if ((op as OperatorToken).op == '+') { val result = (left as ValueToken).value + (right as ValueToken).value (0..2).forEach { _ -> added.removeAt(i) } added.add(i, ValueToken(result)) } else { i += 2 } } return added.computeBasic() } }
0
Kotlin
0
0
6173c9da58e3118803ff6ec5b1f1fc1c134516cb
2,729
adventofcode2020
MIT License
leetcode/kotlin/number-of-islands.kt
PaiZuZe
629,690,446
false
null
data class Cell(val row: Int, val col: Int) class Solution { fun numIslands(grid: Array<CharArray>): Int { val visited = Array(grid.size) { BooleanArray(grid[0].size) { false } } var islands = 0 for (i in grid.indices) { for (j in grid[i].indices) { val cell = Cell(i, j) if (grid[i][j] == '1' && !visited[cell.row][cell.col]) { bfs(cell, grid, visited) islands++ } } } return islands } private fun bfs(start: Cell, grid: Array<CharArray>, visited: Array<BooleanArray>) { val frontier = ArrayDeque<Cell>(listOf(start)) visited[start.row][start.col] = true while (frontier.isNotEmpty()) { val cell = frontier.removeFirst() getNeighbors(cell, grid.size, grid[0].size).filter { neighbor -> !visited[neighbor.row][neighbor.col] && grid[neighbor.row][neighbor.col] == '1' }.forEach { visited[it.row][it.col] = true frontier.addLast(it) } } } private fun getNeighbors(cell: Cell, maxRow: Int, maxCol: Int): List<Cell> { val neighbors = mutableListOf<Cell>() val row = cell.row val col = cell.col if (row > 0) { neighbors.add(Cell(row - 1, col)) } if (row < maxRow - 1) { neighbors.add(Cell(row + 1, col)) } if (col > 0) { neighbors.add(Cell(row, col - 1)) } if (col < maxCol - 1) { neighbors.add(Cell(row, col + 1)) } return neighbors.toList() } }
0
Kotlin
0
0
175a5cd88959a34bcb4703d8dfe4d895e37463f0
1,698
interprep
MIT License
src/main/kotlin/net/voldrich/aoc2021/Day13.kt
MavoCz
434,703,997
false
{"Kotlin": 119158}
package net.voldrich.aoc2021 import net.voldrich.BaseDay // link to task fun main() { Day13().run() } class Day13 : BaseDay() { override fun task1() : Int { val paper = PaperInstructions() return foldPaper(paper.foldInstructions.first(), paper.points.toSet()).size } override fun task2() : Int { val paper = PaperInstructions() val finalPoints = paper.foldInstructions.fold(paper.points.toSet()) { points, f -> foldPaper(f, points) } renderPointsAsAscii(finalPoints) // human reader output: "EPLGRULR" return finalPoints.size } private fun renderPointsAsAscii(points: Set<Point>) { val sx = points.maxOf { it.x } val sy = points.maxOf { it.y } // render points to screen, the dump but fast way for (y in (0..sy)) { for (x in (0..sx)) { if (points.contains(Point(y,x))) { print("x") } else { print(" ") } } println() } } private fun foldPaper(fold: FoldInstruction, points: Set<Point>) : Set<Point> { return if (fold.axis == "y") { points.filter { it.y < fold.value }.toSet().union( points.filter { it.y > fold.value }.map { Point(2*fold.value - it.y, it.x) }.toSet()) } else { points.filter { it.x < fold.value }.toSet().union( points.filter { it.x > fold.value }.map { Point(it.y, 2*fold.value - it.x) }.toSet()) } } inner class PaperInstructions { val points: List<Point> val foldInstructions: List<FoldInstruction> init { val groupBy = input.lines().groupBy { it.contains("fold along") } points = groupBy[false]!!.mapNotNull { line -> if (line.isNotBlank()) { val (x, y) = line.split(",") Point(y.toInt(), x.toInt()) } else { null } } val regex = Regex("fold along ([a-z])=([0-9]+)") foldInstructions = groupBy[true]!!.map { line -> val matches = regex.find(line)!! FoldInstruction(matches.groups[1]!!.value, matches.groups[2]!!.value.toInt()) } } override fun toString(): String { return "DotGrid(points=$points, foldInstructions=$foldInstructions)" } } data class Point(val y : Int, val x: Int) data class FoldInstruction(val axis : String, val value: Int) }
0
Kotlin
0
0
0cedad1d393d9040c4cc9b50b120647884ea99d9
2,605
advent-of-code
Apache License 2.0
src/main/kotlin/day25.kt
Gitvert
725,292,325
false
{"Kotlin": 97000}
import java.util.* fun day25 (lines: List<String>) { val components = parseComponentConnections(lines) val connections = mutableListOf<Pair<String, String>>() components.forEach { component -> component.value.forEach { if (!connections.contains(Pair(component.key, it)) && !connections.contains(Pair(it, component.key))) { connections.add(Pair(component.key, it)) } } } val connectionCount = countConnectionUsages(connections, components).entries.sortedByDescending { it.value } val remainingConnections = connections.toMutableList() remainingConnections.remove(connectionCount[0].key) remainingConnections.remove(connectionCount[1].key) remainingConnections.remove(connectionCount[2].key) val lhs = getReachableComponents(remainingConnections, remainingConnections.first().first) val rem = remainingConnections.filterNot { lhs.contains(it.first) || lhs.contains(it.second) } val rhs = getReachableComponents(rem, rem.first().first) println("Day 25 part 1: ${lhs.size * rhs.size}") println() } fun countConnectionUsages(connections: MutableList<Pair<String, String>>, components: MutableMap<String, MutableSet<String>>): MutableMap<Pair<String, String>, Int> { val connectionCount = mutableMapOf<Pair<String, String>, Int>() connections.forEach { connectionCount[it] = 0 } components.forEach { component -> val queue: Queue<String> = LinkedList() val visited = mutableListOf(component.key) queue.add(component.key) while(queue.isNotEmpty()) { val current = queue.peek() queue.remove() connections.filter { it.first == current || it.second == current }.forEach { val next = if (it.first == current) { it.second } else { it.first } if (!visited.contains(next)) { visited.add(next) queue.add(next) connectionCount[it] = connectionCount[it]!! + 1 } } } } return connectionCount } fun getReachableComponents(connections: List<Pair<String, String>>, start: String): List<String> { val queue: Queue<String> = LinkedList() val visited = mutableListOf(start) queue.add(start) while(queue.isNotEmpty()) { val current = queue.peek() queue.remove() connections.filter { it.first == current || it.second == current }.forEach { val next = if (it.first == current) { it.second } else { it.first } if (!visited.contains(next)) { visited.add(next) queue.add(next) } } } return visited } fun parseComponentConnections(lines: List<String>): MutableMap<String, MutableSet<String>> { val components = mutableMapOf<String, MutableSet<String>>() lines.forEach { line -> line.replace(":", "").split(" ").forEach { components[it] = mutableSetOf() } } lines.forEach { line -> val from = line.split(": ")[0] val to = line.split(": ")[1].split(" ") to.forEach { components[from]?.add(it) components[it]?.add(from) } } return components }
0
Kotlin
0
0
f204f09c94528f5cd83ce0149a254c4b0ca3bc91
3,500
advent_of_code_2023
MIT License
src/Day04.kt
jdappel
575,879,747
false
{"Kotlin": 10062}
fun main() { fun part1(input: List<String>): Int { return input.fold(0) { acc, line -> val (firstElf, secondElf) = line.split(",") val (firstElfStart, firstElfEnd) = firstElf.split("-") val (secondElfStart, secondElfEnd) = secondElf.split("-") val firstElfRange = firstElfStart.toInt()..firstElfEnd.toInt() val secondElfRange = secondElfStart.toInt()..secondElfEnd.toInt() val cnt = if (secondElfRange.all { it in firstElfRange } || firstElfRange.all { it in secondElfRange }) 1 else 0 acc + cnt } } fun part2(input: List<String>): Int { return input.fold(0) { acc, line -> val (firstElf, secondElf) = line.split(",") val (firstElfStart, firstElfEnd) = firstElf.split("-") val (secondElfStart, secondElfEnd) = secondElf.split("-") val firstElfRange = firstElfStart.toInt()..firstElfEnd.toInt() val secondElfRange = secondElfStart.toInt()..secondElfEnd.toInt() val cnt = if (secondElfRange.any { it in firstElfRange } || firstElfRange.any { it in secondElfRange }) 1 else 0 acc + cnt } } // test if implementation meets criteria from the description, like: //val testInput = readInput("Day01_test") //check(part1(testInput) == 1) val input = readInput("Day04_test") println(part2(input)) }
0
Kotlin
0
0
ddcf4f0be47ccbe4409605b37f43534125ee859d
1,436
AdventOfCodeKotlin
Apache License 2.0
lc003/src/main/kotlin/max_sum_of_rectangle_no_larger_than_k/max_sum_of_rectangle_no_larger_than_k.kt
warmthdawn
467,419,502
false
{"Kotlin": 28653, "Java": 8222}
package max_sum_of_rectangle_no_larger_than_k import kotlin.math.sign class Solution { fun maxSumSubmatrix(matrix: Array<IntArray>, k: Int): Int { val lineSums = matrix.map { line -> val size = line.size Array(size) { i -> var sum = 0 IntArray(size - i) { j -> sum += line[i + j] sum } } } val columns = matrix[0].size val lines = matrix.size var max = Int.MIN_VALUE (0 until columns) .forEach { x1 -> (0 until columns - x1) .forEach { xp -> for (y1 in (0 until lines)) { var sum = 0 for (y2 in (y1 until lines)) { sum += lineSums[y2][x1][xp] if (sum <= k) { max = if (sum > max) sum else max } } } } } return max } } //TLE class SolutionDeprecated { fun maxSumSubmatrix(matrix: Array<IntArray>, k: Int): Int { val lineSums = matrix.map { val listIt = it.asList() it.indices.map { a -> (a until it.size) .map { b -> listIt .subList(a, b + 1) .sum() } .toTypedArray() }.toTypedArray() } val columns = matrix[0].size val lines = matrix.size return (0 until columns) .asSequence() .flatMap { x1 -> (0 until columns - x1) .asSequence() .flatMap { x2p -> (0 until lines) .asSequence() .flatMap { y1 -> (y1 until lines) .asSequence() .map { y2 -> (y1..y2) .asSequence() .map { y0 -> lineSums[y0][x1][x2p] } .sum() } } } } .filter { it <= k } .max()!! } }
0
Kotlin
0
0
40dc158a934f0fc4a3c6076bf1b5babf8413e190
2,711
LeetCode
MIT License
advent-of-code-2018/src/test/java/aoc/Advent4.kt
yuriykulikov
159,951,728
false
{"Kotlin": 1666784, "Rust": 33275}
package aoc import org.assertj.core.api.Assertions.assertThat import org.junit.Ignore import org.junit.Test import java.text.SimpleDateFormat import java.util.* import java.util.Locale private val sdf = SimpleDateFormat("YYYY-MM-dd HH:mm", Locale.ENGLISH) sealed class Line data class ShiftStart(val calendar: Calendar, val id: Int) : Line() data class FellAsleep(val calendar: Calendar) : Line() { val minute = calendar.get(Calendar.MINUTE) } data class WokeUp(val calendar: Calendar) : Line() { val minute = calendar.get(Calendar.MINUTE) } /** Parse string to sealed [Line] */ fun String.parseLine(): Line { fun String.toCalendar(): Calendar { val str = this return Calendar.getInstance().apply { time = sdf.parse(str) } } val parsed = this.split('[', ']').filter { it.isNotEmpty() } val calendar = parsed.first().toCalendar() return when { parsed[1].contains("Guard #") -> { val id = parsed[1].dropWhile { it != '#' }.drop(1).takeWhile { it != ' ' }.toInt() ShiftStart(calendar = calendar, id = id) } parsed[1].contains("falls asleep") -> FellAsleep(calendar = calendar) else -> WokeUp(calendar = calendar) } } data class Shift(val id: Int, val naps: List<Pair<Int, Int>>) { val total = naps.map { it.second - it.first }.sum() } data class SleepyMinute(val minute: Int, val times: Int) private fun mostSleepyMinute(shifts: List<Shift>): Int { return mostSleepy(shifts).minute } private fun mostSleepy(shifts: List<Shift>): SleepyMinute { return shifts.flatMap { it.naps } .flatMap { it.first..it.second } .groupBy { it } .map { entry -> SleepyMinute(minute = entry.key, times = entry.value.size) } .maxBy { it.times } ?: SleepyMinute(0, 0) } /** * Stateful shift collector. Collects into [shifts]. */ class ShiftCollector { private var start: ShiftStart = ShiftStart(Calendar.getInstance(), 0) private var fellAsleep: FellAsleep = FellAsleep(Calendar.getInstance()) private var naps: List<Pair<Int, Int>> = listOf() var shifts: List<Shift> = listOf() fun processNext(input: Line): ShiftCollector { when (input) { is ShiftStart -> { // emit shift shifts = shifts.plus(Shift(start.id, naps)) naps = listOf() start = input } is FellAsleep -> fellAsleep = input is WokeUp -> { naps = naps.plus(fellAsleep.minute to input.minute) } } return this } } fun parseShifts(input: String): List<Shift> { return input.lines() .asSequence() // terminate the sequence .plus("[2000-11-05 00:03] Guard #100500 begins shift") // apparently it is all messed up, sort it .sorted() .map { string -> string.parseLine() } .fold(ShiftCollector()) { collector, next: Line -> collector.processNext(next) } .shifts .drop(1) .toList() } class Advent4 { @Test fun `strategy 1 for test input result is 240`() { val (id, shifts) = parseShifts(guardTestInput).onEach { println(it) } .groupBy { it.id } .entries .maxBy { entry -> entry.value.sumBy { shift -> shift.total } }!! assertThat(id).isEqualTo(10) val minute = mostSleepyMinute(shifts) assertThat(minute).isEqualTo(24) assertThat(minute * id).isEqualTo(240) } @Test fun `strategy 1 for real input result is 50558`() { val (id, shifts: List<Shift>) = parseShifts(guardInput).onEach { println(it) } .groupBy { it.id } .entries .maxBy { entry -> entry.value.sumBy { shift -> shift.total } }!! assertThat(id).isEqualTo(1487) val minute = mostSleepyMinute(shifts) assertThat(minute).isEqualTo(34) assertThat(minute * id).isEqualTo(50558) } @Test fun `strategy 2 for test input is 4455`() { val (id, shifts: List<Shift>) = parseShifts(guardTestInput).onEach { println(it) } .groupBy { it.id } .entries .maxBy { entry -> mostSleepy(entry.value).times }!! val mostSleepyMinute = mostSleepyMinute(shifts) assertThat(id).isEqualTo(99) assertThat(mostSleepyMinute).isEqualTo(45) assertThat(id * mostSleepyMinute).isEqualTo(4455) } @Ignore @Test fun `strategy 2 for real input is 4455`() { val (id, shifts: List<Shift>) = parseShifts(guardInput).onEach { println(it) } .groupBy { it.id } .entries .maxBy { entry -> mostSleepy(entry.value).times }!! val mostSleepyMinute = mostSleepyMinute(shifts) assertThat(id).isEqualTo(613) assertThat(mostSleepyMinute).isEqualTo(46) assertThat(id * mostSleepyMinute).isEqualTo(28198) } } private val guardTestInput = """ [1518-11-01 00:00] Guard #10 begins shift [1518-11-01 00:05] falls asleep [1518-11-01 00:25] wakes up [1518-11-01 00:30] falls asleep [1518-11-01 00:55] wakes up [1518-11-01 23:58] Guard #99 begins shift [1518-11-02 00:40] falls asleep [1518-11-02 00:50] wakes up [1518-11-03 00:05] Guard #10 begins shift [1518-11-03 00:24] falls asleep [1518-11-03 00:29] wakes up [1518-11-04 00:02] Guard #99 begins shift [1518-11-04 00:36] falls asleep [1518-11-04 00:46] wakes up [1518-11-05 00:03] Guard #99 begins shift [1518-11-05 00:45] falls asleep [1518-11-05 00:55] wakes up """.trimIndent() private val guardInput = """ [1518-07-31 00:54] wakes up [1518-04-09 00:01] Guard #3407 begins shift [1518-04-03 00:36] wakes up [1518-10-24 00:03] Guard #1049 begins shift [1518-03-15 00:11] falls asleep [1518-09-25 00:04] Guard #293 begins shift [1518-07-29 00:38] falls asleep [1518-06-05 00:37] wakes up [1518-10-10 23:59] Guard #3203 begins shift [1518-09-17 00:50] wakes up [1518-04-18 00:32] falls asleep [1518-05-19 00:39] falls asleep [1518-10-15 00:00] Guard #3119 begins shift [1518-03-22 00:43] falls asleep [1518-08-31 00:54] wakes up [1518-04-27 00:51] falls asleep [1518-11-11 00:24] falls asleep [1518-05-15 00:49] falls asleep [1518-07-15 00:58] wakes up [1518-06-29 00:43] wakes up [1518-06-26 00:39] wakes up [1518-04-12 00:53] wakes up [1518-02-21 00:02] Guard #613 begins shift [1518-06-28 00:46] falls asleep [1518-08-25 00:57] wakes up [1518-06-19 23:56] Guard #223 begins shift [1518-11-12 00:59] wakes up [1518-04-17 00:58] wakes up [1518-09-26 00:54] wakes up [1518-08-16 00:42] wakes up [1518-02-24 00:22] falls asleep [1518-06-07 23:56] Guard #293 begins shift [1518-07-12 23:56] Guard #1567 begins shift [1518-09-04 00:25] falls asleep [1518-06-26 23:58] Guard #1747 begins shift [1518-04-04 23:59] Guard #613 begins shift [1518-07-23 00:52] wakes up [1518-09-17 00:56] wakes up [1518-04-20 00:51] falls asleep [1518-04-21 00:00] falls asleep [1518-08-23 23:56] Guard #887 begins shift [1518-02-10 00:54] wakes up [1518-08-15 00:48] falls asleep [1518-03-13 00:51] wakes up [1518-04-21 00:43] falls asleep [1518-04-24 00:54] falls asleep [1518-05-22 00:04] Guard #2341 begins shift [1518-11-15 00:56] wakes up [1518-05-07 00:57] wakes up [1518-09-14 00:38] wakes up [1518-04-17 23:59] Guard #431 begins shift [1518-08-27 00:02] falls asleep [1518-07-12 00:04] falls asleep [1518-03-13 00:57] falls asleep [1518-04-22 00:03] Guard #2357 begins shift [1518-05-22 23:59] Guard #887 begins shift [1518-06-08 00:10] falls asleep [1518-10-27 00:21] falls asleep [1518-07-30 00:55] wakes up [1518-07-04 00:03] Guard #1031 begins shift [1518-02-18 00:01] Guard #3407 begins shift [1518-08-13 00:53] wakes up [1518-10-19 00:18] wakes up [1518-08-16 00:29] wakes up [1518-02-24 23:59] Guard #1747 begins shift [1518-02-15 00:41] falls asleep [1518-03-15 00:56] wakes up [1518-04-16 00:56] wakes up [1518-05-18 23:48] Guard #541 begins shift [1518-08-20 00:58] wakes up [1518-11-14 00:48] wakes up [1518-08-20 00:36] falls asleep [1518-04-29 23:56] Guard #613 begins shift [1518-08-03 00:27] wakes up [1518-02-26 00:38] wakes up [1518-03-03 00:35] falls asleep [1518-06-04 00:59] wakes up [1518-02-18 23:49] Guard #3203 begins shift [1518-05-15 00:56] wakes up [1518-02-19 00:17] wakes up [1518-09-17 00:04] Guard #1049 begins shift [1518-05-21 00:56] wakes up [1518-08-19 00:39] wakes up [1518-02-22 00:17] falls asleep [1518-02-27 00:32] wakes up [1518-04-30 00:43] falls asleep [1518-03-22 00:11] falls asleep [1518-10-09 00:11] falls asleep [1518-09-12 00:25] falls asleep [1518-03-16 00:21] wakes up [1518-08-15 00:52] wakes up [1518-07-19 00:44] wakes up [1518-03-02 00:07] falls asleep [1518-04-28 00:35] wakes up [1518-10-13 00:17] falls asleep [1518-08-08 00:33] falls asleep [1518-10-01 23:56] Guard #1031 begins shift [1518-06-21 00:51] wakes up [1518-08-08 00:03] falls asleep [1518-05-03 00:30] falls asleep [1518-10-08 00:59] wakes up [1518-07-27 00:25] wakes up [1518-11-07 00:48] wakes up [1518-05-25 00:45] wakes up [1518-05-27 00:34] falls asleep [1518-08-10 00:31] falls asleep [1518-08-08 00:48] wakes up [1518-11-01 00:34] falls asleep [1518-07-19 00:38] falls asleep [1518-06-02 00:06] falls asleep [1518-10-15 00:29] wakes up [1518-08-22 00:18] falls asleep [1518-08-27 00:56] wakes up [1518-10-05 00:48] falls asleep [1518-05-19 00:13] wakes up [1518-05-21 00:55] falls asleep [1518-03-26 00:41] wakes up [1518-10-25 00:49] wakes up [1518-05-23 00:51] wakes up [1518-03-25 00:21] falls asleep [1518-10-14 00:21] wakes up [1518-06-01 00:44] falls asleep [1518-02-27 00:39] falls asleep [1518-07-22 00:57] wakes up [1518-09-07 23:50] Guard #503 begins shift [1518-08-01 23:49] Guard #503 begins shift [1518-09-11 00:02] Guard #3119 begins shift [1518-07-20 00:27] falls asleep [1518-09-09 00:47] wakes up [1518-10-10 00:01] Guard #431 begins shift [1518-05-08 23:56] Guard #541 begins shift [1518-08-28 00:33] falls asleep [1518-11-01 00:51] wakes up [1518-05-19 00:04] falls asleep [1518-04-20 23:50] Guard #503 begins shift [1518-07-05 00:55] wakes up [1518-06-18 00:22] falls asleep [1518-07-24 00:41] wakes up [1518-07-15 00:13] falls asleep [1518-05-06 00:46] falls asleep [1518-06-26 00:47] wakes up [1518-06-25 00:47] wakes up [1518-05-16 00:47] wakes up [1518-05-14 00:18] wakes up [1518-11-12 00:33] falls asleep [1518-06-29 23:57] Guard #3137 begins shift [1518-04-05 00:55] wakes up [1518-03-11 00:44] wakes up [1518-04-29 00:47] wakes up [1518-09-03 00:03] wakes up [1518-07-18 23:56] Guard #3203 begins shift [1518-06-21 00:43] falls asleep [1518-06-14 00:13] falls asleep [1518-10-08 00:37] falls asleep [1518-11-07 00:33] falls asleep [1518-02-25 23:56] Guard #3119 begins shift [1518-10-18 00:09] falls asleep [1518-05-23 00:33] falls asleep [1518-08-11 00:44] wakes up [1518-05-27 00:50] wakes up [1518-10-27 00:00] Guard #2803 begins shift [1518-06-19 00:00] Guard #1567 begins shift [1518-08-02 23:48] Guard #1049 begins shift [1518-02-18 00:50] wakes up [1518-05-22 00:50] wakes up [1518-10-15 00:38] falls asleep [1518-08-02 00:36] falls asleep [1518-09-22 00:00] Guard #3119 begins shift [1518-05-16 00:51] falls asleep [1518-05-13 00:03] Guard #1049 begins shift [1518-03-25 00:45] falls asleep [1518-04-18 00:57] wakes up [1518-05-27 00:42] falls asleep [1518-04-07 00:49] wakes up [1518-07-22 00:01] Guard #223 begins shift [1518-05-31 00:56] wakes up [1518-09-28 00:03] Guard #1061 begins shift [1518-08-13 00:03] Guard #1567 begins shift [1518-06-06 00:01] Guard #3137 begins shift [1518-08-15 00:25] wakes up [1518-11-20 00:24] falls asleep [1518-09-26 00:17] falls asleep [1518-02-14 00:02] falls asleep [1518-11-17 00:24] falls asleep [1518-08-24 00:28] wakes up [1518-06-27 00:53] wakes up [1518-02-13 00:04] Guard #2803 begins shift [1518-07-13 00:36] falls asleep [1518-07-10 00:16] falls asleep [1518-02-16 00:00] Guard #1747 begins shift [1518-10-06 00:53] wakes up [1518-02-12 00:42] falls asleep [1518-03-31 00:48] falls asleep [1518-03-28 00:54] wakes up [1518-09-05 23:58] Guard #887 begins shift [1518-03-29 00:18] falls asleep [1518-03-09 23:57] Guard #503 begins shift [1518-04-10 00:59] wakes up [1518-09-14 00:24] falls asleep [1518-06-25 23:49] Guard #293 begins shift [1518-06-10 23:56] Guard #1487 begins shift [1518-09-23 00:42] falls asleep [1518-10-28 00:57] wakes up [1518-11-06 00:11] falls asleep [1518-05-02 00:03] falls asleep [1518-03-19 00:14] wakes up [1518-06-29 00:53] falls asleep [1518-04-14 00:54] wakes up [1518-10-04 00:52] wakes up [1518-05-14 00:59] wakes up [1518-05-13 00:40] falls asleep [1518-04-06 00:46] falls asleep [1518-09-08 00:29] wakes up [1518-10-30 00:40] falls asleep [1518-03-03 00:59] wakes up [1518-05-15 00:03] Guard #2341 begins shift [1518-06-10 00:00] falls asleep [1518-05-14 00:34] falls asleep [1518-03-22 00:04] Guard #1567 begins shift [1518-03-27 00:00] falls asleep [1518-04-07 00:19] falls asleep [1518-08-22 00:36] wakes up [1518-11-16 00:51] wakes up [1518-08-26 00:45] falls asleep [1518-09-04 00:05] falls asleep [1518-07-01 00:00] falls asleep [1518-08-02 00:53] falls asleep [1518-05-16 00:05] falls asleep [1518-09-27 00:25] wakes up [1518-09-19 00:58] wakes up [1518-11-21 00:41] falls asleep [1518-03-21 00:59] wakes up [1518-02-16 00:21] falls asleep [1518-03-21 00:47] falls asleep [1518-02-25 00:57] wakes up [1518-04-11 00:00] falls asleep [1518-05-28 00:31] wakes up [1518-07-18 00:21] wakes up [1518-03-20 00:15] wakes up [1518-09-26 00:01] falls asleep [1518-11-14 00:33] falls asleep [1518-08-02 00:29] wakes up [1518-10-07 00:59] wakes up [1518-05-19 00:55] wakes up [1518-04-14 00:10] falls asleep [1518-10-12 00:56] wakes up [1518-07-31 23:56] Guard #2803 begins shift [1518-04-03 23:51] Guard #1049 begins shift [1518-06-30 00:13] falls asleep [1518-11-02 00:03] falls asleep [1518-07-03 00:01] Guard #2003 begins shift [1518-06-24 00:43] falls asleep [1518-10-29 00:46] wakes up [1518-08-30 23:46] Guard #223 begins shift [1518-03-24 00:22] wakes up [1518-10-12 00:46] falls asleep [1518-06-23 23:56] Guard #1747 begins shift [1518-08-27 00:24] wakes up [1518-11-09 00:45] wakes up [1518-05-29 23:57] Guard #887 begins shift [1518-11-18 23:52] Guard #3119 begins shift [1518-09-25 00:13] falls asleep [1518-10-30 00:02] Guard #223 begins shift [1518-03-28 00:34] wakes up [1518-09-16 00:43] wakes up [1518-07-30 00:34] falls asleep [1518-09-13 00:35] falls asleep [1518-08-06 00:00] Guard #2341 begins shift [1518-02-10 00:30] falls asleep [1518-07-09 00:56] wakes up [1518-02-25 00:55] falls asleep [1518-10-24 00:54] wakes up [1518-08-10 00:57] wakes up [1518-07-12 00:05] wakes up [1518-07-02 00:01] Guard #3407 begins shift [1518-03-13 00:03] Guard #613 begins shift [1518-11-15 00:21] wakes up [1518-03-10 00:54] falls asleep [1518-05-09 00:17] falls asleep [1518-11-08 00:59] wakes up [1518-09-04 23:56] Guard #887 begins shift [1518-09-10 00:39] wakes up [1518-05-14 00:06] falls asleep [1518-02-12 00:34] wakes up [1518-09-20 00:36] falls asleep [1518-04-23 00:46] wakes up [1518-08-16 00:04] falls asleep [1518-03-08 00:03] Guard #3137 begins shift [1518-08-31 00:37] falls asleep [1518-08-07 00:35] falls asleep [1518-06-26 00:50] falls asleep [1518-04-05 23:57] Guard #2803 begins shift [1518-09-14 00:02] Guard #541 begins shift [1518-06-25 00:04] falls asleep [1518-03-29 00:00] Guard #2003 begins shift [1518-02-28 23:46] Guard #1487 begins shift [1518-04-25 00:01] Guard #541 begins shift [1518-02-26 00:41] falls asleep [1518-06-06 00:21] falls asleep [1518-02-22 23:52] Guard #1031 begins shift [1518-07-28 00:36] wakes up [1518-05-29 00:26] falls asleep [1518-10-31 00:39] falls asleep [1518-09-13 00:41] wakes up [1518-11-05 00:06] falls asleep [1518-10-26 00:56] wakes up [1518-07-06 00:57] wakes up [1518-07-11 00:27] falls asleep [1518-10-18 00:00] Guard #3407 begins shift [1518-09-05 00:46] wakes up [1518-10-06 00:25] falls asleep [1518-06-21 00:29] wakes up [1518-09-05 00:49] falls asleep [1518-09-30 23:57] Guard #431 begins shift [1518-04-25 23:56] Guard #293 begins shift [1518-03-23 00:53] wakes up [1518-05-10 23:56] Guard #3407 begins shift [1518-06-03 00:36] wakes up [1518-03-04 00:58] wakes up [1518-07-27 00:33] falls asleep [1518-04-22 23:54] Guard #223 begins shift [1518-08-06 00:35] falls asleep [1518-07-10 00:04] Guard #1487 begins shift [1518-07-27 23:51] Guard #3011 begins shift [1518-02-11 00:16] wakes up [1518-09-11 00:28] falls asleep [1518-08-19 00:03] Guard #3119 begins shift [1518-05-10 00:40] falls asleep [1518-09-20 00:04] Guard #613 begins shift [1518-10-02 00:37] falls asleep [1518-05-10 00:04] Guard #431 begins shift [1518-06-11 00:54] wakes up [1518-05-07 00:28] falls asleep [1518-10-09 00:50] falls asleep [1518-07-17 00:39] wakes up [1518-11-23 00:39] wakes up [1518-05-28 00:48] falls asleep [1518-10-18 00:49] falls asleep [1518-11-04 00:04] falls asleep [1518-03-30 00:31] falls asleep [1518-02-10 23:56] Guard #2003 begins shift [1518-08-03 23:57] Guard #2357 begins shift [1518-03-10 23:59] Guard #431 begins shift [1518-03-20 00:02] falls asleep [1518-03-25 00:41] wakes up [1518-09-16 00:26] falls asleep [1518-10-27 00:13] falls asleep [1518-03-19 00:13] falls asleep [1518-02-19 23:58] Guard #3407 begins shift [1518-05-01 00:36] falls asleep [1518-05-25 23:57] Guard #887 begins shift [1518-08-09 00:14] falls asleep [1518-07-06 00:01] Guard #2803 begins shift [1518-08-15 23:50] Guard #1567 begins shift [1518-02-22 00:45] wakes up [1518-07-20 00:45] wakes up [1518-04-14 00:04] Guard #1487 begins shift [1518-08-16 00:54] falls asleep [1518-07-02 00:24] falls asleep [1518-03-03 00:21] falls asleep [1518-11-22 00:15] falls asleep [1518-10-13 00:46] wakes up [1518-03-31 23:57] Guard #541 begins shift [1518-07-10 00:49] wakes up [1518-02-12 00:11] falls asleep [1518-06-01 00:26] wakes up [1518-04-09 00:17] falls asleep [1518-07-21 00:45] wakes up [1518-08-09 00:03] Guard #503 begins shift [1518-10-14 00:04] Guard #503 begins shift [1518-11-15 00:00] falls asleep [1518-06-11 23:53] Guard #3119 begins shift [1518-10-16 23:47] Guard #223 begins shift [1518-03-22 00:54] wakes up [1518-07-10 23:58] Guard #613 begins shift [1518-05-31 00:03] Guard #2341 begins shift [1518-09-30 00:04] Guard #1049 begins shift [1518-02-10 00:03] Guard #3119 begins shift [1518-05-14 00:38] wakes up [1518-11-18 00:58] wakes up [1518-10-04 00:40] falls asleep [1518-09-13 00:03] Guard #3137 begins shift [1518-02-24 00:00] Guard #223 begins shift [1518-10-13 00:23] wakes up [1518-05-20 00:18] falls asleep [1518-10-01 00:46] falls asleep [1518-07-09 00:00] Guard #3011 begins shift [1518-11-16 23:56] Guard #613 begins shift [1518-05-29 00:50] wakes up [1518-09-24 00:50] wakes up [1518-11-06 00:56] wakes up [1518-06-03 00:51] falls asleep [1518-09-22 00:48] wakes up [1518-04-17 00:04] Guard #1487 begins shift [1518-07-24 00:58] wakes up [1518-04-28 00:28] falls asleep [1518-04-26 00:59] wakes up [1518-04-11 23:50] Guard #1049 begins shift [1518-07-04 00:53] falls asleep [1518-03-18 00:52] wakes up [1518-05-26 00:43] falls asleep [1518-06-23 00:56] falls asleep [1518-11-23 00:19] falls asleep [1518-06-25 00:25] wakes up [1518-11-12 00:49] falls asleep [1518-08-18 00:52] wakes up [1518-06-23 00:16] falls asleep [1518-05-03 00:20] wakes up [1518-06-26 00:00] falls asleep [1518-11-16 00:40] falls asleep [1518-11-09 00:04] Guard #1049 begins shift [1518-04-06 00:41] wakes up [1518-08-14 00:03] falls asleep [1518-11-13 00:11] falls asleep [1518-03-05 00:32] falls asleep [1518-03-08 00:15] falls asleep [1518-05-02 23:57] Guard #431 begins shift [1518-11-15 00:38] wakes up [1518-05-25 00:09] falls asleep [1518-03-07 00:38] wakes up [1518-11-13 00:46] wakes up [1518-07-05 00:36] wakes up [1518-08-23 00:54] wakes up [1518-06-22 00:31] falls asleep [1518-06-24 23:49] Guard #3137 begins shift [1518-10-18 23:56] Guard #2003 begins shift [1518-07-08 00:00] Guard #1031 begins shift [1518-09-24 00:00] falls asleep [1518-07-30 00:30] wakes up [1518-04-05 00:31] falls asleep [1518-10-16 00:17] falls asleep [1518-08-08 00:20] falls asleep [1518-03-01 00:56] wakes up [1518-06-27 00:26] falls asleep [1518-04-27 00:00] Guard #293 begins shift [1518-09-26 00:10] wakes up [1518-03-19 00:28] falls asleep [1518-10-28 00:37] falls asleep [1518-03-19 00:58] wakes up [1518-07-24 00:52] falls asleep [1518-10-02 00:31] wakes up [1518-07-25 00:00] Guard #503 begins shift [1518-06-13 00:41] wakes up [1518-07-05 00:50] falls asleep [1518-04-27 00:48] wakes up [1518-05-27 23:58] Guard #503 begins shift [1518-05-29 00:01] Guard #1049 begins shift [1518-03-12 00:52] wakes up [1518-10-13 00:41] falls asleep [1518-07-16 00:03] Guard #541 begins shift [1518-07-08 00:50] wakes up [1518-11-17 00:57] wakes up [1518-04-19 00:00] Guard #3407 begins shift [1518-04-19 00:37] wakes up [1518-11-14 23:51] Guard #3119 begins shift [1518-08-09 23:57] Guard #3011 begins shift [1518-07-25 00:31] falls asleep [1518-06-01 00:19] falls asleep [1518-06-15 23:50] Guard #223 begins shift [1518-04-21 00:55] wakes up [1518-10-04 00:00] Guard #613 begins shift [1518-10-25 23:57] Guard #1049 begins shift [1518-04-24 00:13] falls asleep [1518-08-30 00:50] wakes up [1518-05-19 23:59] Guard #3407 begins shift [1518-09-02 00:01] Guard #613 begins shift [1518-06-06 23:56] Guard #3119 begins shift [1518-11-18 00:36] falls asleep [1518-07-18 00:05] falls asleep [1518-10-09 00:33] wakes up [1518-10-03 00:20] falls asleep [1518-02-17 00:33] wakes up [1518-04-21 00:32] wakes up [1518-04-29 00:42] falls asleep [1518-09-17 00:49] falls asleep [1518-08-22 00:02] Guard #293 begins shift [1518-06-11 00:12] falls asleep [1518-07-14 00:55] wakes up [1518-05-17 00:09] wakes up [1518-08-07 00:57] wakes up [1518-04-26 00:49] wakes up [1518-11-10 23:59] Guard #1487 begins shift [1518-07-07 00:59] wakes up [1518-07-29 23:59] Guard #503 begins shift [1518-03-14 00:41] falls asleep [1518-03-26 23:50] Guard #1567 begins shift [1518-06-03 00:53] wakes up [1518-11-02 00:28] wakes up [1518-09-15 00:29] wakes up [1518-11-18 00:00] Guard #3203 begins shift [1518-10-05 00:03] falls asleep [1518-09-11 00:51] falls asleep [1518-09-06 00:53] wakes up [1518-03-15 23:58] Guard #3011 begins shift [1518-07-01 00:59] wakes up [1518-07-14 00:47] falls asleep [1518-10-07 00:02] falls asleep [1518-02-25 00:50] wakes up [1518-06-27 00:51] falls asleep [1518-07-02 00:11] falls asleep [1518-03-28 00:42] falls asleep [1518-07-26 00:06] falls asleep [1518-04-11 00:28] falls asleep [1518-06-26 00:54] wakes up [1518-06-12 00:56] falls asleep [1518-09-18 00:44] falls asleep [1518-08-31 00:23] wakes up [1518-03-12 00:55] falls asleep [1518-06-27 00:40] wakes up [1518-04-23 00:56] falls asleep [1518-11-20 23:46] Guard #2341 begins shift [1518-07-29 00:35] wakes up [1518-05-18 00:34] falls asleep [1518-07-23 00:18] falls asleep [1518-06-01 00:46] wakes up [1518-08-28 23:57] Guard #2341 begins shift [1518-08-04 23:52] Guard #1487 begins shift [1518-02-27 00:29] falls asleep [1518-04-10 23:54] Guard #3011 begins shift [1518-06-22 00:02] Guard #223 begins shift [1518-06-05 00:12] wakes up [1518-10-05 00:43] wakes up [1518-08-09 00:31] wakes up [1518-07-12 00:40] wakes up [1518-11-15 00:24] falls asleep [1518-04-24 00:48] wakes up [1518-02-18 00:37] falls asleep [1518-10-11 00:28] falls asleep [1518-11-10 00:01] Guard #3011 begins shift [1518-07-13 00:41] wakes up [1518-04-17 00:08] falls asleep [1518-03-20 00:51] falls asleep [1518-07-26 00:30] wakes up [1518-02-11 00:12] falls asleep [1518-06-25 00:28] falls asleep [1518-03-24 00:12] falls asleep [1518-09-05 00:10] falls asleep [1518-07-20 00:04] Guard #223 begins shift [1518-03-26 00:33] falls asleep [1518-06-18 00:59] wakes up [1518-10-06 00:00] Guard #1049 begins shift [1518-09-09 23:51] Guard #2803 begins shift [1518-07-22 00:08] falls asleep [1518-06-05 00:06] falls asleep [1518-04-20 00:11] falls asleep [1518-08-06 00:56] wakes up [1518-10-31 00:10] falls asleep [1518-03-07 00:29] wakes up [1518-04-02 00:21] falls asleep [1518-05-24 00:55] wakes up [1518-04-06 00:54] wakes up [1518-11-19 00:59] wakes up [1518-02-22 00:01] Guard #1567 begins shift [1518-04-13 00:00] Guard #613 begins shift [1518-03-19 23:54] Guard #1031 begins shift [1518-09-11 00:08] falls asleep [1518-09-21 00:52] wakes up [1518-04-08 00:14] falls asleep [1518-07-21 00:49] falls asleep [1518-10-31 00:19] falls asleep [1518-10-14 00:35] wakes up [1518-06-03 00:04] Guard #1487 begins shift [1518-05-22 00:48] falls asleep [1518-08-08 00:21] wakes up [1518-06-22 00:40] wakes up [1518-08-03 00:36] falls asleep [1518-09-01 00:42] wakes up [1518-03-01 00:05] falls asleep [1518-07-02 00:18] wakes up [1518-07-18 00:36] falls asleep [1518-06-23 00:04] Guard #293 begins shift [1518-10-03 00:29] wakes up [1518-09-21 00:41] falls asleep [1518-09-19 00:29] falls asleep [1518-06-02 00:00] Guard #1049 begins shift [1518-04-28 23:58] Guard #613 begins shift [1518-11-05 00:56] wakes up [1518-06-09 00:52] wakes up [1518-11-20 00:25] wakes up [1518-05-11 00:14] falls asleep [1518-09-02 23:52] Guard #1031 begins shift [1518-02-26 00:44] wakes up [1518-04-28 00:01] Guard #1487 begins shift [1518-03-04 00:04] falls asleep [1518-04-20 00:52] wakes up [1518-05-24 00:45] falls asleep [1518-05-15 23:48] Guard #2803 begins shift [1518-07-16 23:58] Guard #2803 begins shift [1518-03-14 00:56] wakes up [1518-10-14 00:07] falls asleep [1518-07-13 00:58] wakes up [1518-06-23 00:35] wakes up [1518-10-15 00:16] falls asleep [1518-09-25 00:29] wakes up [1518-10-21 00:12] falls asleep [1518-07-27 00:47] wakes up [1518-04-30 00:48] wakes up [1518-05-15 00:52] wakes up [1518-11-06 00:01] Guard #1049 begins shift [1518-02-16 00:51] wakes up [1518-04-16 00:27] falls asleep [1518-05-12 00:00] Guard #3119 begins shift [1518-11-08 00:48] falls asleep [1518-08-29 00:57] wakes up [1518-04-15 00:24] falls asleep [1518-05-22 00:34] wakes up [1518-07-21 00:53] wakes up [1518-05-30 00:57] wakes up [1518-04-14 23:56] Guard #3407 begins shift [1518-07-08 00:10] falls asleep [1518-08-30 00:27] falls asleep [1518-08-09 00:39] falls asleep [1518-06-19 00:46] falls asleep [1518-08-14 23:56] Guard #887 begins shift [1518-11-20 00:58] wakes up [1518-08-06 23:56] Guard #3011 begins shift [1518-05-31 00:42] wakes up [1518-09-11 00:15] wakes up [1518-03-10 00:57] wakes up [1518-09-03 23:51] Guard #431 begins shift [1518-07-13 00:47] falls asleep [1518-10-25 00:14] falls asleep [1518-07-12 00:08] falls asleep [1518-08-28 00:02] Guard #3119 begins shift [1518-09-22 00:27] falls asleep [1518-04-13 00:49] wakes up [1518-06-26 00:35] falls asleep [1518-05-27 00:55] falls asleep [1518-03-07 00:54] wakes up [1518-11-15 00:52] falls asleep [1518-03-12 00:56] wakes up [1518-11-09 00:28] falls asleep [1518-06-04 00:37] falls asleep [1518-08-02 00:01] falls asleep [1518-07-31 00:45] falls asleep [1518-08-27 00:54] falls asleep [1518-05-16 00:30] wakes up [1518-08-14 00:43] wakes up [1518-05-30 00:51] falls asleep [1518-08-31 00:03] falls asleep [1518-06-09 23:53] Guard #293 begins shift [1518-06-19 00:47] wakes up [1518-11-15 23:57] Guard #223 begins shift [1518-06-20 00:58] wakes up [1518-10-11 23:56] Guard #503 begins shift [1518-05-26 00:50] wakes up [1518-05-26 23:57] Guard #887 begins shift [1518-06-06 00:43] falls asleep [1518-06-03 00:31] falls asleep [1518-09-04 00:21] wakes up [1518-03-25 00:58] wakes up [1518-06-21 00:19] falls asleep [1518-02-14 00:42] falls asleep [1518-11-13 00:04] Guard #3407 begins shift [1518-03-24 00:35] falls asleep [1518-06-14 00:52] wakes up [1518-08-16 00:58] wakes up [1518-07-30 23:59] Guard #431 begins shift [1518-03-30 00:00] Guard #223 begins shift [1518-06-23 00:57] wakes up [1518-11-03 23:53] Guard #3137 begins shift [1518-03-15 00:55] falls asleep [1518-03-09 00:33] wakes up [1518-11-07 00:00] Guard #3011 begins shift [1518-03-06 00:26] falls asleep [1518-10-19 00:10] falls asleep [1518-11-08 00:04] Guard #1567 begins shift [1518-09-06 00:13] falls asleep [1518-05-07 00:00] Guard #541 begins shift [1518-05-13 00:56] wakes up [1518-08-30 00:46] falls asleep [1518-07-28 23:58] Guard #1747 begins shift [1518-06-28 00:02] Guard #541 begins shift [1518-11-10 00:31] falls asleep [1518-06-06 00:47] wakes up [1518-08-02 00:44] wakes up [1518-03-23 00:07] falls asleep [1518-06-08 00:27] wakes up [1518-10-22 00:59] wakes up [1518-08-24 00:20] falls asleep [1518-09-22 00:59] wakes up [1518-05-01 00:29] wakes up [1518-10-12 00:39] wakes up [1518-03-02 00:48] wakes up [1518-02-14 00:31] wakes up [1518-07-08 00:42] falls asleep [1518-04-25 00:22] wakes up [1518-08-08 00:53] wakes up [1518-06-30 00:43] wakes up [1518-08-07 23:46] Guard #3203 begins shift [1518-10-31 00:36] wakes up [1518-08-09 00:41] wakes up [1518-06-20 00:55] falls asleep [1518-09-03 00:52] wakes up [1518-05-28 00:38] wakes up [1518-08-23 00:00] Guard #1031 begins shift [1518-05-27 00:56] wakes up [1518-06-12 00:05] falls asleep [1518-06-17 23:58] Guard #887 begins shift [1518-07-04 23:57] Guard #1031 begins shift [1518-02-21 00:25] falls asleep [1518-08-29 00:54] falls asleep [1518-08-19 00:54] wakes up [1518-09-15 00:04] Guard #1049 begins shift [1518-03-22 00:21] wakes up [1518-09-18 00:51] wakes up [1518-03-23 23:58] Guard #431 begins shift [1518-10-10 00:25] falls asleep [1518-02-12 00:44] wakes up [1518-02-15 00:12] falls asleep [1518-11-03 00:53] wakes up [1518-09-06 00:16] wakes up [1518-11-11 00:57] wakes up [1518-02-10 00:11] falls asleep [1518-06-02 00:40] wakes up [1518-08-28 00:17] falls asleep [1518-07-14 00:36] wakes up [1518-06-01 00:02] Guard #3203 begins shift [1518-05-05 00:03] Guard #1567 begins shift [1518-05-28 00:54] wakes up [1518-10-15 00:48] wakes up [1518-07-05 00:27] falls asleep [1518-06-04 00:00] Guard #541 begins shift [1518-07-14 00:06] falls asleep [1518-09-11 00:53] wakes up [1518-11-04 23:56] Guard #503 begins shift [1518-03-13 00:46] falls asleep [1518-07-08 00:37] wakes up [1518-07-24 00:28] falls asleep [1518-04-25 00:09] falls asleep [1518-04-26 00:20] falls asleep [1518-08-05 00:37] wakes up [1518-09-19 00:00] Guard #2803 begins shift [1518-03-27 00:23] wakes up [1518-04-08 00:03] Guard #503 begins shift [1518-02-12 00:03] Guard #431 begins shift [1518-07-06 00:24] falls asleep [1518-04-06 00:30] falls asleep [1518-02-15 00:57] wakes up [1518-10-20 00:35] falls asleep [1518-02-16 23:56] Guard #3137 begins shift [1518-03-22 00:47] falls asleep [1518-06-24 00:44] wakes up [1518-08-13 23:48] Guard #3407 begins shift [1518-05-17 00:25] falls asleep [1518-08-20 00:01] Guard #613 begins shift [1518-11-02 00:37] falls asleep [1518-02-20 00:23] falls asleep [1518-06-15 00:37] falls asleep [1518-08-19 00:24] falls asleep [1518-05-10 00:32] wakes up [1518-10-24 00:46] falls asleep [1518-06-20 23:59] Guard #613 begins shift [1518-03-26 00:03] Guard #1049 begins shift [1518-08-15 00:44] falls asleep [1518-05-01 00:18] falls asleep [1518-11-13 23:56] Guard #3407 begins shift [1518-05-18 00:18] falls asleep [1518-04-03 00:03] Guard #3407 begins shift [1518-04-19 00:56] wakes up [1518-05-15 00:55] falls asleep [1518-11-10 00:40] wakes up [1518-08-29 00:22] falls asleep [1518-07-17 23:54] Guard #1049 begins shift [1518-03-05 23:56] Guard #1049 begins shift [1518-05-12 00:28] falls asleep [1518-08-26 23:53] Guard #1487 begins shift [1518-08-30 00:37] wakes up [1518-02-13 23:47] Guard #3011 begins shift [1518-05-02 00:34] wakes up [1518-09-08 00:02] falls asleep [1518-10-05 00:50] wakes up [1518-05-06 00:58] wakes up [1518-04-28 00:50] falls asleep [1518-07-16 00:51] falls asleep [1518-07-18 00:41] wakes up [1518-09-12 00:04] Guard #613 begins shift [1518-05-30 00:43] wakes up [1518-05-04 00:26] falls asleep [1518-06-05 00:56] wakes up [1518-08-02 00:57] wakes up [1518-11-20 00:38] falls asleep [1518-05-30 00:17] falls asleep [1518-09-03 00:23] falls asleep [1518-03-23 00:04] Guard #613 begins shift [1518-09-29 00:59] wakes up [1518-06-05 00:54] falls asleep [1518-10-23 00:55] falls asleep [1518-09-20 00:51] wakes up [1518-08-11 00:28] falls asleep [1518-06-14 00:25] falls asleep [1518-10-19 00:40] wakes up [1518-08-21 00:48] wakes up [1518-05-31 00:52] falls asleep [1518-07-23 23:58] Guard #2003 begins shift [1518-08-20 23:56] Guard #1049 begins shift [1518-09-23 23:46] Guard #293 begins shift [1518-05-23 00:37] wakes up [1518-04-09 00:58] wakes up [1518-05-04 00:57] wakes up [1518-03-15 00:34] wakes up [1518-08-20 00:38] wakes up [1518-06-12 00:41] wakes up [1518-08-07 00:11] falls asleep [1518-10-26 00:50] wakes up [1518-03-20 00:54] wakes up [1518-04-11 00:13] wakes up [1518-07-14 00:03] Guard #3011 begins shift [1518-03-24 00:48] wakes up [1518-04-13 00:44] falls asleep [1518-03-07 00:17] falls asleep [1518-08-01 00:35] falls asleep [1518-08-24 00:42] wakes up [1518-02-16 00:33] wakes up [1518-10-16 00:54] wakes up [1518-09-30 00:20] falls asleep [1518-02-23 00:01] falls asleep [1518-09-21 00:59] wakes up [1518-04-20 00:44] wakes up [1518-06-30 23:50] Guard #3119 begins shift [1518-04-15 00:41] wakes up [1518-11-18 00:39] wakes up [1518-05-17 00:06] falls asleep [1518-05-20 00:31] wakes up [1518-05-16 00:52] wakes up [1518-02-27 23:56] Guard #223 begins shift [1518-11-19 00:40] falls asleep [1518-11-21 00:05] falls asleep [1518-06-24 00:59] wakes up [1518-05-23 00:54] falls asleep [1518-07-10 00:52] falls asleep [1518-03-02 00:00] Guard #613 begins shift [1518-06-13 00:00] Guard #503 begins shift [1518-05-27 00:39] wakes up [1518-05-03 00:47] wakes up [1518-05-07 23:58] Guard #887 begins shift [1518-04-12 00:04] falls asleep [1518-08-29 00:45] wakes up [1518-05-08 00:29] falls asleep [1518-06-17 00:38] wakes up [1518-10-01 00:47] wakes up [1518-04-07 00:24] wakes up [1518-06-24 00:57] falls asleep [1518-08-15 00:45] wakes up [1518-08-08 00:51] falls asleep [1518-06-17 00:00] Guard #223 begins shift [1518-06-12 00:58] wakes up [1518-04-30 00:56] wakes up [1518-03-03 23:48] Guard #887 begins shift [1518-06-08 23:58] Guard #3203 begins shift [1518-05-01 23:46] Guard #613 begins shift [1518-07-26 23:57] Guard #2003 begins shift [1518-10-30 23:58] Guard #3011 begins shift [1518-02-23 00:56] wakes up [1518-03-13 23:58] Guard #223 begins shift [1518-05-11 00:38] wakes up [1518-08-30 00:01] Guard #613 begins shift [1518-05-03 00:08] falls asleep [1518-06-13 00:07] falls asleep [1518-06-10 00:55] wakes up [1518-10-29 00:17] falls asleep [1518-08-11 23:57] Guard #1061 begins shift [1518-10-21 00:49] wakes up [1518-03-28 00:00] Guard #3203 begins shift [1518-09-19 00:56] falls asleep [1518-05-05 00:23] falls asleep [1518-04-20 00:00] Guard #1487 begins shift [1518-04-19 00:40] falls asleep [1518-07-03 00:45] wakes up [1518-07-28 00:59] wakes up [1518-09-07 00:37] wakes up [1518-02-16 00:38] falls asleep [1518-05-24 00:48] wakes up [1518-08-26 00:50] wakes up [1518-07-29 00:53] wakes up [1518-05-17 00:52] wakes up [1518-10-31 00:53] wakes up [1518-06-26 00:23] wakes up [1518-08-15 00:17] falls asleep [1518-06-28 00:51] wakes up [1518-07-30 00:17] falls asleep [1518-03-28 00:11] falls asleep [1518-10-26 00:55] falls asleep [1518-04-09 23:52] Guard #2803 begins shift [1518-08-28 00:26] wakes up [1518-09-08 23:56] Guard #3011 begins shift [1518-03-03 00:00] Guard #2803 begins shift [1518-08-17 00:28] wakes up [1518-09-09 00:07] falls asleep [1518-07-21 00:09] falls asleep [1518-03-31 00:03] Guard #223 begins shift [1518-11-11 23:56] Guard #3119 begins shift [1518-10-20 00:48] wakes up [1518-10-12 23:57] Guard #1747 begins shift [1518-02-27 00:56] wakes up [1518-10-17 00:58] wakes up [1518-10-10 00:33] wakes up [1518-02-21 00:32] wakes up [1518-06-16 00:00] falls asleep [1518-05-23 23:59] Guard #3407 begins shift [1518-06-14 23:57] Guard #3011 begins shift [1518-05-05 23:51] Guard #1031 begins shift [1518-09-02 00:50] wakes up [1518-03-05 00:39] wakes up [1518-05-09 00:49] wakes up [1518-08-08 00:12] wakes up [1518-03-07 00:50] falls asleep [1518-07-11 23:47] Guard #3407 begins shift [1518-05-10 00:55] wakes up [1518-03-29 00:21] wakes up [1518-05-18 00:52] wakes up [1518-09-11 00:47] wakes up [1518-05-28 00:36] falls asleep [1518-05-23 00:57] wakes up [1518-05-14 00:49] falls asleep [1518-10-15 23:59] Guard #887 begins shift [1518-06-09 00:46] falls asleep [1518-09-26 23:51] Guard #3407 begins shift [1518-10-12 00:27] falls asleep [1518-09-21 00:00] Guard #503 begins shift [1518-11-03 00:26] falls asleep [1518-09-02 00:36] falls asleep [1518-04-01 00:52] wakes up [1518-04-24 00:56] wakes up [1518-04-24 00:03] Guard #1567 begins shift [1518-10-08 23:59] Guard #3407 begins shift [1518-06-15 00:55] falls asleep [1518-09-12 00:58] wakes up [1518-02-27 00:04] Guard #1049 begins shift [1518-08-26 00:00] Guard #613 begins shift [1518-03-15 00:02] Guard #2803 begins shift [1518-03-09 00:26] falls asleep [1518-05-28 00:23] falls asleep [1518-11-21 00:35] falls asleep [1518-03-06 00:52] wakes up [1518-02-20 00:48] wakes up [1518-06-28 23:58] Guard #1487 begins shift [1518-04-16 00:00] Guard #541 begins shift [1518-03-05 00:01] Guard #887 begins shift [1518-10-11 00:49] wakes up [1518-05-16 00:34] falls asleep [1518-08-28 00:41] wakes up [1518-02-26 00:17] falls asleep [1518-03-04 00:56] falls asleep [1518-07-04 00:59] wakes up [1518-03-06 23:59] Guard #541 begins shift [1518-04-02 00:00] Guard #3137 begins shift [1518-10-18 00:45] wakes up [1518-04-23 00:11] wakes up [1518-10-21 00:00] Guard #223 begins shift [1518-11-04 00:45] wakes up [1518-03-17 00:00] Guard #541 begins shift [1518-05-17 23:56] Guard #1487 begins shift [1518-05-18 00:21] wakes up [1518-07-28 00:52] falls asleep [1518-04-23 00:34] falls asleep [1518-10-22 00:02] Guard #1031 begins shift [1518-11-22 23:58] Guard #223 begins shift [1518-11-19 23:57] Guard #1747 begins shift [1518-08-24 00:39] falls asleep [1518-05-06 00:03] falls asleep [1518-09-10 00:36] falls asleep [1518-10-19 23:58] Guard #2341 begins shift [1518-04-01 00:06] falls asleep [1518-05-12 00:49] wakes up [1518-03-18 00:02] Guard #3119 begins shift [1518-09-16 00:02] Guard #2803 begins shift [1518-03-08 00:49] falls asleep [1518-07-11 00:58] wakes up [1518-07-10 00:58] wakes up [1518-09-29 00:22] falls asleep [1518-04-02 00:42] wakes up [1518-05-20 23:58] Guard #293 begins shift [1518-07-09 00:24] falls asleep [1518-03-11 23:58] Guard #431 begins shift [1518-10-03 00:02] Guard #3137 begins shift [1518-06-05 00:02] Guard #2803 begins shift [1518-07-03 00:25] falls asleep [1518-10-09 00:51] wakes up [1518-10-22 23:59] Guard #2341 begins shift [1518-09-01 00:07] falls asleep [1518-06-06 00:29] wakes up [1518-11-18 00:42] falls asleep [1518-05-24 00:52] falls asleep [1518-09-23 00:00] Guard #1031 begins shift [1518-09-22 00:54] falls asleep [1518-08-05 00:01] falls asleep [1518-03-11 00:21] falls asleep [1518-10-19 00:30] falls asleep [1518-05-17 00:02] Guard #3011 begins shift [1518-04-29 00:53] wakes up [1518-09-07 00:26] falls asleep [1518-07-16 00:55] wakes up [1518-04-07 00:02] Guard #1747 begins shift [1518-03-12 00:21] falls asleep [1518-08-17 00:01] Guard #293 begins shift [1518-09-29 00:02] Guard #613 begins shift [1518-11-19 00:24] wakes up [1518-04-04 00:05] falls asleep [1518-02-28 00:21] falls asleep [1518-11-21 00:37] wakes up [1518-04-10 00:33] wakes up [1518-07-28 00:03] falls asleep [1518-05-22 00:22] falls asleep [1518-03-07 00:36] falls asleep [1518-03-16 00:20] falls asleep [1518-06-16 00:54] wakes up [1518-03-13 00:58] wakes up [1518-10-27 00:15] wakes up [1518-08-03 00:01] falls asleep [1518-08-18 00:03] Guard #1487 begins shift [1518-09-23 00:52] wakes up [1518-05-02 00:42] falls asleep [1518-04-07 00:53] falls asleep [1518-10-26 00:30] falls asleep [1518-07-02 00:39] wakes up [1518-02-13 00:11] falls asleep [1518-10-28 23:59] Guard #2003 begins shift [1518-11-21 00:59] wakes up [1518-05-23 00:40] falls asleep [1518-07-25 00:38] wakes up [1518-04-19 00:34] falls asleep [1518-03-21 00:50] wakes up [1518-10-28 00:01] Guard #223 begins shift [1518-09-04 00:38] wakes up [1518-03-09 00:00] Guard #2803 begins shift [1518-07-07 00:04] Guard #223 begins shift [1518-11-03 00:00] Guard #3119 begins shift [1518-09-03 00:00] falls asleep [1518-07-22 23:59] Guard #3137 begins shift [1518-08-23 00:13] falls asleep [1518-10-02 00:14] falls asleep [1518-05-31 00:08] falls asleep [1518-08-16 00:34] falls asleep [1518-10-30 00:58] wakes up [1518-07-17 00:10] falls asleep [1518-10-04 23:51] Guard #613 begins shift [1518-05-06 00:30] wakes up [1518-05-05 00:39] wakes up [1518-06-29 00:21] falls asleep [1518-09-10 00:02] falls asleep [1518-08-18 00:22] falls asleep [1518-04-11 00:58] wakes up [1518-06-29 00:54] wakes up [1518-11-12 00:43] wakes up [1518-08-19 00:52] falls asleep [1518-09-05 00:50] wakes up [1518-11-02 00:49] wakes up [1518-08-11 00:04] Guard #3137 begins shift [1518-08-03 00:59] wakes up [1518-06-17 00:34] falls asleep [1518-05-01 00:00] Guard #2003 begins shift [1518-07-29 00:28] falls asleep [1518-04-23 00:01] falls asleep [1518-08-05 00:54] wakes up [1518-07-21 00:00] Guard #503 begins shift [1518-10-25 00:03] Guard #541 begins shift [1518-11-01 00:01] Guard #1031 begins shift [1518-03-22 00:44] wakes up [1518-09-06 00:34] falls asleep [1518-07-27 00:18] falls asleep [1518-10-31 00:12] wakes up [1518-04-27 00:53] wakes up [1518-03-25 00:03] Guard #887 begins shift [1518-09-21 00:56] falls asleep [1518-06-07 00:55] wakes up [1518-06-14 00:00] Guard #223 begins shift [1518-03-03 00:31] wakes up [1518-11-01 23:48] Guard #613 begins shift [1518-04-03 00:09] falls asleep [1518-06-15 00:52] wakes up [1518-08-25 00:00] Guard #503 begins shift [1518-08-21 00:17] falls asleep [1518-04-10 00:05] falls asleep [1518-04-30 00:51] falls asleep [1518-03-17 00:38] falls asleep [1518-07-14 23:58] Guard #1487 begins shift [1518-10-06 23:50] Guard #503 begins shift [1518-08-13 00:18] falls asleep [1518-09-07 00:04] Guard #1487 begins shift [1518-02-13 00:32] wakes up [1518-03-30 00:44] wakes up [1518-06-15 00:59] wakes up [1518-08-05 00:53] falls asleep [1518-10-23 00:59] wakes up [1518-06-26 00:43] falls asleep [1518-08-07 00:28] wakes up [1518-04-29 00:50] falls asleep [1518-05-04 00:04] Guard #1747 begins shift [1518-07-07 00:48] falls asleep [1518-02-19 00:02] falls asleep [1518-06-05 00:24] falls asleep [1518-04-07 00:39] falls asleep [1518-03-18 00:25] falls asleep [1518-10-08 00:00] Guard #293 begins shift [1518-04-28 00:57] wakes up [1518-05-10 00:16] falls asleep [1518-10-02 00:51] wakes up [1518-09-19 00:36] wakes up [1518-10-27 00:39] wakes up [1518-11-22 00:00] Guard #3137 begins shift [1518-02-15 00:21] wakes up [1518-03-17 00:56] wakes up [1518-11-19 00:04] falls asleep [1518-09-30 00:49] wakes up [1518-03-04 00:46] wakes up [1518-03-08 00:54] wakes up [1518-08-20 00:44] falls asleep [1518-02-25 00:14] falls asleep [1518-09-25 23:48] Guard #1487 begins shift [1518-08-01 00:47] wakes up [1518-04-07 00:54] wakes up [1518-04-04 00:40] wakes up [1518-09-17 00:54] falls asleep [1518-06-07 00:20] falls asleep [1518-10-14 00:24] falls asleep [1518-02-17 00:15] falls asleep [1518-02-10 00:19] wakes up [1518-05-13 23:58] Guard #1567 begins shift [1518-05-08 00:52] wakes up [1518-11-21 00:29] wakes up [1518-04-10 00:44] falls asleep [1518-04-27 00:18] falls asleep [1518-05-01 00:54] wakes up [1518-04-23 00:59] wakes up [1518-08-25 00:33] falls asleep [1518-02-24 00:29] wakes up [1518-11-22 00:56] wakes up [1518-09-18 00:01] Guard #3203 begins shift [1518-03-21 00:02] Guard #431 begins shift [1518-10-18 00:53] wakes up [1518-02-28 00:59] wakes up [1518-03-31 00:55] wakes up [1518-09-10 00:29] wakes up [1518-03-08 00:44] wakes up [1518-07-26 00:01] Guard #3407 begins shift [1518-06-14 00:18] wakes up [1518-05-02 00:59] wakes up [1518-03-18 23:58] Guard #3011 begins shift [1518-03-21 00:56] falls asleep [1518-04-26 00:55] falls asleep [1518-09-15 00:13] falls asleep [1518-05-25 00:00] Guard #887 begins shift [1518-09-01 00:04] Guard #223 begins shift [1518-02-14 23:56] Guard #223 begins shift [1518-10-17 00:03] falls asleep [1518-08-17 00:17] falls asleep [1518-09-27 00:04] falls asleep [1518-10-22 00:48] falls asleep [1518-02-14 00:57] wakes up [1518-04-08 00:52] wakes up """.trimIndent()
0
Kotlin
0
1
f5efe2f0b6b09b0e41045dc7fda3a7565cb21db3
44,066
advent-of-code
MIT License
src/Day11.kt
undermark5
574,819,802
false
{"Kotlin": 67472}
import java.math.BigInteger data class Monkey( val id: String, private var _items: MutableList<Long>, val operation: (Long, Long) -> Long, val testValue: Int, val successPartner: Int, val failPartner: Int, ) { var inspectionCount = 0L private set val items: List<Long> get() = _items fun takeTurn(): List<Pair<Int, Long>> { inspectionCount += _items.size return _items.map{ operation(it, Long.MAX_VALUE) }.map { it / 3.toLong() }.map { if (it % testValue.toLong() == 0L ) { successPartner to it } else { failPartner to it } }.also { _items.clear() } } fun takeTurnPart2(modulus: Int): List<Pair<Int, Long>> { inspectionCount += _items.size return _items.map{ operation(it, modulus.toLong()) }.map { if (it % testValue == 0L ) { successPartner to it } else { failPartner to it } }.also { _items.clear() } } fun catchItem(worryLevel: Long) { _items.add(worryLevel) } } val monkeyInstructionsRegex = Regex("Monkey (?<id>\\d+):\\n*\\s*Starting items: (?<starting>(?:\\d+(?:, )?)*)\\n*\\s*Operation: new = (?<left>[old\\d]+) (?<op>[*+]) (?<right>[old\\d]+)\\n\\s*Test: divisible by (?<divisor>\\d+)\\n\\s*If true: throw to monkey (?<success>\\d+)\\n\\s*If false: throw to monkey (?<failure>\\d+)") fun main() { fun part1(input: List<String>): Long { val monkeys = input.joinToString("\n").split("\n\n").map { monkeyInstructionsRegex.matchEntire(it)?.groups as MatchNamedGroupCollection }.map { val id = it["id"] val starting = it["starting"] val op = it["op"] val left = it["left"] val right = it["right"] val divisor = it["divisor"] val success = it["success"] val failure = it["failure"] val operator: (Long, Long, Long) -> Long = if (op?.value == "*") { { left, right, _ -> left * right } } else { { left, right, _ -> left + right } } val operation: (Long, Long) -> Long = { input, divisor -> val leftValue = if (left?.value == "old") { input } else { left?.value?.toLong() ?: 0L } val rightValue = if (right?.value == "old") { input } else { right?.value?.toLong() ?: 0L } operator(leftValue, rightValue, divisor) } Monkey( id?.value ?: "", starting?.value?.split(", ")?.mapNotNull { it.toLongOrNull() }?.toMutableList() ?: mutableListOf(), operation, divisor?.value?.toInt() ?: 0, success?.value?.toInt() ?: 0, failure?.value?.toInt() ?: 0 ) } for (i in 0 until 20) { for (monkey in monkeys) { val itemsThrown = monkey.takeTurn() itemsThrown.forEach { monkeys[it.first].catchItem(it.second) } } } return monkeys.sortedByDescending { it.inspectionCount }.map{it.inspectionCount }.take(2).reduce(Long::times) } fun part2(input: List<String>): Long { val monkeys = input.joinToString("\n").split("\n\n").map { monkeyInstructionsRegex.matchEntire(it)?.groups as MatchNamedGroupCollection }.map { val id = it["id"] val starting = it["starting"] val op = it["op"] val left = it["left"] val right = it["right"] val divisor = it["divisor"] val success = it["success"] val failure = it["failure"] val operator: (Long, Long, Long) -> Long = if (op?.value == "*") { { left, right, divisor -> ((left % divisor) * (right % divisor)) % divisor } } else { { left, right, divisor -> ((left % divisor) + (right % divisor)) % divisor } } val operation: (Long, Long) -> Long = { input, divisor -> val leftValue = if (left?.value == "old") { input } else { left?.value?.toLong() ?: 0L } val rightValue = if (right?.value == "old") { input } else { right?.value?.toLong() ?: 0L } operator(leftValue, rightValue, divisor) } Monkey( id?.value ?: "", starting?.value?.split(", ")?.mapNotNull { it.toLongOrNull() }?.toMutableList() ?: mutableListOf(), operation = operation, divisor?.value?.toInt() ?: 0, success?.value?.toInt() ?: 0, failure?.value?.toInt() ?: 0 ) } val lcm = monkeys.map { it.testValue }.reduce(Int::times) for (i in 0 until 10000) { for (monkey in monkeys) { val itemsThrown = monkey.takeTurnPart2(lcm) itemsThrown.forEach { monkeys[it.first].catchItem(it.second) } } print("") } return monkeys.sortedByDescending { it.inspectionCount }.map{it.inspectionCount }.take(2).reduce(Long::times) } // test if implementation meets criteria from the description, like: val testInput = readInput("Day11_test") println(part1(testInput)) check(part1(testInput) == 10605L) check(part2(testInput) == 2713310158L) val input = readInput("Day11") println(part1(input)) // println(part2(testInput)) println(part2(input)) }
0
Kotlin
0
0
e9cf715b922db05e1929f781dc29cf0c7fb62170
6,090
AoC_2022_Kotlin
Apache License 2.0
src/Day02.kt
thorny-thorny
573,065,588
false
{"Kotlin": 57129}
fun main() { fun decodeLine(line: String) = (line.first() - 'A' + 1) to (line.last() - 'X' + 1) fun roundScore(opponent: Int, me: Int) = me + ((4 + me - opponent) % 3) * 3 fun part1(input: List<String>): Int { return input.sumOf { val (opponent, me) = decodeLine(it) roundScore(opponent, me) } } fun part2(input: List<String>): Int { return input.sumOf { val (opponent, strategy) = decodeLine(it) val me = when (strategy) { 1 -> (opponent + 1) % 3 + 1 2 -> opponent 3 -> opponent % 3 + 1 else -> throw Exception("Unknown strategy") } roundScore(opponent, me) } } val testInput = readInput("Day02_test") check(part1(testInput) == 15) check(part2(testInput) == 12) val input = readInput("Day02") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
843869d19d5457dc972c98a9a4d48b690fa094a6
962
aoc-2022
Apache License 2.0
src/main/java/strassenbahn/ThriftTicket.kt
ununhexium
125,272,921
false
null
package strassenbahn import java.util.LinkedList import kotlin.math.max interface Ticket { fun getPrice(area: Int): Float val description: String val adultCapacity: Int val childrenCapacity: Int val allowedTrips: Int } data class Wanted( val area: Int, val adults: Int = 0, val children: Int = 0, val tripsPerPeople: Int = 1 ) { fun noPassenger() = (adults + children) <= 0 } class TicketImpl( override val description: String, val prices: Map<Int, Number>, override val adultCapacity: Int = 0, override val childrenCapacity: Int = 0, override val allowedTrips: Int = 1 ) : Ticket { override fun getPrice(area: Int): Float { return prices[area]?.toFloat() ?: throw IllegalArgumentException("No price for area $area") } override fun toString() = description } data class Proposition(val tickets: Map<Ticket, Int>) { // constructor(pairs: List<Pair<Ticket, Int>>): this(pairs.toMap()) // constructor(pair: Pair<Ticket, Int>): this(listOf(pair).toMap()) companion object { val EMPTY = Proposition(mapOf()) } fun getPrice(area: Int, trips: Int = 1) = tickets.map { // are many tickets are needed to make the desired number of trips val ticketsCount = Math.ceil(trips / it.key.allowedTrips.toDouble()).toInt() it.key.getPrice(area) * it.value * ticketsCount }.sum() val flatTickets: List<Ticket> by lazy { tickets.flatMap { entry -> List(entry.value) { entry.key } } } val adultSeats = flatTickets.sumBy { it.adultCapacity } val childrenSeats = flatTickets.sumBy { it.childrenCapacity } operator fun plus(ticket: Ticket): Proposition { val new = this.tickets.toMutableMap() new[ticket] = (this.tickets[ticket] ?: 0) + 1 return Proposition(new) } fun canAccommodate(wanted: Wanted) = listOf( // strict adult and child separation { this.adultSeats >= wanted.adults && this.childrenSeats >= wanted.children }, // children use adult ticket { val freeAdultSeats = this.adultSeats - wanted.adults val freeChildrenSeats = (this.childrenSeats + freeAdultSeats) - wanted.children if (freeAdultSeats < 0) { // not enough seats for adults false } else { freeChildrenSeats >= 0 } } ).any { it() } } /** * Find the cheapest price given a request and an offer */ fun cheapestPrice(wanted: Wanted, offer: List<Ticket>): Proposition { if (wanted.noPassenger()) { throw IllegalArgumentException("Need at least 1 traveler") } return browseAllPropositions( wanted, offer.sortedByDescending { it.adultCapacity } ) } fun browseAllPropositions( wanted: Wanted, offer: List<Ticket> ): Proposition { var bestSoFar = Proposition.EMPTY var bestPriceSoFar = Float.MAX_VALUE /** * The Int, an index, is there to know which element in the offer list * was used to create the proposition and avoid repeating propositions */ val queue = LinkedList<Pair<Int, Proposition>>(listOf(0 to bestSoFar)) /** * we may have to look for solutions which don't use all the seats * but we must not look for too long in that direction as this is: * 1. leading to OutOfMemory because a solution which can accomodate only chlidren isn't suited for adults * TODO: tune ratios */ val maxChildrenToAdultRatio = offer.maxCAratio() val maxAdultToChildrenRatio = offer.maxACratio() val extraAdultsCapacity = offer.maxBy { it.adultCapacity }!!.adultCapacity + wanted.adults * maxAdultToChildrenRatio val extraChildrenCapacity = offer.maxBy { it.childrenCapacity }!!.childrenCapacity + wanted.children * maxChildrenToAdultRatio while (queue.isNotEmpty()) { val (index, current) = queue.removeAt(0) val price = current.getPrice(wanted.area, wanted.tripsPerPeople) if (price < bestPriceSoFar) { if (current.canAccommodate(wanted)) { bestSoFar = current bestPriceSoFar = price } for (i in index until offer.size) { val new = current + offer[i] // Don't look too far val noExcessAdultsCapacity = new.adultSeats <= wanted.adults + extraAdultsCapacity val noExcessChildrenCapacity = new.childrenSeats <= wanted.children + extraChildrenCapacity // stop searching when it's more expansive than an existing solution val newPrice = new.getPrice(wanted.area, wanted.tripsPerPeople) if (noExcessAdultsCapacity && noExcessChildrenCapacity && newPrice < bestPriceSoFar) { queue.add(i to new) } } } } return bestSoFar } private fun <E : Ticket> List<E>.maxCAratio(): Double { val found = this.map { if (it.adultCapacity > 0) it.childrenCapacity / it.adultCapacity else 0 }.max() ?: 1 // don't return 0 return max(1.0, found.toDouble()) } private fun <E : Ticket> List<E>.maxACratio(): Double { val found = this.map { if (it.childrenCapacity > 0) it.adultCapacity / it.childrenCapacity else 0 }.max() ?: 1 // don't return 0 return max(1.0, found.toDouble()) }
0
Kotlin
0
0
11aca6b37e06fe1e8ad31467703dacf857332825
5,626
samples
The Unlicense
src/Day02.kt
andrewgadion
572,927,267
false
{"Kotlin": 16973}
enum class Shape(val Score: Int) { Rock(1), Paper(2), Scissors(3); fun Play(other: Shape): Int { if (other == this) return 3 + Score return when(this) { Rock -> if (other == Scissors) 6 else 0 Paper -> if (other == Rock) 6 else 0 Scissors -> if (other == Paper) 6 else 0 } + Score } fun GetAltShape(str: String): Shape { return when(str.trim()) { "X" -> when(this) { Rock -> Scissors Paper -> Rock Scissors -> Paper } "Y" -> this "Z" -> when(this) { Rock -> Paper Paper -> Scissors Scissors -> Rock } else -> throw Exception("Unknown $str") } } companion object { fun Parse(str: String): Shape = when(str.trim()) { "A", "X" -> Rock "B", "Y" -> Paper "C", "Z" -> Scissors else -> throw Exception("Unknown $str") } } } fun main() { fun part1(input: List<String>): Long { return input.fold(0) { acc, cur -> val shapes = cur.split(" ").map(Shape::Parse) acc + shapes[1].Play(shapes[0]) } } fun part2(input: List<String>): Long { return input.fold(0) { acc, cur -> val (a, b) = cur.split(" ") val shape = Shape.Parse(a) acc + shape.GetAltShape(b).Play(shape) } } val input = readInput("day2") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
4d091e2da5d45a786aee4721624ddcae681664c9
1,617
advent-of-code-2022
Apache License 2.0
src/Day12.kt
adrianforsius
573,044,406
false
{"Kotlin": 68131}
import org.assertj.core.api.Assertions.assertThat fun level(c: Char): Int = when (c) { 'S' -> 0 'E' -> 'z' - 'a' + 1 else -> c - 'a' } fun findCoord(input: List<String>, char: Char): Point = input .withIndex() .map {(index, it) -> Point(index, it.indexOf(char)) }.find{ it.x != -1 } ?: Point(0, 0) fun findCoords(input: List<String>, char: Char): List<Point> = input .withIndex() .map {(index, it) -> Point(index, it.indexOf(char)) }.filter{ it.x != -1 } data class Point(var y: Int, var x: Int) fun main() { fun part1(input: List<String>): Int { val start = findCoord(input, 'S') val end = findCoord(input, 'E') val height = input.size val width = input.first().length fun pathFind(): Int { val q: ArrayDeque<Pair<Point, Int>> = ArrayDeque(0) q.add(Pair(start, 0)) var visited = mutableSetOf(start) while(q.isNotEmpty()) { val (p, distance) = q.removeFirst() if (p == end) { return distance } val up = Point(p.y-1, p.x) val down = Point(p.y+1, p.x) val left = Point(p.y, p.x-1) val right = Point(p.y, p.x+1) for (pp in listOf(down, up, left, right)) { if (pp.y >= 0 && pp.x >= 0 && pp.y < height && pp.x < width) { val currentStep = input[p.y][p.x] val nextStep = input[pp.y][pp.x] val standingLevel = level(currentStep) val nextLevelMax = level(nextStep) if (nextLevelMax <= standingLevel+1) { if (visited.add(pp)) { q.add(Pair(pp, distance+1)) } } } } } return 0 } return pathFind() } fun part2(input: List<String>): Int { val start = findCoord(input, 'E') val ends = findCoords(input, 'a') val height = input.size val width = input.first().length fun pathFind(): Int { val q: ArrayDeque<Pair<Point, Int>> = ArrayDeque(0) q.add(Pair(start, 0)) var visited = mutableSetOf(start) while(q.isNotEmpty()) { val (p, distance) = q.removeFirst() if (p in ends) { return distance } val up = Point(p.y-1, p.x) val down = Point(p.y+1, p.x) val left = Point(p.y, p.x-1) val right = Point(p.y, p.x+1) for (pp in listOf(down, up, left, right)) { if (pp.y >= 0 && pp.x >= 0 && pp.y < height && pp.x < width) { val currentStep = input[p.y][p.x] val nextStep = input[pp.y][pp.x] val standingLevel = level(currentStep) val nextLevelMax = level(nextStep) if (nextLevelMax >= standingLevel-1) { if (visited.add(pp)) { q.add(Pair(pp, distance+1)) } } } } } return 0 } return pathFind() } // test if implementation meets criteria from the description, like: // Test val testInput = readInput("Day12_test") val output1 = part1(testInput) assertThat(output1).isEqualTo(31) // Answer val input = readInput("Day12") val outputAnswer1 = part1(input) assertThat(outputAnswer1).isEqualTo(383) // Test val output2 = part2(testInput) assertThat(output2).isEqualTo(29) // Answer val outputAnswer2 = part2(input) assertThat(outputAnswer2).isEqualTo(377) }
0
Kotlin
0
0
f65a0e4371cf77c2558d37bf2ac42e44eeb4bdbb
4,026
kotlin-2022
Apache License 2.0
src/Day15.kt
abeltay
572,984,420
false
{"Kotlin": 91982, "Shell": 191}
import kotlin.math.abs fun main() { fun manhattanDistance(a: Pair<Int, Int>, b: Pair<Int, Int>): Int { return abs(a.first - b.first) + abs(a.second - b.second) } fun isTouching(a: Pair<Int, Int>, b: Pair<Int, Int>): Boolean { if (a.first > b.first) { return isTouching(b, a) } return a.second + 1 >= b.first } fun addLine(existing: MutableList<Pair<Int, Int>>, line: Pair<Int, Int>) { for (it in existing) { if (isTouching(it, line)) { existing.remove(it) val from = if (it.first < line.first) it.first else line.first val to = if (it.second > line.second) it.second else line.second addLine(existing, Pair(from, to)) return } } existing.add(line) } val inputLineRegex = """Sensor at x=(-?\d+), y=(-?\d+): closest beacon is at x=(-?\d+), y=(-?\d+)""".toRegex() fun part1(input: List<String>, row: Int): Int { val line = mutableListOf<Pair<Int, Int>>() val beacons = hashSetOf<Int>() for (it in input) { val (startX, startY, endX, endY) = inputLineRegex .matchEntire(it) ?.destructured ?: throw IllegalArgumentException("Incorrect input line $it") val sensor = Pair(startX.toInt(), startY.toInt()) val beacon = Pair(endX.toInt(), endY.toInt()) val dist = manhattanDistance(sensor, beacon) // Check intersect if (sensor.second + dist < row || sensor.second - dist > row) { continue } val firstDist = dist - abs(sensor.second - row) val from = sensor.first - firstDist val to = sensor.first + firstDist if (beacon.second == row) { beacons.add(beacon.first) } addLine(line, Pair(from, to)) } var answer = 0 for (it in line) { if (it.first < 0 && it.second >= 0) { answer++ } answer += it.second - it.first answer -= beacons.count { beacon -> (beacon >= it.first && beacon <= it.second) } } return answer } fun part2(input: List<String>, limit: Int): Long { for (row in 0 until limit) { val line = mutableListOf<Pair<Int, Int>>() for (it in input) { val (startX, startY, endX, endY) = inputLineRegex .matchEntire(it) ?.destructured ?: throw IllegalArgumentException("Incorrect input line $it") val sensor = Pair(startX.toInt(), startY.toInt()) val beacon = Pair(endX.toInt(), endY.toInt()) val dist = manhattanDistance(sensor, beacon) // Check intersect if (sensor.second + dist < row || sensor.second - dist > row) { continue } val firstDist = dist - abs(sensor.second - row) val from = sensor.first - firstDist val to = sensor.first + firstDist addLine(line, Pair(from, to)) } for (it in line) { val x = it.second + 1 if (x in 0 until limit) { return x.toLong() * 4000000 + row.toLong() } } } return 0 } val testInput = readInput("Day15_test") check(part1(testInput, 10) == 26) check(part2(testInput, 20) == 56000011.toLong()) val input = readInput("Day15") println(part1(input, 2000000)) println(part2(input, 4000000)) }
0
Kotlin
0
0
a51bda36eaef85a8faa305a0441efaa745f6f399
3,739
advent-of-code-2022
Apache License 2.0
src/main/kotlin/g2301_2400/s2338_count_the_number_of_ideal_arrays/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g2301_2400.s2338_count_the_number_of_ideal_arrays // #Hard #Dynamic_Programming #Math #Number_Theory #Combinatorics // #2023_07_01_Time_201_ms_(100.00%)_Space_37.8_MB_(100.00%) import kotlin.math.ln class Solution { fun idealArrays(n: Int, maxValue: Int): Int { val mod = (1e9 + 7).toInt() val maxDistinct = (ln(maxValue.toDouble()) / ln(2.0)).toInt() + 1 val dp = Array(maxDistinct + 1) { IntArray(maxValue + 1) } dp[1].fill(1) dp[1][0] = 0 for (i in 2..maxDistinct) { for (j in 1..maxValue) { var k = 2 while (j * k <= maxValue && dp[i - 1][j * k] != 0) { dp[i][j] += dp[i - 1][j * k] k++ } } } val sum = IntArray(maxDistinct + 1) for (i in 1..maxDistinct) { sum[i] = dp[i].sum() } val invs = LongArray(n.coerceAtMost(maxDistinct) + 1) invs[1] = 1 for (i in 2 until invs.size) { invs[i] = mod - mod / i * invs[mod % i] % mod } var result = maxValue.toLong() var comb = n.toLong() - 1 var i = 2 while (i <= maxDistinct && i <= n) { result += sum[i] * comb % mod comb *= (n - i).toLong() comb %= mod.toLong() comb *= invs[i] comb %= mod.toLong() i++ } return (result % mod).toInt() } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,473
LeetCode-in-Kotlin
MIT License
src/Day05.kt
ben-dent
572,931,260
false
{"Kotlin": 10265}
fun main() { fun part1(input: List<String>): String { val piles = getBoxes(input) var boxes = piles.first val i = piles.second val newData = input.subList(i + 2, input.size) for (line in newData) { val s1 = line.split("move ")[1] val s2 = s1.split(" from ") val number = s2[0].toInt() val s3 = s2[1].split(" to ") val from = s3[0].toInt() val to = s3[1].toInt() boxes = move1(from, to, number, boxes) } var toReturn = "" for (key in boxes.keys) { toReturn += boxes[key]!![0] } return toReturn } fun part2(input: List<String>): String { val piles = getBoxes(input) var boxes = piles.first val i = piles.second val newData = input.subList(i + 2, input.size) for (line in newData) { val s1 = line.split("move ")[1] val s2 = s1.split(" from ") val number = s2[0].toInt() val s3 = s2[1].split(" to ") val from = s3[0].toInt() val to = s3[1].toInt() boxes = move2(from, to, number, boxes) } var toReturn = "" for (key in boxes.keys) { toReturn += boxes[key]!![0] } return toReturn } // test if implementation meets criteria from the description, like: val testInput = readInput("Day05_test") check(part1(testInput) == "CMZ") check(part2(testInput) == "MCD") val input = readInput("Day05") println(part1(input)) println(part2(input)) } fun move2(from: Int, to: Int, number: Int, boxes: HashMap<Int, ArrayList<String>>): HashMap<Int, ArrayList<String>> { var firstData = boxes[from]!! val secondData = boxes[to]!! val newTo = ArrayList(firstData.subList(0, number)) newTo.addAll(secondData) firstData = ArrayList(firstData.drop(number)) boxes[from] = firstData boxes[to] = newTo return boxes } fun move1(from: Int, to: Int, number: Int, boxes: HashMap<Int, ArrayList<String>>): HashMap<Int, ArrayList<String>> { val firstData = boxes[from]!! val secondData = boxes[to]!! val newTo = ArrayList<String>() var newFrom = ArrayList<String>(firstData) val temp = ArrayList<String>() for (i in 1..number) { temp.add(newFrom[0]) newFrom = ArrayList(newFrom.drop(1)) } newTo.addAll(temp.reversed()) newTo.addAll(secondData) boxes[to] = newTo boxes[from] = newFrom return boxes } fun getBoxes(input: List<String>): Pair<HashMap<Int, ArrayList<String>>, Int> { val map = HashMap<Int, ArrayList<String>>() for (i in input.indices) { val line = input[i] if (line.isEmpty() || line.contains(" 1 ")) { return Pair(map, i) } var count = 1 val list = ArrayList<String>() var current = "" var j = 0 while (j < line.length) { val c = line[j] current += c if (count == 3) { list.add(current.trim()) current = "" count = 0 ++j } ++j ++count } for (k in 0 until list.size) { val item = list[k] if (item.isNotBlank()) { val toAdd = item.split("[")[1].split("]")[0] val prev = map.getOrDefault(k + 1, ArrayList()) prev.add(toAdd) map[k + 1] = prev } } } return Pair(map, -1) }
0
Kotlin
0
0
2c3589047945f578b57ceab9b975aef8ddde4878
3,624
AdventOfCode2022Kotlin
Apache License 2.0
src/main/kotlin/com/mobiento/aoc/Day02.kt
markburk
572,970,459
false
{"Kotlin": 22252}
package com.mobiento.aoc class Day02 { fun part1(input: List<String>): Int { return input.sumOf { line -> line.split(" ").takeIf { it.size >= 2 }?.let { parts -> scoreForRoundPart1(parts[0], parts[1]) } ?: 0 } } fun scoreForRoundPart1(a: String, b: String): Int { val opponentChoice = Choice.fromOpponentChoice(a) val playerChoice = Choice.fromPlayerChoice(b) val outcome = calculateOutcome(opponentChoice, playerChoice) return outcome.value + playerChoice.value } fun part2(input: List<String>): Int { return input.sumOf { line -> line.split(" ").takeIf { it.size >= 2 }?.let { parts -> scoreForRoundPart2(parts[0], parts[1]) } ?: 0 } } fun scoreForRoundPart2(a: String, b: String): Int { val opponentChoice = Choice.fromOpponentChoice(a) val expectedOutcome = Outcome.fromSource(b) val playerChoice = playerChoiceForOutcome(opponentChoice, expectedOutcome) return expectedOutcome.value + playerChoice.value } enum class Outcome(val source: String, val value: Int) { LOSE("X", 0), DRAW("Y", 3), WIN("Z", 6); companion object { fun fromSource(source: String): Outcome { return values().find { it.source == source } ?: throw Exception("No matching source: $source") } } } enum class Choice(val opponentChoice: String, val playerChoice: String, val value: Int) { ROCK("A", "X", 1), PAPER("B", "Y", 2), SCISSORS("C", "Z", 3); companion object { fun fromPlayerChoice(choice: String): Choice { return values().find { it.playerChoice == choice } ?: throw Exception("No matching choice for $choice") } fun fromOpponentChoice(choice: String): Choice { return values().find { it.opponentChoice == choice } ?: throw Exception("No matching choice for $choice") } } } private fun playerChoiceForOutcome(opponentChoice: Choice, expectedOutcome: Outcome): Choice { return when (opponentChoice) { Choice.ROCK -> when (expectedOutcome) { Outcome.LOSE -> Choice.SCISSORS Outcome.DRAW -> Choice.ROCK Outcome.WIN -> Choice.PAPER } Choice.PAPER -> when (expectedOutcome) { Outcome.LOSE -> Choice.ROCK Outcome.DRAW -> Choice.PAPER Outcome.WIN -> Choice.SCISSORS } Choice.SCISSORS -> when(expectedOutcome) { Outcome.LOSE -> Choice.PAPER Outcome.DRAW -> Choice.SCISSORS Outcome.WIN -> Choice.ROCK } } } private fun calculateOutcome(opponentChoice: Choice, playerChoice: Choice): Outcome { return when (opponentChoice) { Choice.ROCK -> when (playerChoice) { Choice.ROCK -> Outcome.DRAW Choice.PAPER -> Outcome.WIN Choice.SCISSORS -> Outcome.LOSE } Choice.PAPER -> when (playerChoice) { Choice.ROCK -> Outcome.LOSE Choice.PAPER -> Outcome.DRAW Choice.SCISSORS -> Outcome.WIN } Choice.SCISSORS -> when (playerChoice) { Choice.ROCK -> Outcome.WIN Choice.PAPER -> Outcome.LOSE Choice.SCISSORS -> Outcome.DRAW } } } }
0
Kotlin
0
0
d28656b4d54c506a01252caf6b493e4f7f97e896
3,607
potential-lamp
Apache License 2.0
src/main/kotlin/ru/timakden/aoc/util/Utils.kt
timakden
76,895,831
false
{"Kotlin": 321649}
package ru.timakden.aoc.util import java.math.BigInteger import java.security.MessageDigest import java.util.* import kotlin.io.path.Path import kotlin.io.path.readLines import kotlin.time.measureTime /** * Generates the MD5 hash of a string. * * @return the MD5 hash as a hexadecimal string */ fun String.md5() = BigInteger(1, MessageDigest.getInstance("MD5").digest(toByteArray())) .toString(16) .padStart(32, '0') /** * Determines whether a string is a number or not. * * @return `true` if the string is a number, `false` otherwise */ fun String.isNumber() = this.matches("\\d+(?:\\.\\d+)?".toRegex()) /** * Determines whether a string consists only of letters (a-z or A-Z). * * @return `true` if the string consists only of letters, `false` otherwise */ fun String.isLetter() = this.matches("[a-zA-Z]+".toRegex()) /** * Measures the elapsed time taken to execute the given block of code. * Prints the elapsed time in milliseconds. * * @param block the block of code to measure the elapsed time for */ fun measure(block: () -> Unit) = println("Elapsed time: ${measureTime(block)}") /** * Reads the contents of a text file. * * @param name the name of the file to read, excluding the file extension * @return a list of strings representing the lines of the file */ fun readInput(name: String) = Path("src/main/kotlin/ru/timakden/aoc/$name.txt").readLines() /** * Calculates the greatest common divisor (GCD) of two numbers. * * @param a The first number. * @param b The second number. * @return The GCD of the two numbers. */ tailrec fun gcd(a: Long, b: Long): Long = if (b == 0L) a else gcd(b, a % b) /** * Calculates the least common multiple (LCM) of two numbers. * * @param a The first number. * @param b The second number. * @return The LCM of the two numbers. */ fun lcm(a: Long, b: Long) = a / gcd(a, b) * b /** * Calculates the shortest distances from the starting points to all reachable nodes using the Dijkstra algorithm. * * @param startingPoints The list of starting points. * @param neighbors A function that returns the neighbors of a given node. * @param distanceBetween A function that calculates the distance between two nodes. * @return A map containing the shortest distances from the starting points to all reachable nodes. */ fun <T> dijkstra( startingPoints: List<T>, neighbors: T.() -> List<T>, distanceBetween: (currentNode: T, nextNode: T) -> UInt, ): Map<T, UInt> { data class State(val node: T, val distance: UInt) val bestDistance = hashMapOf<T, UInt>() val boundary = PriorityQueue<State>(compareBy { it.distance }) for (start in startingPoints) boundary += State(start, 0u) while (boundary.isNotEmpty()) { val (currentNode, currentDistance) = boundary.poll() if (currentNode in bestDistance) continue bestDistance[currentNode] = currentDistance for (nextNode in neighbors(currentNode)) if (nextNode !in bestDistance) boundary += State(nextNode, currentDistance + distanceBetween(currentNode, nextNode)) } return bestDistance }
0
Kotlin
0
3
acc4dceb69350c04f6ae42fc50315745f728cce1
3,124
advent-of-code
MIT License
jvm/src/main/kotlin/io/prfxn/aoc2021/day14.kt
prfxn
435,386,161
false
{"Kotlin": 72820, "Python": 362}
// Extended Polymerization (https://adventofcode.com/2021/day/14) package io.prfxn.aoc2021 fun main() { val lines = textResourceReader("input/14.txt").readLines() val template = lines.first() val rules = lines.drop(2).map { with (it.split(" -> ")) { first() to last() } } val spc = template.windowed(2).groupBy { it }.map { (k, v) -> k to v.size.toLong() }.toMap() // starting pair counts val sec = template.groupBy(Char::toString).map { (k, v) -> k to v.size.toLong() }.toMap() // starting element counts fun maxMinCountsDiffAfterSteps(steps: Int) = with ( generateSequence(spc to sec) { (pc, ec) -> rules.fold(pc to ec) { (npc, nec), (p, e) -> pc[p]?.takeIf { it > 0 } ?.let { n -> val (p1, p2) = (p[0] + e + p[1]).windowed(2) sequenceOf( p to -n, p1 to n, p2 to n ).fold(npc) { npc, (p, d) -> npc + mapOf(p to (npc[p] ?: 0) + d) } to nec + mapOf(e to (nec[e] ?: 0) + n) } ?: (npc to nec) } }.drop(1).take(steps).last().second.values ) { maxOf { it } - minOf { it } } val answer1 = maxMinCountsDiffAfterSteps(10) val answer2 = maxMinCountsDiffAfterSteps(40) sequenceOf(answer1, answer2).forEach(::println) } /** output 2703 2984946368465 */
0
Kotlin
0
0
148938cab8656d3fbfdfe6c68256fa5ba3b47b90
1,665
aoc2021
MIT License
src/Day04.kt
JaydenPease
574,590,496
false
{"Kotlin": 11645}
fun main() { // fun part1(input: List<String>): Int { // return input.size // } // // fun part2(input: List<String>): Int { // return input.size // } // test if implementation meets criteria from the description, like: val testInput = readInput("Day04_test") //println(Day04_part1(testInput)) //println(Day04_part2(testInput)) val input = readInput("Day04") //println(Day04_part1(input)) println(Day04_part2(input)) } fun Day04_part1(input: List<String>): Int { var count: Int = 0 for(i in input.indices) { val sections = input[i].split(",") val first = sections[0].split("-") val second = sections[1].split("-") if((first[0].toInt() - second[0].toInt() <= 0 && first[1].toInt() - second[1].toInt() >= 0) || (first[0].toInt() - second[0].toInt() >= 0 && first[1].toInt() - second[1].toInt() <= 0)) { count++ } } return count } fun Day04_part2(input: List<String>): Int { var count: Int = 0 for(i in input.indices) { val sections = input[i].split(",") val first = sections[0].split("-") val second = sections[1].split("-") if(second[0].toInt() - first[1].toInt() <= 0 && second[1].toInt() - first[0].toInt() >= 0) { count++ } } return count }
0
Kotlin
0
0
0a5fa22b3653c4b44a716927e2293fc4b2ed9eb7
1,353
AdventOfCode-2022
Apache License 2.0
2022/src/main/kotlin/com/github/akowal/aoc/Day03.kt
akowal
573,170,341
false
{"Kotlin": 36572}
package com.github.akowal.aoc class Day03 { private val rucksacks = inputFile("day03").readLines() fun solvePart1(): Int { return rucksacks.sumOf { rucksack -> val items1 = rucksack.take(rucksack.length / 2).toCharArray().toSet() val items2 = rucksack.drop(rucksack.length / 2).toCharArray().toSet() val common = items1.intersect(items2).single() val p = priority(common) p } } fun solvePart2(): Int { val groups = rucksacks.windowed(3, 3) return groups.sumOf { rucksack -> val badge = rucksack.map { it.toCharArray().toSet() } .reduce(Set<Char>::intersect) .single() priority(badge) } } private fun priority(c: Char) = when (c) { in 'a'..'z' -> 1 + c.code - 'a'.code in 'A'..'Z' -> 27 + c.code - 'A'.code else -> error("xoxoxo") } } fun main() { val solution = Day03() println(solution.solvePart1()) println(solution.solvePart2()) }
0
Kotlin
0
0
02e52625c1c8bd00f8251eb9427828fb5c439fb5
1,060
advent-of-kode
Creative Commons Zero v1.0 Universal
src/main/kotlin/com/onegravity/sudoku/model/Util.kt
1gravity
407,597,760
false
{"Kotlin": 148326}
package com.onegravity.sudoku.model import java.util.* /** * Map region codes to cell indices * * Region codes for rows would look like this: * 0 0 0 0 0 0 0 0 0 * 1 1 1 1 1 1 1 1 1 * 2 2 2 2 2 2 2 2 2 * etc. * * Region codes for columns would look like this: * 0 1 2 3 4 5 6 7 8 * 0 1 2 3 4 5 6 7 8 * 0 1 2 3 4 5 6 7 8 * etc. * * Region codes for (standard) blocks would look like this: * 0 0 0 1 1 1 2 2 2 * 0 0 0 1 1 1 2 2 2 * 0 0 0 1 1 1 2 2 2 * 3 3 3 4 4 4 5 5 5 * 3 3 3 4 4 4 5 5 5 * 3 3 3 4 4 4 5 5 5 * etc. * * @param codesArray one or multiple arrays [0-80] each one holding region codes. * * @return A Map mapping the region code to an IntArray of the region's cells (or rather their indices from 0..80) */ fun mapCodes2Indices(vararg codesArray: IntArray): MutableMap<Int, IntArray> = TreeMap<Int, IntArray>().apply { for (codes in codesArray) { assert(codes.size == 81) for (index in 0..80) { val code = codes[index] if (code >= 0) { val codeList = this[code]?.toMutableList() ?: ArrayList() codeList.add(index) this[code] = codeList.toIntArray() } } } } /** * Computes the cell indices for regions identified by their region codes. ** * @return An Array of cell indices (IntArray). The Array index matches the region codes. * E.g. a Hyper puzzle has four extra regions so the Array holds 4 lists of cell indices: * region 0 -> (10,11,12,19,20,21,28,29,30) * region 1 -> (14,15,16,23,24,25,32,33,34) * region 2 -> (46,47,48,55,56,57,64,65,66) * region 3 -> (50,51,52,59,60,61,68,69,70) */ fun computeRegionIndices(vararg codesArray: IntArray): Array<IntArray> = mapCodes2Indices(*codesArray).run { keys.map { code -> this[code] ?.toTypedArray() ?.toIntArray()!! }.toTypedArray() } /** * Generic function to compute neighbors for all cells. * The regions are defined by region codes (see mapCodes2Positions). * * The resulting array(s) are [81][9] arrays holding the neighbors for all 81 cell -> [cellIndex][0-8]: * * row: * index 0 -> indices 1 2 3 4 5 6 7 8 * index 1 -> indices 0 2 3 4 5 6 7 8 * etc. * * column: * index 0 -> indices 9 18 27 36 45 54 63 72 * index 1 -> indices 10 19 28 37 46 55 64 73 * etc. * * blocks * index 0 -> indices 1 2 9 10 11 18 19 20 * index 1 -> indices 0 2 9 10 11 18 19 20 * etc. */ fun computeNeighbors(vararg codesArray: IntArray): Array<IntArray> { val indices = computeRegionIndices(*codesArray) return (0..80).map { index -> codesArray.fold(ArrayList<Int>()) { list, codes -> val code = codes[index] val neighbors = if (code >= 0) { indices[code].filter { it != index } } else emptyList() list.addAll(neighbors) list }.sorted().toIntArray() }.toTypedArray() }
0
Kotlin
0
1
4e8bfb119a57a101db4d873bf86cd5722105ebb3
3,054
Dancing-Links-Kotlin
Apache License 2.0
src/com/wd/algorithm/leetcode/ALGO0003.kt
WalkerDenial
327,944,547
false
null
package com.wd.algorithm.leetcode import com.wd.algorithm.test import kotlin.math.max /** * 3. 无重复字符的最长子串 * * 给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。 * */ class ALGO0003 { /** * 方式一:暴力解法 * 逐个生产子字符串,看看是否含有重复的字符 * 时间复杂度 T(n²) */ fun lengthOfLongestSubstring1(s: String): Int { var endIndex = 0 var maxLength = 0 val data = s.toCharArray() val set = HashSet<Int>(data.size) for (i in data.indices) { endIndex = i set.clear() set.add(data[i].toInt()) if (i == data.size - 1) endIndex++ else for (j in (i + 1) until data.size) { endIndex = j val index = data[j].toInt() if (set.contains(index)) break set.add(index) if (j == s.length - 1) endIndex++ } maxLength = maxLength.coerceAtLeast(endIndex - i) } return maxLength } /** * 方式二:滑动窗口及优化 * 向右递增,如果发现重复,则移动起始点下标,并记录当前长度 * 时间复杂度 T(n) */ fun lengthOfLongestSubstring2(s: String): Int { if (s.isEmpty()) return 0 val array = IntArray(128) { -1 } var startIndex = -1 var maxLength = 1 var endChar: Int for (end in s.indices) { endChar = s[end].code startIndex = max(startIndex, array[endChar]) maxLength = max(maxLength, end - startIndex) array[endChar] = end } return maxLength } } fun main() { val clazz = ALGO0003() val str = "pwwkew" (clazz::lengthOfLongestSubstring1).test(str) (clazz::lengthOfLongestSubstring2).test(str) }
0
Kotlin
0
0
245ab89bd8bf467625901034dc1139f0a626887b
1,924
AlgorithmAnalyze
Apache License 2.0
kotlin/36_Valid_Sudoku.kt
giovanniPepi
607,763,568
false
null
// Leet Code problem 36, Valid Sudoku // problem description found on following link: // https://leetcode.com/problems/valid-sudoku/description/ class Solution { fun isValidSudoku(board: Array<CharArray>): Boolean { // my board is an instance of Sudoku class val myboard = Sudoku(board) // mycharlist receives several lists for checking if // line, column or square is false. var mycharlist = listOf<Char>() // loop from 1st to 9th... for (i in 0..8){ // ... line mycharlist = myboard.getLine(i).sorted() //(sorted because during check number should always increase // and never repeat if (!listcheck(mycharlist)) return false // ... column mycharlist = myboard.getColumn(i).sorted() if (!listcheck(mycharlist)) return false // ... and square mycharlist = myboard.getSquare(i).sorted() if (!listcheck(mycharlist)) return false } return true } // this function receives a list of 9 sorted chars. // an empty char is represented by a ".", which when converted to int becomes 46. // a valid char is converted to a number that should always increase and never repeat. // if it repeats, return false fun listcheck(list: List<Char>): Boolean{ // num stores the last known number var num = 0 for (i in list.indices){ // if empty (".") goes to next iteration if (list[i].toInt() == 46) continue // if a number repeats it's false if (num == list[i].toInt()) return false // stores present number in num else num = list[i].toInt() } return true } } // class for receiveing a Sudoku board and performing some board functions class Sudoku(val board: Array<CharArray>) { // gets a line in a board fun getLine (line: Int): CharArray { return board[line] } // gets a column in a board fun getColumn (column: Int): CharArray{ var columnArray = CharArray(9) // loop around every line in same column for (i in 0..8){ columnArray[i] = board[i][column] } return columnArray } // gets a 3 by 3 square from a board fun getSquare (square: Int): CharArray{ var squareArray = CharArray(9) // adopting that 3x3 squares are indexed from 0 to 8. // square 0 has starting line 0 and starting column 0 // square 1 has starting line 0 and starting column 3 // and so on until... // square 8 has starting line 6 and starting column 6 // the following equations perform that calculation val startLine = (square / 3) * 3 val startCol = (square % 3) * 3 var k = 0 // double loop from starting position up to the following 2 positions for (i in startLine..(startLine + 2)){ for (j in startCol..(startCol + 2)){ squareArray[k] = board[i][j] k++ } } return squareArray } }
0
Kotlin
1
0
ccb853bce41206f30cbfb1ff4ca8e8f22feb0ee2
3,168
bastterCode
MIT License
src/main/kotlin/aoc22/Day10.kt
tom-power
573,330,992
false
{"Kotlin": 254717, "Shell": 1026}
package aoc22 import aoc22.Day10Domain.Addx import aoc22.Day10Domain.Cycle import aoc22.Day10Domain.Instruction import aoc22.Day10Domain.Noop import aoc22.Day10Domain.Register import aoc22.Day10Parser.toInstructions import aoc22.Day10Runner.run import aoc22.Day10SolutionPart1.part1Day10 import aoc22.Day10SolutionPart2.part2Day10 import common.Year22 object Day10: Year22 { fun List<String>.part1(): Int = part1Day10() fun List<String>.part2(): String = part2Day10() } object Day10SolutionPart1 { fun List<String>.part1Day10(): Int = toInstructions() .run() .toSamples() .toSignalStrength() .sumOf { it } private fun List<Cycle>.toSamples(): List<Cycle> = drop(19).windowed(1, 40).map { it.first() } private fun List<Cycle>.toSignalStrength(): List<Int> = map { it.value * it.registerDuring.x } } object Day10SolutionPart2 { fun List<String>.part2Day10(): String = toInstructions() .run() .draw() private const val width = 40 private fun List<Cycle>.draw(): String = chunked(width) .mapIndexed { index, cycles -> cycles.map { cycle -> when { cycle.toPixel(index) in cycle.toSprite() -> "#" else -> "." } }.joinToString("") }.joinToString(System.lineSeparator()) private fun Cycle.toPixel(index: Int): Int = (value - (index * width)) - 1 private fun Cycle.toSprite(): IntRange = registerDuring.x.run { this - 1..this + 1 } } object Day10Runner { fun List<Instruction>.run(): List<Cycle> = toRegisters().toCycles() private fun List<Instruction>.toRegisters(): List<Register> = fold(emptyList()) { acc, instruction -> val last = acc.lastOrNull() ?: Register(x = 1) when (instruction) { Noop -> acc + last is Addx -> acc + last + Register(x = last.x + instruction.v) } } private fun List<Register>.toCycles(): List<Cycle> = mapIndexed { index, register -> Cycle( value = index + 1, registerDuring = getOrElse(index - 1) { register }, registerAfter = register ) } } object Day10Parser { fun List<String>.toInstructions(): List<Instruction> = map { when { it == "noop" -> Noop it.startsWith("addx") -> Addx(it.split(" ")[1].toInt()) else -> error("didn't find") } } } object Day10Domain { sealed class Instruction object Noop : Instruction() data class Addx(val v: Int) : Instruction() data class Register(val x: Int) data class Cycle(val value: Int, val registerDuring: Register, val registerAfter: Register) }
0
Kotlin
0
0
baccc7ff572540fc7d5551eaa59d6a1466a08f56
2,974
aoc
Apache License 2.0
kotlin/src/com/daily/algothrim/leetcode/medium/CanPartitionKSubsets.kt
idisfkj
291,855,545
false
null
package com.daily.algothrim.leetcode.medium /** * 698. 划分为k个相等的子集 * * 给定一个整数数组 nums 和一个正整数 k,找出是否有可能把这个数组分成 k 个非空子集,其总和都相等。 * * 示例 1: * 输入: nums = [4, 3, 2, 3, 5, 2, 1], k = 4 * 输出: True * 说明: 有可能将其分成 4 个子集(5),(1,4),(2,3),(2,3)等于总和。 * 示例 2: * 输入: nums = [1,2,3,4], k = 3 * 输出: false * * 1 <= k <= len(nums) <= 16 * 0 < nums[i] < 10000 * 每个元素的频率在 [1,4] 范围内 */ class CanPartitionKSubsets { companion object { @JvmStatic fun main(args: Array<String>) { println( CanPartitionKSubsets().canPartitionKSubsets( intArrayOf(4, 3, 2, 3, 5, 2, 1), 4 ) ) println( CanPartitionKSubsets().canPartitionKSubsets( intArrayOf(1, 2, 3, 4), 3 ) ) println( CanPartitionKSubsets().canPartitionKSubsets( intArrayOf(1, 1, 1, 1, 2, 2, 2, 2), 4 ) ) } } /** * 状态压缩 + 记忆化搜索 */ fun canPartitionKSubsets(nums: IntArray, k: Int): Boolean { var total = 0 nums.forEach { total += it } // 不能整除,代表划分不成功 if (total % k != 0 || nums.isEmpty()) return false // 获得每个子集的和,即平均值 val average = total / k nums.sort() // 如果排序后,最大值大于平均值,则失败 if (nums[nums.size - 1] > average) return false // 由于 1 <= k <= len(nums) <= 16,所以可以使用正整数s的各个位数来代表每个数的使用情况 // 1代表未使用,0代表已经使用 // 同时 s 代表对应的状态个数 // 例如 k = 4(后续都已4为例), 对应的s = 16, 即存在16种不同的状态,那么1.shl(4) = 10000 = 16 // 默认值都为true val dp = BooleanArray(1.shl(nums.size)) { true } // 1.shl(num.size) - 1 => 1.shl(4) - 1 = 1111 = 15 各个位数都为1代表都未使用 // p = 0 代表当前的和,初始都未选中,所以为0 return dfs(nums, average, dp, nums.size, 1.shl(nums.size) - 1, 0) } private fun dfs(nums: IntArray, average: Int, dp: BooleanArray, n: Int, s: Int, p: Int): Boolean { // 如果s = 0 代表0000,各个位数都未0,即nums中的数据都已经使用,且符合条件 if (s == 0) return true // 如果当前S状态已经使用过,即false,则直接返回,跳过 if (!dp[s]) return dp[s] // 标记当前S 的状态已经使用过 dp[s] = false // 遍历nums中各个数 for (i in 0 until n) { // 如果加上当前i的值后,超过平均值,则跳过该值,不做选择 if (nums[i] + p > average) break // 否则,进行标记选择当前值 // 在标记选择之前,判断当前i值是否已经选择过 // 这里通过s右运算i位,再与1做且运算,即得到当前i位数的值,如果不为0,则进入下一个数据的选择 // 例如 s = 1111 = 15, i = 2 // 1111.shr(2) = 0011, 0011.and(0001) = 0001 != 0 if ((s.shr(i).and(1)) != 0) { // 选择i之后,改变s,进入选中i之后的状态 // s = 1111, i = 2 // s = 1111 => 1011(选择i之后的状态) // 这里通过 s.xor(1.shl(i)) 来获取这个值: 1011 // 例如 // 1111.xor(1.shl(2)) => 1111.xor(0100) => 1011 // 最后 p为,(p + num[i]) % average // 这里取模是为了过滤到下一个子集的选取,即如果当前刚好等于平均值,则继续一个符合的子集。即从0开始。 if (dfs(nums, average, dp, n, s.xor(1.shl(i)), (p + nums[i]) % average)) { return true } } } return false } }
0
Kotlin
9
59
9de2b21d3bcd41cd03f0f7dd19136db93824a0fa
4,244
daily_algorithm
Apache License 2.0
src/day2/day02.kt
TP1cks
573,328,994
false
{"Kotlin": 5377}
package day2 import readInputLines typealias GameRecord = Pair<String, String> typealias Game = Pair<Shape, Shape> fun main () { part1() part2() } fun part1() { val games = getGameRecords().map { gameRecord -> Game(symbolToShape(gameRecord.first), symbolToShape(gameRecord.second)) } println("Part 1: Overall Score: ${getOverallScore(games)}") // 10404 } fun part2() { val games = getGameRecords().map { gameRecord -> val elfShape = symbolToShape(gameRecord.first) val shapeForDesiredOutcome = when (symbolToDesiredResult(gameRecord.second)) { GameResult.WIN -> elfShape.losesTo() GameResult.DRAW -> elfShape GameResult.LOSE -> elfShape.beats() } Game(elfShape, shapeForDesiredOutcome) } println("Part 2: Overall Score: ${getOverallScore(games)}") } fun getOverallScore(games: List<Game>) : Int { return games.fold(0) {acc: Int, game: Game -> acc + determineGameScore(game)} } fun determineGameScore(game: Game) : Int { return pointsByGameResult(game.second.versus(game.first)) + game.second.playScore } fun pointsByGameResult(gameResult: GameResult) : Int { return when (gameResult) { GameResult.WIN -> 6 GameResult.DRAW -> 3 GameResult.LOSE -> 0 } } fun getGameRecords() : List<GameRecord> = readInputLines("day2/input").map { gameRecord -> val gameShapes = gameRecord.split(" ") Pair(gameShapes[0], gameShapes[1]) } fun symbolToShape(symbol: String) : Shape { return when (symbol) { "A", "X" -> Rock() "B", "Y" -> Paper() "C", "Z" -> Scissors() else -> {throw Exception("invalid shape")} } } fun symbolToDesiredResult(symbol: String) : GameResult { return when (symbol) { "X" -> GameResult.LOSE "Y" -> GameResult.DRAW "Z" -> GameResult.WIN else -> {throw Exception("invalid desired result")} } }
0
Kotlin
0
0
52f79a4593384fe651d905ddaea379f49ddfe513
1,947
advent-of-code-2022
Apache License 2.0
src/year2022/25/Day25.kt
Vladuken
573,128,337
false
{"Kotlin": 327524, "Python": 16475}
package year2022.`25` import kotlin.math.pow import kotlin.math.roundToLong import readInput fun String.toDecimal(): Long { return split("").filter { it.isNotEmpty() }.map { when (it) { "2" -> 2 "1" -> 1 "0" -> 0 "-" -> -1 "=" -> -2 else -> error("!!") } }.reversed().mapIndexed { index, i -> val pow = 5.0.pow(index).roundToLong() pow * i }.sum() } fun Long.toSNUFU(): String { val answer = StringBuilder() var number = this while (number != 0L) { val whatToAppend = when (number % 5) { 2L -> "2" 1L -> "1" 0L -> "0" 3L -> { number += 5 "=" } 4L -> { number += 5 "-" } else -> error("!!") } answer.append(whatToAppend) number /= 5L } return answer.reversed().toString() } fun main() { fun part1(input: List<String>): String { return input.sumOf { it.toDecimal() }.toSNUFU() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day25_test") val part1Test = part1(testInput) println(part1Test) check(part1Test == "2=-1=0") val input = readInput("Day25") println(part1(input)) }
0
Kotlin
0
5
c0f36ec0e2ce5d65c35d408dd50ba2ac96363772
1,404
KotlinAdventOfCode
Apache License 2.0
src/main/kotlin/Day5.kt
maldoinc
726,264,110
false
{"Kotlin": 14472}
import kotlin.io.path.Path import kotlin.io.path.readLines data class Mapping(val destinationStart: Long, val sourceStart: Long, val size: Long) fun getSection(contents: String, sectionName: String) = Regex("`$sectionName map:`(.+?)(`[a-z]|$)") .findAll(contents) .map { it.groupValues[1] } .first() .split("`") .map { it.split(" ").map(String::toLong).toList() } .map { Mapping(it[0], it[1], it[2]) } .toList() fun getLocation(seed: Long, transformations: List<List<Mapping>>): Long = transformations.fold(seed) { num, mappings -> mappings .filter { num >= it.sourceStart && num <= it.sourceStart + it.size } .map { it.destinationStart + (num - it.sourceStart) } .firstOrNull() ?: num } fun main(args: Array<String>) { val contents = Path(args[0]).readLines() val seeds = contents.first().split(": ").last().split(" ").map(String::toLong).toSet() val normalizedContents = contents.filter(String::isNotEmpty).joinToString("`") val transformations = listOf( getSection(normalizedContents, "seed-to-soil"), getSection(normalizedContents, "soil-to-fertilizer"), getSection(normalizedContents, "fertilizer-to-water"), getSection(normalizedContents, "water-to-light"), getSection(normalizedContents, "light-to-temperature"), getSection(normalizedContents, "temperature-to-humidity"), getSection(normalizedContents, "humidity-to-location"), ) val part1 = seeds.minOf { getLocation(it, transformations) } val part2 = seeds .windowed(2) .parallelStream() // 15$ for this .map { range -> var min = Long.MAX_VALUE var iteration = 0 println(range) for (i in generateSequence(0L) { if (it == range[1]) null else it + 1 }) { iteration += 1 if (iteration % 10_000_000 == 0) { val percent = 100 * i.toDouble() / range[1].toDouble() println("$percent\t:${range[0]}\t${range[1]}") iteration = 0 } min = min.coerceAtMost(getLocation(range[0] + i, transformations)) } min } .toList() .min() println(part1) println(part2) }
0
Kotlin
0
1
47a1ab8185eb6cf16bc012f20af28a4a3fef2f47
2,484
advent-2023
MIT License
src/main/kotlin/GiantSquid_4.kt
Flame239
433,046,232
false
{"Kotlin": 64209}
val input: Input by lazy { val lines = readFile("GiantSquid").split("\n") val numbers = lines[0].split(",").map { Integer.parseInt(it) } val boards = mutableListOf<Board>() var curRow = 2 while (curRow < lines.size) { val curBoard: MutableList<List<Int>> = mutableListOf() // could use lines.drop(1).chunked(6) for (i in 0 until 5) { curBoard.add(lines[curRow + i].split(Regex("\\s+")).map { Integer.parseInt(it) }) } boards.add(Board(curBoard)) curRow += 6 } Input(numbers, boards) } fun findWinningBoard(): Int { val (numbers, boards) = input numbers.forEach { num -> boards.forEachIndexed { index, board -> if (board.mark(num)) { println("Won board index $index in number $num") return board.unmarkedSum() * num } } } return -1 } fun findLastWinningBoard(): Int { val (numbers, boards) = input val finishedBoards = BooleanArray(boards.size) var lastWinningBoardResult: Int = -1 numbers.forEach { num -> boards.forEachIndexed { index, board -> if (board.mark(num)) { if (!finishedBoards[index]) { lastWinningBoardResult = board.unmarkedSum() * num finishedBoards[index] = true } } } } return lastWinningBoardResult } fun main() { println(findWinningBoard()) println(findLastWinningBoard()) } data class Input(val numbers: List<Int>, val boards: List<Board>) class Board(val rows: List<List<Int>>) { private val quintuples: MutableList<Quintuple> = mutableListOf() init { for (i in 0 until 5) { quintuples.add(Quintuple(rows[i])) } for (i in 0 until 5) { val curRow = mutableListOf<Int>() for (j in 0 until 5) { curRow.add(rows[j][i]) } quintuples.add(Quintuple(curRow)) } } fun mark(number: Int): Boolean { var win = false quintuples.forEach { win = win or it.mark(number) } return win } fun unmarkedSum(): Int = quintuples.map { it.unmarkedSum() }.sum() / 2 } class Quintuple(private val numbers: List<Int>) { private val marked = BooleanArray(5) fun mark(number: Int): Boolean { numbers.forEachIndexed { index, num -> if (number == num) { marked[index] = true } } return marked.all { it } } fun unmarkedSum(): Int = numbers.filterIndexed { index, _ -> !marked[index] }.sum() }
0
Kotlin
0
0
ef4b05d39d70a204be2433d203e11c7ebed04cec
2,656
advent-of-code-2021
Apache License 2.0
src/aoc2022/day12/AoC12.kt
Saxintosh
576,065,000
false
{"Kotlin": 30013}
package aoc2022.day12 import readLines data class P(val x: Int, val y: Int) { fun up() = P(x + 1, y) fun down() = P(x - 1, y) fun left() = P(x, y - 1) fun right() = P(x, y + 1) override fun toString() = "($x,$y)" } class XYMap(lines: List<String>) { private val start: P private val end: P private val grid: List<String> init { val ys = lines.indexOfFirst { it.contains("S") } val xs = lines[ys].indexOf('S') start = P(xs, ys) val ye = lines.indexOfFirst { it.contains("E") } val xe = lines[ye].indexOf('E') end = P(xe, ye) grid = lines.map { it.replace("S", "a").replace("E", "z") } } operator fun get(p: P) = grid.getOrNull(p.y)?.getOrNull(p.x) private fun findPossibleSteps(p: P) = buildList { val ch = get(p)!! + 1 fun addIfGood(aP: P) = get(aP)?.takeIf { it <= ch }?.let { add(aP) } addIfGood(p.up()) addIfGood(p.left()) addIfGood(p.down()) addIfGood(p.right()) } fun findAs() = buildList { grid.forEachIndexed { y, row -> row.forEachIndexed { x, c -> if (c == 'a') add(P(x, y)) } } } class APath(val list: List<P>) { constructor(p: P) : this(listOf(p)) fun plus(p: P) = APath(list.plus(p)) fun last() = list.last() operator fun contains(p: P) = p in list val size get() = list.size override fun toString() = list.toString() } fun find(startP: P = start): APath? { var pathsToTry = listOf(APath(startP)) var goodPath: APath? = null var goodSize = Int.MAX_VALUE val visitedPs = mutableSetOf<P>() while (pathsToTry.isNotEmpty()) { val newPathsToTry = mutableListOf<APath>() for (path in pathsToTry) { val steps = findPossibleSteps(path.last()) for (p in steps) { if (p in visitedPs) continue val newPath = path.plus(p) when { newPath.size >= goodSize -> Unit p == end -> { goodPath = newPath goodSize = newPath.size } else -> { val oldPath = newPathsToTry.firstOrNull { p in it } if (oldPath != null) { if (oldPath.size > newPath.size) { newPathsToTry.remove(oldPath) newPathsToTry.add(newPath) } } else { newPathsToTry.add(path.plus(p)) } } } } visitedPs.add(path.last()) } pathsToTry = newPathsToTry } return goodPath } } fun main() { fun part1(lines: List<String>): Int { val m = XYMap(lines) return m.find()!!.size - 1 } fun part2(lines: List<String>): Int { val m = XYMap(lines) return m.findAs().mapNotNull { m.find(it) }.minBy { it.size }.size - 1 } readLines(31, 29, ::part1, ::part2) }
0
Kotlin
0
0
877d58367018372502f03dcc97a26a6f831fc8d8
2,623
aoc2022
Apache License 2.0
src/main/kotlin/com/hj/leetcode/kotlin/problem218/Solution.kt
hj-core
534,054,064
false
{"Kotlin": 619841}
package com.hj.leetcode.kotlin.problem218 import java.util.* /** * LeetCode page: [218. The Skyline Problem](https://leetcode.com/problems/the-skyline-problem/); */ class Solution { /* Complexity: * Time O(NLogN) and Space O(N) where N is the size of buildings; */ fun getSkyline(buildings: Array<IntArray>): List<List<Int>> { val sortedWalls = getWallsSortedByLocationThenSignedHeight(buildings) val skyline = mutableListOf<List<Int>>() val firstWall = sortedWalls.first() val firstSkylinePoint = listOf(firstWall.location, firstWall.unsignedHeight) skyline.add(firstSkylinePoint) val countPerActiveWallHeight = TreeMap<Int, Int>(reverseOrder<Int>()) countPerActiveWallHeight[0] = 1 // Use to connect discrete building groups; for (wall in sortedWalls) { updateCountPerActiveWallHeight(wall, countPerActiveWallHeight) val maxActiveWallHeight: Int = countPerActiveWallHeight.firstKey() val heightOfLastSkylinePoint = skyline.last()[1] val isNewSkylinePoint = maxActiveWallHeight != heightOfLastSkylinePoint if (isNewSkylinePoint) { val newPoint = listOf(wall.location, maxActiveWallHeight) skyline.add(newPoint) } } return skyline } private fun getWallsSortedByLocationThenSignedHeight(buildings: Array<IntArray>): List<Wall> { val walls = mutableListOf<Wall>() for (building in buildings) { walls.add(leftWallOf(building)) walls.add(rightWallOf(building)) } walls.sortWith(compareBy({ it.location }, { it.signedHeight })) return walls } private data class Wall(val location: Int, val signedHeight: Int) { val unsignedHeight get() = Math.abs(signedHeight) } private fun leftWallOf(building: IntArray): Wall { val location = building[0] val signedHeight = building[2] * (-1) return Wall(location, signedHeight) } private fun rightWallOf(building: IntArray): Wall { val location = building[1] val signedHeight = building[2] return Wall(location, signedHeight) } private fun updateCountPerActiveWallHeight(currWall: Wall, counts: MutableMap<Int, Int>) { val unsignedHeight = currWall.unsignedHeight val currCount = counts[unsignedHeight] ?: 0 val newCount = if (currWall.isLeft()) currCount + 1 else currCount - 1 if (newCount == 0) { counts.remove(unsignedHeight) } else { counts[unsignedHeight] = newCount } } private fun Wall.isLeft() = signedHeight < 0 }
1
Kotlin
0
1
14c033f2bf43d1c4148633a222c133d76986029c
2,714
hj-leetcode-kotlin
Apache License 2.0
src/Day20/Day20.kt
Nathan-Molby
572,771,729
false
{"Kotlin": 95872, "Python": 13537, "Java": 3671}
package Day20 import readInput import java.math.BigInteger import kotlin.math.* class LinkedListNode(var number: BigInteger) { var nextNode: LinkedListNode? = null var prevNode: LinkedListNode? = null fun move(listSize: BigInteger) { var smallNumber = number % (listSize - BigInteger.ONE) if (number < BigInteger.ZERO) { smallNumber += listSize - BigInteger.ONE } val smallNumberInt = smallNumber.toInt() for (i in 0 until smallNumberInt) { val oldPrevNode = prevNode!! val jumpedNode = nextNode!! val newNextNode = nextNode!!.nextNode!! //deal with old prevNode oldPrevNode.nextNode = jumpedNode //deal with jumped node jumpedNode.prevNode = oldPrevNode jumpedNode.nextNode = this prevNode = jumpedNode // deal with new next node nextNode = newNextNode newNextNode.prevNode = this } } override fun toString(): String { var nextNode = nextNode!! var string = number.toString() + "," while (nextNode != this) { string += nextNode.number.toString() + "," nextNode = nextNode.nextNode!! } return string } } class EncryptedFile() { var nodes = mutableListOf<LinkedListNode>() fun readInput(input: List<String>) { for (rowIndex in input.withIndex()) { val newNode = LinkedListNode(rowIndex.value.toBigInteger()) if (rowIndex.index != 0) { newNode.prevNode = nodes[rowIndex.index - 1] } nodes.add(newNode) } for (i in 0 until nodes.size - 1) { nodes[i].nextNode = nodes[i + 1] } nodes[0].prevNode = nodes[nodes.size - 1] nodes[nodes.size - 1].nextNode = nodes[0] } fun multiplyNumbers() { for (node in nodes) { node.number *= BigInteger.valueOf(811589153) } } fun move() { for (node in nodes) { node.move(BigInteger.valueOf(nodes.size.toLong())) } } fun getResult(): BigInteger { val zeroNode = nodes.first {it.number == BigInteger.ZERO } var currentNode = zeroNode var nodesOfInterest = mutableListOf<LinkedListNode>() for (i in 0 until 1000) { currentNode = currentNode.nextNode!! } nodesOfInterest.add(currentNode) for (i in 0 until 1000) { currentNode = currentNode.nextNode!! } nodesOfInterest.add(currentNode) for (i in 0 until 1000) { currentNode = currentNode.nextNode!! } nodesOfInterest.add(currentNode) return nodesOfInterest.sumOf { it.number } } fun part2(): BigInteger { for (i in 0 until 10) { move() } return getResult() } } fun main() { fun part1(input: List<String>): BigInteger { val encryptedFile = EncryptedFile() encryptedFile.readInput(input) encryptedFile.move() return encryptedFile.getResult() } fun part2(input: List<String>): BigInteger { val encryptedFile = EncryptedFile() encryptedFile.readInput(input) encryptedFile.multiplyNumbers() return encryptedFile.part2() } val testInput = readInput("Day20","Day20_test") println(part1(testInput)) // check(part1(testInput) == 64) println(part2(testInput)) // check(part2(testInput) == 58) val input = readInput("Day20","Day20") // println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
750bde9b51b425cda232d99d11ce3d6a9dd8f801
3,666
advent-of-code-2022
Apache License 2.0
y2021/src/main/kotlin/adventofcode/y2021/Day10.kt
Ruud-Wiegers
434,225,587
false
{"Kotlin": 503769}
package adventofcode.y2021 import adventofcode.io.AdventSolution object Day10 : AdventSolution(2021, 10, "Syntax Scoring") { override fun solvePartOne(input: String) = input.lineSequence().sumOf(::firstError) override fun solvePartTwo(input: String) = input.lineSequence() .filter { firstError(it) == 0 } .map(::remains) .map(::score) .toList() .sorted() .let { it[it.size / 2] } private fun firstError(str: String): Int { val stack = mutableListOf<Char>() str.forEach { when (it) { ')' -> if (stack.removeLast() != '(') return 3 ']' -> if (stack.removeLast() != '[') return 57 '}' -> if (stack.removeLast() != '{') return 1197 '>' -> if (stack.removeLast() != '<') return 25137 else -> stack += it } } return 0 } private fun remains(str: String) = buildList<Char> { str.forEach { if (it in ")]}>") removeLast() else add(it) } } private fun score(it: List<Char>) = it.reversed().fold(0L) { acc, c -> acc * 5 + "_([{<".indexOf(c) } }
0
Kotlin
0
3
fc35e6d5feeabdc18c86aba428abcf23d880c450
1,168
advent-of-code
MIT License
src/Day04.kt
jfiorato
573,233,200
false
null
fun main() { fun getSet(input: String): Set<Int> { val (start, end) = input.split("-").map { it.toInt() } return IntRange(start, end).toSet() } fun part1(input: List<String>): Int { var counter = 0 for (line in input) { val (assignment1, assignment2) = line.split(",") val assignment1Set = getSet(assignment1) val assignment2Set = getSet(assignment2) if ((assignment1Set - assignment2Set).isEmpty()) { counter += 1 } else if ((assignment2Set - assignment1Set).isEmpty()) { counter += 1 } } return counter } fun part2(input: List<String>): Int { var counter = 0 for (line in input) { val (assignment1, assignment2) = line.split(",") val assignment1Set = getSet(assignment1) val assignment2Set = getSet(assignment2) if ((assignment1Set.intersect(assignment2Set)).isNotEmpty()) { counter += 1 } } return counter } // 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
4455a5e9c15cd067d2661438c680b3d7b5879a56
1,373
kotlin-aoc-2022
Apache License 2.0
src/day01/Day01.kt
veronicamengyan
573,063,888
false
{"Kotlin": 14976}
package day01 import java.util.Comparator import java.util.PriorityQueue import readInput /** * Potential improvement: * * use sorted and takeLast(3) instead of priority queue from java */ fun main() { fun findMaxCalories1(input: List<String>): Long { var maxCalories = 0L var currentCaloriesPerElf = 0L for(item in input) { if (item.isEmpty()) { if (currentCaloriesPerElf > maxCalories) { maxCalories = currentCaloriesPerElf } currentCaloriesPerElf = 0L } else { var calorie = item.toLong() currentCaloriesPerElf += calorie } } return maxCalories } fun findMaxCalories2(input: List<String>): Long { val myCustomComparator = Comparator<Long> { a, b -> when { (a == b) -> 0 (a > b) -> -1 else -> 1 } } val maxHeap = PriorityQueue<Long>(myCustomComparator) var currentCaloriesPerElf = 0L for(item in input) { if (item.isEmpty()) { maxHeap.add(currentCaloriesPerElf) currentCaloriesPerElf = 0L } else { var calorie = item.toLong() currentCaloriesPerElf += calorie } } maxHeap.add(currentCaloriesPerElf) val top1 = maxHeap.remove() val top2 = maxHeap.remove() val top3 = maxHeap.remove() return top1 + top2 + top3 } // test if implementation meets criteria from the description, like: val testInput = readInput("day01/Day01_test") println(findMaxCalories1(testInput)) check(findMaxCalories1(testInput) == 24000L) println(findMaxCalories2(testInput)) check(findMaxCalories2(testInput) == 45000L) val input = readInput("day01/Day01") println(findMaxCalories1(input)) println(findMaxCalories2(input)) }
0
Kotlin
0
0
d443cfa49e9d8c9f76fdb6303ecf104498effb88
1,999
aoc-2022-in-kotlin
Apache License 2.0
src/day21/Code.kt
fcolasuonno
572,734,674
false
{"Kotlin": 63451, "Dockerfile": 1340}
package day21 import day06.main import readInput import java.math.BigInteger sealed class Monkey data class Number(val number: BigInteger) : Monkey() data class Op(val left: String, val right: String, val op: (BigInteger, BigInteger) -> BigInteger) : Monkey() fun main() { fun parse(input: List<String>) = input.map { val (name, value) = it.split(": ") name to (value.toLongOrNull()?.let { Number(BigInteger.valueOf(it)) } ?: value.split(" ") .let { (left, op, right) -> Op( left, right, when (op) { "+" -> BigInteger::plus "-" -> BigInteger::minus "*" -> BigInteger::times "/" -> BigInteger::div else -> throw UnsupportedOperationException() } ) }) }.toMap() fun Map<String, Monkey>.value(node: String) = DeepRecursiveFunction<Monkey, BigInteger> { monkey -> when (monkey) { is Number -> monkey.number is Op -> monkey.op( callRecursive(getValue(monkey.left)), callRecursive(getValue(monkey.right)) ) } }(getValue(node)) fun part1(input: Map<String, Monkey>) = input.value("root") fun part2(input: MutableMap<String, Monkey>) = with(input) { val (left, right) = getValue("root") as Op input["humn"] = Number(BigInteger.ZERO) val zero = value(left) - value(right) input["humn"] = Number(BigInteger.valueOf(Long.MAX_VALUE)) val max = value(left) - value(right) val crescent = max > zero generateSequence(0L..Long.MAX_VALUE) { range -> val mid = range.first + (range.last - range.first) / 2L input["humn"] = Number(BigInteger.valueOf(mid)) val diff = value(left) - value(right) when (diff.signum().let { if (crescent) it else -it }) { 0 -> null 1 -> range.first..mid else -> mid..range.last } }.last() input.value("humn").toLong() } val input = parse(readInput(::main.javaClass.packageName)) println("Part1=\n" + part1(input)) println("Part2=\n" + part2(input.toMutableMap())) }
0
Kotlin
0
0
9cb653bd6a5abb214a9310f7cac3d0a5a478a71a
2,388
AOC2022
Apache License 2.0
src/DayFive.kt
P-ter
573,301,805
false
{"Kotlin": 9464}
fun main() { val exclusions = listOf("ab", "cd", "pq", "xy") val vowels = listOf("a", "e", "i", "o", "u") fun part1(input: List<String>): Int { var total = 0 input.forEach {line -> val pairs = line.windowed(2) if(pairs.intersect(exclusions).isEmpty() && pairs.any { it[0] == it[1] } && line.filter { vowels.contains("$it") }.length >= 3) { total++ } } return total } fun part2(input: List<String>): Int { var total = 0 input.forEach { line -> val pairs = line.windowed(2) val overlaped = pairs.any { pair -> val firstIndex = pairs.indexOfFirst { it == pair } val lastIndex = pairs.indexOfLast { it == pair } (firstIndex != lastIndex) && (firstIndex+1 != lastIndex) } val repeat = line.windowed(3).any { it.first() == it.last() } if(overlaped && repeat) { total++ } } return total } val input = readInput("dayfive") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
fc46b19451145e0c41b1a50f62c77693865f9894
1,171
aoc-2015
Apache License 2.0
src/main/kotlin/days/Day3.kt
andilau
544,512,578
false
{"Kotlin": 29165}
package days @AdventOfCodePuzzle( name = "Squares With Three Sides", url = "https://adventofcode.com/2016/day/3", date = Date(day = 3, year = 2016) ) class Day3(input: List<String>) : Puzzle { private val triangles: List<Triangle> = input.mapNotNull { Triangle.from(it) } override fun partOne(): Int = triangles.count { it.possible } override fun partTwo(): Int = triangles .windowed(3,3,false) .flatMap { threeTriangles -> listOf( Triangle(listOf(threeTriangles[0].sides[0], threeTriangles[1].sides[0], threeTriangles[2].sides[0])), Triangle(listOf(threeTriangles[0].sides[1], threeTriangles[1].sides[1], threeTriangles[2].sides[1])), Triangle(listOf(threeTriangles[0].sides[2], threeTriangles[1].sides[2], threeTriangles[2].sides[2])), ) } .count { it.possible } data class Triangle(val sides: List<Int>) { val possible: Boolean get() { return sides.sorted().let { it[0] + it[1] > it[2] } } companion object { fun from(layout: String): Triangle? { return layout.split(' ') .filter { it.isNotBlank() } .map { it.toInt() } .let { if (it.size == 3) Triangle(it) else null } } } } }
3
Kotlin
0
0
b2a836bd3f1c5eaec32b89a6ab5fcccc91b665dc
1,415
advent-of-code-2016
Creative Commons Zero v1.0 Universal
kotlin/src/com/daily/algothrim/leetcode/MedianSlidingWindow.kt
idisfkj
291,855,545
false
null
package com.daily.algothrim.leetcode import java.util.* /** * 480. 滑动窗口中位数 * 中位数是有序序列最中间的那个数。如果序列的长度是偶数,则没有最中间的数;此时中位数是最中间的两个数的平均数。 * * 例如: * * [2,3,4],中位数是 3 * [2,3],中位数是 (2 + 3) / 2 = 2.5 * 给你一个数组 nums,有一个长度为 k 的窗口从最左端滑动到最右端。窗口中有 k 个数,每次窗口向右移动 1 位。你的任务是找出每次窗口移动后得到的新窗口中元素的中位数,并输出由它们组成的数组。 */ class MedianSlidingWindow { companion object { @JvmStatic fun main(args: Array<String>) { MedianSlidingWindow().solution(intArrayOf(1,3,-1,-3,5,3,6,7), 3).forEach { println(it) } println() MedianSlidingWindow().solution(intArrayOf(1, 4, 2, 3), 4).forEach { println(it) } println() MedianSlidingWindow().solution(intArrayOf(2147483647,2147483647), 2).forEach { println(it) } } } // nums = [1,3,-1,-3,5,3,6,7],以及 k = 3。 // 返回该滑动窗口的中位数数组 [1,-1,-1,3,5,6]。 // O(nlogn) // O(n) fun solution(nums: IntArray, k: Int): DoubleArray { val dh = DualHeap(k) for (i in 0 until k) { dh.insert(nums[i]) } val result = DoubleArray(nums.size - k + 1) result[0] = dh.getMedian() for (j in k until nums.size) { dh.insert(nums[j]) dh.erase(nums[j - k]) result[j - k + 1] = dh.getMedian() } return result } class DualHeap(private val k: Int) { private val small = PriorityQueue<Int>(kotlin.Comparator { o1, o2 -> return@Comparator o2.compareTo(o1) }) private val large = PriorityQueue<Int>(kotlin.Comparator { o1, o2 -> return@Comparator o1.compareTo(o2) }) private val delayed = hashMapOf<Int, Int>() private var smallSize = 0 private var largeSize = 0 fun getMedian(): Double { return if (k.and(1) == 1) small.peek().toDouble() else ((small.peek().toDouble() + large.peek().toDouble())) / 2 } fun insert(num: Int) { if (small.isEmpty() || num <= small.peek()) { small.offer(num) ++smallSize } else { large.offer(num) ++largeSize } makeBalance() } fun erase(num: Int) { delayed[num] = delayed.getOrDefault(num, 0) + 1 if (num <= small.peek()) { --smallSize if (num == small.peek()) { prune(small) } } else { --largeSize if (num == large.peek()) { prune(large) } } makeBalance() } private fun prune(heap: PriorityQueue<Int>) { while (heap.isNotEmpty()) { val num = heap.peek() if (delayed.containsKey(num)) { delayed[num] = delayed[num]?.minus(1) ?: 0 if (delayed[num] == 0) { delayed.remove(num) } heap.poll() } else { break } } } private fun makeBalance() { if (smallSize > largeSize + 1) { large.offer(small.poll()) --smallSize ++largeSize prune(small) } else if (smallSize < largeSize) { small.offer(large.poll()) ++smallSize --largeSize prune(large) } } } }
0
Kotlin
9
59
9de2b21d3bcd41cd03f0f7dd19136db93824a0fa
3,991
daily_algorithm
Apache License 2.0
src/main/kotlin/day14/Day14.kt
Jessevanbekkum
112,612,571
false
null
package day14 import day10.hash64 fun hash(input: String): Int { val toIntArray = (0..127).map { it -> val s = hash64(input + "-" + it) s.toCharArray().map { c -> countBits(c) }.sum() }.toIntArray() return toIntArray.sum() } fun countBits(inp: Char): Int { return Integer.valueOf(inp.toString(), 16).toString(2).toCharArray().filter { c -> c == '1' }.count() } fun hashSquare(input: String): MutableList<MutableList<Char>> { val array = (0..127).map { it -> val s = hash64(input + "-" + it) assert(s.length == 32) s.toCharArray().map { c -> bitRow(c) }.flatten().toMutableList() } assert(array.size == 128) return array.toMutableList() } fun bitRow(inp: Char): List<Char> { return (16 + Integer.valueOf(inp.toString(), 16)).toString(2).map { c -> when { c == '0' -> '.' else -> '#' } }.subList(1, 5) } fun countAreas(sq: MutableList<MutableList<Char>>): Int { var c = 0 (0..127).forEach { x -> (0..127).forEach { y -> run { if (sq[x][y] == '#') { clean(sq, x, y) c++ } } } } return c } fun clean(sq: MutableList<MutableList<Char>>, x: Int, y: Int) { if (x < 0 || x > 127 || y < 0 || y > 127 || sq[x][y] == '.') { return } else { sq[x][y] = '.' clean(sq, x - 1, y) clean(sq, x + 1, y) clean(sq, x, y - 1) clean(sq, x, y + 1) } }
0
Kotlin
0
0
1340efd354c61cd070c621cdf1eadecfc23a7cc5
1,544
aoc-2017
Apache License 2.0
src/main/kotlin/day7/Day7.kt
afTrolle
572,960,379
false
{"Kotlin": 33530}
package day7 import Day import kotlin.LazyThreadSafetyMode.NONE fun main() { Day7("Day07").apply { println(part1(parsedInput)) println(part2(parsedInput)) } } class Day7(input: String) : Day<List<Day7.Dir>>(input) { class Dir( var filesSize: Int = 0, val dirs: MutableMap<String, Dir> = mutableMapOf(), val parent: Dir? = null ) { val size: Int by lazy(NONE) { filesSize + dirs.values.sumOf { it.size } } val allDirs: List<Dir> get() = listOf(this) + dirs.values.flatMap { it.allDirs } } override fun parseInput(): List<Dir> = Dir().also { root -> inputByLines.map { it.split(" ") + "" }.fold(root) { workspace, (a, b, c) -> when { a == "\$" && b == "ls" -> workspace a == "\$" && b == "cd" && c == "/" -> workspace a == "\$" && b == "cd" && c == ".." -> workspace.parent!! a == "\$" && b == "cd" -> workspace.dirs[c]!! a == "dir" -> workspace.apply { dirs[b] = Dir(parent = workspace) } else -> workspace.apply { filesSize += a.toInt() } } } }.allDirs override fun part1(input: List<Dir>): Any = input.map { it.size }.filter { it <= 100000 }.sum() override fun part2(input: List<Dir>): Any { val neededDiskSpace = 30000000 + input.first().size - 70000000 return input.map { it.size }.filter { it > neededDiskSpace }.min() } }
0
Kotlin
0
0
4ddfb8f7427b8037dca78cbf7c6b57e2a9e50545
1,483
aoc-2022
Apache License 2.0
src/main/kotlin/days/Day3.kt
MisterJack49
729,926,959
false
{"Kotlin": 31964}
package days import common.Coordinates class Day3 : Day(3) { override fun partOne() = inputList.toSchematic() .identifyParts() .sumOf { it.value } override fun partTwo() = inputList.toSchematic() .identifyGearParts() .identifyGearSystems() .map { it.calculateRatio() } .sumOf { it.value } } private typealias Line = CharArray private typealias GearSystem = Pair<Symbol, List<Number>> private data class Number( val value: Int = 0, val line: Int = 0, val start: Int = 0, val end: Int = 0 ) { fun getAdjacentCoordinates(): List<Coordinates> { val adjacent = mutableListOf<Coordinates>() adjacent.add(Coordinates(start - 1, line)) adjacent.add(Coordinates(end + 1, line)) for (i in start - 1..end + 1) { adjacent.add(Coordinates(i, line - 1)) adjacent.add(Coordinates(i, line + 1)) } return adjacent } } private data class Symbol(val value: Char, val line: Int, val index: Int) private data class GearPart(val number: Number, val gear: Symbol) private data class Schematic(val data: Array<Line>) { private val width get() = data.first().size - 1 private val height get() = data.size - 1 private fun scanNumbers(): List<Number> = data.mapIndexed { idx, line -> line.scanNumbers().map { it.copy(line = idx) } }.flatten() private fun getAdjacent(coordinates: List<Coordinates>): List<Symbol> = coordinates.map { Symbol(data[it.y][it.x], it.y, it.x) } fun identifyParts(): List<Number> = scanNumbers() .filter { number -> getAdjacent( number.getAdjacentCoordinates() .filterOutbound(width, height) ).map { it.value }.hasSymbols() } fun identifyGearParts(): List<GearPart> = scanNumbers().mapNotNull { number -> val gear = getAdjacent( number.getAdjacentCoordinates() .filterOutbound(width, height) ).firstOrNull { it.value == '*' } if (gear != null) GearPart(number, gear) else null } } private fun List<GearPart>.identifyGearSystems(): List<GearSystem> = groupBy({ it.gear }, { it.number }) .filterValues { it.size == 2 } .toList() private fun GearSystem.calculateRatio() = second.reduce { acc, number -> Number(value = acc.value * number.value) } private fun List<Char>.hasSymbols() = filterNot { it.isDigit() } .filterNot { it == '.' } .any() private fun List<Coordinates>.filterOutbound(x: Int, y: Int) = filterNot { it.x < 0 || it.y < 0 } .filterNot { it.x > x || it.y > y } private fun Line.scanNumbers(): List<Number> { var acc = "" val numbers = mutableListOf<Number>() var number = Number() forEachIndexed { idx, char -> if (char.isDigit() && acc.isEmpty()) { acc += char number = number.copy(start = idx) } else if (char.isDigit()) { acc += char } if (char.isDigit().not() && acc.isNotEmpty()) { number = number.copy(end = idx - 1) numbers.add(number.copy(value = acc.toInt())) number = Number() acc = "" } } if (acc.isNotEmpty()) { number = number.copy(end = size - 1) numbers.add(number.copy(value = acc.toInt())) } return numbers } private fun List<String>.toSchematic(): Schematic = Schematic( map { it.toCharArray() } .toTypedArray() )
0
Kotlin
0
0
807a6b2d3ec487232c58c7e5904138fc4f45f808
3,750
AoC-2023
Creative Commons Zero v1.0 Universal
advent-of-code-2023/src/main/kotlin/eu/janvdb/aoc2023/day04/day04.kt
janvdbergh
318,992,922
false
{"Java": 1000798, "Kotlin": 284065, "Shell": 452, "C": 335}
package eu.janvdb.aoc2023.day04 import eu.janvdb.aocutil.kotlin.readLines //const val FILENAME = "input04-test.txt" const val FILENAME = "input04.txt" val LINE_REGEX = Regex("^Card +(\\d+): ([\\d ]+)\\|([\\d ]+)$") val SPLIT_REGEX = Regex(" +") fun main() { val puzzle = Puzzle.parse(readLines(2023, FILENAME)) println(puzzle.score1()) println(puzzle.score2()) } data class Puzzle(val cards: List<Card>) { private val numbersOfEachCard = MutableList(cards.size) { 1 } init { cards.forEachIndexed { index, puzzle -> IntRange(1, puzzle.matches).forEach { numbersOfEachCard[index + it] += numbersOfEachCard[index] } } } fun score1(): Int { return cards.sumOf { it.score1() } } fun score2(): Int { return numbersOfEachCard.sum() } companion object { fun parse(lines: List<String>): Puzzle { val cards = lines.map { Card.parse(it) } return Puzzle(cards) } } } data class Card(val id: Int, val values: Set<Int>, val winners: Set<Int>) { val matches = values.intersect(winners).size fun score1(): Int { if (matches == 0) return 0 return 1 shl (matches - 1) } companion object { fun parse(input: String): Card { val matchResult = LINE_REGEX.find(input)!! val id = matchResult.groupValues[1].toInt() val values = matchResult.groupValues[2].trim().split(SPLIT_REGEX).map { it.toInt() }.toSet() val winners = matchResult.groupValues[3].trim().split(SPLIT_REGEX).map { it.toInt() }.toSet() return Card(id, values, winners) } } }
0
Java
0
0
78ce266dbc41d1821342edca484768167f261752
1,492
advent-of-code
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/PalindromePairs.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 dev.shtanko.algorithms.ALPHABET_LETTERS_COUNT /** * 336. Palindrome Pairs * @see <a href="https://leetcode.com/problems/palindrome-pairs/">Source</a> */ fun interface PalindromePairs { fun palindromePairs(words: Array<String>): List<List<Int>> } class PalindromePairsTrie : PalindromePairs { override fun palindromePairs(words: Array<String>): List<List<Int>> { val res: MutableList<List<Int>> = ArrayList() val root = TrieNode() for (i in words.indices) { addWord(root, words[i], i) } for (i in words.indices) { search(words, i, root, res) } return res } private class TrieNode { var next: Array<TrieNode?> = arrayOfNulls(ALPHABET_LETTERS_COUNT) var index: Int = -1 var list: MutableList<Int> = ArrayList() } private fun addWord(root: TrieNode, word: String, index: Int) { var root0: TrieNode? = root for (i in word.length - 1 downTo 0) { val j = word[i].code - 'a'.code if (root0?.next?.get(j) == null) { root0?.next?.set(j, TrieNode()) } if (isPalindrome(word, 0, i)) { root0?.list?.add(index) } root0 = root0?.next?.get(j) } root0?.list?.add(index) root0?.index = index } private fun search( words: Array<String>, i: Int, root: TrieNode, res: MutableList<List<Int>>, ) { var node: TrieNode? = root for (j in 0 until words[i].length) { val safeIdx = node?.index ?: -1 if (safeIdx >= 0 && node?.index != i && isPalindrome(words[i], j, words[i].length - 1)) { res.add(mutableListOf(i, node?.index ?: -1)) } node = node?.next?.get(words[i][j].code - 'a'.code) if (node == null) return } for (j in node?.list ?: emptyList()) { if (i == j) continue res.add(listOf(i, j)) } } private fun isPalindrome(word: String, i: Int, j: Int): Boolean { var i0 = i var j0 = j while (i0 < j0) { if (word[i0++] != word[j0--]) return false } return true } } class PalindromePairsImpl : PalindromePairs { override fun palindromePairs(words: Array<String>): List<List<Int>> { val res: MutableList<List<Int>> = ArrayList() if (words.isEmpty()) { return res } val map: HashMap<String, Int> = HashMap() for (i in words.indices) { map[words[i]] = i } if (map.containsKey("")) { val blankIdx = map[""] ?: -1 for (i in words.indices) { if (isPalindrome(words[i])) { if (i == blankIdx) continue res.add(listOf(blankIdx, i)) res.add(listOf(i, blankIdx)) } } } for (i in words.indices) { val cutR = reverseStr(words[i]) if (map.containsKey(cutR)) { val found = map[cutR] ?: -1 if (found == i) continue res.add(listOf(i, found)) } } reverse(words, map, res) return res } private fun reverse(words: Array<String>, map: HashMap<String, Int>, res: MutableList<List<Int>>) { for (i in words.indices) { val cur = words[i] for (cut in 1 until cur.length) { if (isPalindrome(cur.substring(0, cut))) { val cutR = reverseStr(cur.substring(cut)) if (map.containsKey(cutR)) { val found = map[cutR] ?: -1 if (found == i) continue res.add(listOf(found, i)) } } if (isPalindrome(cur.substring(cut))) { val cutR = reverseStr(cur.substring(0, cut)) if (map.containsKey(cutR)) { val found = map[cutR] ?: -1 if (found == i) continue res.add(listOf(i, found)) } } } } } private fun reverseStr(str: String?): String { val sb = StringBuilder(str) return sb.reverse().toString() } private fun isPalindrome(s: String): Boolean { var i = 0 var j = s.length - 1 while (i <= j) { if (s[i] != s[j]) { return false } i++ j-- } return true } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
5,339
kotlab
Apache License 2.0
src/main/kotlin/day11/Day11.kt
qnox
575,581,183
false
{"Kotlin": 66677}
package day11 import readInput class Monkey( items: List<Long>, val operation: (Long) -> Long, val test: (Long) -> Boolean, val ifTrue: Int, val ifFalse: Int ) { fun inspectFirst(): Boolean { _count += 1 val old = _items[0] val worry = operation(old) _items[0] = worry return test(worry) } fun addItem(item: Long) { _items.add(item) } fun removeFirst(): Long = _items.removeFirst() fun hasItems(): Boolean = _items.isNotEmpty() private val _items = items.toMutableList() private var _count = 0 val count: Int get() = _count val items: List<Long> get() = _items } fun main() { fun match(input: String, regex: Regex): MatchNamedGroupCollection { val trimmed = input.trim() val match = regex.matchEntire(trimmed) ?: error("Failed to match `$trimmed` `$regex`") return match.groups as MatchNamedGroupCollection } fun parseMonkey(input: Iterator<String>, worryPostOp: (Long) -> Long): Monkey { val id = match(input.next(), "Monkey (\\d+):".toRegex())[1]!!.value val items = match(input.next(), "Starting items: (.+)".toRegex())[1]!!.value .split(", ") .map { it.toLong() } val (op, value) = match(input.next(), "Operation: new = old (.) (.+)".toRegex()).let { it[1]!!.value to it[2]!!.value } val divisibleBy = match(input.next(), "Test: divisible by (\\d+)".toRegex())[1]!!.value.toInt() val ifTrue = match(input.next(), "If true: throw to monkey (\\d+)".toRegex())[1]!!.value.toInt() val ifFalse = match(input.next(), "If false: throw to monkey (\\d+)".toRegex())[1]!!.value.toInt() if (input.hasNext()) { check(input.next() == "") } val operation: (Long) -> Long = { val v = if (value == "old") { it } else { value.toLong() } when (op) { "*" -> it * v "+" -> it + v else -> error("Unknown op $op") } } return Monkey(items, { worryPostOp(operation(it)) }, { it % divisibleBy == 0L }, ifTrue, ifFalse) } fun parseMonkeys(input: List<String>, worryPostOp: (Long) -> Long): List<Monkey> { val monkeys = mutableListOf<Monkey>() val iterator = input.iterator() while (iterator.hasNext()) { val monkey = parseMonkey(iterator, worryPostOp) monkeys.add(monkey) } return monkeys } fun round(monkeys: List<Monkey>) { for (monkey in monkeys) { while (monkey.hasItems()) { if (monkey.inspectFirst()) { monkeys[monkey.ifTrue].addItem(monkey.removeFirst()) } else { monkeys[monkey.ifFalse].addItem(monkey.removeFirst()) } } } } fun part1(input: List<String>): Long { val monkeys = parseMonkeys(input) { it / 3 } repeat(20) { round(monkeys) println("Round $it") for (i in monkeys.indices) { println("Monkey $i: ${monkeys[i].items.joinToString()}") } } return monkeys.sortedByDescending { it.count }.let { (m1, m2) -> m1.count.toLong() * m2.count } } fun part2(input: List<String>): Long { val monkeys = parseMonkeys(input) { it } repeat(10_000) { round(monkeys) println("Round $it") for (i in monkeys.indices) { println("Monkey $i: ${monkeys[i].items.joinToString()}") } } return monkeys.sortedByDescending { it.count }.let { (m1, m2) -> m1.count.toLong() * m2.count } } val testInput = readInput("day11", "test") val input = readInput("day11", "input") check(part1(testInput) == 10605L) println(part1(input)) check(part2(testInput) == 2713310158L) println(part2(testInput)) println() println(part2(input)) }
0
Kotlin
0
0
727ca335d32000c3de2b750d23248a1364ba03e4
4,107
aoc2022
Apache License 2.0
src/main/kotlin/g0201_0300/s0218_the_skyline_problem/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g0201_0300.s0218_the_skyline_problem // #Hard #Top_Interview_Questions #Array #Heap_Priority_Queue #Ordered_Set #Divide_and_Conquer // #Segment_Tree #Binary_Indexed_Tree #Line_Sweep // #2022_10_25_Time_365_ms_(93.14%)_Space_45.7_MB_(93.71%) import java.util.TreeMap class Solution { fun getSkyline(blds: Array<IntArray>): List<List<Int>> { val ans = ArrayList<List<Int>>() if (blds.isEmpty()) { return ans } val totalBuildings = blds.size val buildings = Array<Building?>(totalBuildings * 2) { null } var idx = 0 for (building in blds) { buildings[idx] = Building(building[0], building[2], true) buildings[idx + 1] = Building(building[1], building[2], false) idx += 2 } buildings.sort() val skyline = TreeMap<Int, Int>() skyline[0] = 1 var prevMaxHeight = 0 for (building in buildings) { if (building == null) { continue } val height = building.height if (building.isStart) { skyline[height] = 1 + (skyline[height] ?: 0) } else { skyline[height] = (skyline[height] ?: 1) - 1 if (skyline[height] == 0) skyline.remove(height) } val xCoor = building.xCoor val curMaxHeight = skyline.lastKey() if (prevMaxHeight != curMaxHeight) { ans.add(arrayListOf(xCoor, curMaxHeight)) prevMaxHeight = curMaxHeight } } return ans } private class Building(val xCoor: Int, val height: Int, val isStart: Boolean) : Comparable<Building> { override fun compareTo(other: Building): Int { return COMPARATOR.compare(this, other) } private companion object { private val COMPARATOR = Comparator<Building> { a, b -> when { a.xCoor != b.xCoor -> a.xCoor.compareTo(b.xCoor) a.isStart && b.isStart -> b.height.compareTo(a.height) !(a.isStart || b.isStart) -> a.height.compareTo(b.height) else -> if (a.isStart) -1 else 1 } } } } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
2,294
LeetCode-in-Kotlin
MIT License
src/Day23.kt
EdoFanuel
575,561,680
false
{"Kotlin": 80963}
import utils.Coord2DInt import utils.Orientation class Day23 { fun parseInput(input: List<String>): Set<Coord2DInt> { val result = mutableSetOf<Coord2DInt>() for (i in input.indices) { for (j in input[i].indices) { if (input[i][j] == '#') result += Coord2DInt(i, j) } } return result } fun simulate(start: Set<Coord2DInt>, iteration: Int): Set<Coord2DInt> { var elves = start val priority = mutableListOf( Orientation.NORTH, Orientation.SOUTH, Orientation.WEST, Orientation.EAST ) repeat(iteration) { val proposedMovement = elves.associateWith { move(it, elves, priority) } val actualMovement = mutableSetOf<Coord2DInt>() for ((source, dest) in proposedMovement) { actualMovement += if (proposedMovement.count { it.value == dest } > 1) source else dest } elves = actualMovement priority += priority.removeFirst() // shift list one step to the left } return elves } fun simulateEndless(start: Set<Coord2DInt>): Int { var elves = start val priority = mutableListOf( Orientation.NORTH, Orientation.SOUTH, Orientation.WEST, Orientation.EAST ) var count = 0 while (true) { val proposedMovement = elves.associateWith { move(it, elves, priority) } if (proposedMovement.all { it.key == it.value }) { break } val actualMovement = mutableSetOf<Coord2DInt>() for ((source, dest) in proposedMovement) { actualMovement += if (proposedMovement.count { it.value == dest } > 1) source else dest } elves = actualMovement priority += priority.removeFirst() // shift list one step to the left count++ } return count + 1 } private fun move(start: Coord2DInt, blockers: Set<Coord2DInt>, priority: MutableList<Orientation>): Coord2DInt { val n = start + Orientation.NORTH.direction val s = start + Orientation.SOUTH.direction val w = start + Orientation.WEST.direction val e = start + Orientation.EAST.direction val nw = n + Orientation.WEST.direction val ne = n + Orientation.EAST.direction val sw = s + Orientation.WEST.direction val se = s + Orientation.EAST.direction if (setOf(n, nw ,w ,sw, s, se, e, ne).all { it !in blockers }) return start // not moving if no one else is around val mapping = mapOf( Orientation.NORTH to (setOf(n, nw, ne).all { it !in blockers } to n), Orientation.SOUTH to (setOf(s, sw, se).all { it !in blockers } to s), Orientation.WEST to (setOf(nw, w, sw).all { it !in blockers } to w), Orientation.EAST to (setOf(ne, e, se).all { it !in blockers } to e) ) for (direction in priority) { if (mapping[direction]!!.first) return mapping[direction]!!.second } return start } } fun main() { val day = Day23() fun part1(input: List<String>): Int { val elves = day.parseInput(input) val result = day.simulate(elves, 10) val rows = result.maxOf { it.x } - result.minOf { it.x } + 1 val cols = result.maxOf { it.y } - result.minOf { it.y } + 1 println("Rectangle size = $rows x $cols. Elves: ${result.size}") return rows * cols - result.size } fun part2(input: List<String>): Int { val elves = day.parseInput(input) return day.simulateEndless(elves) } val test = readInput("Day23_test") println("=== Part 1 (test) ===") println(part1(test)) println("=== Part 2 (test) ===") println(part2(test)) val input = readInput("Day23") println("=== Part 1 (puzzle) ===") println(part1(input)) println("=== Part 2 (puzzle) ===") println(part2(input)) }
0
Kotlin
0
0
46a776181e5c9ade0b5e88aa3c918f29b1659b4c
4,076
Advent-Of-Code-2022
Apache License 2.0
src/Day24.kt
Kvest
573,621,595
false
{"Kotlin": 87988}
import java.util.* fun main() { val testInput = readInput("Day24_test") val testMap = BlizzardMap(testInput) check(part1(testMap) == 18) check(part2(testMap) == 54) val input = readInput("Day24") val map = BlizzardMap(input) println(part1(map)) println(part2(map)) } private fun part1(map: BlizzardMap): Int { val initialMap = map[0] val startI = 0 val startJ = initialMap[startI].indexOfFirst { it } val targetI = initialMap.lastIndex val targetJ = initialMap[targetI].indexOfFirst { it } return solve( map = map, startMinute = 0, startI = startI, startJ = startJ, targetI = targetI, targetJ = targetJ, ) } private fun part2(map: BlizzardMap): Int { val initialMap = map[0] val startI = 0 val startJ = initialMap[startI].indexOfFirst { it } val targetI = initialMap.lastIndex val targetJ = initialMap[targetI].indexOfFirst { it } val m1 = solve( map = map, startMinute = 0, startI = startI, startJ = startJ, targetI = targetI, targetJ = targetJ, ) val m2 = solve( map = map, startMinute = m1, startI = targetI, startJ = targetJ, targetI = startI, targetJ = startJ, ) val m3 = solve( map = map, startMinute = m2, startI = startI, startJ = startJ, targetI = targetI, targetJ = targetJ, ) return m3 } private fun solve( map: BlizzardMap, startMinute: Int, startI: Int, startJ: Int, targetI: Int, targetJ: Int ): Int { val queue = PriorityQueue<Item>() queue.offer(Item(startMinute, IJ(startI, startJ))) val visited = mutableSetOf<Int>() while (queue.isNotEmpty()) { val (minute, ij) = queue.poll() val (i, j) = ij val key = minute * 1_000_000 + i * 1_000 + j if (key in visited) { continue } visited.add(key) if (i == targetI && j == targetJ) { return minute } val currentMap = map[minute + 1] if (currentMap[i][j]) { queue.offer(Item(minute + 1, IJ(i, j))) } if (i > 0 && currentMap[i - 1][j]) { queue.offer(Item(minute + 1, IJ(i - 1, j))) } if (i < currentMap.lastIndex && currentMap[i + 1][j]) { queue.offer(Item(minute + 1, IJ(i + 1, j))) } if (j > 0 && currentMap[i][j - 1]) { queue.offer(Item(minute + 1, IJ(i, j - 1))) } if (j < currentMap[i].lastIndex && currentMap[i][j + 1]) { queue.offer(Item(minute + 1, IJ(i, j + 1))) } } error("Path not found") } private class BlizzardMap(initialState: List<String>) { private val cache = mutableListOf<BooleanMatrix>() private val template: BooleanMatrix private val blizzards: List<Blizzard> init { blizzards = buildList { initialState.forEachIndexed { i, row -> row.forEachIndexed { j, ch -> when (ch) { '>' -> add(Blizzard(MutableIJ(i, j), BlizzardDirection.RIGHT)) 'v' -> add(Blizzard(MutableIJ(i, j), BlizzardDirection.DOWN)) '<' -> add(Blizzard(MutableIJ(i, j), BlizzardDirection.LEFT)) '^' -> add(Blizzard(MutableIJ(i, j), BlizzardDirection.UP)) } } } } template = Array(initialState.size) { i -> BooleanArray(initialState[i].length) { j -> initialState[i][j] != '#' } } //generate default map generateNextMap() } operator fun get(i: Int): BooleanMatrix { while (cache.lastIndex < i) { generateNextMap() } return cache[i] } private fun generateNextMap() { val next = template.deepCopyOf() blizzards.forEach { with(it) { next[position.i][position.j] = false //Also, move blizzard to the new position when (direction) { BlizzardDirection.RIGHT -> position.j = if (position.j < (template[0].lastIndex - 1)) { position.j + 1 } else { 1 } BlizzardDirection.DOWN -> position.i = if (position.i < (template.lastIndex - 1)) { position.i + 1 } else { 1 } BlizzardDirection.LEFT -> position.j = if (position.j > 1) { position.j - 1 } else { template[0].lastIndex - 1 } BlizzardDirection.UP -> position.i = if (position.i > 1) { position.i - 1 } else { template.lastIndex - 1 } } } } cache.add(next) } } private enum class BlizzardDirection { RIGHT, DOWN, LEFT, UP } private class Blizzard( val position: MutableIJ, val direction: BlizzardDirection, )
0
Kotlin
0
0
6409e65c452edd9dd20145766d1e0ea6f07b569a
5,322
AOC2022
Apache License 2.0
src/day03/Day03.kt
Harvindsokhal
572,911,840
false
{"Kotlin": 11823}
package day03 import readInput fun main() { val data = readInput("day03/day03_data") val alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" fun sortRucksack(list: List<String>): Int { var sum = 0 list.forEach { item -> val half = item.length / 2 val pt1 = item.slice(0 until half).toCharArray() val pt2 = item.slice(half until item.length).toCharArray() val common = pt1.intersect(pt2.toSet()).take(1).first() sum += alphabet.indexOf(common) + 1 } return sum } fun sortRucksackGroup(list: List<String>): Int { val grouped = list.chunked(3) var sum = 0 grouped.forEach { val group = it.map { it.toCharArray() } val first = group[0] val second = group[1] val third = group[2] val common = first.intersect(second.toSet()).intersect(third.toSet()).take(1).first() sum+= alphabet.indexOf(common) + 1 } return sum } fun part1(list:List<String>) = sortRucksack(list) fun part2(list:List<String>) = sortRucksackGroup(list) println(part1(data)) println(part2(data)) }
0
Kotlin
0
0
7ebaee4887ea41aca4663390d4eadff9dc604f69
1,227
aoc-2022-kotlin
Apache License 2.0
src/com/kingsleyadio/adventofcode/y2023/Day09.kt
kingsleyadio
435,430,807
false
{"Kotlin": 134666, "JavaScript": 5423}
package com.kingsleyadio.adventofcode.y2023 import com.kingsleyadio.adventofcode.util.readInput fun main() { val input = readInput(2023, 9).readLines().map { line -> line.split(" ").map(String::toInt) } part1(input) part2(input) } private fun part1(input: List<List<Int>>) = println(input.sumOf(::findNextNumber)) // Could also use findNext(line.reversed()) private fun part2(input: List<List<Int>>) = println(input.sumOf(::findPreviousNumber)) private fun findNextNumber(sequence: List<Int>): Int { val diff = sequence.zipWithNext { a, b -> b - a } // Could also reduce until sequence is empty return if (diff.all { it == 0 }) sequence.last() else sequence.last() + findNextNumber(diff) } private fun findPreviousNumber(sequence: List<Int>): Int { val diff = sequence.zipWithNext { a, b -> b - a } // Could also reduce until sequence is empty return if (diff.all { it == 0 }) sequence.first() else sequence.first() - findPreviousNumber(diff) }
0
Kotlin
0
1
9abda490a7b4e3d9e6113a0d99d4695fcfb36422
987
adventofcode
Apache License 2.0
src/main/kotlin/utils/CharGrid.kt
dkhawk
573,106,005
false
{"Kotlin": 574941}
package utils import kotlin.math.abs import kotlin.math.pow import kotlin.math.sign import kotlin.math.sqrt data class Vector(val x: Int = 0, val y: Int = 0) : Comparable<Vector> { val sign: Vector get() = Vector(x.sign, y.sign) operator fun times(scale: Int): Vector { return Vector(x * scale, y * scale) } operator fun minus(other: Vector): Vector = Vector(x - other.x, y - other.y) operator fun plus(other: Vector): Vector = Vector(x + other.x, y + other.y) fun advance(heading: Heading): Vector { return this + heading.vector } fun advance(heading: Heading8): Vector { return this + heading.vector } fun directionTo(end: Vector) = (end - this) fun distance(goal: Vector): Double { val dx = goal.x - x val dy = goal.y - y return sqrt(((dx*dx) + (dy*dy)).toDouble()) } fun abs(): Vector { return Vector(abs(x), abs(y)) } override fun compareTo(other: Vector): Int = compareValuesBy(this, other, { it.x }, { it.y }) fun neighborsConstrained(top: Int = 0, bottom: Int, left: Int = 0, right: Int): List<Vector> { return Heading.values().mapNotNull { heading -> val candidate = this.advance(heading) if (candidate.y in top..bottom && candidate.x in left..right) { candidate } else { null } } } fun neighbors() = Heading.values().map { heading -> this.advance(heading) } fun cityDistanceTo(beacon: Vector): Int = abs(beacon.x - x) + abs(beacon.y - y) fun inBounds(min: Vector, max: Vector) = this in min..max fun neighbors8() = Heading8.values().map { heading -> this.advance(heading) } fun toHeading() = Heading.values().first { this == it.vector } fun headingTo(destination: Vector) = directionTo(destination).sign.toHeading() } enum class Direction { NORTH, EAST, SOUTH, WEST } enum class Heading(val vector: Vector) { NORTH(Vector(0, -1)), WEST(Vector(-1, 0)), EAST(Vector(1, 0)), SOUTH(Vector(0, 1)); fun turnRight(): Heading { return values()[(this.ordinal + 1) % values().size] } fun turnLeft(): Heading { return values()[(this.ordinal + values().size - 1) % values().size] } fun opposite() : Heading { return when (this) { NORTH -> SOUTH WEST -> EAST EAST -> WEST SOUTH -> NORTH } } fun turnTo(other: Heading): Int { return other.ordinal - ordinal } } data class Vector3dLong(val x: Long, val y: Long, val z: Long) { operator fun plus(other: Vector3dLong): Vector3dLong = Vector3dLong(x + other.x, y + other.y, z + other.z) fun distanceTo(other: Vector3dLong): Long = abs(x - other.x) + abs(y - other.y) + abs(z - other.z) override fun toString(): String = "<$x,$y,$z>" } data class Vector3d(val x: Int, val y: Int, val z: Int) { constructor(list: List<Int>) : this(list[0], list[1], list[2]) operator fun plus(other: Vector3d): Vector3d = Vector3d(x + other.x, y + other.y, z + other.z) operator fun minus(other: Vector3d): Vector3d = Vector3d(x - other.x, y - other.y, z - other.z) fun distanceTo(other: Vector3d): Int = abs(x - other.x) + abs(y - other.y) + abs(z - other.z) fun abs(): Vector3d { return Vector3d(abs(x), abs(y), abs(z)) } override fun toString(): String = "<$x,$y,$z>" fun getNeighbors() = Heading3d.values().map { this + it.vector } fun distance(other: Vector3d): Double { val dx2 = (x - other.x).toDouble().pow(2) val dy2 = (y - other.y).toDouble().pow(2) val dz2 = (z - other.z).toDouble().pow(2) return sqrt(dx2 + dy2 + dz2) } fun headingTo(destination: Vector3d) = (destination - this).sign().toHeading3d() fun toHeading3d(): Heading3d = Heading3d.values().first { it.vector == this } fun sign() = Vector3d(x.sign, y.sign, z.sign) fun advance(heading: Heading3d) = this + heading.vector fun advance(heading: Direction3d) = this + heading.vector } enum class Heading3d(val vector: Vector3d) { TOP(Vector3d(0, 0, -1)), BOTTOM(Vector3d(0, 0, 1)), FRONT(Vector3d(0, -1, 0)), BACK(Vector3d(0, 1, 0)), LEFT(Vector3d(-1, 0, 0)), RIGHT(Vector3d(1, 0, 0)) } enum class Direction3d(val vector: Vector3d) { UP_Z(Vector3d(0, 0, 1)), DOWN_Z(Vector3d(0, 0, -1)), UP_Y(Vector3d(0, 1, 0)), DOWN_Y(Vector3d(0, -1, 0)), UP_X(Vector3d(1, 0, 0)), DOWN_X(Vector3d(-1, 0, 0)) } enum class Heading8(val vector: Vector) { NORTH(Vector(0, -1)), NORTHEAST(Vector(1, -1)), EAST(Vector(1, 0)), SOUTHEAST(Vector(1, 1)), SOUTH(Vector(0, 1)), SOUTHWEST(Vector(-1, 1)), WEST(Vector(-1, 0)), NORTHWEST(Vector(-1, -1)); fun turnRight(): Heading8 { return values()[(this.ordinal + 1) % values().size] } fun turnLeft(): Heading8 { return values()[(this.ordinal + values().size - 1) % values().size] } } interface Grid<T> { fun coordsToIndex(x: Int, y: Int) : Int fun setIndex(index: Int, value: T) fun getIndex(index: Int): T } class CharGrid() : Grid<Char> { var width: Int = 0 var height: Int = 0 var grid : CharArray = CharArray(width * height) constructor(input: CharArray, width: Int, height: Int? = null) : this() { grid = input.clone() this.width = width this.height = height ?: (grid.size / width) } constructor(inputLines: List<String>) : this() { width = inputLines.first().length height = inputLines.size grid = inputLines.map(String::toList).flatten().toCharArray() } constructor(size: Int, default: Char = ' ') : this() { width = size height = size grid = CharArray(width * height) grid.fill(default) } constructor(width: Int, height: Int, default: Char = '.') : this() { this.width = width this.height = height grid = CharArray(width * height) grid.fill(default) } override fun toString(): String { val output = StringBuilder() output.append("$width, $height\n") grid.toList().windowed(width, width) { output.append(it.joinToString("")).append('\n') } return output.toString() } fun toStringWithHighlights( highlight: String = COLORS.LT_RED.toString(), predicate: (Char, Vector) -> Boolean, ): String { val output = StringBuilder() output.append("$width, $height\n") var row = 0 grid.toList().windowed(width, width) { output.append( it.withIndex().joinToString("") { (index, c) -> val shouldHighlight = predicate(c, Vector(index, row)) if (shouldHighlight) { highlight + c.toString() + NO_COLOR } else { c.toString() } } ).append('\n') row += 1 } return output.toString() } fun toStringWithMultipleHighlights( vararg highlight: Pair<String, (Char, Vector) -> Boolean> ): String { val output = StringBuilder() output.append("$width, $height\n") var row = 0 grid.toList().windowed(width, width) { output.append( it.withIndex().joinToString("") { (index, c) -> val hl = highlight.firstOrNull { it.second(c, Vector(index, row)) } if (hl != null) { hl.first + c.toString() + NO_COLOR } else { c.toString() } } ).append('\n') row += 1 } return output.toString() } operator fun get(Vector: Vector): Char = getCell(Vector) fun findCharacter(target: Char): Vector? { val index = grid.indexOf(target) if (index == -1) { return null } return indexToVector(index) } fun indexToVector(index: Int): Vector { val y = index / width val x = index % width return Vector(x, y) } fun setCell(Vector: Vector, c: Char) { grid[vectorToIndex(Vector)] = c } fun vectorToIndex(Vector: Vector): Int { return Vector.x + Vector.y * width } fun getCell(Vector: Vector): Char { return grid[vectorToIndex(Vector)] } fun getCellOrNull(Vector: Vector): Char? { if (!validLocation(Vector)) { return null } return grid[vectorToIndex(Vector)] } fun getNeighbors(index: Int): List<Char> { val Vector = indexToVector(index) return getNeighbors(Vector) } fun getCell_xy(x: Int, y: Int): Char { return grid[coordsToIndex(x, y)] } override fun coordsToIndex(x: Int, y: Int): Int { return x + y * width } fun getNeighbors(vector: Vector): List<Char> { return Heading.values().mapNotNull { heading -> val v = vector + heading.vector if (validLocation(v)) { getCell(v) } else { null } } } fun getNeighborsWithLocation(vector: Vector): List<Pair<Vector, Char>> { return Heading.values().mapNotNull { heading -> val v = vector + heading.vector if (validLocation(v)) { v to getCell(v) } else { null } } } fun getNeighbor8sWithLocation(index: Int): List<Pair<Vector, Char>> { val vector = indexToVector(index) return Heading8.values().mapNotNull { heading -> val v = vector + heading.vector if (validLocation(v)) { v to getCell(v) } else { null } } } fun getNeighborsWithLocation(index: Int): List<Pair<Vector, Char>> = getNeighborsWithLocation(indexToVector(index)) fun getNeighborsIf(Vector: Vector, predicate: (Char, Vector) -> Boolean): List<Vector> { return Heading.values().mapNotNull { heading-> val loc = Vector + heading.vector if (validLocation(loc) && predicate(getCell(loc), loc)) { loc } else { null } } } override fun getIndex(index: Int): Char { return grid[index] } override fun setIndex(index: Int, value: Char) { grid[index] = value } fun initialize(input: String) { input.forEachIndexed{ i, c -> if (i < grid.size) grid[i] = c } } fun getNeighbors8(Vector: Vector, default: Char): List<Char> { return Heading8.values() .map { heading-> Vector + heading.vector } .map { neighborVector -> if (validLocation(neighborVector)) getCell(neighborVector) else default } } fun validLocation(Vector: Vector): Boolean { return Vector.x < width && Vector.y < height && Vector.x >= 0 && Vector.y >= 0 } fun copy(): CharGrid { return CharGrid(grid, width, height) } fun getNeighbors8(index: Int): List<Char> { val Vector = indexToVector(index) return Heading8.values() .map { heading-> Vector + heading.vector } .mapNotNull { neighborVector -> if (validLocation(neighborVector)) getCell(neighborVector) else null } } fun advance(action: (index: Int, Vector: Vector, Char) -> Char): CharGrid { val nextGrid = CharArray(width * height) for ((index, item) in grid.withIndex()) { val loc = indexToVector(index) nextGrid[index] = action(index, loc, item) } return CharGrid(nextGrid, width, height) } fun sameAs(other: CharGrid): Boolean { return grid contentEquals other.grid } fun getBorders(): List<Int> { val trans = mapOf('.' to '0', '#' to '1') return listOf( (0 until width).mapNotNull { trans[getCell_xy(it, 0)] }, (0 until height).mapNotNull { trans[getCell_xy(width - 1, it)] }, (0 until width).mapNotNull { trans[getCell_xy(it, height - 1)] }, (0 until height).mapNotNull { trans[getCell_xy(0, it)] }, ).flatMap { listOf(it, it.reversed()) }.map { it.joinToString("") } .map { it.toInt(2) } } fun rotate(rotation: Int): CharGrid { var r = rotation var src = this if (r < 0) { while (r < 0) { val nextGrid = CharGrid(CharArray(width * height), width, height) (0 until height).forEach { row -> val rowContent = src.getRow(row).reversedArray() nextGrid.setColumn(row, rowContent) } r += 1 src = nextGrid } } else { while (r > 0) { val nextGrid = CharGrid(CharArray(width * height), width, height) (0 until height).forEach { row -> val rowContent = src.getRow(row) nextGrid.setColumn((width - 1) - row, rowContent) } r -= 1 src = nextGrid } } return src } private fun setColumn(col: Int, content: CharArray) { var index = col repeat(height) { grid[index] = content[it] index += width } } fun setColumn(col: Int, c: Char) { var index = col repeat(height) { grid[index] = c index += width } } fun getRow(row: Int): CharArray { val start = row * width return grid.sliceArray(start until (start + width)) } private fun setRow(row: Int, content: CharArray) { val start = row * width val end = start + width (start until end).forEachIndexed { index, it -> grid[it] = content[index] } } fun getBorder(heading: Heading) { val trans = mapOf('.' to '0', '#' to '1') val thing = when (heading) { Heading.NORTH -> (0 until width).mapNotNull { trans[getCell_xy(it, 0)] } Heading.EAST -> (0 until height).mapNotNull { trans[getCell_xy(width - 1, it)] } Heading.SOUTH -> (0 until width).mapNotNull { trans[getCell_xy(it, height - 1)] } Heading.WEST -> (0 until height).mapNotNull { trans[getCell_xy(0, it)] } }.joinToString("") println(thing) // .map { it.toInt(2) } } fun flipAlongVerticalAxis(): CharGrid { var i = 0 var j = width - 1 val nextGrid = CharGrid(CharArray(width * height), width, height) while (i < j) { nextGrid.setColumn(j, getColumn(i)) nextGrid.setColumn(i, getColumn(j)) i++ j-- } if (i == j) { nextGrid.setColumn(i, getColumn(i)) } return nextGrid } fun flipAlongHorizontalAxis(): CharGrid { var i = 0 var j = height - 1 val nextGrid = CharGrid(CharArray(width * height), width, height) while (i < j) { nextGrid.setRow(j, getRow(i)) nextGrid.setRow(i, getRow(j)) i++ j-- } if (i == j) { nextGrid.setRow(i, getRow(j)) } return nextGrid } fun getColumn(col: Int): CharArray { val result = CharArray(height) var index = col repeat(height) { result[it] = grid[index] index += width } return result } fun stripBorder(): CharGrid { val nextWidth = width - 2 val nextHeight = height - 2 val nextGrid = CharGrid(CharArray(nextWidth * nextHeight), nextWidth, nextHeight) (1 .. nextHeight).forEach { row -> (1 .. nextHeight).forEach { col -> nextGrid.setCell_xy(col - 1, row - 1, getCell_xy(col, row)) } } return nextGrid } fun setCell_xy(x: Int, y: Int, ch: Char) { grid[coordsToIndex(x, y)] = ch } fun getPermutations(): List<CharGrid> { return getFlips().flatMap { it.getRotations() } } private fun getFlips(): List<CharGrid> { return listOf( this, this.flipAlongHorizontalAxis(), this.flipAlongVerticalAxis(), this.flipAlongHorizontalAxis().flipAlongVerticalAxis() ) } private fun getRotations(): List<CharGrid> { return (0..3).map { rotate(it) } } fun insertAt_xy(xOffset: Int, yOffset: Int, other: CharGrid) { repeat(other.height) { row -> val y = row + yOffset repeat(other.width) { col -> val x = col + xOffset setCell_xy(x, y, other.getCell_xy(col, row)) } } } fun findAll(predicate: (Int, Char) -> Boolean): List<Pair<Int, Char>> { return grid.withIndex().filter { (index, value) -> predicate(index, value) }.map { (index, value) -> index to value } } fun pivot(): CharGrid { val outGrid = CharGrid(CharArray(width * height), height, width) repeat(height) { row -> repeat(width) { col -> outGrid.setCell_xy(row, col, getCell_xy(col, row)) } } return outGrid } fun rotateClockwise(): CharGrid { val outGrid = CharGrid(CharArray(width * height), height, width) repeat(height) { row -> repeat(width) { col -> val outY = col val outX = (height - 1) - row val src = getCell_xy(col, row) outGrid.setCell_xy(outX, outY, src) } } return outGrid } fun rotateCounterClockwise(): CharGrid { val outGrid = CharGrid(CharArray(width * height), height, width) repeat(height) { row -> repeat(width) { col -> val outX = row val outY = (width - 1) - col val src = getCell_xy(col, row) outGrid.setCell_xy(outX, outY, src) } } return outGrid } operator fun set(it: Vector, value: Char) { this.setCell(it, value) } } fun Iterable<Vector>.unzip(): Pair<List<Int>, List<Int>> { val expectedSize = 100 val listT = ArrayList<Int>(expectedSize) val listR = ArrayList<Int>(expectedSize) for (location in this) { listT.add(location.x) listR.add(location.y) } return listT to listR }
0
Kotlin
0
1
4cbe3200832ce8d81333bb5e851ad66dfe390e6e
16,830
AoCDesktop
Apache License 2.0
src/Day01/Day01.kt
G-lalonde
574,649,075
false
{"Kotlin": 39626}
import java.util.* fun main() { fun part1(input: List<String>): Int { var mostCalories = Double.MIN_VALUE var calories = 0.0 for (line: String in input) { if (line.isEmpty()) { if (calories > mostCalories) { mostCalories = calories } calories = 0.0 } else { calories += line.toDouble() } } return mostCalories.toInt() } fun part2(input: List<String>): Int { var mostCalories = mutableListOf<Double>() var calories = 0.0 for (line: String in input) { if (line.isEmpty()) { mostCalories.add(calories) mostCalories.sortByDescending { it } mostCalories = mostCalories.take(3).toMutableList() calories = 0.0 } else { calories += line.toDouble() } } mostCalories.add(calories) mostCalories.sortByDescending { it } mostCalories = mostCalories.take(3).toMutableList() return mostCalories.sum().toInt() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") check(part1(testInput) == 24000) check(part2(testInput) == 45000) val input = readInput("Day01") println("Answer for part 1 : ${part1(input)}") println("Answer for part 2 : ${part2(input)}") }
0
Kotlin
0
0
3463c3228471e7fc08dbe6f89af33199da1ceac9
1,494
aoc-2022
Apache License 2.0
src/Day02.kt
kthun
572,871,866
false
{"Kotlin": 17958}
fun main() { fun part1(input: List<String>): Int { return input.sumOf { line -> val (opponent, self) = line.split(" ") val symbolValue = when (self) { "X" -> 1 "Y" -> 2 "Z" -> 3 else -> throw IllegalArgumentException("Unknown symbol: $self") } val winBonus = when (opponent) { "A" -> when (self) { "X" -> 3 "Y" -> 6 "Z" -> 0 else -> throw IllegalArgumentException("Unknown self: $self") } "B" -> when (self) { "X" -> 0 "Y" -> 3 "Z" -> 6 else -> throw IllegalArgumentException("Unknown self: $self") } "C" -> when (self) { "X" -> 6 "Y" -> 0 "Z" -> 3 else -> throw IllegalArgumentException("Unknown self: $self") } else -> throw IllegalArgumentException("Unknown opponent: $opponent") } symbolValue + winBonus } } fun part2(input: List<String>): Int { return input.sumOf { line -> val (opponent, goal) = line.split(" ") val (ownSymbol, winBonus) = when (goal) { "X" -> when (opponent) { "A" -> Pair("C", 0) "B" -> Pair("A", 0) "C" -> Pair("B", 0) else -> throw IllegalArgumentException("Unknown opponent: $opponent") } "Y" -> when (opponent) { "A" -> Pair("A", 3) "B" -> Pair("B", 3) "C" -> Pair("C", 3) else -> throw IllegalArgumentException("Unknown opponent: $opponent") } "Z" -> when (opponent) { "A" -> Pair("B", 6) "B" -> Pair("C", 6) "C" -> Pair("A", 6) else -> throw IllegalArgumentException("Unknown opponent: $opponent") } else -> throw IllegalArgumentException("Unknown goal: $goal") } val symbolValue = when (ownSymbol) { "A" -> 1 "B" -> 2 "C" -> 3 else -> throw IllegalArgumentException("Unknown symbol: $ownSymbol") } symbolValue + winBonus } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day02_test") check(part1(testInput) == 15) check(part2(testInput) == 12) val input = readInput("Day02") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
5452702e4e20ef2db3adc8112427c0229ebd1c29
2,860
aoc-2022
Apache License 2.0
src/main/kotlin/se/saidaspen/aoc/aoc2018/Day09.kt
saidaspen
354,930,478
false
{"Kotlin": 301372, "CSS": 530}
package se.saidaspen.aoc.aoc2018 import se.saidaspen.aoc.util.* fun main() = Day09.run() object Day09 : Day(2018, 9) { override fun part1() : Any = play(ints(input)[0] * 1L, ints(input)[1] * 1L) override fun part2(): Any = play(ints(input)[0] * 1L, ints(input)[1] * 100L) private fun play(numPlayers: Long, highestNum: Long): Long { val marbles = mutableMapOf<Long, P<Long, Long>?>() val scores = mutableMapOf<Long, Long>().withDefault { 0 } var current = 1L var nextMarble = 1L var currentPlayer = 1L marbles[0] = null while (true) { when { nextMarble == 1L -> { marbles[0] = P(1, 1) marbles[1] = P(0, 0) current = nextMarble } nextMarble % 23L == 0L -> { val fiveCCw = moveCCw(marbles, current, 5) val sixCCw = moveCCw(marbles, current, 6) val sevenCcw = moveCCw(marbles, current, 7) val eightCcw = moveCCw(marbles, current, 8) scores[currentPlayer] = scores.getValue(currentPlayer) + nextMarble + sevenCcw marbles[eightCcw] = P(marbles[eightCcw]!!.first, sixCCw) marbles[sixCCw] = P(eightCcw, fiveCCw) current = sixCCw } else -> { val oneCw = moveCw(marbles, current, 1) val twoCw = moveCw(marbles, current, 2) val threeCw = moveCw(marbles, current, 3) marbles[oneCw] = P(moveCCw(marbles, oneCw, 1), nextMarble) marbles[twoCw] = P(nextMarble, threeCw) marbles[nextMarble] = P(oneCw, twoCw) current = nextMarble } } nextMarble++ currentPlayer = if (currentPlayer == numPlayers) 1 else currentPlayer + 1 if (nextMarble > highestNum) break } return scores.values.maxOrNull()!! } private fun moveCw(marbles: MutableMap<Long, P<Long, Long>?>, current: Long, steps : Long): Long { var curr = current for (i in 0 until steps) curr = marbles[curr]!!.second return curr } private fun moveCCw(marbles: MutableMap<Long, P<Long, Long>?>, current: Long, steps : Long): Long { var curr = current for (i in 0 until steps) curr = marbles[curr]!!.first return curr } }
0
Kotlin
0
1
be120257fbce5eda9b51d3d7b63b121824c6e877
2,530
adventofkotlin
MIT License
src/test/kotlin/Day09.kt
christof-vollrath
317,635,262
false
null
import io.kotest.core.spec.style.FunSpec import io.kotest.matchers.shouldBe /* --- Day 9: Encoding Error --- See https://adventofcode.com/2020/day/9 */ fun List<Long>.checkProperty(preamble: Int): List<Long> { fun checkNumber(nr: Long, numbersToCheck: Set<Long>): Boolean { numbersToCheck.forEach { numberToCheck -> val diff = nr - numberToCheck if (diff != numberToCheck) { if (numbersToCheck.contains(diff)) return true } } return false } return sequence { for (i in preamble until size) { val numbersToCheck = drop(i-preamble).take(preamble).toSet() val number = get(i) if (! checkNumber(number, numbersToCheck)) yield(number) } }.toList() } fun List<Long>.findWeakness(wrongNumber: Long): Set<Long> { fun checkContiguousSet(from: Int): Set<Long>? { var sum = 0L val contiguousSet = sequence { for (i in from until size) { if (sum >= wrongNumber) break val current = get(i) yield(current) sum += current } }.toSet() return if (sum == wrongNumber) contiguousSet else null } for(from in 0 until size-1) { val contiguousSet = checkContiguousSet(from) if (contiguousSet != null) return contiguousSet } throw IllegalArgumentException("no solution found") } fun parseNumbers(numbersString: String): List<Long> = numbersString.split("\n").map{ it.toLong() } val numbersString = """ 35 20 15 25 47 40 62 55 65 95 102 117 150 182 127 219 299 277 309 576 """.trimIndent() class Day09_Part1 : FunSpec({ val numbers = parseNumbers(numbersString) context("parse numbers") { test("numbers parsed correctly") { numbers.size shouldBe 20 } } context("check numbers which have not this property") { val exampleSolution = numbers.checkProperty(5) exampleSolution shouldBe setOf(127) } }) class Day09_Part1_Exercise: FunSpec({ val input = readResource("day09Input.txt")!! val numbers = parseNumbers(input) val result = numbers.checkProperty(25) test("solution") { result.first() shouldBe 1721308972L } }) class Day09_Part2 : FunSpec({ val numbers = parseNumbers(numbersString) context("find weakness") { val wrongNumber = numbers.checkProperty(5).first() val weakness = numbers.findWeakness(wrongNumber) weakness.minOrNull() shouldBe 15 weakness.maxOrNull() shouldBe 47 } }) class Day09_Part2_Exercise : FunSpec({ val input = readResource("day09Input.txt")!! val numbers = parseNumbers(input) val wrongNumber = numbers.checkProperty(25).first() val weakness = numbers.findWeakness(wrongNumber) val min = weakness.minOrNull()!! val max = weakness.maxOrNull()!! val solution = min + max test("solution") { solution shouldBe 209694133L } })
1
Kotlin
0
0
8ad08350aa4bd1a29b7e18765fc7a2d6de8021e8
3,189
advent_of_code_2020
Apache License 2.0
2022/12/12.kt
LiquidFun
435,683,748
false
{"Kotlin": 40554, "Python": 35985, "Julia": 29455, "Rust": 20622, "C++": 1965, "Shell": 1268, "APL": 191}
fun bfs(field: List<String>, queue: MutableList<Pair<Int, Int>>, target: Pair<Int, Int>): Int { val dist = queue.associate { it to 0 }.toMutableMap() val dirs = listOf(-1 to 0, 1 to 0, 0 to 1, 0 to -1) while (!queue.isEmpty()) { val (y, x) = queue.removeFirst() dirs .map { (ya, xa) -> Pair(y+ya, x+xa) } .filter { (ya, xa) -> ya in field.indices && xa in field[0].indices } .filter { !dist.contains(it) } .filter { (ya, xa) -> field[ya][xa] <= field[y][x] + 1 } .forEach { dist[it] = dist[Pair(y, x)]!! + 1 queue.add(it) } } return dist[target]!! } fun main() { var field = generateSequence(::readlnOrNull).toList() fun findChars(c: Char) = field .mapIndexed { y, l -> l.mapIndexed { x, _ -> y to x } } .flatten() .filter { (y, x) -> field[y][x] == c } .toMutableList() val S = findChars('S') val E = findChars('E').first() field = field.map { it.replace("S", "a").replace("E", "z") } println(bfs(field, S, E)) println(bfs(field, findChars('a'), E)) }
0
Kotlin
7
43
7cd5a97d142780b8b33b93ef2bc0d9e54536c99f
1,155
adventofcode
Apache License 2.0
year2023/day02/part2/src/main/kotlin/com/curtislb/adventofcode/year2023/day02/part2/Year2023Day02Part2.kt
curtislb
226,797,689
false
{"Kotlin": 2146738}
/* --- Part Two --- The Elf says they've stopped producing snow because they aren't getting any water! He isn't sure why the water stopped; however, he can show you how to get to the water source to check it out for yourself. It's just up ahead! As you continue your walk, the Elf poses a second question: in each game you played, what is the fewest number of cubes of each color that could have been in the bag to make the game possible? Again consider the example games from earlier: ``` 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 ``` - In game 1, the game could have been played with as few as 4 red, 2 green, and 6 blue cubes. If any color had even one fewer cube, the game would have been impossible. - Game 2 could have been played with a minimum of 1 red, 3 green, and 4 blue cubes. - Game 3 must have been played with at least 20 red, 13 green, and 6 blue cubes. - Game 4 required at least 14 red, 3 green, and 15 blue cubes. - Game 5 needed no fewer than 6 red, 3 green, and 2 blue cubes in the bag. The power of a set of cubes is equal to the numbers of red, green, and blue cubes multiplied together. The power of the minimum set of cubes in game 1 is 48. In games 2-5 it was 12, 1560, 630, and 36, respectively. Adding up these five powers produces the sum 2286. For each game, find the minimum set of cubes that must have been present. What is the sum of the power of these sets? */ package com.curtislb.adventofcode.year2023.day02.part2 import com.curtislb.adventofcode.common.io.mapLines import com.curtislb.adventofcode.common.number.product import com.curtislb.adventofcode.year2023.day02.cubes.CubeGame import java.nio.file.Path import java.nio.file.Paths /** * Returns the solution to the puzzle for 2023, day 2, part 2. * * @param inputPath The path to the input file for this puzzle. */ fun solve(inputPath: Path = Paths.get("..", "input", "input.txt")): Long { val games = inputPath.toFile().mapLines { CubeGame.fromString(it) } return games.sumOf { it.findMinPossibleColorCounts().counts.product() } } fun main() { println(solve()) }
0
Kotlin
1
1
6b64c9eb181fab97bc518ac78e14cd586d64499e
2,364
AdventOfCode
MIT License
src/main/kotlin/14/14.kt
Wrent
225,133,563
false
null
import java.math.BigInteger import java.math.RoundingMode import kotlin.math.ceil import kotlin.math.roundToLong fun main() { val chemicals = mutableMapOf<String, Chemical>() chemicals.put("ORE", Chemical("ORE")) INPUT14.split("\n") .forEach { reaction -> val (inputs, output) = reaction.split(" => ") val from = inputs.split(", ") .map { parseChemical(it) } .map { (quantity, name) -> chemicals.putIfAbsent(name, Chemical(name)) Pair(quantity, chemicals[name]!!) } val (quantity, name) = parseChemical(output) chemicals.put(name, Chemical(name, quantity, from)) } println("first result") run { val required = mutableMapOf<String, Long>() required["FUEL"] = 1 while (!required.isDone()) { val next = required.getNext(chemicals) required[next.first] = required[next.first]!! - chemicals[next.first]!!.quantity*next.second required.addAll(chemicals[next.first]!!.from, next.second) } val result = required["ORE"]!! println(result) } println("second result") // 1 -> 114125 // 2 -> 201368 // 3 -> 271463 // 100 -> 8325117 // 100 -> 8409208 // var prev = 0 // var diffs = mutableListOf<Int>() // for (j in 1 until 252 ) { val required = mutableMapOf<String, Long>() required["FUEL"] = 12039407 while (!required.isDone()) { val next = required.getNext(chemicals) required[next.first] = required[next.first]!! - (chemicals[next.first]!!.quantity*next.second) required.addAll(chemicals[next.first]!!.from, next.second) } val result = required["ORE"]!! println(result) // println("diff ${result - prev}, result $result") // diffs.add(result - prev) // prev = result // } // val avgDiff = diffs.average() // println("1000000000000".toBigDecimal().divide(avgDiff.toBigDecimal(), 20, RoundingMode.HALF_UP)) } private fun MutableMap<String, Long>.addAll(from: List<Pair<Long, Chemical>>, amount: Long) { from.forEach { if (this[it.second.name] == null) { this.put(it.second.name, it.first*amount) } else { this[it.second.name] = this[it.second.name]!! + (it.first*amount) } } } private fun MutableMap<String, Long>.isDone(): Boolean { return this .filter { it.key != "ORE" } .filter { it.value > 0 } .count() == 0 } private fun MutableMap<String, Long>.getNext(chemicals: Map<String, Chemical>): Pair<String, Long> { val next = this .filter { it.key != "ORE" } .filter { it.value > 0 } .entries .first() val chemical = chemicals[next.key]!! return Pair(next.key, ceil(next.value.toDouble() / chemical.quantity).toLong()) } fun parseChemical(chemical: String): Pair<Long, String> { val (quantity, name) = chemical.split(" ") return Pair(quantity.toLong(), name) } data class Chemical(val name: String, val quantity: Long = 0, val from: List<Pair<Long, Chemical>> = mutableListOf()) const val TEST141 = """10 ORE => 10 A 1 ORE => 1 B 7 A, 1 B => 1 C 7 A, 1 C => 1 D 7 A, 1 D => 1 E 7 A, 1 E => 1 FUEL""" const val TEST142 = """9 ORE => 2 A 8 ORE => 3 B 7 ORE => 5 C 3 A, 4 B => 1 AB 5 B, 7 C => 1 BC 4 C, 1 A => 1 CA 2 AB, 3 BC, 4 CA => 1 FUEL""" const val TEST143 = """157 ORE => 5 NZVS 165 ORE => 6 DCFZ 44 XJWVT, 5 KHKGT, 1 QDVJ, 29 NZVS, 9 GPVTF, 48 HKGWZ => 1 FUEL 12 HKGWZ, 1 GPVTF, 8 PSHF => 9 QDVJ 179 ORE => 7 PSHF 177 ORE => 5 HKGWZ 7 DCFZ, 7 PSHF => 2 XJWVT 165 ORE => 2 GPVTF 3 DCFZ, 7 NZVS, 5 HKGWZ, 10 PSHF => 8 KHKGT""" const val TEST144 = """2 VPVL, 7 FWMGM, 2 CXFTF, 11 MNCFX => 1 STKFG 17 NVRVD, 3 JNWZP => 8 VPVL 53 STKFG, 6 MNCFX, 46 VJHF, 81 HVMC, 68 CXFTF, 25 GNMV => 1 FUEL 22 VJHF, 37 MNCFX => 5 FWMGM 139 ORE => 4 NVRVD 144 ORE => 7 JNWZP 5 MNCFX, 7 RFSQX, 2 FWMGM, 2 VPVL, 19 CXFTF => 3 HVMC 5 VJHF, 7 MNCFX, 9 VPVL, 37 CXFTF => 6 GNMV 145 ORE => 6 MNCFX 1 NVRVD => 8 CXFTF 1 VJHF, 6 MNCFX => 4 RFSQX 176 ORE => 6 VJHF""" const val TEST145 = """171 ORE => 8 CNZTR 7 ZLQW, 3 BMBT, 9 XCVML, 26 XMNCP, 1 WPTQ, 2 MZWV, 1 RJRHP => 4 PLWSL 114 ORE => 4 BHXH 14 VRPVC => 6 BMBT 6 BHXH, 18 KTJDG, 12 WPTQ, 7 PLWSL, 31 FHTLT, 37 ZDVW => 1 FUEL 6 WPTQ, 2 BMBT, 8 ZLQW, 18 KTJDG, 1 XMNCP, 6 MZWV, 1 RJRHP => 6 FHTLT 15 XDBXC, 2 LTCX, 1 VRPVC => 6 ZLQW 13 WPTQ, 10 LTCX, 3 RJRHP, 14 XMNCP, 2 MZWV, 1 ZLQW => 1 ZDVW 5 BMBT => 4 WPTQ 189 ORE => 9 KTJDG 1 MZWV, 17 XDBXC, 3 XCVML => 2 XMNCP 12 VRPVC, 27 CNZTR => 2 XDBXC 15 KTJDG, 12 BHXH => 5 XCVML 3 BHXH, 2 VRPVC => 7 MZWV 121 ORE => 7 VRPVC 7 XCVML => 6 RJRHP 5 BHXH, 4 VRPVC => 5 LTCX""" const val INPUT14 = """1 JNDQ, 11 PHNC => 7 LBJSB 1 BFKR => 9 VGJG 11 VLXQL => 5 KSLFD 117 ORE => 6 DMSLX 2 VGJG, 23 MHQGW => 6 HLVR 2 QBJLJ => 6 DBJZ 1 CZDM, 21 ZVPJT, 1 HLVR => 5 VHGQP 1 RVKX => 1 FKMQD 38 PHNC, 10 MHQGW => 5 GMVJX 4 CZDM, 26 ZVHX => 7 QBGQB 5 LBJSB, 2 DFZRS => 4 QBJLJ 4 TJXZM, 11 DWXW, 14 VHGQP => 9 ZBHXN 20 VHGQP => 8 SLXQ 1 VQKM => 9 BDZBN 115 ORE => 4 BFKR 1 VGJG, 1 SCSXF => 5 PHNC 10 NXZXH, 7 ZFXP, 7 ZCBM, 7 MHNLM, 1 BDKZM, 3 VQKM => 5 RMZS 147 ORE => 2 WHRD 16 CQMKW, 8 BNJK => 5 MHNLM 1 HLVR => 5 TJQDC 9 GSLTP, 15 PHNC => 5 SFZTF 2 MJCD, 2 RVKX, 4 TJXZM => 1 MTJSD 1 DBJZ, 3 SLXQ, 1 GMSB => 9 MGXS 1 WZFK => 8 XCMX 1 DFZRS => 9 GSLTP 17 PWGXR => 2 DFZRS 4 BFKR => 7 JNDQ 2 VKHN, 1 SFZTF, 2 PWGXR => 4 JDBS 2 ZVPJT, 1 PHNC => 6 VQKM 18 GMSB, 2 MGXS, 5 CQMKW => 3 XGPXN 4 JWCH => 3 BNJK 1 BFKR => 2 PWGXR 12 PHNC => 2 GMSB 5 XGPXN, 3 VQKM, 4 QBJLJ => 9 GXJBW 4 MHQGW => 9 DWXW 1 GMSB, 1 BFKR => 5 DBKC 1 VLXQL, 10 KSLFD, 3 JWCH, 7 DBKC, 1 MTJSD, 2 WZFK => 9 GMZB 4 JDBS => 8 BRNWZ 2 ZBHXN => 7 HMNRT 4 LBJSB => 7 BCXGX 4 MTJSD, 1 SFZTF => 8 ZCBM 12 BRNWZ, 4 TJXZM, 1 ZBHXN => 7 WZFK 10 HLVR, 5 LBJSB, 1 VKHN => 9 TJXZM 10 BRNWZ, 1 MTJSD => 6 CMKW 7 ZWHT => 7 VKHN 5 CQMKW, 2 DBKC => 6 ZFXP 1 CMKW, 5 JNDQ, 12 FKMQD, 72 BXZP, 28 GMVJX, 15 BDZBN, 8 GMZB, 8 RMZS, 9 QRPQB, 7 ZVHX => 1 FUEL 10 MGXS => 9 JWCH 1 BFKR => 8 SCSXF 4 SFZTF, 13 CZDM => 3 RVKX 1 JDBS, 1 SFZTF => 9 TSWV 2 GMVJX, 1 PHNC => 1 CZDM 6 JDBS => 1 BXZP 9 TSWV, 5 TJXZM => 8 NXZXH 1 HMNRT, 5 TSWV => 4 VLXQL 16 WZFK, 11 XCMX, 1 GXJBW, 16 NXZXH, 1 QBGQB, 1 ZCBM, 10 JWCH => 3 QRPQB 12 SCSXF, 6 VGJG => 4 ZVPJT 10 JNDQ => 3 ZWHT 1 DBJZ, 9 BCXGX => 2 CQMKW 1 WHRD, 14 DMSLX => 8 MHQGW 3 VKHN, 8 TJQDC => 4 MJCD 1 QBJLJ => 4 ZVHX 1 MHQGW, 4 ZVHX => 3 BDKZM"""
0
Kotlin
0
0
0a783ed8b137c31cd0ce2e56e451c6777465af5d
6,507
advent-of-code-2019
MIT License
src/benchmark/BenchmarkUtils.kt
aaronoe
186,243,764
false
null
package de.aaronoe.benchmark import de.aaronoe.models.Seminar import de.aaronoe.models.Student import java.io.StringWriter private const val PREFIX_META_DATA = 'd' private const val PREFIX_SEMINAR = 't' private const val PREFIX_STUDENT = 's' enum class PopularityResult { MORE, EQUAL, LESS } fun Pair<List<Student>, List<Seminar>>.deepCopy(): Pair<List<Student>, List<Seminar>> { val seminarMap = this.second.map { it.copy() }.associateBy { it.id } val students = this.first.map { it.copy(preferences = it.preferences.map { seminarMap.get(it.id)!! }) } val seminars = seminarMap.values.toList() return students to seminars } fun formatDataToInput(students: List<Student>, seminars: List<Seminar>) = with(StringWriter()) { var id = 0 val seminarIdMap = seminars.associateBy({ it.id }, { id++ }) appendln("$PREFIX_META_DATA ${seminars.size} ${students.size}") seminars.forEachIndexed { index, seminar -> appendln("$PREFIX_SEMINAR $index ${seminar.capacity}") } students.forEachIndexed { index, student -> append("$PREFIX_STUDENT $index ${student.preferences.size}") student.preferences.forEach { seminar -> val mappedId = seminarIdMap.getValue(seminar.id) append(" $mappedId") } appendln() } toString() } infix fun Result.isMorePopularThan(other: Result): PopularityResult { val first = matching.getPreferenceIndexMap() val second = other.matching.getPreferenceIndexMap() val allStudents = first.entries.map { it.key }.union(second.entries.map { it.key }) val comparisons = allStudents.map { val firstIndex = first[it] ?: Int.MAX_VALUE val secondIndex = second[it] ?: Int.MAX_VALUE firstIndex.compareTo(secondIndex) }.groupBy { it } val greater = comparisons[1]?.size ?: 0 val smaller = comparisons[-1]?.size ?: 0 return when { greater < smaller -> PopularityResult.MORE greater > smaller -> PopularityResult.LESS else -> PopularityResult.EQUAL } } private fun Map<Seminar, List<Student>>.getPreferenceIndexMap(): Map<Student, Int> { return flatMap { (seminar, students) -> students.map { student -> student to student.preferences.indexOf(seminar) } }.toMap() }
0
Kotlin
0
1
8265e6553aca23c3bf2c5236ba56d46ab7e2b3f3
2,295
matching_server
MIT License
src/main/kotlin/_2022/Day15.kt
novikmisha
572,840,526
false
{"Kotlin": 145780}
package _2022 import readInput import java.math.BigInteger import kotlin.math.abs fun main() { fun printMap(map: Map<Pair<Int, Int>, _2022.BeaconItem>) { val minX = map.keys.minBy { it.first }.first - 1 val maxX = map.keys.maxBy { it.first }.first + 1 val minY = 0 val maxY = map.keys.maxBy { it.second }.second + 1 for (y in minY..maxY) { for (x in minX..maxX) { print(map.getOrDefault(Pair(x, y), _2022.BeaconItem.AIR).mapChar) } println() } } fun getCoordinates(str: String): Pair<Int, Int> { val cuttedStr = str.replace("Sensor at ", "") .replace("closest beacon is at", "") .trim() val (x, y) = cuttedStr.split(",") .map { it.replace("x=", "") .replace("y=", "") .trim() .toInt() } return Pair(x, y) } fun getDistance(firstCord: Pair<Int, Int>, secondCord: Pair<Int, Int>) = abs(firstCord.first - secondCord.first) + abs(firstCord.second - secondCord.second) fun part1(input: List<String>, yRow: Int): Int { val beaconMap = mutableMapOf<Pair<Int, Int>, _2022.BeaconItem>() val scannedMap = mutableMapOf<Pair<Int, Int>, Int>() val sensors = mutableMapOf<Pair<Int, Int>, Int>() input.forEach { val (sensor, beacon) = it.split(":") val sensorCoord = getCoordinates(sensor) val beaconCoord = getCoordinates(beacon) val distance = getDistance(sensorCoord, beaconCoord) sensors[sensorCoord] = distance beaconMap[sensorCoord] = _2022.BeaconItem.SENSOR beaconMap[beaconCoord] = _2022.BeaconItem.BEACON } val minBy = sensors.minBy { it.key.first - it.value } val minX = minBy.key.first - minBy.value val maxBy = sensors.maxBy { it.key.first + it.value } val maxX = maxBy.key.first + maxBy.value var counter = 0 for (i in minX..maxX) { val coord = Pair(i, yRow) if (beaconMap.getOrDefault(coord, _2022.BeaconItem.AIR) == _2022.BeaconItem.BEACON) { continue } val closeSensors = sensors.any { val distance = getDistance(it.key, coord) distance <= it.value } if (closeSensors) { counter++ } } // printMap(beaconMap) return counter } fun part2(input: List<String>, maxCoord: Int): BigInteger? { val beaconMap = mutableMapOf<Pair<Int, Int>, _2022.BeaconItem>() val scannedMap = mutableMapOf<Pair<Int, Int>, Int>() val sensors = mutableMapOf<Pair<Int, Int>, Int>() input.forEach { val (sensor, beacon) = it.split(":") val sensorCoord = getCoordinates(sensor) val beaconCoord = getCoordinates(beacon) val distance = getDistance(sensorCoord, beaconCoord) sensors[sensorCoord] = distance beaconMap[sensorCoord] = _2022.BeaconItem.SENSOR beaconMap[beaconCoord] = _2022.BeaconItem.BEACON } val maxX = maxCoord val maxY = maxCoord for (sensor in sensors) { val pointsToCheck = mutableSetOf<Pair<Int, Int>>() (sensor.key.first..(sensor.key.first + sensor.value + 1)) .zip((sensor.key.second - sensor.value - 1)..sensor.key.second) .forEach { if ((0..maxX).contains(it.first) && (0..maxY).contains(it.second)) { pointsToCheck.add(it) } } ((sensor.key.first + sensor.value + 1) downTo sensor.key.first) .zip(sensor.key.second..(sensor.key.second + sensor.value + 1)) .forEach { if ((0..maxX).contains(it.first) && (0..maxY).contains(it.second)) { pointsToCheck.add(it) } } (sensor.key.first downTo (sensor.key.first - sensor.key.second - 1)) .zip((sensor.key.second + sensor.value + 1) downTo sensor.key.second) .forEach { if ((0..maxX).contains(it.first) && (0..maxY).contains(it.second)) { pointsToCheck.add(it) } } ((sensor.key.first - sensor.key.second - 1)..sensor.key.first) .zip(sensor.key.second downTo (sensor.key.second - sensor.value - 1)) .forEach { if ((0..maxX).contains(it.first) && (0..maxY).contains(it.second)) { pointsToCheck.add(it) } } for (coord in pointsToCheck) { if (beaconMap.getOrDefault(coord, _2022.BeaconItem.AIR) == _2022.BeaconItem.BEACON) { continue } val closeSensors = sensors.all { val distance = getDistance(it.key, coord) distance > it.value } if (closeSensors) { return coord.first.toBigInteger().multiply(4000000.toBigInteger()).plus(coord.second.toBigInteger()) } } } return BigInteger.ZERO } // test if implementation meets criteria from the description, like: val testInput = readInput("Day15_test") println(part1(testInput, 10)) println(part2(testInput, 20)) val input = readInput("Day15") println(part1(input, 2000000)) println(part2(input, 4000000)) } enum class BeaconItem(val mapChar: Char) { BEACON('B'), SENSOR('S'), AIR('.') }
0
Kotlin
0
0
0c78596d46f3a8bf977bf356019ea9940ee04c88
5,837
advent-of-code
Apache License 2.0
y2023/src/main/kotlin/adventofcode/y2023/Day18.kt
Ruud-Wiegers
434,225,587
false
{"Kotlin": 503769}
package adventofcode.y2023 import adventofcode.io.AdventSolution import adventofcode.util.vector.Direction import adventofcode.util.vector.Direction.* import kotlin.math.absoluteValue fun main() { Day18.solve() } object Day18 : AdventSolution(2023, 18, "<NAME>") { override fun solvePartOne(input: String) = parse(input).let(::area) override fun solvePartTwo(input: String) = parseHex(input).let(::area) private fun area(lines: List<Pair<Direction, Long>>): Long { var x = 0L var area = 0L for ((direction, length) in lines) { when (direction) { UP -> area += x * length DOWN -> area -= x * length RIGHT -> x += length LEFT -> x -= length } } val halfPerimeter = lines.sumOf { it.second } / 2L + 1L return area.absoluteValue + halfPerimeter } } private fun parse(input: String) = input.lines().map { val (dir, len) = it.split(" ") val direction = when (dir) { "R" -> RIGHT "D" -> DOWN "L" -> LEFT "U" -> UP else -> error("direction") } Pair(direction, len.toLong()) } private fun parseHex(input: String) = input.lines().map { val dir = it.takeLast(2).first() val len = it.takeLast(7).dropLast(2) val direction = when (dir) { '0' -> RIGHT '1' -> DOWN '2' -> LEFT '3' -> UP else -> error("direction") } Pair(direction, len.toLong(16)) }
0
Kotlin
0
3
fc35e6d5feeabdc18c86aba428abcf23d880c450
1,530
advent-of-code
MIT License
src/main/kotlin/com/manalili/advent/Day04.kt
maines-pet
162,116,190
false
null
package com.manalili.advent class Day04(private val logs: List<String>){ private var guardList: List<Guard> = listOf() get(){ val guardIdPattern = Regex("""\[(\d{4}-\d{2}-\d{2} \d{2}:\d{2})] Guard #(\d+) begins shift""") val isSleepingPattern = Regex("""\[(\d{4}-\d{2}-\d{2} \d{2}:)(\d{2})] falls asleep""") val isAwakePattern = Regex("""\[(\d{4}-\d{2}-\d{2} \d{2}:)(\d{2})] wakes up""") val guardList = mutableListOf<Guard>() val sortedLogs = logs.sorted() var guard = Guard() for (i in sortedLogs.indices) { val event = sortedLogs[i] when { event.contains("begins shift") -> { if (guard.id != null) { guardList.add(guard) } val id = guardIdPattern.find(event)!!.destructured.component2() guard = Guard(id.toInt()) } event.contains("falls asleep") -> { val sleep = isSleepingPattern.find(event)!!.destructured.component2() guard.minutesAsleep.add(sleep.toInt()) } event.contains("wakes up")-> { val awake = isAwakePattern.find(event)!!.destructured.component2() guard.minutesAwake.add(awake.toInt()) } } if (i == (sortedLogs.size - 1)) guardList.add(guard) } return guardList } fun part01() : Int{ //Get sleepiest guard by total duration asleep val sleepyGuard = guardList.groupingBy { it.id }.aggregate { _, acc: Int?, elem, _ -> (acc ?: 0) + elem.totalMinutesAsleep }.maxBy { it.value }?.key return mostAsleepMinuteMark(guardList.filter { it.id == sleepyGuard } ).first * sleepyGuard!! } fun part02(): Int{ val result = guardList.filter { it.minutesAsleep.isNotEmpty() || it.minutesAwake.isNotEmpty() } .groupBy { it.id } .map { (key, value) -> val (minuteMark, frequency) = mostAsleepMinuteMark(value) Triple(key, minuteMark, frequency) } .maxBy { it.third} return result!!.first!! * result.second } } fun mostAsleepMinuteMark(list: List<Guard>): Pair<Int, Int>{ val asleep = list.flatMap { it.rangeAsleep }.groupingBy { it } .eachCount() .maxBy { it.value } return asleep!!.key to asleep.value } data class Guard( var id: Int? = null, var minutesAsleep: MutableList<Int> = mutableListOf(), var minutesAwake: MutableList<Int> = mutableListOf() ) { val totalMinutesAsleep: Int get() = minutesAwake.sum() - minutesAsleep.sum() val rangeAsleep: List<Int> get() { val minutesMark = mutableListOf<Int>() for (i in minutesAsleep.indices){ minutesMark.addAll((minutesAsleep[i] until minutesAwake[i]).map { it }) } return minutesMark } }
0
Kotlin
0
0
25a01e13b0e3374c4abb6d00cd9b8d7873ea6c25
3,255
adventOfCode2018
MIT License
src/day02/Task.kt
dniHze
433,447,720
false
{"Kotlin": 35403}
package day02 import readInput fun main() { val input = readInput("day02") println(solvePartOne(input)) println(solvePartTwo(input)) } fun solvePartOne(input: List<String>) = input.solveWithAim(aim = false) fun solvePartTwo(input: List<String>) = input.solveWithAim(aim = true) private fun List<String>.solveWithAim(aim: Boolean): Int = toCommandList() .fold(Point(0, 0, 0)) { point, command -> command(point, aim) } .let { (x, y) -> x * y } private fun List<String>.toCommandList() = map { value -> value.split(' ').run { get(0) to get(1).toInt() } }.map { (direction, value) -> when (direction) { "forward" -> horizontalCommand(value) "up" -> verticalCommand(-value) "down" -> verticalCommand(value) else -> noneCommand } } data class Point( val x: Int, val y: Int, val aim: Int, ) private typealias Command = (value: Point, aim: Boolean) -> Point private val noneCommand: Command = { value, _ -> value } private fun horizontalCommand(delta: Int): Command = { point, aim -> if (aim) { point.copy( x = point.x + delta, y = point.y + point.aim * delta, ) } else { point.copy(x = point.x + delta) } } private fun verticalCommand(delta: Int): Command = { point, aim -> if (aim) { point.copy(aim = point.aim + delta) } else { point.copy(y = point.y + delta) } }
0
Kotlin
0
1
f81794bd57abf513d129e63787bdf2a7a21fa0d3
1,446
aoc-2021
Apache License 2.0
src/main/kotlin/com/colinodell/advent2021/Day24.kt
colinodell
433,864,377
true
{"Kotlin": 111114}
package com.colinodell.advent2021 class Day24(input: List<String>) { private val blockVariables = input // Every chunk of 18 lines is an almost-identical block, but with three small differences, so let's capture those .chunked(18) .map { it.joinToString("") } .map { Regex("-?\\d+").findAll(it).map { it.value.toInt() }.toList() } .map { listOf(it[2], it[3], it[9]).map(Int::toLong) } // Extract some useful information from the input program private val numberOfDigits = blockVariables.size private val divZ = blockVariables.map { it[0] } private val addX = blockVariables.map { it[1] } private val addY = blockVariables.map { it[2] } private val maxZAtEachDigit = divZ.indices.map { i -> divZ.drop(i).reduce { a, b -> a * b } } // Use a cache to prevent unnecessary repeated calculations private val cache = mutableMapOf<Pair<Int, Long>, List<String>>() // Special non-null return value that doesn't interfere with string concatenation private val success = listOf("") // Find and store all valid model numbers private val validModelNumbers: List<String> = findValidModelNumbers(0, 0)!!.sorted() fun solvePart1() = validModelNumbers.last() // Highest valid model number fun solvePart2() = validModelNumbers.first() // Lowest valid model number private fun findValidModelNumbers(digit: Int, lastZ: Long): List<String>? { // Have we already calculated this? if (cache.containsKey(Pair(digit, lastZ))) { return cache[Pair(digit, lastZ)] } // If we've generated all the digits, check if the result is valid if (digit >= numberOfDigits) { // Valid model numbers must have a Z value of 0 return if (lastZ == 0L) success else null } // If we can't divide by Z any further, there's no point in recursing any deeper if (lastZ > maxZAtEachDigit[digit]) { return null } val nextX = addX[digit] + lastZ % 26 // If nextX is a valid digit, use that to generate the next digit; otherwise, try all digits 1-9 val candidates = if (nextX in 1..9) listOf(nextX) else (1L..9L) val result = candidates.flatMap { c -> findValidModelNumbers(digit + 1, calculateNextZ(digit, lastZ, c)).mapIfNotNull { "$c$it" } } return result.also { cache[Pair(digit, lastZ)] = it } } private fun calculateNextZ(digit: Int, lastZ: Long, nextX: Long): Long { val nextZ = lastZ / divZ[digit] val x = addX[digit] + lastZ % 26 return if (x == nextX) nextZ else nextZ * 26 + nextX + addY[digit] } }
0
Kotlin
0
1
a1e04207c53adfcc194c85894765195bf147be7a
2,689
advent-2021
Apache License 2.0
src/Day14.kt
Riari
574,587,661
false
{"Kotlin": 83546, "Python": 1054}
fun main() { data class Tile(val x: Int, val y: Int) data class Slice(val tiles: Array<CharArray>, var deepestRock: Int = 0) { fun copyOf(): Slice { return Slice(tiles.map { it.copyOf() }.toTypedArray(), deepestRock) } } fun processInput(input: List<String>): Slice { val slice = Slice(Array(1000) { CharArray(1000) { '.' } }) for (line in input) { val path = line.split(" -> ") .map { it.split(',') } .map { Tile(it[0].toInt(), it[1].toInt()) } .windowed(2, 1) for ((a, b) in path) { for (y in minOf(a.y, b.y)..maxOf(a.y, b.y)) { for (x in minOf(a.x, b.x)..maxOf(a.x, b.x)) { slice.tiles[y][x] = '#' } } if (a.y > slice.deepestRock) slice.deepestRock = a.y else if (b.y > slice.deepestRock) slice.deepestRock = b.y } } return slice } // Simulates sand falling until it falls into the abyss (part 1) or blocks the source (part 2) fun simulate(slice: Slice): Int { var settled = 0 outer@ while (true) { var x = 500; var y = 0 if (slice.tiles[y][x] == 'o') break var hasSettled = false while (!hasSettled) { if (y > slice.deepestRock) break@outer if (slice.tiles.getOrNull(y + 1)?.get(x) == '.') { y++ } else if (slice.tiles.getOrNull(y + 1)?.getOrNull(x - 1) == '.') { x--; y++ } else if (slice.tiles.getOrNull(y + 1)?.getOrNull(x + 1) == '.') { x++; y++ } else { hasSettled = true; settled++ slice.tiles[y][x] = 'o' } } } return settled } fun part1(slice: Slice): Int { return simulate(slice) } fun part2(slice: Slice): Int { // Add floor slice.deepestRock += 2 for (x in 0 until slice.tiles[slice.deepestRock].size) { slice.tiles[slice.deepestRock][x] = '#' } return simulate(slice) } val testInput = processInput(readInput("Day14_test")) check(part1(testInput.copyOf()) == 24) check(part2(testInput) == 93) val input = processInput(readInput("Day14")) println(part1(input.copyOf())) println(part2(input)) }
0
Kotlin
0
0
8eecfb5c0c160e26f3ef0e277e48cb7fe86c903d
2,514
aoc-2022
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/CountSubTrees.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2023 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import dev.shtanko.algorithms.ALPHABET_LETTERS_COUNT /** * 1519. Number of Nodes in the Sub-Tree With the Same Label * @see <a href="https://leetcode.com/problems/number-of-nodes-in-the-sub-tree-with-the-same-label/">Source</a> */ fun interface CountSubTrees { operator fun invoke(n: Int, edges: Array<IntArray>, labels: String): IntArray } class CountSubTreesDFS : CountSubTrees { override operator fun invoke(n: Int, edges: Array<IntArray>, labels: String): IntArray { val g: MutableMap<Int, MutableList<Int>> = HashMap() for (e in edges) { g.computeIfAbsent(e[0]) { ArrayList() }.add(e[1]) g.computeIfAbsent(e[1]) { ArrayList() }.add(e[0]) } val ans = IntArray(n) dfs(g, 0, -1, labels, ans) return ans } private fun dfs(g: Map<Int, List<Int>>, node: Int, parent: Int, labels: String, ans: IntArray): IntArray { val cnt = IntArray(ALPHABET_LETTERS_COUNT) val c = labels[node] for (child in g[node] ?: emptyList()) { if (child != parent) { val sub = dfs(g, child, node, labels, ans) for (i in 0 until ALPHABET_LETTERS_COUNT) { cnt[i] += sub[i] } } } ++cnt[c.code - 'a'.code] ans[node] = cnt[c.code - 'a'.code] return cnt } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
2,014
kotlab
Apache License 2.0
solutions/src/main/kotlin/de/thermondo/solutions/advent2022/day01/Part1Solution.kt
thermondo
552,876,124
false
{"Kotlin": 23756, "Makefile": 274}
package de.thermondo.solutions.advent2022.day01 import de.thermondo.utils.Exclude import de.thermondo.utils.stringFromFile /** * The jungle must be too overgrown and difficult to navigate in vehicles or access from the air; the Elves' expedition * traditionally goes on foot. As your boats approach land, the Elves begin taking inventory of their supplies. * One important consideration is food - in particular, the number of Calories each Elf is carrying (your puzzle input). * * The Elves take turns writing down the number of Calories contained by the various meals, snacks, rations, etc. that * they've brought with them, one item per line. Each Elf separates their own inventory from the previous Elf's * inventory (if any) by a blank line. * * For example, suppose the Elves finish writing their items' Calories and end up with the following list: * * 1000 * 2000 * 3000 * * 4000 * 5000 * 6000 * * 7000 * 8000 * 9000 * * 10000 * * This list represents the Calories of the food carried by five Elves: * - The first Elf is carrying food with 1000, 2000, and 3000 Calories, a total of 6000 Calories. * - The second Elf is carrying one food item with 4000 Calories. * - The third Elf is carrying food with 5000 and 6000 Calories, a total of 11000 Calories. * - The fourth Elf is carrying food with 7000, 8000, and 9000 Calories, a total of 24000 Calories. * - The fifth Elf is carrying one food item with 10000 Calories. * * In case the Elves get hungry and need extra snacks, they need to know which Elf to ask: they'd like to know how many * Calories are being carried by the Elf carrying the most Calories. In the example above, this is 24000 * (carried by the fourth Elf). * * Find the Elf carrying the most Calories. How many total Calories is that Elf carrying? */ @Exclude fun main() { val input = stringFromFile("/advent2022/InputDay01.txt") val calories = input?.let(::calculateCaloriesPartOne) println("The Elf is carrying $calories calories.") } fun calculateCaloriesPartOne(input: String): Int { val elves = input.split("\n\n") val calories = mutableListOf<Int>() for (elf in elves) { calories.add(elf.split("\n").sumOf { it.toInt() }) } calories.sortDescending() return calories.take(1).sum() }
6
Kotlin
1
0
ef413904ce4bbe82861776f2efe5efd43dd5dc99
2,307
lets-learn-kotlin
MIT License
src/algorithmdesignmanualbook/datastructures/SmallestNumberInRange.kt
realpacific
234,499,820
false
null
package algorithmdesignmanualbook.datastructures import _utils.UseCommentAsDocumentation import kotlin.test.assertTrue private typealias Table = Array<Array<Int?>> private interface SmallestNumberInRange { fun getSmallest(startIndex: Int, endIndex: Int): Int } /** * * Suppose that we are given a sequence of n values x1, x2, ..., xn and seek to * quickly answer repeated queries of the form: given i and j, find the smallest value * in xi, . . . , xj. * * Given arrays of integer [values] of size n, convert it into matrix M of nxn * such that M[i][j + 1] <= M[i][j] and anything before M[i][i] is null. M[i][i] holds the ith index item of [values] */ @UseCommentAsDocumentation class SmallestNumberInRangeMatrixApproach(private val values: Array<Int>) : SmallestNumberInRange { // O(n^2) initialization private val table: Table = Array(values.size) { row -> Array(values.size) { col -> if (col == row) { values[row] } else null } } // O(n^2) initialization init { for (i in 0..values.lastIndex) { for (j in i..values.lastIndex) { val compareValue = values[j] val previousValue = table.getOrNull(i)?.getOrNull(j - 1) ?: table[i][i]!! if (previousValue < compareValue) { table[i][j] = previousValue } else { table[i][j] = compareValue } } } table.forEach { row -> row.forEach { print(String.format("%6s", it)) } println() } } /** * O(1) search */ override fun getSmallest(startIndex: Int, endIndex: Int): Int { require(startIndex < table.size && endIndex < table.size && startIndex <= endIndex) return table[startIndex][endIndex]!! } } /** * Uses map with key as i#j */ class SmallestNumberInRangeHashMapApproach(private val values: Array<Int>) : SmallestNumberInRange { private val map = mutableMapOf<String, Int>() private fun get(startIndex: Int, endIndex: Int): Int? { return map["$startIndex#$endIndex"] } private fun set(startIndex: Int, endIndex: Int, value: Int) { map["$startIndex#$endIndex"] = value } init { for (i in 0..values.lastIndex) { for (j in i..values.lastIndex) { val currentValue = values[j] if (i == j) { set(i, i, currentValue) continue } val prevValue = get(i, j - 1) ?: get(i, i)!! if (prevValue < currentValue) { set(i, j, prevValue) } else { set(i, j, currentValue) } } } println(map) } /** * O(1) search */ override fun getSmallest(startIndex: Int, endIndex: Int): Int { require(startIndex <= endIndex && endIndex < values.size) return get(startIndex, endIndex)!! } } fun main() { val input = arrayOf(1, 2, 4, 0, 3) val matrixSolution = SmallestNumberInRangeMatrixApproach(input) val hashMapSolution = SmallestNumberInRangeHashMapApproach(input) listOf(matrixSolution, hashMapSolution).forEach { solution -> assertTrue { solution.getSmallest(0, 4) == 0 } assertTrue { solution.getSmallest(1, 4) == 0 } assertTrue { solution.getSmallest(2, 4) == 0 } assertTrue { solution.getSmallest(3, 4) == 0 } assertTrue { solution.getSmallest(4, 4) == 3 } assertTrue { solution.getSmallest(0, 2) == 1 } assertTrue { solution.getSmallest(1, 2) == 2 } assertTrue { solution.getSmallest(2, 2) == 4 } } }
4
Kotlin
5
93
22eef528ef1bea9b9831178b64ff2f5b1f61a51f
3,771
algorithms
MIT License
src/Day02.kt
becsegal
573,649,289
false
{"Kotlin": 9779}
import java.io.File fun main() { val notationToShape = mapOf( "A" to "Rock", "B" to "Paper", "C" to "Scissors", "X" to "Rock", "Y" to "Paper", "Z" to "Scissors" ) val shapePoints = mapOf( "Rock" to 1, "Paper" to 2, "Scissors" to 3 ) val winOver = mapOf( "A" to "B", // A-Rock loses to B-Paper "B" to "C", // B-Paper loses to C-Scissors "C" to "A" // C-Scissors loses to A-Rock ) val loseTo = mapOf( "A" to "C", // A-Rock beats C-Scissors "B" to "A", // B-Paper beats A-Rock "C" to "B" // C-Scissors beats B-Paper ) fun scoreRoundForPlayer(player: String?, opponent: String): Int { val playerShape = notationToShape[player]; val opponentShape = notationToShape[opponent]; var score: Int = shapePoints[playerShape] ?: 0; if (playerShape === opponentShape) { score += 3; } else if ( (playerShape == "Rock" && opponentShape == "Scissors") || (playerShape == "Paper" && opponentShape == "Rock") || (playerShape == "Scissors" && opponentShape == "Paper") ) { score += 6; } return score; } fun chooseShapeForResult(opponentNotation: String, result: String): String? { if (result == "Y") { // Draw return opponentNotation; } else if (result == "X") { // Lose return loseTo[opponentNotation]; } else { return winOver[opponentNotation]; } } fun part1(filename: String): Int? { var score: Int = 0; File(filename).forEachLine { val shapes = it.split(" "); score += scoreRoundForPlayer(shapes[1], shapes[0]) } return score; } fun part2(filename: String): Int? { var score: Int = 0; File(filename).forEachLine { val notation = it.split(" "); val playerShapeNotation = chooseShapeForResult(notation[0], notation[1]); score += scoreRoundForPlayer(playerShapeNotation, notation[0]) } return score; } println(part1("input_day02.txt")) println(part2("input_day02.txt")) }
0
Kotlin
0
0
a4b744a3e3c940c382aaa1d5f5c93ae0df124179
2,243
advent-of-code-2022
Apache License 2.0
src/main/kotlin/d16/d16.kt
LaurentJeanpierre1
573,454,829
false
{"Kotlin": 118105}
package d16 import readInput data class Valve(val name: String, val flow: Int, var next: List<String>) { override fun hashCode(): Int { return name.hashCode() } override fun equals(other: Any?): Boolean { return other is Valve && name == other.name } } val valves = mutableMapOf<String,Valve>() val visited = mutableSetOf<Valve>() var nbClosed = 0 data class Memory(val name: String, val time: Int) val best = mutableMapOf<Memory, Int>() data class Memory2(val nameM: String,val nameE: String, val time: Int) val best2 = mutableMapOf<Memory2, Int>() fun part1(input: List<String>): Int { readFile(input) for (valve in valves) { valve.value.next = valve.value.next.sortedWith { s1, s2 -> -valves[s1]!!.flow.compareTo(valves[s2]!!.flow) } } val start = valves["AA"]!! return maxFlow(start, 1, 0, 0) } fun maxFlow(start: Valve, time: Int, currentFlow: Int, totalReleased: Int): Int { if (time > 30) return totalReleased if (visited.size >= nbClosed) return totalReleased + (31-time)*currentFlow // All valves open if ((best[Memory(start.name, time)]?:0) > totalReleased) return totalReleased best[Memory(start.name, time)] = totalReleased var open=0 if (start.flow > 0 && start !in visited && time < 30) { visited.add(start) for (next in start.next) { val res = maxFlow(valves[next]!!, time + 2, currentFlow + start.flow, totalReleased+currentFlow*2+start.flow) if (res > open) open = res } //open = start.next.map{ maxFlow(valves[it]!!, time + 2, currentFlow + start.flow, totalReleased+currentFlow*2+start.flow)}.max() visited.remove(start) } //val closed = start.next.map{ maxFlow(valves[it]!!, time + 1, currentFlow, totalReleased+currentFlow)}.max() var closed = 0 for (next in start.next) { val res = maxFlow(valves[next]!!, time + 1, currentFlow, totalReleased+currentFlow) if (res > closed) closed = res } return Math.max(open, closed) } fun maxFlowElephant(start: Valve, elephant: Valve, time: Int, currentFlow: Int, totalReleased: Int, opening: Boolean, elephantOpening:Boolean): Int { var open=0 if (elephantOpening) { for (next in elephant.next) { var next1 = next val res = maxFlowMe(start, valves[next1]!!, time + 1, currentFlow, totalReleased+currentFlow, opening, false) if (res > open) open = res } return open } else { var shouldOpen = elephant.flow > 0 if (elephant.flow > 0 && elephant !in visited && time < 26) if (shouldOpen){ visited.add(elephant) open = maxFlowMe(start, elephant, time + 1, currentFlow + elephant.flow, totalReleased+currentFlow+ elephant.flow, opening, true) visited.remove(elephant) } var closed = 0 for (next in elephant.next) { var next1 = next val res = maxFlowMe(start, valves[next1]!!, time + 1, currentFlow, totalReleased+currentFlow, opening, false) if (res > closed) closed = res } return Math.max(open, closed) } } var topValue = 0 fun maxFlowMe(start: Valve, elephant: Valve, time: Int, currentFlow: Int, totalReleased: Int, opening: Boolean, elephantOpening:Boolean): Int { if (time > 26) { if (totalReleased > topValue) { topValue = totalReleased println("Current top is $topValue") } return totalReleased } if (visited.size >= nbClosed) { val value = totalReleased + (26 - time) * currentFlow if (value > topValue) { topValue = value println("Current top is $topValue") } return value // All valves open } if ((best2[Memory2(start.name, elephant.name, time)]?:0) > totalReleased) return totalReleased best2[Memory2(start.name, elephant.name, time)] = totalReleased best2[Memory2(elephant.name, start.name, time)] = totalReleased var open=0 if (opening) { for (next in start.next) { var next1 = next val res = maxFlowElephant(valves[next1]!!, elephant, time, currentFlow, totalReleased, false, elephantOpening) if (res > open) open = res } return open } else { var shouldOpen = start.flow > 0 if (start.flow > 0 && start !in visited && time < 26) if (shouldOpen) { visited.add(start) open = maxFlowElephant(start, elephant, time, currentFlow + start.flow, totalReleased, true, elephantOpening) visited.remove(start) } var closed = 0 for (next in start.next) { var next1 = next val res = maxFlowElephant(valves[next1]!!, elephant, time, currentFlow, totalReleased, false, elephantOpening) if (res > closed) closed = res } return Math.max(open, closed) } } fun readFile(input: List<String>) { val match = Regex("Valve ([A-Z]{2}) has flow rate=(\\d+); tunnels? leads? to valves? ([A-Z, ]+)") for (line in input) { val res = match.matchEntire(line)!!.groupValues val name = res[1] val flow = res[2].toInt() val next = res[3] println("$name ($flow) -> $next") val next2 = next.split(", ") val valve = Valve(name, flow, next2) valves[name] = valve if (flow>0) nbClosed++ } } fun part2(input: List<String>): Int { readFile(input) for (valve in valves) { valve.value.next = valve.value.next.sortedWith { s1, s2 -> -valves[s1]!!.flow.compareTo(valves[s2]!!.flow) } } val start = valves["AA"]!! return maxFlowMe(start, start, 1, 0, 0, false, false) } fun main() { //val input = readInput("d16/test") val input = readInput("d16/input1") //println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
5cf6b2142df6082ddd7d94f2dbde037f1fe0508f
6,046
aoc2022
Creative Commons Zero v1.0 Universal
src/main/kotlin/com/github/brpeterman/advent2022/Rucksacks.kt
brpeterman
573,059,778
false
{"Kotlin": 53108}
package com.github.brpeterman.advent2022 class Rucksacks { fun scoreMisfits(rucksacks: List<Pair<Set<String>, Set<String>>>): Int { return rucksacks.fold(0) { total, sack -> val misfit = sack.first.intersect(sack.second).first() total + score(misfit) } } fun scoreBadges(rucksacks: List<Pair<Set<String>, Set<String>>>): Int { return rucksacks.chunked(3) .fold(0) { total, group -> val badge = unify(group[0]) .intersect(unify(group[1])) .intersect(unify(group[2])) .first() total + score(badge) } } fun unify(rucksack: Pair<Set<String>, Set<String>>): Set<String> { return rucksack.first + rucksack.second } fun score(item: String): Int { if (item.matches("[a-z]".toRegex())) { return item[0].code - 96 } else if (item.matches("[A-Z]".toRegex())) { return item[0].code - 38 } return 0 } companion object { fun parseInput(input: String): List<Pair<Set<String>, Set<String>>> { return input.split("\n") .filter { it.isNotBlank() } .map { line -> val left = line.substring(0, (line.length/2)) val right = line.substring(line.length/2) Pair( left.split("").filter {it.isNotBlank()}.toSet(), right.split("").filter {it.isNotBlank()}.toSet()) } } } }
0
Kotlin
0
0
1407ca85490366645ae3ec86cfeeab25cbb4c585
1,603
advent2022
MIT License
src/main/kotlin/de/niemeyer/aoc2022/Day24.kt
stefanniemeyer
572,897,543
false
{"Kotlin": 175820, "Shell": 133}
/** * Advent of Code 2022, Day 24: <NAME> * Problem Description: https://adventofcode.com/2022/day/27 */ package de.niemeyer.aoc2022 import de.niemeyer.aoc.direction.DirectionCCS import de.niemeyer.aoc.direction.arrowToDirectionCCS import de.niemeyer.aoc.points.Point2D import de.niemeyer.aoc.utils.Resources.resourceAsList import de.niemeyer.aoc.utils.getClassName import de.niemeyer.aoc.utils.lcm fun main() { val name = getClassName() val testInput = resourceAsList(fileName = "${name}_test.txt") val puzzleInput = resourceAsList(fileName = "${name}.txt") check(Day24(testInput).part1() == 18) val puzzleResultPart1 = Day24(puzzleInput).part1() println(puzzleResultPart1) check(puzzleResultPart1 == 288) check(Day24(testInput).part2() == 54) val puzzleResultPart2 = Day24(puzzleInput).part2() println(puzzleResultPart2) check(puzzleResultPart2 == 861) } class Day24(val input: List<String>) { private val yMax = input.lastIndex private val xMax = input.first().lastIndex private val start = Point2D(input.first().indexOfFirst { it == '.' }, yMax) private val goal = Point2D(input.last().indexOfFirst { it == '.' }, 0) private val blizzardLoop = (yMax - 1).lcm(xMax - 1) private val steps = mutableMapOf( 0 to input.flatMapIndexed { y, line -> line.withIndex().filter { it.value in DirectionCCS.ARROWS } .map { (x, c) -> val p = Point2D(x, yMax - y) p to listOf(Blizzard(p, c.arrowToDirectionCCS())) } }.toMap() ) data class Blizzard(val pos: Point2D, val directionCCS: DirectionCCS) data class State(val step: Int, val position: Point2D) fun part1(): Int = solve(State(0, start), goal) fun part2() = listOf(start, goal, start, goal) .windowed(2) .fold(0) { step, (from, to) -> solve(State(step, from), to) } private fun solve(initialState: State, targetPosition: Point2D): Int { val seenStates = mutableMapOf<Point2D, MutableSet<Int>>() val possibleStates = ArrayDeque(setOf(initialState)) while (!possibleStates.isEmpty()) { val state = possibleStates.removeFirst() if (state.position == targetPosition) { return state.step - 1 } if (seenStates.getOrPut(state.position) { mutableSetOf() }.add(state.step % blizzardLoop)) { val nextBlizzards = steps.computeIfAbsent(state.step % blizzardLoop) { steps[state.step % blizzardLoop - 1]!!.values.flatMap { blizzards -> blizzards.map { blizzard -> blizzard.next().let { it.pos to it } } }.groupBy({ it.first }, { it.second }).toMap() } listOf(DirectionCCS.Down, DirectionCCS.Left, DirectionCCS.Up, DirectionCCS.Right) .map { dir -> state.position.move(dir) } .filter { (it.x in (1 until xMax) && it.y in (1 until yMax)) || it == start || it == goal } .plus(state.position) .filterNot { nextBlizzards.keys.contains(it) } // test if new position is occupied by blizzard .forEach { nextPosition -> possibleStates.addLast(State(state.step + 1, nextPosition)) } } } error("Solution not found") } fun Blizzard.next(): Blizzard { val nextPos = this.pos.move(directionCCS).let { if (it.x == 0) { it.copy(x = xMax - 1) } else if (it.y == 0) { it.copy(y = yMax - 1) } else if (it.x == xMax) { it.copy(x = 1) } else if (it.y == yMax) { it.copy(y = 1) } else { it } } return Blizzard(nextPos, directionCCS) } }
0
Kotlin
0
0
ed762a391d63d345df5d142aa623bff34b794511
3,986
AoC-2022
Apache License 2.0
src/Day5.kt
CyrilFind
573,965,299
false
{"Kotlin": 4160}
import java.util.Stack fun main() { val input = readInput("day5") val stacks = List(9) { Stack<String>() } val cratesRegex = """(?:\[(\w)\]| ( ) ) (?:\[(\w)\]| ( ) ) (?:\[(\w)\]| ( ) ) (?:\[(\w)\]| ( ) ) (?:\[(\w)\]| ( ) ) (?:\[(\w)\]| ( ) ) (?:\[(\w)\]| ( ) ) (?:\[(\w)\]| ( ) ) (?:\[(\w)\]| ( ) )""".toRegex() val moveRegex = """^move (\d+) from (\d+) to (\d+)""".toRegex() fun printStacks() { stacks.forEachIndexed { index, element -> println("${index + 1}: $element") } println("--------------------------------") } input.filter { it.matches(cratesRegex) }.map { cratesRegex.find(it)!!.destructured.toList() .mapIndexed { index, s -> if (index % 2 == 1) null else s } .filterNotNull() }.reversed().forEach { line -> line.forEachIndexed { index, element -> if (element.isNotEmpty()) stacks[index].add(element) } } println("init") printStacks() // part 1 // input.filter { it.matches(moveRegex) }.forEach { // val (quantity, origin, destination) = moveRegex.find(it)!!.destructured // repeat(quantity.toInt()) { // println("$origin -> $destination") // if (stacks[origin.toInt() - 1].isEmpty()) return@repeat // val toMove = stacks[origin.toInt() - 1].pop() // stacks[destination.toInt() - 1].push(toMove) // printStacks() // } // } // part 2 input.filter { it.matches(moveRegex) }.forEach { input -> val (quantity, origin, destination) = moveRegex.find(input)!!.destructured val toMove = mutableListOf<String>() repeat(quantity.toInt()) { println("$origin -> $destination") if (stacks[origin.toInt() - 1].isEmpty()) return@repeat toMove.add(stacks[origin.toInt() - 1].pop()) } toMove.reversed().forEach { stacks[destination.toInt() - 1].push(it) } printStacks() } stacks.forEach { print(if(it.isEmpty()) "-" else it.peek()) } }
0
Kotlin
0
0
eb673682474d09c8f8b166c9e44ae52d85a777c9
2,052
AoC2022
Apache License 2.0
src/main/kotlin/aoc2023/Day11.kt
lukellmann
574,273,843
false
{"Kotlin": 175166}
package aoc2023 import AoCDay import kotlin.math.abs // https://adventofcode.com/2023/day/11 object Day11 : AoCDay<Long>( title = "Cosmic Expansion", part1ExampleAnswer = 374, part1Answer = 9639160, part2Answer = 752936133304, ) { private data class Galaxy(val x: Long, val y: Long) private fun parseUniverse(image: String) = image .lineSequence() .withIndex() .flatMap { (y, line) -> line.withIndex().filter { (_, char) -> char == '#' }.map { (x, _) -> Galaxy(x.toLong(), y.toLong()) } } .toSet() private fun manhattanDistance(g1: Galaxy, g2: Galaxy) = abs(g1.x - g2.x) + abs(g1.y - g2.y) private fun getSumOfShortestPathLengths(image: String, expansion: Int): Long { val universe = parseUniverse(image) val emptyXs = (0..<universe.maxOf(Galaxy::x)).filter { x -> universe.none { it.x == x } } val emptyYs = (0..<universe.maxOf(Galaxy::y)).filter { y -> universe.none { it.y == y } } val expanded = universe.map { (x, y) -> val xExpansion = (expansion - 1) * emptyXs.count { it < x } val yExpansion = (expansion - 1) * emptyYs.count { it < y } Galaxy(x + xExpansion, y + yExpansion) } return expanded.withIndex().sumOf { (i, g1) -> expanded.take(i).sumOf { g2 -> manhattanDistance(g1, g2) } } } override fun part1(input: String) = getSumOfShortestPathLengths(image = input, expansion = 2) override fun part2(input: String) = getSumOfShortestPathLengths(image = input, expansion = 1_000_000) }
0
Kotlin
0
1
344c3d97896575393022c17e216afe86685a9344
1,581
advent-of-code-kotlin
MIT License
04/src/commonMain/kotlin/Main.kt
daphil19
725,415,769
false
{"Kotlin": 131380}
import kotlin.math.pow expect fun getLines(inputOrPath: String): List<String> fun main() { var lines = getLines(INPUT_FILE) // lines = ("Card 1: 41 48 83 86 17 | 83 86 6 31 17 9 48 53\n" + // "Card 2: 13 32 20 16 61 | 61 30 68 82 17 32 24 19\n" + // "Card 3: 1 21 53 59 44 | 69 82 63 72 16 21 14 1\n" + // "Card 4: 41 92 73 84 69 | 59 84 76 51 58 5 54 83\n" + // "Card 5: 87 83 26 28 32 | 88 30 70 12 93 22 82 36\n" + // "Card 6: 31 18 13 56 72 | 74 77 10 23 35 67 36 11").split("\n") day1(lines) day2(lines) } fun String.toNumbers() = split(" ").filter { it.isNotBlank() }.map { it.toLong() }.toSet() fun day1(lines: List<String>) { val prefix = Regex("Card +\\d+: +") val res = lines.sumOf { line -> val (mine, winning) = line.replace(prefix, "").split("|").zipWithNext() .map { scratch -> scratch.first.toNumbers() to scratch.second.toNumbers() }.first() 2.0.pow((mine intersect winning).size - 1.0).toLong() } println(res) } fun day2(lines: List<String>) { // hopefully this doesn't blow up val cards = LongArray(lines.size) { 1 } lines.forEachIndexed { i, line -> val (num, line) = line.replace("Card +".toRegex(), "").split(":").zipWithNext { a, b -> a.toLong() to b.replace(": +".toRegex(), "")}.first() val (mine, winning) = line.split("|").zipWithNext() .map { scratch -> scratch.first.toNumbers() to scratch.second.toNumbers() }.first() // future cards grow according to how many cards we have at the current index (1..(mine intersect winning).size).forEach { cards[i + it] = cards[i + it] + cards[i] } } // println(cards.contentToString()) println(cards.sum()) }
0
Kotlin
0
0
70646b330cc1cea4828a10a6bb825212e2f0fb18
1,788
advent-of-code-2023
Apache License 2.0
aoc2023/src/main/kotlin/de/havox_design/aoc2023/day23/ALongWalk.kt
Gentleman1983
737,309,232
false
{"Kotlin": 746488, "Java": 441473, "Scala": 33415, "Groovy": 5725, "Python": 3319}
package de.havox_design.aoc2023.day23 import de.havox_design.aoc.utils.kotlin.model.coordinates.* import java.util.* class ALongWalk(private var filename: String) { private val ICON_FORREST = '#' private val ICON_PATH = '.' private val ICON_SLOPE_DOWN = 'v' private val ICON_SLOPE_LEFT = '<' private val ICON_SLOPE_RIGHT = '>' private val ICON_SLOPE_UP = '^' fun solvePart1(): Long = findLongestWay(parseCoordinateMap()) fun solvePart2(): Int = findLongestWayIgnoringSlopes(parseCoordinateMap()) @SuppressWarnings("kotlin:S6611") private fun findLongestWay(map: Map<Coordinate, Char>): Long { val xRange = map.xRange() .let { (a, b) -> a..b } val yRange = map.yRange() .let { (a, b) -> a..b } val queue = priorityQueueOf( Comparator .comparing { it: Triple<Coordinate, Long, Set<Coordinate>> -> it.second } ) val start = map .filter { it.key.y == yRange.first } .filter { it.value == ICON_PATH } .keys .first() val target = map .filter { it.key.y == yRange.last } .filter { it.value == ICON_PATH } .keys .first() val visited = mutableMapOf<Coordinate, Long>() var longestTrail = 0L queue.add(Triple(start, 0L, setOf(start))) while (queue.isNotEmpty()) { val (current, length, path) = queue.poll() when (current) { target -> { longestTrail = longestTrail .coerceAtLeast(length) } } when { current in visited && visited[current]!! > length -> continue } visited[current] = length FourDirectionsFlipped.entries .asSequence() .map { it to it + current } .filter { (_, coordinate) -> coordinate.x in xRange && coordinate.y in yRange } .filter { (_, coordinate) -> coordinate !in path } .filter { (direction, coordinate) -> map[coordinate]!! != ICON_FORREST && map[coordinate]!! != direction.uphill() } .map { (_, it) -> Triple(it, length + 1, path + it) } .toCollection(queue) } return longestTrail } @SuppressWarnings("kotlin:S3776", "kotlin:S6611") private fun findLongestWayIgnoringSlopes(map: Map<Coordinate, Char>): Int { val xRange = map .xRange() .let { (a, b) -> a..b } val yRange = map .yRange() .let { (a, b) -> a..b } val adjacencyMap = map .filter { it.value != ICON_FORREST } .keys .associateWith { coordinate -> adjacentCoordinates(coordinate) .filter { it.x in xRange && it.y in yRange } .filter { map[it]!! != ICON_FORREST } .toList() } .toMutableMap() val distanceMap = adjacencyMap .flatMap { (key, value) -> value.map { key to it } + value.map { it to key } } .associateWith { 1 } .toMutableMap() val canBeFixed = adjacencyMap .filter { it.value.size == 2 } val fixQueue = canBeFixed .keys .toMutableList() while (fixQueue.isNotEmpty()) { val current = fixQueue.removeFirst() when (current) { !in adjacencyMap -> continue } var (from, to) = adjacencyMap[current]!! var diff = 2 var lastFrom = current var next: Coordinate while (adjacencyMap[from]!!.size == 2) { next = adjacencyMap[from]!! .first { it != lastFrom } adjacencyMap.remove(from) lastFrom = from from = next diff++ } var lastTo = current while (adjacencyMap[to]!!.size == 2) { next = adjacencyMap[to]!! .first { it != lastTo } adjacencyMap.remove(to) lastTo = to to = next diff++ } adjacencyMap.remove(current) adjacencyMap[from] = adjacencyMap[from]!! .mapNotNull { when (it) { from -> null lastFrom -> to else -> it } } adjacencyMap[to] = adjacencyMap[to]!! .mapNotNull { when (it) { to -> null lastTo -> from else -> it } } distanceMap[from to to] = diff distanceMap[to to from] = diff } val start = map .filter { it.key.y == yRange.first } .filter { it.value == ICON_PATH } .keys .first() val target = map .filter { it.key.y == yRange.last } .filter { it.value == ICON_PATH } .keys .first() val queue = priorityQueueOf(Comparator .comparing { it: Triple<Coordinate, Int, Set<Coordinate>> -> -it.second } ) var count = 0L val visited = mutableMapOf<Pair<Coordinate, Int>, Int>() var longestTrail = 0 queue.add(Triple(start, 0, setOf(start))) while (queue.isNotEmpty()) { val (current, length, path) = queue.poll() when (current) { target -> { longestTrail = longestTrail .coerceAtLeast(length) } } count++ visited[current to path.size] = length adjacencyMap[current]!! .asSequence() .filter { it !in path } .map { Triple(it, length + distanceMap[current to it]!!, path + it) } .toCollection(queue) } return longestTrail } private fun FourDirectionsFlipped.uphill() = when (this) { FourDirectionsFlipped.DOWN -> ICON_SLOPE_UP FourDirectionsFlipped.LEFT -> ICON_SLOPE_RIGHT FourDirectionsFlipped.RIGHT -> ICON_SLOPE_LEFT FourDirectionsFlipped.UP -> ICON_SLOPE_DOWN } private fun <T> priorityQueueOf(comparator: java.util.Comparator<T>, vararg args: T): PriorityQueue<T> { val queue = PriorityQueue<T>(comparator) queue.addAll(args) return queue } private fun parseCoordinateMap(): Map<Coordinate, Char> = getResourceAsText(filename) .flatMapIndexed { rowNumber, row -> row .mapIndexed { columnNumber, char -> Coordinate(columnNumber, rowNumber) to char } } .toMap() private fun getResourceAsText(path: String): List<String> = this.javaClass.classLoader.getResourceAsStream(path)!!.bufferedReader().readLines() }
4
Kotlin
0
1
35ce3f13415f6bb515bd510a1f540ebd0c3afb04
7,456
advent-of-code
Apache License 2.0
src/Day02.kt
mr-cell
575,589,839
false
{"Kotlin": 17585}
private val part1Scores = mapOf( "A X" to 1 + 3, "A Y" to 2 + 6, "A Z" to 3 + 0, "B X" to 1 + 0, "B Y" to 2 + 3, "B Z" to 3 + 6, "C X" to 1 + 6, "C Y" to 2 + 0, "C Z" to 3 + 3, ) private val part2Scores = mapOf( "A X" to 3 + 0, "A Y" to 1 + 3, "A Z" to 2 + 6, "B X" to 1 + 0, "B Y" to 2 + 3, "B Z" to 3 + 6, "C X" to 2 + 0, "C Y" to 3 + 3, "C Z" to 1 + 6, ) fun main() { fun part1(input: List<String>): Int = input.sumOf { part1Scores[it] ?: 0 } fun part2(input: List<String>): Int = input.sumOf { part2Scores[it] ?: 0 } // test if implementation meets criteria from the description, like: val testInput = readInput("Day02_test") check(part1(testInput) == 15) check(part2(testInput) == 12) val input = readInput("Day02") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
2528bf0f72bcdbe7c13b6a1a71e3d7fe1e81e7c9
983
advent-of-code-2022
Apache License 2.0
src/main/kotlin/com/dr206/2022/Day03.kt
dr206
572,377,838
false
{"Kotlin": 9200}
fun main() { fun findValueOfIntersectingLetters(listOfLists: List<List<String>>) = listOfLists.sumOf { val letter = it.fold(it[0].toSet()) { acc, item -> acc.intersect(item.toSet()) }.first() letter.code % 32 + if (letter.isUpperCase()) 26 else 0 } fun part1(input: List<String>): Int { val rucksackCompartmentsList = input.map { it.chunked(it.length/2) } return findValueOfIntersectingLetters(rucksackCompartmentsList) } fun part2(input: List<String>): Int { val elfGroupList = input.chunked(3) return findValueOfIntersectingLetters(elfGroupList) } // 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("Part 1 ${part1(input)}") println("Part 2 ${part2(input)}") }
0
Kotlin
0
0
57b2e7227d992de87a51094a971e952b3774fd11
946
advent-of-code-in-kotlin
Apache License 2.0
src/main/kotlin/day2/Day2.kt
afTrolle
572,960,379
false
{"Kotlin": 33530}
package day2 import Day import day2.Day2.Hand.* import day2.Day2.Score.* import ext.reverse fun main() { Day2("Day02").solve() } class Day2(input: String) : Day<List<Day2.Round>>(input) { enum class Hand(val opponent: Char, val player: Char, val score: Int) { Rock('A', 'X', 1), Paper('B', 'Y', 2), Scissor('C', 'Z', 3) } enum class Score(val score: Int, val input: Char) { Win(6, 'Z'), Draw(3, 'Y'), Loss(0, 'X') } class Round( opponentHand: Hand, playerHand: Hand, outcome: Score ) { private val roundScore = when { opponentHand == playerHand -> Draw winMap[opponentHand] == playerHand -> Win else -> Loss }.score private val handNeededOfOutcome = when (outcome) { Win -> winMap[opponentHand]!! Draw -> opponentHand Loss -> lossMap[opponentHand]!! }.score val scoreByHands = playerHand.score + roundScore val scoreByOutcome = handNeededOfOutcome + outcome.score } override fun parseInput(): List<Round> = inputByLines.map { Round(handMap[it[0]]!!, handMap[it[2]]!!, gameOutComeMap[it[2]]!!) } override fun part1(input: List<Round>): Any = input.sumOf { it.scoreByHands } override fun part2(input: List<Round>): Any = input.sumOf { it.scoreByOutcome } companion object { val handMap: Map<Char, Hand> = Hand.values().run { associateBy(Hand::opponent) + associateBy(Hand::player) } val gameOutComeMap = Score.values().associateBy(Score::input) val winMap = listOf( Rock to Paper, Paper to Scissor, Scissor to Rock, ).toMap() val lossMap = winMap.reverse() } }
0
Kotlin
0
0
4ddfb8f7427b8037dca78cbf7c6b57e2a9e50545
1,801
aoc-2022
Apache License 2.0
src/main/kotlin/aoc22/Day05.kt
tom-power
573,330,992
false
{"Kotlin": 254717, "Shell": 1026}
package aoc22 import common.Collections.transpose import aoc22.Day05Runner.crane9000 import aoc22.Day05Runner.crane9001 import aoc22.Day05Domain.Movement import aoc22.Day05Parser.toMovements import aoc22.Day05Parser.toStacks import common.Collections.partitionedBy import common.Year22 object Day05: Year22 { fun List<String>.part1(): String = moveCratesWith(::crane9000) fun List<String>.part2(): String = moveCratesWith(::crane9001) } private fun List<String>.moveCratesWith(crane: (List<Stack>, List<Movement>) -> List<Stack>): String = partitionedBy("") .let { crane(it[0].dropLast(1).toStacks(), it[1].toMovements()) } .joinToString("") { it.last().toString() } object Day05Runner { fun crane9000(stacks: List<Stack>, movements: List<Movement>): List<Stack> = craneWithOrder(stacks, movements, true) fun crane9001(stacks: List<Stack>, movements: List<Movement>): List<Stack> = craneWithOrder(stacks, movements, false) private fun craneWithOrder(stacks: List<Stack>, movements: List<Movement>, reversed: Boolean) = movements.fold(stacks.map { it.toMutableList() }) { acc, movement -> acc.apply { val from: Stack = acc[movement.from - 1].takeLastReversed(movement.number, reversed) acc[movement.to - 1].addAll(from) acc[movement.from - 1].removeLast(from.count()) } } private fun Stack.takeLastReversed(n: Int, reversed: Boolean) = takeLast(n).toMutableList() .run { if (reversed) reversed() else this } private fun MutableList<Char>.removeLast(n: Int) { repeat(n) { this.removeLast() } } } private typealias Stack = List<Char> object Day05Domain { data class Movement(val number: Int, val from: Int, val to: Int) } object Day05Parser { fun List<String>.toStacks(): List<Stack> { val max = this.maxBy { it.count() }.count() return map { row -> row.padEnd(max, ' ').chunked(4).map { it.filter(Char::isUpperCase) } } .transpose() .map { row -> row.reversed() .filter(String::isNotBlank) .map { it[0] } } } fun List<String>.toMovements(): List<Movement> = map { it.split(" ").mapNotNull(String::toIntOrNull) } .map { Movement(it[0], it[1], it[2]) } }
0
Kotlin
0
0
baccc7ff572540fc7d5551eaa59d6a1466a08f56
2,441
aoc
Apache License 2.0
src/main/kotlin/g0401_0500/s0407_trapping_rain_water_ii/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g0401_0500.s0407_trapping_rain_water_ii // #Hard #Array #Breadth_First_Search #Matrix #Heap_Priority_Queue // #2022_12_03_Time_500_ms_(100.00%)_Space_64.7_MB_(100.00%) import java.util.PriorityQueue class Solution { private class Cell(val row: Int, val col: Int, val value: Int) : Comparable<Cell?> { override operator fun compareTo(other: Cell?): Int { return value - other!!.value } } private var water = 0 private lateinit var visited1: Array<BooleanArray> fun trapRainWater(heightMap: Array<IntArray>): Int { if (heightMap.size == 0) { return 0 } val walls = PriorityQueue<Cell>() water = 0 visited1 = Array(heightMap.size) { BooleanArray(heightMap[0].size) } val rows = heightMap.size val cols = heightMap[0].size // build wall for (c in 0 until cols) { walls.add(Cell(0, c, heightMap[0][c])) walls.add(Cell(rows - 1, c, heightMap[rows - 1][c])) visited1[0][c] = true visited1[rows - 1][c] = true } for (r in 1 until rows - 1) { walls.add(Cell(r, 0, heightMap[r][0])) walls.add(Cell(r, cols - 1, heightMap[r][cols - 1])) visited1[r][0] = true visited1[r][cols - 1] = true } // end build wall while (walls.isNotEmpty()) { val min = walls.poll() visit(heightMap, min, walls) } return water } private fun visit(height: Array<IntArray>, start: Cell, walls: PriorityQueue<Cell>) { fill(height, start.row + 1, start.col, walls, start.value) fill(height, start.row - 1, start.col, walls, start.value) fill(height, start.row, start.col + 1, walls, start.value) fill(height, start.row, start.col - 1, walls, start.value) } private fun fill(height: Array<IntArray>, row: Int, col: Int, walls: PriorityQueue<Cell>, min: Int) { if (row >= 0 && col >= 0 && row < height.size && col < height[0].size && !visited1[row][col] ) { if (height[row][col] >= min) { walls.add(Cell(row, col, height[row][col])) visited1[row][col] = true } else { water += min - height[row][col] visited1[row][col] = true fill(height, row + 1, col, walls, min) fill(height, row - 1, col, walls, min) fill(height, row, col + 1, walls, min) fill(height, row, col - 1, walls, min) } } } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
2,624
LeetCode-in-Kotlin
MIT License
src/main/kotlin/day9.kt
kevinrobayna
436,414,545
false
{"Ruby": 195446, "Kotlin": 42719, "Shell": 1288}
fun day9ProblemReader(string: String): List<Long> { return string .split("\n") .map { line -> line.toLong() } .toList() } // https://adventofcode.com/2020/day/9 class Day9( private val numbers: List<Long>, private val preamble: Int, ) { fun solvePart1(): Long { for (inx in preamble..numbers.size) { val previousFile = numbers.slice((inx - preamble)..inx) if (!calculateAllCombinations(previousFile).contains(numbers[inx])) { return numbers[inx] } } return 0 } private fun calculateAllCombinations(subset: List<Long>): Set<Long> { val additions = mutableSetOf<Long>() for (n1 in subset) { for (n2 in subset) { if (n1 != n2) { additions.add(n1.plus(n2)) } } } return additions; } fun solvePart2(): Long { val numberToCheck = solvePart1() var numbersToAdd = mutableListOf<Long>() for (inx in 1..numbers.size) { inner@ for (x in inx..numbers.size) { numbersToAdd.add(numbers[x]) val addition = numbersToAdd.sum() if (addition > numberToCheck) { numbersToAdd = mutableListOf() break@inner } else if (addition == numberToCheck) { val sortedList : List<Long> = numbersToAdd.sorted() return sortedList[0] + sortedList[sortedList.size - 1] } } } return 0 } } fun main() { val problem = day9ProblemReader(Day9::class.java.getResource("day9.txt").readText()) println("solution = ${Day9(problem, 25).solvePart1()}") println("solution = ${Day9(problem, 25).solvePart2()}") }
0
Ruby
0
0
9e48ecdebdb4c479ef00f0fd3b1a44a211fb6577
1,851
adventofcode_2020
MIT License
src/Day10/day10.kt
NST-d
573,224,214
false
null
package Day10 import utils.* class Machine(instructions: List<Instruction>) { private val instructions: Map<Int, Instruction> private var registerOverTime: MutableMap<Int, Int> init { this.instructions = HashMap() this.registerOverTime = HashMap() registerOverTime[1] = 1 instructions.fold(1) { acc, instruction -> this.instructions[acc] = instruction acc + instruction.cycles } evaluateInstructions() } fun signalStrength(cycle: Int) = cycle * (registerOverTime[cycle]?: 0) val finalRegisterState get() = registerOverTime[registerOverTime.keys.max()]!! fun printStateOverTime(){ for (i in 1 .. instructions.map { (key, instruction) -> instruction.cycles }.sum() ) { println("${i}: ${registerOverTime[i]} -[${instructions[i]?:""}]-> ${registerOverTime[i+1]}") } } interface Instruction { fun execute(machine: Machine, cycle: Int) val cycles: Int } class AddInstruction(val value: Int, override val cycles: Int = 2) : Instruction { override fun execute(machine: Machine, cycle: Int) { machine.registerOverTime[cycle] = machine.registerOverTime[cycle]!! + value } override fun toString(): String { return "Add $value" } } class NoopInstruction(override val cycles: Int = 1) : Instruction { override fun execute(machine: Machine, cycle: Int) { /* no-op */ } override fun toString(): String { return "Noop" } } private fun evaluateInstructions(){ for((start,instruction) in instructions ) { for( i in 1 .. instruction.cycles){ registerOverTime[start + i] = registerOverTime[start] ?: 0 } instruction.execute(this, start+instruction.cycles) } } } fun main() { fun part1(input: List<String>): Int{ val instructions = input.map { val cmd = it.split(" ") when(cmd[0]){ "noop" -> Machine.NoopInstruction() "addx" -> Machine.AddInstruction(cmd[1].toInt()) else -> error("Unknown instruction") } } val machine = Machine(instructions) machine.printStateOverTime() return (20..240 step 40 ).map { machine.signalStrength(it) }.sum() } val simple = """noop addx 3 addx -5""".split("\n") val test = readTestLines("Day10") val input = readInputLines("Day10") println(part1(input)) }
0
Kotlin
0
0
c4913b488b8a42c4d7dad94733d35711a9c98992
2,649
aoc22
Apache License 2.0
src/day08/Day08_part2.kt
seastco
574,758,881
false
{"Kotlin": 72220}
package day08 import readLines fun traverseLeft(forest: List<List<Int>>, i: Int, j: Int): Int { var count = 0 for (curr in j-1 downTo 0) { count += 1 if (forest[i][j] <= forest[i][curr]) { break } } return count } fun traverseRight(forest: List<List<Int>>, i: Int, j: Int): Int { var count = 0 for (curr in j+1 until forest[i].size) { count += 1 if (forest[i][j] <= forest[i][curr]) { break } } return count } fun traverseUp(forest: List<List<Int>>, i: Int, j: Int): Int { var count = 0 for (curr in i-1 downTo 0) { count += 1 if (forest[i][j] <= forest[curr][j]) { break } } return count } fun traverseDown(forest: List<List<Int>>, i: Int, j: Int): Int { var count = 0 for (curr in i+1 until forest.size) { count += 1 if (forest[i][j] <= forest[curr][j]) { break } } return count } private fun part2(forest: List<List<Int>>): Int { var max = 0 for (i in forest.indices) { for (j in forest[i].indices) { val r = traverseRight(forest, i, j) val l = traverseLeft(forest, i, j) val u = traverseUp(forest, i, j) val d = traverseDown(forest, i, j) max = max.coerceAtLeast(l * r * u * d) } } return max } fun main() { val input = readLines("day08/input") val forest = input.map { it.toCharArray().map { char -> char.digitToInt() }} println(part2(forest)) }
0
Kotlin
0
0
2d8f796089cd53afc6b575d4b4279e70d99875f5
1,585
aoc2022
Apache License 2.0
src/Day04.kt
Kvest
573,621,595
false
{"Kotlin": 87988}
fun main() { val testInput = readInput("Day04_test") check(part1(testInput) == 2) check(part2(testInput) == 4) val input = readInput("Day04") println(part1(input)) println(part2(input)) } private fun part1(input: List<String>): Int { return input .map(String::parseSectionRanges) .count { it.first in it.second || it.second in it.first } } private fun part2(input: List<String>): Int { return input .map(String::parseSectionRanges) .count { it.first.first in it.second || it.second.first in it.first } } private val ROW_FORMAT = Regex("(\\d+)-(\\d+),(\\d+)-(\\d+)") private fun String.parseSectionRanges(): Pair<IntRange, IntRange> { val match = ROW_FORMAT.find(this) val (a, b, c, d) = requireNotNull(match).destructured return IntRange(a.toInt(), b.toInt()) to IntRange(c.toInt(), d.toInt()) }
0
Kotlin
0
0
6409e65c452edd9dd20145766d1e0ea6f07b569a
880
AOC2022
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/MaximumWidthRamp.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2020 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import java.awt.Point fun interface MaximumWidthRampStrategy { operator fun invoke(arr: IntArray): Int } class MaximumWidthRampSort : MaximumWidthRampStrategy { override fun invoke(arr: IntArray): Int { val n: Int = arr.size val b = Array(n) { 0 } for (i in 0 until n) { b[i] = i } b.sortWith { i, j -> arr[i].compareTo(arr[j]) } var ans = 0 var m = n for (i in b) { ans = ans.coerceAtLeast(i - m) m = m.coerceAtMost(i) } return ans } } class MaximumWidthRampBinarySearch : MaximumWidthRampStrategy { override fun invoke(arr: IntArray): Int { val n: Int = arr.size if (n == 0) return 0 var ans = 0 val candidates: MutableList<Point> = ArrayList() candidates.add(Point(arr[n - 1], n - 1)) // candidates: i's decreasing, by increasing value of A[i] for (i in n - 2 downTo 0) { // Find largest j in candidates with A[j] >= A[i] var lo = 0 var hi = candidates.size while (lo < hi) { val local = hi - lo val mi = lo + local / 2 if (candidates[mi].x < arr[i]) lo = mi + 1 else hi = mi } if (lo < candidates.size) { val j: Int = candidates[lo].y ans = ans.coerceAtLeast(j - i) } else { candidates.add(Point(arr[i], i)) } } return ans } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
2,198
kotlab
Apache License 2.0
src/Day04.kt
ben-dent
572,931,260
false
{"Kotlin": 10265}
fun main() { fun part1(input: List<String>): Int { return input.count { contains(it, 1) } } fun part2(input: List<String>): Int { return input.count { contains(it, 2) } } // 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)) } fun contains(input: String, part: Int): Boolean { val commaSplit = input.split(",") val left = commaSplit[0] val right = commaSplit[1] var split = left.split("-") var currentSet = HashSet<Int>() val map = HashMap<Int, Set<Int>>() for (i in split[0].toInt()..split[1].toInt()) { currentSet.add(i) } map[1] = currentSet currentSet = HashSet() split = right.split("-") for (i in split[0].toInt()..split[1].toInt()) { currentSet.add(i) } map[2] = currentSet if (part == 1) { return map[1]!!.containsAll(map[2]!!) || map[2]!!.containsAll(map[1]!!) } for (v in map[1]!!) { val two = map[2]!! if (two.contains(v)) { return true } } return false }
0
Kotlin
0
0
2c3589047945f578b57ceab9b975aef8ddde4878
1,266
AdventOfCode2022Kotlin
Apache License 2.0
src/main/kotlin/days/Day11.kt
mstar95
317,305,289
false
null
package days import days.Cell.EMPTY import days.Cell.FLOOR import days.Cell.OCCUPIED typealias NextCell = (Pair<Int, Int>, Cell, List<List<Cell>>) -> Cell class Day11 : Day(11) { override fun partOne(): Any { val input = prepareInput(inputList) //printRoad(input) val board = live(input, ::nextCellAdjacent) return board.flatten().filter { it == OCCUPIED }.size } override fun partTwo(): Any { val input = prepareInput(inputList) //printRoad(input) val board = live(input, ::nextCellSeen) return board.flatten().filter { it == OCCUPIED }.size } var c = 0; private fun live(current: List<List<Cell>>, nextCell: NextCell): List<List<Cell>> { val next = current.mapIndexed { y, row -> row.mapIndexed { x, it -> nextCell(x to y, it, current) } } // printRoad(next) // if (c++ == 3) { // return next // } return if (next == current) current else live(next, nextCell) } private fun nextCellAdjacent(point: Pair<Int, Int>, current: Cell, board: List<List<Cell>>) = when (current) { FLOOR -> current EMPTY -> if (adjacentCells(point, board).any { it == OCCUPIED }) EMPTY else OCCUPIED OCCUPIED -> if (adjacentCells(point, board).filter { it == OCCUPIED }.size >= 4) EMPTY else OCCUPIED } private fun nextCellSeen(point: Pair<Int, Int>, current: Cell, board: List<List<Cell>>) = when (current) { FLOOR -> current EMPTY -> if (seenCells(point, board).any { it == OCCUPIED }) EMPTY else OCCUPIED OCCUPIED -> if (seenCells(point, board).filter { it == OCCUPIED }.size >= 5) EMPTY else OCCUPIED } private fun adjacentCells(point: Pair<Int, Int>, board: List<List<Cell>>): List<Cell> = adjacentPositions(point) .map { board.getOrNull(it.second)?.getOrNull(it.first) ?: FLOOR } private fun seenCells(point: Pair<Int, Int>, board: List<List<Cell>>): List<Cell> = directions().map { seenCell(point, board, it) } private fun seenCell(point: Pair<Int, Int>, board: List<List<Cell>>, direction: Pair<Int, Int>): Cell { val nextPoint: Pair<Int, Int> = point + direction val (nextX, nextY) = nextPoint val nextCell = board.getOrNull(nextY)?.getOrNull(nextX) return when (nextCell) { null -> FLOOR OCCUPIED, EMPTY -> nextCell FLOOR -> seenCell(nextPoint, board, direction) } } private fun adjacentPositions(point: Pair<Int, Int>): List<Pair<Int, Int>> = directions().map { it.plus(point) } private fun directions(): List<Pair<Int, Int>> = listOf( Pair(-1, -1), Pair(0, -1), Pair(1, -1), Pair(-1, 0), Pair(1, 0), Pair(-1, 1), Pair(0, 1), Pair(1, 1) ) private fun printRoad(input: List<List<Cell>>) { println("BOARD") input.forEach { println(it) } } private fun prepareInput(list: List<String>): List<List<Cell>> = list.map { l -> l.map { when (it) { '.' -> FLOOR 'L' -> EMPTY else -> throw error(it) } } } } private operator fun Pair<Int, Int>.plus(another: Pair<Int, Int>): Pair<Int, Int> { return first + another.first to second + another.second } enum class Cell { FLOOR, EMPTY, OCCUPIED }
0
Kotlin
0
0
ca0bdd7f3c5aba282a7aa55a4f6cc76078253c81
3,463
aoc-2020
Creative Commons Zero v1.0 Universal
src/day03/Day03.kt
sanyarajan
572,663,282
false
{"Kotlin": 24016}
package day03 import readInput val priorityValues = mapOf( 'a' to 1, 'b' to 2, 'c' to 3, 'd' to 4, 'e' to 5, 'f' to 6, 'g' to 7, 'h' to 8, 'i' to 9, 'j' to 10, 'k' to 11, 'l' to 12, 'm' to 13, 'n' to 14, 'o' to 15, 'p' to 16, 'q' to 17, 'r' to 18, 's' to 19, 't' to 20, 'u' to 21, 'v' to 22, 'w' to 23, 'x' to 24, 'y' to 25, 'z' to 26, 'A' to 27, 'B' to 28, 'C' to 29, 'D' to 30, 'E' to 31, 'F' to 32, 'G' to 33, 'H' to 34, 'I' to 35, 'J' to 36, 'K' to 37, 'L' to 38, 'M' to 39, 'N' to 40, 'O' to 41, 'P' to 42, 'Q' to 43, 'R' to 44, 'S' to 45, 'T' to 46, 'U' to 47, 'V' to 48, 'W' to 49, 'X' to 50, 'Y' to 51, 'Z' to 52, ) fun main() { fun part1(input: List<String>): Int { var score = 0 input.forEach { line -> //split line in half val firstCompartment = line.subSequence(0, line.length / 2) val secondCompartment = line.subSequence(line.length / 2, line.length) //find the character that is common to both compartments val commonCharacter = firstCompartment.find { secondCompartment.contains(it) } //get the priority of the common character val priority = priorityValues[commonCharacter] //add the priority to the score score += priority!! } return score } fun part2(input: List<String>): Int { var score = 0 //process lines 3 at a time for (i in input.indices step 3) { val firstRucksack = input[i] val secondRucksack = input[i + 1] val thirdRucksack = input[i + 2] //find the common character between all three rucksacks val commonCharacter = firstRucksack.find { secondRucksack.contains(it) && thirdRucksack.contains(it) } //get the priority of the common character val priority = priorityValues[commonCharacter] //add the priority to the score score += priority!! } return score } // test if implementation meets criteria from the description, like: val testInput = readInput("day03/Day03_test") check(part1(testInput) == 157) check(part2(testInput) == 70) val input = readInput("day03/day03") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
e23413357b13b68ed80f903d659961843f2a1973
2,493
Kotlin-AOC-2022
Apache License 2.0
src/main/kotlin/ru/timakden/aoc/year2016/Day04.kt
timakden
76,895,831
false
{"Kotlin": 321649}
package ru.timakden.aoc.year2016 import arrow.core.Option import arrow.core.none import arrow.core.some import ru.timakden.aoc.util.measure import ru.timakden.aoc.util.readInput /** * [Day 4: Security Through Obscurity](https://adventofcode.com/2016/day/4). */ object Day04 { @JvmStatic fun main(args: Array<String>) { measure { val input = readInput("year2016/Day04") println("Part One: ${part1(input)}") println("Part Two: ${part2(input)}") } } fun part1(input: List<String>) = input.filter(isRealRoom).fold(0) { acc, s -> val id = s.substring(s.lastIndexOf('-') + 1, s.indexOf('[')).toInt() acc + id } fun part2(input: List<String>): Option<Int> { input.filter(isRealRoom).forEach { val encryptedName = it.substringBeforeLast('-') val id = it.substring(it.lastIndexOf('-') + 1, it.indexOf('[')).toInt() val decryptedName = decryptRoomName(encryptedName, id) if (decryptedName == "northpole object storage") return id.some() } return none() } private val isRealRoom: (String) -> Boolean = { val encryptedName = it.substringBeforeLast('-').replace("-", "") val checksum = it.substring(it.indexOf('[') + 1, it.indexOf(']')) calculateChecksum(encryptedName) == checksum } private fun calculateChecksum(encryptedName: String): String { val map = sortedMapOf<Char, Int>() encryptedName.forEach { var count = map[it] ?: 0 map[it] = ++count } val newMap = mutableMapOf<Char, Int>() repeat(5) { map.maxByOrNull { it.value }?.let { newMap[it.key] = it.value map.remove(it.key) } } return newMap.keys.fold("") { acc, c -> acc + c.toString() } } private fun decryptRoomName(encryptedName: String, id: Int): String { var decryptedName = "" encryptedName.forEach { var nextLetter = it repeat((1..id).count()) { nextLetter = getNextLetter(nextLetter) } decryptedName += nextLetter.toString() } return decryptedName } private fun getNextLetter(char: Char) = when (char) { ' ' -> ' ' '-' -> ' ' 'z' -> 'a' else -> char + 1 } }
0
Kotlin
0
3
acc4dceb69350c04f6ae42fc50315745f728cce1
2,386
advent-of-code
MIT License
src/main/kotlin/day5/Day5.kt
stoerti
726,442,865
false
{"Kotlin": 19680}
package io.github.stoerti.aoc.day5 import io.github.stoerti.aoc.IOUtils import io.github.stoerti.aoc.StringExt.longValues import java.util.ListResourceBundle import java.util.Locale fun main(args: Array<String>) { val lines = IOUtils.readInput("day_5_input").toMutableList().also { it.add("") } val seeds = lines.removeAt(0).substring(7).longValues() lines.removeAt(0) // remove next empty line too val mappings = mutableMapOf<String, Mapping>() val mappingBuffer = mutableListOf<String>() var mappingName = "" while (lines.isNotEmpty()) { val line = lines.removeAt(0) if (line.contains("map:")) { mappingName = line.removeSuffix(" map:") } else if (line.isBlank()) { mappings[mappingName] = Mapping.fromString(mappingBuffer) mappingBuffer.clear() } else { mappingBuffer.add(line) } } println(mappings) val result1 = seeds.map { seed -> seed .let { mappings["seed-to-soil"]!!.map(it) } .let { mappings["soil-to-fertilizer"]!!.map(it) } .let { mappings["fertilizer-to-water"]!!.map(it) } .let { mappings["water-to-light"]!!.map(it) } .let { mappings["light-to-temperature"]!!.map(it) } .let { mappings["temperature-to-humidity"]!!.map(it) } .let { mappings["humidity-to-location"]!!.map(it) } }.also { println(it) }.min() println("Result 1: $result1") } data class Mapping( val mappings: List<MappingPart> ) { companion object { fun fromString(lineBlock: List<String>): Mapping = Mapping(lineBlock.map { val destStart = it.split(" ")[0].toLong() val sourceStart = it.split(" ")[1].toLong() val rangeSize = it.split(" ")[2].toLong() MappingPart(sourceStart, destStart, rangeSize) }) } fun map(source: Long) : Long { mappings.find { it.matches(source) }?.let { return it.map(source) } return source } } data class MappingPart( val sourceStart: Long, val destStart: Long, val size: Long, ) { fun matches(source: Long) : Boolean { return sourceStart <= source && source < sourceStart + size } fun map(source: Long) : Long { return source + destStart - sourceStart } }
0
Kotlin
0
0
05668206293c4c51138bfa61ac64073de174e1b0
2,163
advent-of-code
Apache License 2.0
archive/src/main/kotlin/com/grappenmaker/aoc/year20/Day21.kt
770grappenmaker
434,645,245
false
{"Kotlin": 409647, "Python": 647}
package com.grappenmaker.aoc.year20 import com.grappenmaker.aoc.PuzzleSet import com.grappenmaker.aoc.onceSplit fun PuzzleSet.day21() = puzzle(day = 21) { data class Food(val ingredients: Set<String>, val allergens: List<String>) val foods = inputLines.map { l -> val (ingredientsParts, allergensPart) = l.onceSplit(" (contains ") Food(ingredientsParts.split(" ").toSet(), allergensPart.substringBefore(')').split(", ")) } // TODO: improve this ugly code (probably wontfix lol) val assoc = foods.flatMap { f -> f.allergens.map { it to f.ingredients } } .groupBy { (a) -> a }.mapValues { (_, b) -> b.map { (_, c) -> c } } val allIngredients = assoc.values.flatten().flatten().toSet() val canBe = assoc.mapValues { it.value.reduce { acc, curr -> acc intersect curr }.toSet() } val yesAllergen = canBe.values.reduce { acc, curr -> acc + curr }.toSet() partOne = foods.sumOf { f -> (allIngredients - yesAllergen).count { it in f.ingredients } }.s() partTwo = canBe.findUnambiguousSolution().entries.sortedBy { (a) -> a }.joinToString(",") { (_, b) -> b } } // Keys mapped to values that are "possible", find the only solution // TODO: maybe util fun <K, V> Map<K, Set<V>>.findUnambiguousSolution(): Map<K, V> { val toLookAt = mapValues { it.value.toMutableSet() }.toMutableMap() val result = mutableMapOf<K, V>() while (toLookAt.isNotEmpty()) { val (key, onlyPoss) = toLookAt.entries.first { it.value.size == 1 } toLookAt -= key val poss = onlyPoss.single() toLookAt.forEach { it.value -= poss } result[key] = poss } return result }
0
Kotlin
0
7
92ef1b5ecc3cbe76d2ccd0303a73fddda82ba585
1,661
advent-of-code
The Unlicense
src/Day04.kt
Excape
572,551,865
false
{"Kotlin": 36421}
fun main() { fun parseRanges(input: List<String>) = input.map { it.split(",").map { it.split("-").map { it.toInt() } } } .map { Pair((it[0][0]..it[0][1]).toSet(), (it[1][0]..it[1][1]).toSet()) } fun part1(input: List<String>) = parseRanges(input) .count { (it.first union it.second).size <= maxOf(it.first.size, it.second.size) } fun part2(input: List<String>) = parseRanges(input) .map{ it.first intersect it.second} .count { it.isNotEmpty() } val testInput = readInput("Day04_test") check(part1(testInput) == 2) check(part2(testInput) == 4) val input = readInput("Day04") println("part 1: ${part1(input)}") println("part 2: ${part2(input)}") }
0
Kotlin
0
0
a9d7fa1e463306ad9ea211f9c037c6637c168e2f
733
advent-of-code-2022
Apache License 2.0
src/main/kotlin/aoc2022/Day02.kt
lukellmann
574,273,843
false
{"Kotlin": 175166}
package aoc2022 import AoCDay import aoc2022.Day02.Shape.* import util.component1 import util.component2 import util.component3 import util.illegalInput // https://adventofcode.com/2022/day/2 object Day02 : AoCDay<Int>( title = "Rock Paper Scissors", part1ExampleAnswer = 15, part1Answer = 13809, part2ExampleAnswer = 12, part2Answer = 12316, ) { private enum class Shape(val defeats: () -> Shape, val isDefeatedBy: () -> Shape, val score: Int) { ROCK(defeats = { SCISSORS }, isDefeatedBy = { PAPER }, score = 1), PAPER(defeats = { ROCK }, isDefeatedBy = { SCISSORS }, score = 2), SCISSORS(defeats = { PAPER }, isDefeatedBy = { ROCK }, score = 3), } private fun Char.toShape() = when (this) { 'A' -> ROCK 'B' -> PAPER 'C' -> SCISSORS else -> illegalInput(this) } private fun calculateRoundScore(myShape: Shape, opponentShape: Shape): Int { val outcome = when { myShape == opponentShape -> 3 // it's a draw myShape.defeats() == opponentShape -> 6 // I won else -> 0 // I lost } return myShape.score + outcome } private fun sumRoundScores(input: String, selectMyShape: (opponentShape: Shape, column2: Char) -> Shape) = input .lineSequence() .sumOf { (column1, _, column2) -> val opponentShape = column1.toShape() val myShape = selectMyShape(opponentShape, column2) calculateRoundScore(myShape, opponentShape) } override fun part1(input: String) = sumRoundScores( input, selectMyShape = { _, column2 -> when (column2) { 'X' -> ROCK 'Y' -> PAPER 'Z' -> SCISSORS else -> illegalInput(column2) } }, ) override fun part2(input: String) = sumRoundScores( input, selectMyShape = { opponentShape, column2 -> when (column2) { 'X' -> opponentShape.defeats() // I need to loose 'Y' -> opponentShape // I need the round to end in a draw 'Z' -> opponentShape.isDefeatedBy() // I need to win else -> illegalInput(column2) } }, ) }
0
Kotlin
0
1
344c3d97896575393022c17e216afe86685a9344
2,287
advent-of-code-kotlin
MIT License
src/Day14.kt
undermark5
574,819,802
false
{"Kotlin": 67472}
sealed interface Direction { object Down : Direction object Left : Direction object Right : Direction object Unknown : Direction } data class Cave(val data: List<MutableList<Char>>) fun main() { fun canMove(currentPos: Pair<Int, Int>, cave: List<MutableList<Char>>): Direction { if (currentPos.second + 1 == cave.size) return Direction.Unknown val downLeft = (currentPos.first - 1) to (currentPos.second + 1) val downRight = (currentPos.first + 1) to (currentPos.second + 1) val down = (currentPos.first) to (currentPos.second + 1) return when { cave.getOrNull(down.reversed) == '.' -> Direction.Down cave.getOrNull(downLeft.reversed) == '.' -> Direction.Left cave.getOrNull(downRight.reversed) == '.' -> Direction.Right else -> Direction.Unknown } } fun move(currentPos: Pair<Int, Int>, direction: Direction): Pair<Int, Int> { return when (direction) { Direction.Down -> currentPos.first to (currentPos.second + 1) Direction.Left -> currentPos.first - 1 to currentPos.second + 1 Direction.Right -> currentPos.first + 1 to currentPos.second + 1 Direction.Unknown -> Int.MAX_VALUE to Int.MAX_VALUE } } fun dropGrain(cave: List<MutableList<Char>>, lowestSurface: Int): Boolean { val initialLanding = cave.map { it[500] }.indexOfFirst { it == '#' || it == 'O' } - 1 if (initialLanding < 0) return false else { var currentPos = 500 to initialLanding var currentDirection: Direction = canMove(currentPos, cave) while (currentDirection != Direction.Unknown) { currentPos = move(currentPos, currentDirection) currentDirection = canMove(currentPos, cave) } cave[currentPos.reversed] = 'O' return currentPos.second >= lowestSurface } } fun part1(input: List<String>): Int { val cave = List(1000) { MutableList(1000) { '.' } } var lowestSurface = 0 input.map { it.split(" -> ").map { it.split(",").map { it.toInt() }.toPair() }.windowed(2, 1).map { val (start, end) = it.toPair() val (x1, y1) = start val (x2, y2) = end if (x1 == x2) { val min = minOf(y1, y2) val max = maxOf(y1, y2) for (i in min..max) { cave[i][x1] = '#' } } else { val min = minOf(x1, x2) val max = maxOf(x1, x2) for (i in min..max) { cave[y1][i] = '#' } } lowestSurface = maxOf(lowestSurface, maxOf(y1, y2)) } } var grains = 0 var isSettled: Boolean do { grains++ isSettled = dropGrain(cave, lowestSurface) } while (!isSettled) return grains - 1 } fun part2(input: List<String>): Int { val cave = List(1000) { MutableList(10000) { '.' } } var lowestSurface = 0 input.map { it.split(" -> ").map { it.split(",").map { it.toInt() }.toPair() }.windowed(2, 1).map { val (start, end) = it.toPair() val (x1, y1) = start val (x2, y2) = end if (x1 == x2) { val min = minOf(y1, y2) val max = maxOf(y1, y2) for (i in min..max) { cave[i][x1] = '#' } } else { val min = minOf(x1, x2) val max = maxOf(x1, x2) for (i in min..max) { cave[y1][i] = '#' } } lowestSurface = maxOf(lowestSurface, maxOf(y1, y2)) } } cave[lowestSurface + 2].replaceAll { '#' } var grains = 0 do { grains++ dropGrain(cave, lowestSurface) } while (cave[(500 to 0).reversed] == '.') return grains } // test if implementation meets criteria from the description, like: val testInput = readInput("Day14_test") check(part1(testInput) == 24) check(part2(testInput) == 93) val input = readInput("Day14") println(part1(input)) println(part2(input)) } fun List<List<Char>>.trimmed(): List<List<Char>> { val top = this.indexOfFirst { it.any { it != '.' } }.coerceAtLeast(0) val bottom = this.indexOfLast { it.any { it != '.' } }.coerceAtLeast(0) val left = this.map{it.indexOfFirst { it != '.' }}.filter{it >= 0 }.min().coerceAtLeast(0) val right = this.maxOf { it.indexOfLast { it != '.' } }.coerceAtLeast(0) return this.slice(top..bottom).map { it.slice(left..right) } }
0
Kotlin
0
0
e9cf715b922db05e1929f781dc29cf0c7fb62170
5,119
AoC_2022_Kotlin
Apache License 2.0
src/main/kotlin/biz/koziolek/adventofcode/year2021/day21/day21.kt
pkoziol
434,913,366
false
{"Kotlin": 715025, "Shell": 1892}
package biz.koziolek.adventofcode.year2021.day21 import biz.koziolek.adventofcode.* fun main() { val inputFile = findInput(object {}) val lines = inputFile.bufferedReader().readLines() val (player1, player2) = parseDiracDiceStartingPositions(lines) val dice = RollCountingDice(DeterministicDice(sides = 100)) val wonGame = play(DiracDiceGame(player1, player2, dice)) println("Losing player score * total dice rolls: ${answerPart1(wonGame)}") val (player1Wins, player2Wins) = playQuantum(DiracDiceGame(player1, player2, QuantumDice(sides = 3))) if (player1Wins > player2Wins) { println("Player 1 wins in $player1Wins universes") } else { println("Player 2 wins in $player2Wins universes") } } data class Player(val position: Int, val score: Int) interface Dice { val sides: Int fun rollNext(): Int } class RollCountingDice(private val dice: Dice, start: Int = 0) : Dice { private var _rolls = start val rolls get() = _rolls override val sides = dice.sides override fun rollNext(): Int { _rolls++ return dice.rollNext() } } class DeterministicDice(override val sides: Int) : Dice { private var lastRolled = 0 override fun rollNext(): Int { lastRolled++ if (lastRolled > sides) { lastRolled = 1 } return lastRolled } } class QuantumDice(override val sides: Int) : Dice { override fun rollNext() = throw IllegalStateException("Quantum dice does not return one value") } data class DiracDiceGame( val player1: Player, val player2: Player, val dice: Dice, ) { val winner = when { hasWon(player1) -> player1 hasWon(player2) -> player2 else -> null } val loser = when { hasWon(player1) -> player2 hasWon(player2) -> player1 else -> null } fun playNextTurn(): DiracDiceGame { val newPlayer1 = rollAndMove(player1) val newPlayer2 = if (!hasWon(newPlayer1)) rollAndMove(player2) else player2 return copy( player1 = newPlayer1, player2 = newPlayer2, ) } private fun hasWon(player: Player) = player.score >= 1000 private fun rollAndMove(player: Player): Player { val rolled = dice.rollNext() + dice.rollNext() + dice.rollNext() val newPosition = (player.position + rolled - 1) % 10 + 1 return player.copy( position = newPosition, score = player.score + newPosition, ) } } fun parseDiracDiceStartingPositions(lines: List<String>): Pair<Player, Player> = Pair( first = Player(position = lines[0].replace("Player 1 starting position: ", "").toInt(), score = 0), second = Player(position = lines[1].replace("Player 2 starting position: ", "").toInt(), score = 0), ) fun play(game: DiracDiceGame): DiracDiceGame = generateSequence(game) { when (it.winner) { null -> it.playNextTurn() else -> null } }.last() fun answerPart1(game: DiracDiceGame): Int = (game.loser?.score ?: 0) * ((game.dice as? RollCountingDice)?.rolls ?: 0) fun playQuantum(game: DiracDiceGame): Pair<Long, Long> { val (player1WinsPerTurn, player1NotYetWinsPerTurn) = countWinsPerTurn(game.player1.position, score = 0, turn = 0, diceSides = game.dice.sides) val (player2WinsPerTurn, player2NotYetWinsPerTurn) = countWinsPerTurn(game.player2.position, score = 0, turn = 0, diceSides = game.dice.sides) var player1Wins = 0L for (player1Turn in 1 until player1WinsPerTurn.size) { player1Wins += player1WinsPerTurn[player1Turn] * player2NotYetWinsPerTurn[player1Turn - 1] } var player2Wins = 0L for (player2Turn in 1 until player2WinsPerTurn.size) { player2Wins += player2WinsPerTurn[player2Turn] * player1NotYetWinsPerTurn[player2Turn] } return Pair(player1Wins, player2Wins) } fun countWinsPerTurn(position: Int, score: Int, turn: Int, diceSides: Int = 3, multiplier: Long = 1): Pair<LongArray, LongArray> { val arraySize = 11 val winningScore = 21 val winsPerTurn = LongArray(arraySize) val notYetWinsPerTurn = LongArray(arraySize) val newTurn = turn + 1 val rollRepeats = buildMap<Int, Int> { for (roll1 in 1..diceSides) { for (roll2 in 1..diceSides) { for (roll3 in 1..diceSides) { val rolled = roll1 + roll2 + roll3 merge(rolled, 1) { a, b -> a + b } } } } } for ((rolled, repeats) in rollRepeats) { val newPosition = (position + rolled - 1) % 10 + 1 val newScore = score + newPosition if (newScore >= winningScore) { winsPerTurn[newTurn] += multiplier * repeats } else { notYetWinsPerTurn[newTurn] += multiplier * repeats val (otherWinsPerTurn, otherNotYetWinsPerTurn) = countWinsPerTurn( position = newPosition, score = newScore, turn = newTurn, diceSides = diceSides, multiplier = multiplier * repeats, ) for (i in 0 until arraySize) { winsPerTurn[i] += otherWinsPerTurn[i] } for (i in 0 until arraySize) { notYetWinsPerTurn[i] += otherNotYetWinsPerTurn[i] } } } return winsPerTurn to notYetWinsPerTurn }
0
Kotlin
0
0
1b1c6971bf45b89fd76bbcc503444d0d86617e95
5,496
advent-of-code
MIT License
aoc-2017/src/main/kotlin/nl/jstege/adventofcode/aoc2017/days/Day20.kt
JStege1206
92,714,900
false
null
package nl.jstege.adventofcode.aoc2017.days import nl.jstege.adventofcode.aoccommon.days.Day import kotlin.math.abs import kotlin.math.sqrt /** * * @author <NAME> */ class Day20 : Day(title = "Particle Swarm") { private companion object Configuration { private const val TIME_LIMIT = 100000L private const val INPUT_PATTERN_STRING = """[a-z]=<(-?\d+),(-?\d+),(-?\d+)>""" private val INPUT_REGEX = INPUT_PATTERN_STRING.toRegex() private val ORIGIN = Point3D(0, 0, 0) } override fun first(input: Sequence<String>): Any { return input.parse() .withIndex() .minBy { (_, it) -> it.positionAtTime(TIME_LIMIT).manhattan(ORIGIN) }!! .index } override fun second(input: Sequence<String>): Any { val particles = input.parse().toList() particles.forEachIndexed { i, p1 -> particles.drop(i + 1).forEach { p2 -> val t = p1.collidesWith(p2) if (t != null) { p1.removed = true p2.removed = true } } } return particles.count { !it.removed } } private fun Sequence<String>.parse() = this .map { it.split(", ") } .map { (rp, rv, ra) -> val p = INPUT_REGEX.matchEntire(rp)!!.groupValues .drop(1) //Drop the first match, the whole string .map { it.toLong() } //All remaining elements are numbers .let { (x, y, z) -> Point3D(x, y, z) } val v = INPUT_REGEX.matchEntire(rv)!!.groupValues .drop(1) //Drop the first match, the whole string .map { it.toLong() } //All remaining elements are numbers .let { (x, y, z) -> Point3D(x, y, z) } val a = INPUT_REGEX.matchEntire(ra)!!.groupValues .drop(1) //Drop the first match, the whole string .map { it.toLong() } //All remaining elements are numbers .let { (x, y, z) -> Point3D(x, y, z) } Particle(p, v, a) } private data class Point3D(val x: Long, val y: Long, val z: Long) { fun manhattan(other: Point3D) = abs(x - other.x) + abs(y - other.y) + abs(z - other.z) operator fun times(n: Long) = Point3D(x * n, y * n, z * n) operator fun plus(o: Point3D) = Point3D(x + o.x, y + o.y, z + o.z) } private data class Particle( val p: Point3D, val v: Point3D, val a: Point3D, var removed: Boolean = false ) { fun positionAtTime(t: Long): Point3D = a * (t * (t + 1) / 2) + v * t + p /** * Particle's position is represented by the formula used in [Particle.positionAtTime], * which is `pos_t=a * t * (t + 1) / 2 + v * t + p`. This is a second degree quadratic * functions, which can thus be solved by the quadratic equation. To solve this first we * rewrite the formula used to the following: `pos_t= a/2 * t * t + (a/2 + v) * t + p`. * * The quadratic equation is further restricted by the following requirements: * - All t >= 0 * - All t >= are integers. * - For all t >= 0 it must be so that p1.positionAtTime(t) == p2.positionAtTime(t) * * Since p1.positionAtTime(t) == p2.positionAtTime(t), it means that p1.x(t) == p2.x(t), * therefore, we can start by checking if there is a collision in x values and simply use * the formula given above to check if the other dimensions collide as well. * * So for p1.x = p2.x we have: * p1a.x/2*t*t + p1a.x/2*p1v.x*t + p1p.x = p2a.x/2*t*t + p2a.x*p2v.x*t + p2p.x * from which we can deduce: * - A = p1a.x/2 - p2a.x / 2 == (p1a.x - p2a.x) / 2 * - B = p1a.x/2*p1v.x - p2a.x/2*p2v.x * - C = p1p.x - p2p.x * Since this can result in non-integer divisions we define A' and B' such that: * - A' = 2 * A = p1a.x - p2a.x * - B' = 2 * B = (p1a.x + p1v.x*2) - (p2a.x + p2v.x*2) * The quadratic equation then becomes: * t=(-B +/- sqrt(B^2 -4*A*C))/(2*A) * Since we're using A' and B' it becomes: * t=(-(2*B) +/- sqrt((2*B) - 4*(2*A)*C))/(2*(2*A))=(-2*B +/- sqrt((2*B) - 16*A*C))/(4*A)) * =(-B' +/- sqrt(B' - 8 * A' * C)) / (2 * A') * * @param other The particle which may collide with this particle. * @return The first value for which the given particles collide, always >= 0 when present, * if no collision occurs, returns null. */ fun collidesWith(other: Particle): Long? { val candidates = mutableSetOf<Long>() // Calculate A' val ap = a.x - other.a.x // Calculate B' val bp = (2 * v.x + a.x) - (2 * other.v.x + other.a.x) val c = p.x - other.p.x if (ap == 0L && bp != 0L) { // Calculate collisions for B * t + C = 0, only add candidate if it is an integer. if ((c * -2) % bp == 0L) { candidates.add(-2 * c / bp) } } else if (ap == 0L && bp == 0L) { // Calculate collisions for C = 0, when C != 0 return null as it is not possible to // have a collision. return if (c == 0L) 0 else null } else { // Use regular quadratic equation as provided in the KDoc, using A' and B'. Take // note that only integer values may be considered. val dp = bp * bp - 8 * ap * c // If discriminant < 0 there are no collisions if (dp < 0) { return null } val s = sqrt(dp.toDouble()).toLong() // Check if the discriminant is a perfect square, if not, no collisions occur in // integer space. if (s * s != dp) { return null } val n1 = -bp + s val n2 = -bp - s // Final division of the quadratic equation. Check if integer and >= 0, if so, // consider as a candidate. if (n1 % (2 * ap) == 0L) { (n1 / (2 * ap)).let { if (it >= 0) candidates.add(it) } } if (s != 0L && n2 % (2 * ap) == 0L) { (n2 / (2 * ap)).let { if (it >= 0) candidates.add(it) } } } // We have only checked the x values of the particle, calculating the 3D position of // all candidates give us our real collisions. We need the first, so find that one. return candidates .filter { this.positionAtTime(it) == other.positionAtTime(it) } .min() } } }
0
Kotlin
0
0
d48f7f98c4c5c59e2a2dfff42a68ac2a78b1e025
6,922
AdventOfCode
MIT License