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/Day13.kt
HaydenMeloche
572,788,925
false
{"Kotlin": 25699}
import kotlinx.serialization.json.* import kotlinx.serialization.decodeFromString fun main() { val input = readInput("Day13") input.asSequence() .filter { it.isNotBlank() } .map { Json.decodeFromString<JsonArray>(it) } .windowed(size = 2, step = 2) .mapIndexedNotNull { index, list -> val leftSide = list[0] val rightSide = list[1] if (compare(leftSide, rightSide) == true) index + 1 else null } .sum() .also { println("answer one: $it") } val partTwoInput = input .toMutableList() partTwoInput.add("[[2]]") partTwoInput.add("[[6]]") partTwoInput .asSequence() .filter { it.isNotBlank() } .map { Json.decodeFromString<JsonArray>(it) } .sortedWith { a, b -> if (compare(a, b) == true) -1 else 1 } .mapIndexedNotNull { index, entry -> if (entry.toString() == partTwoInput[partTwoInput.size - 2] || entry.toString() == partTwoInput[partTwoInput.size - 1]) { index+1 } else null } .reduce(Int::times) .also { println("answer two: $it") } } fun compare(a: JsonArray, b: JsonArray, pos: Int = 0): Boolean? { val left = a.elementAtOrNull(pos) val right = b.elementAtOrNull(pos) return when { left == null && right == null -> null left == null || right == null -> left == null left is JsonPrimitive && right is JsonPrimitive -> if (left == right) compare(a, b, pos + 1) else left.int < right.int left is JsonArray && right is JsonArray -> compare(left, right) ?: compare(a, b, pos + 1) left is JsonPrimitive && right is JsonArray -> compare(JsonArray(listOf(left)), right) ?: compare(a, b, pos + 1) left is JsonArray && right is JsonPrimitive -> compare(left, JsonArray(listOf(right))) ?: compare(a, b, pos + 1) else -> throw IllegalStateException("$left $right") } }
0
Kotlin
0
1
1a7e13cb525bb19cc9ff4eba40d03669dc301fb9
2,112
advent-of-code-kotlin-2022
Apache License 2.0
src/main/kotlin/day04/Day04.kt
daniilsjb
572,664,294
false
{"Kotlin": 69004}
package day04 import java.io.File fun main() { val data = parse("src/main/kotlin/day04/Day04.txt") val answer1 = part1(data) val answer2 = part2(data) println("🎄 Day 04 🎄") println() println("[Part 1]") println("Answer: $answer1") println() println("[Part 2]") println("Answer: $answer2") } private data class Range( val start: Int, val end: Int ) private fun String.toRange(): Range = this.split("-") .map(String::toInt) .let { (start, end) -> Range(start, end) } @Suppress("SameParameterValue") private fun parse(path: String): List<Pair<Range, Range>> = File(path).useLines { lines -> lines .map { it.split(",").map(String::toRange) } .map { (lhs, rhs) -> lhs to rhs } .toList() } private fun Range.contains(other: Range): Boolean = start <= other.start && other.end <= end private fun Range.overlaps(other: Range): Boolean = contains(other) || (other.start <= start && start <= other.end) || (other.start <= end && end <= other.end) private fun part1(data: List<Pair<Range, Range>>): Int = data.count { (a, b) -> a.contains(b) || b.contains(a) } private fun part2(data: List<Pair<Range, Range>>): Int = data.count { (a, b) -> a.overlaps(b) || b.overlaps(a) }
0
Kotlin
0
0
6f0d373bdbbcf6536608464a17a34363ea343036
1,316
advent-of-code-2022
MIT License
src/main/kotlin/day1.kt
Gitvert
725,292,325
false
{"Kotlin": 97000}
fun day1 (lines: List<String>) { day1part1(lines) day1part2(lines) println() } fun day1part1(lines: List<String>) { var sum = 0 lines.forEach { line -> val digits = line.filter { it.isDigit() } sum += Integer.parseInt(digits.first().toString() + digits.last().toString()); } println("Day 1 part 1: $sum") } fun day1part2(lines: List<String>) { var sum = 0 lines.forEach { line -> sum += findInOrder(line) } println("Day 1 part 2: $sum") } fun findInOrder(line: String): Int { val length = line.length var start = 0 var end = 0 val numbers = mutableListOf<Int>() while (start < length) { addIfNumber(line.substring(start, end), numbers) end++ if (end > length) { start++ end = start } } return Integer.parseInt(numbers.first().toString() + numbers.last().toString()) } fun addIfNumber(word: String, numbers: MutableList<Int>) { if (word.length == 1 && word[0].isDigit()) { numbers.add(Integer.parseInt(word[0].toString())) } when (word) { "one" -> numbers.add(1) "two" -> numbers.add(2) "three" -> numbers.add(3) "four" -> numbers.add(4) "five" -> numbers.add(5) "six" -> numbers.add(6) "seven" -> numbers.add(7) "eight" -> numbers.add(8) "nine" -> numbers.add(9) } }
0
Kotlin
0
0
f204f09c94528f5cd83ce0149a254c4b0ca3bc91
1,461
advent_of_code_2023
MIT License
src/Year2022Day14.kt
zhangt2333
575,260,256
false
{"Kotlin": 34993}
import kotlin.math.max import kotlin.math.min fun main() { val entrypoint = Point(0, 500) val directions = arrayOf( Point(+1, 0), Point(+1, -1), Point(+1, +1), ) fun pointFallDown(now: Point, G: Set<Point>, borderLine: Int): Point { return directions.asSequence() .map { Point(now.x + it.x, now.y + it.y) } .filter { it !in G && it.x < borderLine } .firstOrNull() ?: now } fun drawLine(a: Point, b: Point, G: MutableSet<Point>) { for (x in min(a.x, b.x)..max(a.x, b.x)) { for (y in min(a.y, b.y)..max(a.y, b.y)) { G.add(Point(x, y)) } } } fun parse(lines: List<String>): MutableSet<Point> { val G = mutableSetOf<Point>() for (line in lines) { line.splitToSequence(" -> ") .map { val (y, x) = it.split(",") Point(x.toInt(), y.toInt()) } .zipWithNext() .forEach { (a, b) -> drawLine(a, b, G) } } return G } fun part1(lines: List<String>): Int { val G = parse(lines) val maxX = G.asSequence().map { it.x }.max() val originalPointNumber = G.size while (true) { var now = entrypoint.copy() while (true) { val nxt = pointFallDown(now, G, maxX + 1) if (nxt != now) now = nxt else break } if (now.x >= maxX) break G.add(now) } return G.size - originalPointNumber } fun part2(lines: List<String>): Int { val G = parse(lines) val borderLine = G.asSequence().map { it.x }.max() + 2 val originalPointNumber = G.size while (entrypoint !in G) { var now = entrypoint.copy() while (true) { val nxt = pointFallDown(now, G, borderLine) if (nxt != now) now = nxt else break } G.add(now) } return G.size - originalPointNumber } val testLines = readLines(true) assertEquals(24, part1(testLines)) assertEquals(93, part2(testLines)) val lines = readLines() println(part1(lines)) println(part2(lines)) }
0
Kotlin
0
0
cdba887c4df3a63c224d5a80073bcad12786ac71
2,336
aoc-2022-in-kotlin
Apache License 2.0
src/main/kotlin/g1901_2000/s1942_the_number_of_the_smallest_unoccupied_chair/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g1901_2000.s1942_the_number_of_the_smallest_unoccupied_chair // #Medium #Array #Heap_Priority_Queue #Ordered_Set // #2023_06_20_Time_549_ms_(100.00%)_Space_63.6_MB_(100.00%) import java.util.Arrays import java.util.PriorityQueue class Solution { fun smallestChair(times: Array<IntArray>, targetFriend: Int): Int { val minheap = PriorityQueue<Int>() minheap.offer(0) val all = arrayOfNulls<Person>(times.size * 2) for (i in times.indices) { all[2 * i] = Person(i, times[i][0], false, true) all[2 * i + 1] = Person(i, times[i][1], true, false) } Arrays.sort( all ) { a: Person?, b: Person? -> val i = if (a!!.leave) -1 else 1 val j = if (b!!.leave) -1 else 1 if (a.time == b.time) i - j else a.time - b.time } val seat = IntArray(times.size) var i = 0 while (true) { if (all[i]!!.arrive) { if (targetFriend == all[i]!!.idx) { return minheap.peek() } seat[all[i]!!.idx] = minheap.poll() if (minheap.isEmpty()) { minheap.offer(seat[all[i]!!.idx] + 1) } } else { minheap.offer(seat[all[i]!!.idx]) } i++ } } private class Person internal constructor(var idx: Int, var time: Int, var leave: Boolean, var arrive: Boolean) }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,492
LeetCode-in-Kotlin
MIT License
src/Day10.kt
oleskrede
574,122,679
false
{"Kotlin": 24620}
fun main() { val part2Solution = """ ##..##..##..##..##..##..##..##..##..##.. ###...###...###...###...###...###...###. ####....####....####....####....####.... #####.....#####.....#####.....#####..... ######......######......######......#### #######.......#######.......#######..... """.trimIndent() class CPU { var registerX = 1 private set private var cycle = 1 private val cycleValues = mutableListOf(0) fun runProgram(input: List<String>): List<Int> { for (line in input) { val tokens = line.trim().split(" ") val operation = tokens.first() when (operation) { "noop" -> completeCycle() "addx" -> { val v = tokens[1].toInt() repeat(2) { completeCycle() } registerX += v } } } return cycleValues } private fun completeCycle() { cycleValues.add(registerX) cycle++ } } class CRT(val width: Int = 40, val height: Int = 6) { fun draw(cycleValues: List<Int>): List<String> { return cycleValues.take(width * height) .mapIndexed { i, x -> val pixelPos = i % width if (x in pixelPos - 1..pixelPos + 1) { '#' } else { '.' } }.windowed(size = width, step = width) .map { it.joinToString(separator = " ") } } } fun part1(input: List<String>): Int { val cycleValues = CPU().runProgram(input) var signalStrengtSum = 0 for (cycle in 20..220 step 40) { signalStrengtSum += cycleValues[cycle] * cycle } return signalStrengtSum } fun part2(input: List<String>) { val cycleValues = CPU().runProgram(input).drop(1) // Drop cycle 0 val image = CRT().draw(cycleValues) println(image.joinToString(separator = "\n")) } val testInput = readInput("Day10_test") test(part1(testInput), 13140) println("Part 2 testsolution:") println(part2Solution) println() println("Part 2 testresult:") println(part2(testInput)) val input = readInput("Day10") timedRun { part1(input) } println() println("Part 2 result:") timedRun { part2(input) } }
0
Kotlin
0
0
a3484088e5a4200011335ac10a6c888adc2c1ad6
2,613
advent-of-code-2022
Apache License 2.0
src/main/kotlin/g2201_2300/s2232_minimize_result_by_adding_parentheses_to_expression/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g2201_2300.s2232_minimize_result_by_adding_parentheses_to_expression // #Medium #String #Enumeration #2023_06_27_Time_191_ms_(100.00%)_Space_34.4_MB_(100.00%) class Solution { // Variables for final solution, to avoid create combination Strings private var currentLeft = 0 private var currentRight = 0 private var currentMin = Int.MAX_VALUE fun minimizeResult(expression: String): String { // Identify our starting point, to apply the expansion technique val plusIndex = expression.indexOf("+") // We start expanding from the first values to the left and right of the center (plus sign). expand(plusIndex - 1, plusIndex + 1, expression) // Build the final String. We add the parentheses to our expression in the already // calculated indices, defined as global variables. val stringBuilder = StringBuilder() for (i in 0 until expression.length) { if (i == currentLeft) { stringBuilder.append('(') } stringBuilder.append(expression[i]) if (i == currentRight) { stringBuilder.append(')') } } return stringBuilder.toString() } // With this function, we calculate all possible combinations of parentheses from two pointers, // left and right. private fun expand(left: Int, right: Int, expression: String) { if (left < 0 || right >= expression.length) { return } // from zero to first parentheses val a = evaluate(0, left, expression) // from first parentheses to right parentheses (+1 means inclusive) val b = evaluate(left, right + 1, expression) // from right parentheses to the end of expression (+1 means inclusive) val c = evaluate(right + 1, expression.length, expression) // If the expression a * b * c is less than our current minimum // this is our solution, we replace the variables with these new values. if (a * b * c < currentMin) { currentMin = a * b * c currentLeft = left currentRight = right } // Move parentheses left only expand(left - 1, right, expression) // Move parentheses right only expand(left, right + 1, expression) // Move parentheses left and right expand(left - 1, right + 1, expression) } /* This function is responsible for calculating the expressions of each variable. a = (0, left) // from the start of the expression to the first parentheses b = (left, right) // between parentheses, include plus sign c = (right, end of expression) // from the last parentheses to the end */ private fun evaluate(left: Int, right: Int, expression: String): Int { // This means that the parentheses are at the beginning or end of the expression and are // equal to the range of the expression to be evaluated. Return 1 to avoid zero factors in // equation (a * b * c). if (left == right) { return 1 } var number = 0 for (i in left until right) { // If we find a sign, we must add both parts, therefore, we convert the expression to (a // + b). // We return the variable (a) wich is (number) and add to what follows after the sign (i // + 1). // We call the same function to calculate the b value. number = if (expression[i] == '+') { return number + evaluate(i + 1, right, expression) } else { number * 10 + (expression[i].code - '0'.code) } } return number } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
3,734
LeetCode-in-Kotlin
MIT License
src/main/kotlin/aoc2020/day7/LuggageProcessing.kt
arnab
75,525,311
false
null
package aoc2020.day7 object LuggageProcessing { fun parse(data: String): Map<String, List<Pair<String, Int>>> = data.split("\n").map { line -> val(type, specs) = line.split("bags contain ") val containedBags = specs.replace(".", "") .split(", ") .mapNotNull { specPart -> parseBagSpec(specPart) } type.trim() to containedBags }.toMap() private val bagSpecPattern = Regex("""(\d+) (.*) bags?""") private fun parseBagSpec(spec: String): Pair<String, Int>? { val matches = bagSpecPattern.matchEntire(spec) val (count, type) = matches?.destructured ?: return null return Pair(type.trim(), count.toInt()) } fun findBagsContaining(type: String, specs: Map<String, List<Pair<String, Int>>>): List<String> { val bagsContainingType = specs.filterValues { bagSpec -> bagSpec.any { (bagType, _) -> bagType == type } }.keys return (bagsContainingType + bagsContainingType.flatMap { findBagsContaining(it, specs) }).distinct() } fun findBagsContainedIn(type: String, specs: Map<String, List<Pair<String, Int>>>) : Int { val containedBagTypes = specs[type] if (containedBagTypes.isNullOrEmpty()) return 1 return 1 + containedBagTypes.map { (bagType, count) -> val bagsCount = findBagsContainedIn(bagType, specs) count * bagsCount }.sum() } }
0
Kotlin
0
0
1d9f6bc569f361e37ccb461bd564efa3e1fccdbd
1,467
adventofcode
MIT License
src/Day18.kt
syncd010
324,790,559
false
null
class Day18: Day { // This represents a key found on the maze data class MapKey(val id: Char, val steps:Int, val requires: List<Char>) private val dirs = listOf(Position(0, -1), Position(1, 0), Position(0, 1), Position(-1, 0)) private fun List<String>.positionOf(c: Char): Position? { for (y in indices) { val x = get(y).indexOf(c) if (x != -1) return Position(x, y) } return null } fun convert(input: List<String>) : Map<Char, List<MapKey>> { // Finds the accessible keys starting in [from] with a BFS fun findKeys(maze: List<String>, from: Position): List<MapKey> { val keys = mutableListOf<MapKey>() val frontier = mutableListOf(Triple(from, 0, listOf<Char>())) // List of <key position, distance, required keys> val visited = mutableListOf(from) while (frontier.isNotEmpty()) { val (pos, dist, required) = frontier.removeAt(0) for (newPos in dirs.map { pos + it }) { val type = maze[newPos.y][newPos.x] if (newPos in visited || type == '#') continue visited.add(newPos) val newRequired = required.toMutableList() if (type.isLowerCase() || type.isUpperCase()) { if (type.isLowerCase()) keys.add(MapKey(type, dist + 1, required)) newRequired.add(type.toLowerCase()) } frontier.add(Triple(newPos, dist + 1, newRequired)) } } return keys } val mazeMap = mutableMapOf<Char, List<MapKey>>() input.joinToString("") .replace(Regex("([#.])"), "") .forEach { key -> mazeMap[key] = findKeys(input, input.positionOf(key)!!) } return mazeMap } // Represents a path taken. [frontier] is the last key(s) got, [seenKeys] is the path, steps the distance data class Path(val frontier: List<Char>, val seenKeys: List<Char>, val steps: Int) private fun Path.repr(): String = seenKeys.joinToString(" -> ") { "$it" } // Find the paths to get all the keys starting from [start] positions private fun findPaths(mazeMap: Map<Char, List<MapKey>>, start: List<Char>): List<Path> { val numKeys = mazeMap.keys.filter { it.isLowerCase() }.size val frontier = mutableListOf(Path(start, emptyList<Char>(), 0)) val foundPaths = mutableListOf<Path>() // BFS while (frontier.size > 0) { val path = frontier.removeAt(0) if (path.seenKeys.size == numKeys) { foundPaths.add(path) continue } // For each possible independent move for (idx in path.frontier.indices) { // Get the possible keys it can move to: // keys that are on the map, that we haven't seen yet and that are "unlocked" for (newStep in mazeMap[path.frontier[idx]]!!.filter { it.id !in path.seenKeys && it.requires.all { it in path.seenKeys } }) { val newPath = Path( path.frontier.toMutableList().apply { this[idx] = newStep.id }, path.seenKeys + newStep.id, path.steps + newStep.steps) var addPath = true // Check if the new path is just a permutation of an existing one and ignore it if so for (existingPath in frontier) { if ((existingPath.frontier == newPath.frontier) && (existingPath.seenKeys.size == newPath.seenKeys.size) && (existingPath.seenKeys.all { it in newPath.seenKeys }) ) { if (existingPath.steps > newPath.steps) frontier.remove(existingPath) // Found a more efficient path, remove old add new else addPath = false // Old path is more efficient break } } if (addPath) frontier.add(newPath) } } } return foundPaths } override fun solvePartOne(input: List<String>): Int { val mazeMap = convert(input) val foundPaths = findPaths(mazeMap, listOf('@')) // foundPaths.forEach { println("${it.steps} -> ${it.repr()}") } return foundPaths.minBy { it.steps }!!.steps } override fun solvePartTwo(input: List<String>): Int { val startPos = input.positionOf('@')!! val inputStr = input.toMutableList() inputStr[startPos.y-1] = inputStr[startPos.y-1].substring(0, startPos.x - 1) + "1#2" + inputStr[startPos.y-1].substring(startPos.x + 2) inputStr[startPos.y] = inputStr[startPos.y].substring(0, startPos.x - 1) + "###" + inputStr[startPos.y].substring(startPos.x + 2) inputStr[startPos.y+1] = inputStr[startPos.y+1].substring(0, startPos.x - 1) + "3#4" + inputStr[startPos.y+1].substring(startPos.x + 2) val mazeMap = convert(inputStr) val foundPaths = findPaths(mazeMap, listOf('1', '2', '3', '4')) // foundPaths.forEach { println("${it.steps} -> ${it.repr()}") } return foundPaths.minBy { it.steps }!!.steps } }
0
Kotlin
0
0
11c7c7d6ccd2488186dfc7841078d9db66beb01a
5,601
AoC2019
Apache License 2.0
hoon/HoonAlgorithm/src/main/kotlin/programmers/lv02/Lv2_12939_최댓값과최솟값.kt
boris920308
618,428,844
false
{"Kotlin": 137657, "Swift": 35553, "Java": 1947, "Rich Text Format": 407}
package programmers.lv02 /** * * no.12939 * 최댓값과 최솟값 * https://school.programmers.co.kr/learn/courses/30/lessons/12939 * * 문제 설명 * 문자열 s에는 공백으로 구분된 숫자들이 저장되어 있습니다. * str에 나타나는 숫자 중 최소값과 최대값을 찾아 이를 "(최소값) (최대값)"형태의 문자열을 반환하는 함수, solution을 완성하세요. * 예를들어 s가 "1 2 3 4"라면 "1 4"를 리턴하고, "-1 -2 -3 -4"라면 "-4 -1"을 리턴하면 됩니다. * * 제한 조건 * s에는 둘 이상의 정수가 공백으로 구분되어 있습니다. * 입출력 예 * s return * "1 2 3 4" "1 4" * "-1 -2 -3 -4" "-4 -1" * "-1 -1" "-1 -1" * */ fun main() { println(solution("1 2 3 4")) println(solution("-1 -2 -3 -4")) } private fun solution(s: String): String { var answer = "" val splitString = s.split(" ") answer = splitString.minOf { it.toInt() }.toString() + " " + splitString.maxOf { it.toInt() }.toString() return answer }
1
Kotlin
1
2
88814681f7ded76e8aa0fa7b85fe472769e760b4
1,061
HoOne
Apache License 2.0
ahp-base/src/main/kotlin/pl/poznan/put/ahp/MatrixMaker.kt
sbigaret
164,424,298
true
{"Kotlin": 93061, "R": 67629, "Shell": 24899, "Groovy": 24559}
package pl.poznan.put.ahp object MatrixMaker { fun matrix(matrix: Map<String, List<RelationValue>>, diagonalSup: (key: String) -> List<RelationValue>) = matrix.toMatrix(diagonalSup) private inline fun Map<String, List<RelationValue>>.toMatrix(diagonalSup: (key: String) -> List<RelationValue>) = mapValues { (k, v) -> val notDiagonal = v.filter { it.firstID != it.secondID } if (notDiagonal.isEmpty()) return emptyMap<String, List<List<Double>>>() val diagonal = diagonalSup(k) val matrix = (notDiagonal.flatMap { listOf(it, it.reversed()) } + diagonal) .sortedWith(compareBy({ it.firstID }, { it.secondID })) matrix.map { it.firstID to it.secondID } .requireDistinct { "values of '$it' are duplicated comparision for '$k'" } matrix.map { it.value }.chunked(diagonal.size).also { require(it.size == it.last().size) { "dimensions of '$k' are not equal; missing comparisons: ${getMissingValues(matrix, diagonal)}" } require(it.size == diagonal.size) { "too few elements for '$k'; missing comparisons: ${getMissingValues(matrix, diagonal)}" } } } private fun getMissingValues(matrix: List<RelationValue>, diagonal: List<RelationValue>): Set<Pair<String, String>> { val providedComparisons = matrix.map { uniformKey(it.firstID, it.secondID) }.toSet() val requiredComparisons = diagonal .dropLast(1) .mapIndexed { i, f -> diagonal.drop(i + 1) .map { s -> uniformKey(f.firstID, s.secondID) } }.flatten() .toSet() return requiredComparisons - providedComparisons } private fun uniformKey(firstID: String, secondID: String) = if (firstID < secondID) firstID to secondID else secondID to firstID private inline fun <T> List<T>.requireDistinct(onError: (T) -> String) { val set = mutableSetOf<T>() forEach { require(set.contains(it).not()) { onError(it) } set += it } } }
0
Kotlin
0
0
96c182d7e37b41207dc2da6eac9f9b82bd62d6d7
2,315
DecisionDeck
MIT License
day01/part2.kts
bmatcuk
726,103,418
false
{"Kotlin": 214659}
// --- Part Two --- // Your calculation isn't quite right. It looks like some of the digits are // actually spelled out with letters: one, two, three, four, five, six, seven, // eight, and nine also count as valid "digits". // // Equipped with this new information, you now need to find the real first and // last digit on each line. For example: // // two1nine // eightwothree // abcone2threexyz // xtwone3four // 4nineeightseven2 // zoneight234 // 7pqrstsixteen // // In this example, the calibration values are 29, 83, 13, 24, 42, 14, and 76. // Adding these together produces 281. // // What is the sum of all of the calibration values? import java.io.* import kotlin.io.* fun strToInt(s: String): Int { if (s[0].isDigit()) { return s.toInt() } return when (s) { "one" -> 1 "two" -> 2 "three" -> 3 "four" -> 4 "five" -> 5 "six" -> 6 "seven" -> 7 "eight" -> 8 "nine" -> 9 else -> 0 } } val RGX = Regex("(one|two|three|four|five|six|seven|eight|nine|\\d)") val result = File("input.txt").readLines().sumBy { val matches = RGX.findAll(it) val firstDigit = matches.first().groupValues[1] var lastDigit = matches.last() val maybeLastDigit = RGX.find(it, lastDigit.range.start + 1) if (maybeLastDigit != null) { lastDigit = maybeLastDigit } strToInt(firstDigit) * 10 + strToInt(lastDigit.groupValues[1]) } println(result)
0
Kotlin
0
0
a01c9000fb4da1a0cd2ea1a225be28ab11849ee7
1,393
adventofcode2023
MIT License
src/2023/Day03.kt
nagyjani
572,361,168
false
{"Kotlin": 369497}
package `2023` import java.io.File import java.util.* fun main() { Day03().solve() } class Day03 { val input1 = """ 467..114.. ...*...... ..35..633. ......#... 617*...... .....+.58. ..592..... ......755. ...$.*.... .664.598.. """.trimIndent() val input2 = """ """.trimIndent() class PartNumber { var digits = "" val indexes = mutableListOf<Int>() fun add(index: Int, char: Char): PartNumber { digits += char indexes.add(index) return this } fun isSymbol(): Boolean { return !digits.all { it.isDigit() } } fun num() : Int { return digits.toInt() } fun neighbours(x: Int, y: Int): List<Int> { val r = mutableSetOf<Int>() for (ix in indexes) { for (i in -1..1) { for (j in -1..1) { val x1 = ix%x+i val y1 = ix/x+j val ix1 = y1*x + x1 if (x1 in 0 until x && y1 in 0 until y && ix1 !in indexes) { r.add(ix1) } } } } return r.toList() } fun isGear(): Boolean { return digits == "*" } } fun solve() { val f = File("src/2023/inputs/day03.in") val s = Scanner(f) // val s = Scanner(input1) // val s = Scanner(input2) var sum = 0 var sum1 = 0 var x = 0 var y = 0 var lineix = 0 val parts = mutableMapOf<Int, PartNumber>() val partList = mutableListOf<PartNumber>() while (s.hasNextLine()) { lineix++ val line = s.nextLine().trim() if (line.isEmpty()) { continue } x = line.length val ll = line.toCharArray().toList() ll.mapIndexed { index, c -> val index1 = (lineix-1) * x + index if (c != '.') { val p = if (index1 == 0 || !c.isDigit() || index1 - 1 !in parts.keys || parts[index1 - 1]!!.isSymbol()) { val p1 = PartNumber() partList.add(p1) p1 } else { parts[index1 - 1]!! } parts[index1] = p.add(index1, c) } } ++y } for (p in partList) { val n = p.neighbours(x, y) if (n.any { it in parts.keys && parts[it]!!.isSymbol()} && !p.isSymbol()) { sum += p.num() } if (p.isGear()) { val ns = n.filter{it in parts.keys}.map{parts[it]!!}.filter { !it.isSymbol() }.toSet().toList() if (ns.size == 2) { sum1 += ns[0].num() * ns[1].num() } } } print("$sum $sum1\n") } }
0
Kotlin
0
0
f0c61c787e4f0b83b69ed0cde3117aed3ae918a5
3,239
advent-of-code
Apache License 2.0
src/Day03.kt
janbina
112,736,606
false
null
package day03 import getInput import kotlin.coroutines.experimental.buildSequence import kotlin.math.abs import kotlin.math.ceil import kotlin.math.sqrt import kotlin.test.assertEquals enum class Direction { TOP, LEFT, BOTTOM, RIGHT } fun main(args: Array<String>) { val input = getInput(3).readLines().first().toInt() assertEquals(430, part1(input)) assertEquals(312453, part2(input)) } fun spiral(): Sequence<Pair<Int, Int>> = buildSequence { var x = 0 var y = 0 var dx = 1 var dy = 0 while (true) { yield(Pair(x, y)) if ((abs(x) == abs(y) && (x < 0 || y < 0)) || (y >= 0 && (x - y) == 1)) { val tmp = dx dx = dy dy = -tmp } x += dx y += dy } } fun part1(input: Int): Int { return spiral().take(input).last().run { abs(first) + abs(second) } } fun part2(input: Int): Int { val gridSize = ceil(sqrt(input.toDouble())).toInt() val grid = Array(gridSize) { IntArray(gridSize, { 0 }) } var i = gridSize / 2 var j = gridSize / 2 grid[i][j] = 1 grid[i--][++j] = 1 var prevValue = 1 var direction = Direction.TOP while (true) { val nextValue = (grid[i][j-1] + grid[i][j+1] + grid[i-1][j] + grid[i+1][j] + grid [i-1][j-1] + grid [i-1][j+1] + grid [i+1][j+1] + grid [i+1][j-1]) if (nextValue == prevValue) { //if next value is same as previous, we are too far in this direction //return one step back and change direction direction = when (direction) { Direction.TOP -> { i++; j--; Direction.LEFT } Direction.LEFT -> { i++; j++; Direction.BOTTOM } Direction.BOTTOM -> { i--; j++; Direction.RIGHT } Direction.RIGHT -> { i--; j--; Direction.TOP } } continue } if (nextValue > input) { return nextValue } prevValue = nextValue grid[i][j] = nextValue when (direction) { Direction.TOP -> i-- Direction.LEFT -> j-- Direction.BOTTOM -> i++ Direction.RIGHT -> j++ } } }
0
Kotlin
0
0
71b34484825e1ec3f1b3174325c16fee33a13a65
2,193
advent-of-code-2017
MIT License
yandex/y2023/qual/b.kt
mikhail-dvorkin
93,438,157
false
{"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408}
package yandex.y2023.qual private fun solve() { val (n, m) = readInts() val a = readInts() val aSorted = a.sorted() val y = aSorted[m - 1] val yTake = aSorted.take(m).count { it == y } val xDefinitely = a.indices.filter { a[it] < y } val xY = a.indices.filter { a[it] == y } val xLeft = xDefinitely.firstOrNull() ?: n val xRight = xDefinitely.lastOrNull() ?: -1 val ans = (0..(xY.size - yTake)).minOf { i -> val xYLeft = xY[i] val xYRight = xY[i + yTake - 1] maxOf(xYRight, xRight) - minOf(xYLeft, xLeft) + 1 } println(ans) } private fun readStrings() = readln().split(" ") private fun readInts() = readStrings().map { it.toInt() } fun main() = repeat(1) { solve() }
0
Java
1
9
30953122834fcaee817fe21fb108a374946f8c7c
688
competitions
The Unlicense
src/Day03.kt
shoebham
573,035,954
false
{"Kotlin": 9305}
fun main() { fun part1(input: List<String>): Int { var ans=0 for(word in input){ var common:Char? = null val freqMap1 = mutableMapOf<Char,Int>() val freqMap2 = mutableMapOf<Char,Int>() // lower case priority= 1-26 // upper 27-52 val middle = word.length/2 for(i in (0..middle-1)){ freqMap1.put(word[i],freqMap1.getOrDefault(word[i]+1,1)); } for(i in middle .. word.length-1){ freqMap2.put(word[i],freqMap2.getOrDefault(word[i]+1,1)) } freqMap1.map { if(freqMap2.containsKey(it.key)){ val ascii = it.key.toChar().code // println("ascii "+ascii) if(ascii>=65&&ascii<=90){ ans+=(ascii-38) // println("ans"+ (ascii-38)) }else{ ans+=(ascii-96) // println("ans "+(ascii-96)) } } } } return ans } fun part2(input:List<String>):Int{ var ans=0 var j=0 while(j<=input.size-1){ val set1 = mutableSetOf<Char>() val set2 = mutableSetOf<Char>() val set3 = mutableSetOf<Char>() val word1=input[j] val word2=input[j+1] val word3=input[j+2] for(letter in word1)set1.add(letter) for(letter in word2)set2.add(letter) for(letter in word3)set3.add(letter) set1.map { if(set2.contains(it)&&set3.contains(it)){ val ascii = it.code // println("ascii "+ascii) if(ascii>=65&&ascii<=90){ ans+=(ascii-38) // println("ans"+ (ascii-38)) }else{ ans+=(ascii-96) // println("ans "+(ascii-96)) } } } j+=3 } return ans; } val input = readInput("Day03") // println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
f9f0e0540c599a8661bb2354ef27086c06a3c9ab
2,245
advent-of-code-2022
Apache License 2.0
src/Day08.kt
kmakma
574,238,598
false
null
import kotlin.math.max fun main() { fun part1(input: List<String>): Int { val visible = mutableSetOf<Coord2D>() val grid = input.map { line -> line.map { it.digitToInt() } } val lastX = grid.lastIndex val lastY = grid.first().lastIndex visible.addAll(grid.indices.map { Coord2D(it, 0) }) visible.addAll(grid.indices.map { Coord2D(it, lastX) }) visible.addAll(grid.first().indices.map { Coord2D(0, it) }) visible.addAll(grid.last().indices.map { Coord2D(lastY, it) }) var max: Int for (x in 1 until lastX) { max = -1 for (y in grid[x].indices) { if (grid[x][y] > max) { max = grid[x][y] visible.add(Coord2D(x, y)) } if (max == 9) break } max = -1 for (y in grid[x].indices.reversed()) { if (grid[x][y] > max) { max = grid[x][y] visible.add(Coord2D(x, y)) } if (max == 9) break } } for (y in 1 until lastY) { max = -1 for (x in grid.indices) { if (grid[x][y] > max) { max = grid[x][y] visible.add(Coord2D(x, y)) } if (max == 9) break } max = -1 for (x in grid.indices.reversed()) { if (grid[x][y] > max) { max = grid[x][y] visible.add(Coord2D(x, y)) } if (max == 9) break } } return visible.size } fun lowerIdxScore(grid: List<List<Int>>, a: Int, b: Int): Int { val height = grid[a][b] for (i in a - 1 downTo 0) { if (grid[i][b] >= height) return a - i } return a } fun scenicScore(grid: List<List<Int>>, x: Int, y: Int): Int { val height = grid[x][y] val scores = mutableListOf<Int>() var score = 0 for (a in x - 1 downTo 0) { if (grid[a][y] >= height) { score = x - a break } } if (score > 0) scores.add(score) else scores.add(x) score = 0 for (a in x + 1..grid.lastIndex) { if (grid[a][y] >= height) { score = a - x break } } if (score > 0) scores.add(score) else scores.add(grid.lastIndex - x) score = 0 for (b in y - 1 downTo 0) { if (grid[x][b] >= height) { score = y - b break } } if (score > 0) scores.add(score) else scores.add(y) score = 0 for (b in y + 1..grid[x].lastIndex) { if (grid[x][b] >= height) { score = b - y break } } if (score > 0) scores.add(score) else scores.add(grid[x].lastIndex - y) return scores.product() } fun part2(input: List<String>): Int { val grid = input.map { line -> line.map { it.digitToInt() } } var maxScore = 0 grid.forEachIndexed { x, line -> line.indices.forEach { y -> val score = scenicScore(grid, x, y) maxScore = max(maxScore, score) } } return maxScore } val input = readInput("Day08") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
950ffbce2149df9a7df3aac9289c9a5b38e29135
3,593
advent-of-kotlin-2022
Apache License 2.0
src/main/kotlin/com/askrepps/advent2021/day09/Day09.kt
askrepps
726,566,200
false
{"Kotlin": 302802}
/* * MIT License * * Copyright (c) 2021-2023 <NAME> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.askrepps.advent.advent2021.day09 import com.askrepps.advent.util.getInputLines import java.io.File private const val MAX_BASIN_HEIGHT = 8 private val NEIGHBOR_DIRECTIONS = listOf(Pair(-1, 0), Pair(1, 0), Pair(0, -1), Pair(0, 1)) data class Point(val rowIndex: Int, val colIndex: Int, val height: Int) class HeightMap(heightData: List<List<Int>>) { private val points: List<List<Point>> private val numRows: Int private val numColumns: Int init { check(heightData.isNotEmpty()) { "Height map must have data" } numRows = heightData.size numColumns = heightData.first().size check(heightData.all { it.size == numColumns }) { "Map grid is not rectangular" } points = heightData.mapIndexed { rowIndex, rowData -> rowData.mapIndexed { colIndex, height -> Point(rowIndex, colIndex, height) } } } val lowPoints: List<Point> by lazy { calcLowPoints() } private fun getNeighbors(point: Point) = NEIGHBOR_DIRECTIONS.mapNotNull { (deltaRow, deltaCol) -> points.getOrNull(point.rowIndex + deltaRow)?.getOrNull(point.colIndex + deltaCol) } private fun calcLowPoints() = points.flatMap { row -> row.filter { point -> getNeighbors(point).all { it.height > point.height } } } fun getBasinForPoint(lowPoint: Point): Set<Point> { val basin = mutableSetOf(lowPoint) val searchStack = mutableListOf(lowPoint) while (searchStack.isNotEmpty()) { val currentPoint = searchStack.removeLast() getNeighbors(currentPoint) .filter { it !in basin && it.height > currentPoint.height && it.height <= MAX_BASIN_HEIGHT } .forEach { basin.add(it) searchStack.add(it) } } return basin } } fun List<String>.toHeightMap() = HeightMap(heightData = map { line -> line.map { it.code - '0'.code } }) fun getPart1Answer(heightMap: HeightMap) = heightMap.lowPoints.sumOf { it.height + 1 } fun getPart2Answer(heightMap: HeightMap) = heightMap.lowPoints.map { heightMap.getBasinForPoint(it).size } .sortedDescending() .take(3) .fold(1, Int::times) fun main() { val heightMap = File("src/main/resources/2021/input-2021-day09.txt") .getInputLines().toHeightMap() println("The answer to part 1 is ${getPart1Answer(heightMap)}") println("The answer to part 2 is ${getPart2Answer(heightMap)}") }
0
Kotlin
0
0
89de848ddc43c5106dc6b3be290fef5bbaed2e5a
3,681
advent-of-code-kotlin
MIT License
2019/src/main/kotlin/day4.kt
madisp
434,510,913
false
{"Kotlin": 388138}
import utils.Parser import utils.Solution import utils.cut import utils.map fun main() { Day4.run() } object Day4 : Solution<Pair<Int, Int>>() { override val name = "day4" override val parser = Parser { input -> input.cut("-").map { it.toInt() } } fun fits(pwd: String, triplet: Boolean = false): Boolean { if ((0..4).none { pwd[it] == pwd[it + 1] }) { // no doubles, doesn't fit return false } if ((0..4).any { pwd[it] > pwd[it + 1] }) { // decreasing pair of digits return false } if (triplet) { val doubleChars = (0 .. 4).filter { pwd[it] == pwd[it + 1] }.map { pwd[it] }.toSet() if (doubleChars.all { c -> (0..3).any { pwd[it] == c && pwd[it + 1] == c && pwd[it + 2] == c } }) { return false } } return true } override fun part1(input: Pair<Int, Int>): Any? { return (input.first .. input.second).count { fits(it.toString()) } } override fun part2(input: Pair<Int, Int>): Any? { return (input.first .. input.second).count { fits(it.toString(), true) } } }
0
Kotlin
0
1
3f106415eeded3abd0fb60bed64fb77b4ab87d76
1,093
aoc_kotlin
MIT License
2017/src/main/kotlin/Day14.kt
dlew
498,498,097
false
{"Kotlin": 331659, "TypeScript": 60083, "JavaScript": 262}
import grid.Point object Day14 { fun part1(input: String): Int { return inputToDisk(input).sumBy { row -> row.sumBy { if (it) 1 else 0 } } } fun part2(input: String): Int { val disk = inputToDisk(input) val unvisited = mutableSetOf<Point>() disk.forEachIndexed { row, values -> values.forEachIndexed { col, value -> if (value) { unvisited.add(Point(col, row)) } } } var numRegions = 0 while (unvisited.isNotEmpty()) { val start = unvisited.toList()[0] val queue = mutableListOf(start) val visited = mutableSetOf<Point>() while (queue.isNotEmpty()) { val point = queue.removeAt(0) if (point in visited) { continue } visited.add(point) if (disk[point.y][point.x]) { unvisited.remove(point) if (point.y > 0) { queue.add(point.copy(y = point.y - 1)) } if (point.y < 127) { queue.add(point.copy(y = point.y + 1)) } if (point.x > 0) { queue.add(point.copy(x = point.x - 1)) } if (point.x < 127) { queue.add(point.copy(x = point.x + 1)) } } } numRegions++ } return numRegions } private fun inputToDisk(input: String): List<List<Boolean>> { return (0 until 128) .map { a -> val key = "$input-$a" val hash = Day10.part2(key) hash.map { hexToBinaryString(it) }.joinToString("").map { it == '1' } } } private fun hexToBinaryString(char: Char): String { return when (char) { '0' -> "0000" '1' -> "0001" '2' -> "0010" '3' -> "0011" '4' -> "0100" '5' -> "0101" '6' -> "0110" '7' -> "0111" '8' -> "1000" '9' -> "1001" 'a' -> "1010" 'b' -> "1011" 'c' -> "1100" 'd' -> "1101" 'e' -> "1110" 'f' -> "1111" else -> throw IllegalArgumentException("$char") } } }
0
Kotlin
0
0
6972f6e3addae03ec1090b64fa1dcecac3bc275c
2,047
advent-of-code
MIT License
src/main/kotlin/g2301_2400/s2343_query_kth_smallest_trimmed_number/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g2301_2400.s2343_query_kth_smallest_trimmed_number // #Medium #Array #String #Sorting #Heap_Priority_Queue #Divide_and_Conquer #Quickselect #Radix_Sort // #2023_07_01_Time_382_ms_(100.00%)_Space_38.7_MB_(100.00%) class Solution { fun smallestTrimmedNumbers(nums: Array<String>, queries: Array<IntArray>): IntArray { val numberOfDigits = nums[0].length var placeValue = numberOfDigits val list: MutableList<IntArray> = ArrayList(numberOfDigits) while (--placeValue >= 0) { countSort(nums, placeValue, numberOfDigits, list) } val op = IntArray(queries.size) var i = 0 for (query in queries) { val listIndex = query[1] - 1 val place = query[0] - 1 op[i++] = list[listIndex][place] } return op } private fun countSort(arr: Array<String>, exp: Int, numberOfDigits: Int, list: MutableList<IntArray>) { val n = arr.size val output = arrayOfNulls<String>(n) val count = IntArray(10) count.fill(0) // Store count of occurrences in count[] var i = 0 while (i < n) { val digit = arr[i][exp].code - '0'.code count[digit]++ i++ } i = 1 while (i < 10) { count[i] += count[i - 1] i++ } // Build the output array val op = IntArray(n) i = n - 1 while (i >= 0) { val digit = arr[i][exp].code - '0'.code val place = count[digit] - 1 output[place] = arr[i] if (exp == numberOfDigits - 1) { op[place] = i } else { op[place] = list[list.size - 1][i] } count[digit]-- i-- } list.add(op) System.arraycopy(output, 0, arr, 0, n) } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,894
LeetCode-in-Kotlin
MIT License
kotlin/src/com/daily/algothrim/leetcode/FairCandySwap.kt
idisfkj
291,855,545
false
null
package com.daily.algothrim.leetcode /** * 888. 公平的糖果棒交换 * 爱丽丝和鲍勃有不同大小的糖果棒:A[i] 是爱丽丝拥有的第 i 根糖果棒的大小,B[j] 是鲍勃拥有的第 j 根糖果棒的大小。 * * 因为他们是朋友,所以他们想交换一根糖果棒,这样交换后,他们都有相同的糖果总量。(一个人拥有的糖果总量是他们拥有的糖果棒大小的总和。) * * 返回一个整数数组 ans,其中 ans[0] 是爱丽丝必须交换的糖果棒的大小,ans[1] 是 Bob 必须交换的糖果棒的大小。 * * 如果有多个答案,你可以返回其中任何一个。保证答案存在。 * */ class FairCandySwap { companion object { @JvmStatic fun main(args: Array<String>) { FairCandySwap().solution(intArrayOf(1, 1), intArrayOf(2, 2)).forEach { println(it) } } } // 输入:A = [1,1], B = [2,2] // 输出:[1,2] // O(m+n) // O(m) fun solution(A: IntArray, B: IntArray): IntArray { val map = HashSet<Int>() var sumA = 0 var sumB = 0 val result = IntArray(2) for (a in A) { sumA += a map.add(a) } for (b in B) { sumB += b } val sub = (sumA - sumB) / 2 for (b in B) { val a = b + sub if (map.contains(a)) { result[0] = a result[1] = b break } } return result } }
0
Kotlin
9
59
9de2b21d3bcd41cd03f0f7dd19136db93824a0fa
1,579
daily_algorithm
Apache License 2.0
src/main/kotlin/se/saidaspen/aoc/aoc2015/Day16.kt
saidaspen
354,930,478
false
{"Kotlin": 301372, "CSS": 530}
package se.saidaspen.aoc.aoc2015 import se.saidaspen.aoc.util.Day import se.saidaspen.aoc.util.P fun main() = Day16.run() object Day16 : Day(2015, 16) { private val sender = mapOf( P("children", 3), P("cats", 7), P("samoyeds", 2), P("pomeranians", 3), P("akitas", 0), P("vizslas", 0), P("goldfish", 5), P("trees", 3), P("cars", 2), P("perfumes", 1) ) private val sues: List<List<P<String, Int>>> = input.lines().map { it.substring(it.indexOf(" ", it.indexOf(":"))).trim() } .map { it.split(",").map { o -> P(o.split(":")[0].trim(), o.split(":")[1].trim().toInt()) } } .toList() override fun part1(): Any { for (i in sues.indices) { if (sues[i].all { sender[it.first]!! == it.second }) return i + 1 } return "None found" } override fun part2(): Any { for (i in sues.indices) { var matches = true for (prop in sues[i]) { matches = matches && when (val propName = prop.first) { "cats" -> sender[propName]!! < prop.second "trees" -> sender[propName]!! < prop.second "pomeranians" -> sender[propName]!! > prop.second "goldfish" -> sender[propName]!! > prop.second else -> sender[propName]!! == prop.second } } if (matches) return i + 1 } return "None found" } }
0
Kotlin
0
1
be120257fbce5eda9b51d3d7b63b121824c6e877
1,562
adventofkotlin
MIT License
src/main/kotlin/de/startat/aoc2023/Day10.kt
Arondc
727,396,875
false
{"Kotlin": 194620}
package de.startat.aoc2023 class Day10 { data class Maze(val pipes: Set<Pipe>) { val start: Pipe = pipes.first { it.char == 'S' } private fun getPipeAt(column: Int, row: Int): Pipe? = pipes.find { p -> p.column == column && p.row == row } fun findConnectedPipes(pipe: Pipe): Set<Pipe> = pipe.connections.map { c -> when (c) { Connection.NORTH -> Pair(0, -1) Connection.SOUTH -> Pair(0, 1) Connection.EAST -> Pair(1, 0) Connection.WEST -> Pair(-1,0) } }.mapNotNull { getPipeAt(pipe.column + it.first, pipe.row + it.second) } .filter {neighbourPipe -> pipe.isConnectedTo(neighbourPipe)}.toSet() } data class Pipe(val column: Int, val row: Int, val char: Char) { val connections: Set<Connection> = when (char) { '.' -> setOf() '|' -> setOf(Connection.NORTH, Connection.SOUTH) '-' -> setOf(Connection.EAST, Connection.WEST) 'L' -> setOf(Connection.NORTH, Connection.EAST) 'J' -> setOf(Connection.WEST, Connection.NORTH) '7' -> setOf(Connection.WEST, Connection.SOUTH) 'F' -> setOf(Connection.EAST, Connection.SOUTH) 'S' -> setOf(Connection.NORTH, Connection.EAST, Connection.SOUTH, Connection.WEST) else -> throw RuntimeException("This is bad") } get fun isConnectedTo(other: Pipe): Boolean { for (connection in connections){ val connected = when(connection){ Connection.NORTH -> other.connections.contains(Connection.SOUTH) && this.row-1 == other.row Connection.SOUTH -> other.connections.contains(Connection.NORTH)&& this.row+1 == other.row Connection.WEST -> other.connections.contains(Connection.EAST)&& this.column-1 == other.column Connection.EAST -> other.connections.contains(Connection.WEST) && this.column+1 == other.column } if(connected) return true } return false } } class FourWayFlood(val maze: Maze) { data class FloodedPipe(val pipe: Pipe, val liquidNr : Int) private val floodedPipes = mutableSetOf<FloodedPipe>() private val startPipe = maze.start fun flood() { floodedPipes.add(FloodedPipe(startPipe,0)) val floodStarterPipes = maze.findConnectedPipes(startPipe).mapIndexed { index, pipe -> FloodedPipe(pipe, index + 1) } .onEach { floodedPipes.add(it) }.toSet() var newlyFloodedPipe = floodStarterPipes do { newlyFloodedPipe = newlyFloodedPipe.mapNotNull { p -> val notFloodedNeighbors = maze.findConnectedPipes(p.pipe) - floodedPipes.map { it.pipe }.toSet() if (notFloodedNeighbors.isEmpty()) { null }else { FloodedPipe(notFloodedNeighbors.single(),p.liquidNr)} } .onEach { fp -> floodedPipes.add(fp) }.toSet() }while (newlyFloodedPipe.isNotEmpty()) println(floodedPipes.groupingBy { it.liquidNr }.eachCount()) } } enum class Connection {NORTH, EAST, SOUTH, WEST} fun star1() { val maze = parseMaze(day10input) println(maze) val flood= FourWayFlood(maze) flood.flood() } private fun parseMaze(input: String): Maze { val allPipes = mutableSetOf<Pipe>() input.lines().withIndex().forEach { (rowIdx, row) -> row.forEachIndexed { colIdx, char -> allPipes.add(Pipe(colIdx, rowIdx, char)) } } return Maze(allPipes) } fun star2() {} val day10testInput1 = """ -L|F7 7S-7| L|7|| -L-J| L|-JF """.trimIndent() val day10testInput2 = """ ..F7. .FJ|. SJ.L7 |F--J LJ... """.trimIndent() val day10input = """ L777FJF77F-77-F-7F7.FF.J7.-J--J7F|7F.FJ.L-|F|-F|FJ7-J7F-JFF-7.L7FL7J-FF|7--7.L--|77.F-J77.-7FJ7F7FF--.FFJ7-7-F|.FL-L-F7.F|-FF7F|-7-|7-.FF-7. L--77-FJL|7L77.FJ-F-7.|.FJJJ.FFF|FF-77|-|FJ-FJ|LFJ|-L-JLLF|L77|F7L7-|JL-J7LLF7|FLL--7J.-F-|-L-7JF7J7FJ-F-77|.FLJFJ7LJL|7.L7LL7FJFJ|LJLFFJJ|7 .|L|LFJ7-J-J||-7JLL-J---JL7F7L-LF7L7L77JF7L7--J7F7|.F7LF.L|-|FLJ|L|F|FFJJLJFFJ-7||LF7J7FJF-7.L7L|LFJ7LL|7JFJF|.|||F7JJ|L-7|J7LJ.F7--7L7J7FJ- F7J|.L-J-L7F7JFJ.7LJ|-J...L|-|L|||FJFJ..L-FJLL77LLJ7L77J|-7J|F--7-JFL7|F7FFJLJJFJ77L-7-L7F.|J.|F|.L-|7..|FL-FJF-7-LJFL|-L|L|-|F7LL7LL.|FF||. J|-L7J.|||L.F.FJ.|7LF.|FF.LL7|LFJ||FJ|.7.L7|FLF7-L.-JL7.F7J-LJJ7L|FJ||J---JF7JLJLL-7.LFJJJL7LF7JJFFF-777FF7|||L-JF|--7JLFL7.FFFF7|L77.|.JL-7 J7F7|.F-|7-FJ7L-7JF..J.|J7|LL-|L7LJL-7--7JJLFJ|L7F7.FJ77|LJL7FLFFF7L7J-7-|LLJ.|||.LJ7LF.LF||-||FFF-JFJ-J7L-.77-J7F|LJF-F-7L-FF7LF||.F7J..7.7 LF.L|-J7LJ-7.F|J.FL7-LF7F7L-J.77L-7F-J7.FF7F|FF7L-|77FJ-JFF.|7FF7||-|7LJ.-FL-.L-FJ77|7..LF7|7||FFJF-JL|FJLLF.F7|FJL7FJLLL-L-||.FJ||7|.FF-J7| L|7L|7F-J.J|FFF-FJ-7JFLJ|.FJ|.F---JL--7J.LJ-J7.F7J|L77J7.FF.LFFJ|||7F77L|7|FF-J..|||----F7F--JL7L7|.|FL-J.FJ-|FL77FJ|J.F-FJJL-JLLF|77F7L-.LF 7---LF7|.FL7JL|F7L-L-7FL|7F7.FL7F7F---J.7-7..LL-JFLJF-77F7F7|FL7LJ|F||J7L-F-7-L.FFF7..FFJ||F-7FJF||.L7.|-F|.F7LJ|FJ7|J.|.-77F-J-L|JLF-J7LF.. LJ7.FLJL--7L7||-|7LF|7J7F-J|F7|LJ|L-7|LFL--7..|JL7LFL7L7|||L7F-JF-JFJ|.F7FJ7LJFL7FJ|F7FJFJLJJ||F-J|77LFFJF-L|L7|LJ7-7-FJLLL7-7F7F-.||7F7FJ7. LLF-LF-7||JFL-LLF777F--FL7FJ|L-7F|F7L7-JJ7.L-F7.FF7-|L7||||FJL-7|F7|FJF7|||FJF77FL7|||L7|L|F7|||F7|F7-JJ7J77|.L-7J|7LFJ..FL-7|7||F-7-7-LJJ-7 |-|.F-7L7|JFJ.|J||LF7F7JFJ|LL-7L-J|L-J.LF77.L||.FJL7F-JLJLJL7F-J||LJL-JL7J7J7F7-FFJ||L-JL7FJLJ|||LJ||7F|FJ|-FJ.F--J7FL-FF-7|LJF-7J.LL|J.|7.7 J7|F7-L.FF-..F7F|L7||-||L7L--7L--7L7F7F7||-F7||-L-7|L--7F---JL7FJ|F-----JF7F-J|F7L7||F---JL--7|||7FJL--7.7|7L.FFL--F7.F-F-J7J-7FJF-7JJL|L|FL .-JLJ.|7||JFF||FJFJ||7|-FJF--JF--JFJ||||||.|LJL77FJL7F-JL--7F-JL-JL----7J||L7FJ|L-JLJL7F7J.F7|LJ|FJF---JFF|7.FFF7F-JJFJ7|LF-7-|JJ7...FFJ7JFL 7FJ.L-J7JL7FL||L7L7|L7F-JFJLF7L--7L7|||||L7L7F-JFJF-JL----7|L-7F--7F---JFJL7|L7L--7F-7|||7FJLJF-J|FJF-7-||F77F-J|7..FJ|F|.JL7-L7L|L--F|J-F-J -7-FJFL.JF7-FJL7L7LJFJL-7L-7|L7F-JFJ|||||FJ|||.FJFJLF7F-7FJL7FJL-7LJ|F7-L-7||FJF-7LJFJLJL7|F-7|F7||FJFJF77||-L7FJ7-F7-F||F|LJ7FJ.--L-LF.LJ7| ||.F7J|FLJ||L-7|LL-7L7F7|F-J|FJL-7|FJ||LJ|JFJ|FJFJF7|LJFJL-7LJF--JF7FJL7F-J||L7L7L7FJF7F7|LJFJLJ||LJFJFJL7||JFJ|F77|L-7.L7J.LF7.LJFJF7|JJ-L7 -77L7FF|JF--F-JL--7L7||LJ|.FJL7F-JLJFJL-7L7L7LJFJJ||L7FJF--JF7L-7L|LJF-JL-7||FJLL7|L-JLJ|L7.L7F7LJF-J-|F-J|||L7||L7L7FJ7-|J7FJ.FL7J-LLJLL|.| |L7JLJJ|.L|FL7F--7L-J|L-7L7L7FJL---7|F7||FJFL7FJF7||FJL7L7F-J|F-JFJF-JF-7FJLJL7F-JL7|F--JFJF7LJ|F-JF-7||F7|L7FJLJFJFJ|-F7|F-7L7-L|-.|JF--|7. L|.FJ7F-|.|7FLJF7L-7FJF7|FJFJL7F7F-J|||FJL-7FJL7|||LJF-JFLJF-JL-7L7L7-|FJ|F---JL--7L7L--7L7|L-7|L-7L7LJ|||L7|L7F-J.L7L-7J7|F-7J|LJ|.|-L7-L-7 |LJ-.LL-F7F7F7FJL7FJL-JLJL-JF-J|||F7LJ|L7F-JL7FJ||L-7|-F7F7L-7F-JFJFJFJ|-||F7F7F7FJFJF-7|FJ|F-J|F-J|L-7LJL7||FJL7F7J|F-JF77J.JF-J-FFJLLJ77|| |-LF--L7|LJ|||L-7|L7F----7F-JF7||LJL-7L7|L7J-||FJL7FJL7|||L--J|F7|FJFJFJFJ||||||||FJ7L7LJL-JL7FJL--7F-JF7FJ|||F-J|L7|L--JL7|7.|7|.7LJ7LJ|LFJ J--J.LLLL-7LJ|F7||FLJ7F-7|L-7|||L7JF7|FJL7L7FJLJF-JL7FJ||L---7||||L-JFJ|L7|||||||||J|7L----7FJ|F---J|F-JLJFJLJ|F7L7||F----JF7F|F7F77F|7.|FLF |FL.FL|LF7L-7LJLJL---7|FJL-7LJ|L7|FJ|||F7L7LJF--JFF7|||||F7F-JLJLJF--JF--JLJ||LJ||L7LF7|F--J|FJ|F-7FJL7.F7L7F-J|L7|LJL---7FJ|F|LJ-F7-|LJ|FFJ ||JF7JF-JL--JF7F7F7F7LJL-7FJF-JFJ||FJ||||-|F-JF7F7||||FJ|||L---7F7L-7FL----7|L7FJL7|FJL7L--7LJFJL7|L7FJFJL7|L-7|FJL7F----JL7L7F7LFJ|F|7-JL|J |L7-F-L-----7|LJ||LJL---7|L7|F7L7||L7|LJ|FJ|F7|LJ|||||L7||L7F7FJ|L-7|F-7F7FJL-J|LF|||F-JJF7L-7|F7|L7||FJF-JL7FJ||F7||F7LF7FJFJ|L7L7|F|L7J|LL -.|L|J|.F---J|F-JL-7|F--JL-J|||-|||FJL7FJL7LJ||F-J||||FJ|L7||LJFJF7LJ|FJ||L---7L7FJLJL7F-J|F7|LJ||FJ||L7L-7-||7|||||LJL-J||FJF|FJFJL7-7.F|-. L-7.|.F7L-7F7|L7F--JFJF7F7F7LJL-J||L7FJ|7LL7FJ||F7||||L7|FJ|L-7|F|L7FJL-J|F7F7|FJ|F---JL-7||||F7||L7||FJF-JFJL7|||||F--7FJ||F7|L-JF-JJL|7JLJ FF.FF-LF--J|||J||F-7L7|||LJL---7FJ|FJL7L7LFJ|-|||||||L7||L7L7F|L7|FJL---7LJ||LJ||||F--7F-JLJ|||LJ|FJ|||FJF7L7FJ|LJLJL-7LJJ|||||F--JJ|||LJ.FJ FL-7J..L-7FJLJ|LJL7L7||||F-----JL7||F7L7L7L7|FJ||||||FJ||.L7|FJFJ||F7FF7L-7|L-7L7|LJF-JL---7LJL7FJL7|||L7||FJL7|F----7L-7FJ|||||F-7|L7JJ|FLJ -7J.|F|FLLJJJLJ|F7L7|LJLJL7F----7LJLJL7L7L7|LJFJ|LJ|||FJL7FJLJFJFJ||L-JL-7||F7|FJL-7L7F77F7L-7FJL-7||||FJ|||F7LJL-7F7L--JL7LJLJLJFJ7J|.JL77. L|--L7|7.L|-FJ.FJ|FJL-77F7LJF---JF----J-|FJ|F7L7L7FJ|||F-JL--7L7|FJL--7F-J|LJ||L7F-JFJ||FJ|F-J|F7FJLJ||L7||||L----J||-F7LFJF7F7F-J7|LFJL-LL7 |JJ|LLF77|L||.FL7|L-7FJFJL--JF7F7L7JF7-FJL7LJL7L-JL7||||F7F-7|FJ||F--7||F7L-7||FJL-7|L|||FJL-7|||L--7||FJ|||L-7F--7|L-JL-JFJ|||L--7J77J7-LFF .F-7-L|JLL7LF---JL--JL7L-----JLJL7L7|L7L-7L7F7L-7F-J|||LJ|L7||L7||L-7||||L7FJLJ|F-7||FJ|||F7FJLJ|F7FJ|||FJLJF-J|F-JL7F--7FJ-LJL7F-JLLJFJ7-F| 7|FL7.|-.LF-L-------7FJF7F-------JFJ|FJF7|FJ||F7||F7|||F-JF||L7|||F7||||L7||F--JL7|||L7|||||L--7|||L7|||L7F7L-7|L-7||L-7|L---7FJL-7-J|FFL.-| LJ.L-FJFL-FFF7F7F7F7|L-J|L-7F----7L-J|FJ|||FJ||LJLJ|||||F7FJL7||||||||||FJ||L-7F7|||L7|||||L7F7||||FJLJL-J||F7LJF7L-JF7|L----J|F7FJ.LJ.|J-L| ||7|7JL-J||FJLJ|||||L--7|F7LJF---JF-7|L7LJ|L7|L--7L||||LJ|L7FJ|||||||LJ||-||F-J|LJ||.|||||L7||LJLJLJF-----JLJL7FJ|F7FJ|L-7F7F7LJLJF777.|L-J| -LJ-7-J|LL-L7F7LJLJ|F7FJLJ|F7L---7|FJL7L7FJFJL7F7|FJ||L-7|FJ|FJLJ||||F-JL7|||F7L-7||FJ|LJL7||L---7F-JF7F----7FJL7|||L7|F-J||||F---JL7-7L7J.F |.FL77FFJ7.LLJL---7LJ|L--7|||F--7LJL7FJFJL7L7J||||L7|L7FJ||FJL--7||||L7F7||||||F-J||L7|LF7|||F---J|F7|LJF-7FJL--JLJL-JLJF7|||LJF-7F-J-7LJ7-| |.|L||||-F7LLF7F7FL-7|JF7||||L-7L---JL7L7.|FJFJ|||7|L7|L7|||F7F-JLJ||FJ||||||||L-7||FJL7|LJ||L--7FJ||L77L7LJF77F7F7F7F7FJ||LJF-J||L7J||77|.| LLJJF|||.LFF-JLJL---JL-JLJ|||F7L-----7L7|FJ|7|FJ||FJFJ|FJ|||||L7F-7||L7|LJ||||L7FJLJL7FJ|F7|L7F7||FJL-JF7L-7|L7|||||LJ||FJ|F-JF-7L-J-F.F|L-| L||..J7J-LFL7F-7F----7F--7LJLJL7FF7F7L7LJL7L7||FJ|L7L7|L7||LJL7LJFJ||FJ|F-J||L7||F---J|FJ||L7LJ||||F---JL--J|FJ|||LJF-J||J|L--JFJF---77-.7LL FFF-7--7F-LFJ|LLJF--7LJF7L--7F7L-JLJL-JF7||FJ||L-J||FJ|FJ|L--7L7FJ.LJL-J|F7|L-JLJL7F7FJL7|L7L-7||||L--------JL-JLJF7L--JL-JF7F-JL|F--JJF-7FJ FLL7F-.L.|FJFJ-LFJF7L--JL---J|L--------JL7|L7|L-7F-JL7|L7|F7FJFJL---7F--J||L--7F77|||L7FJL7L7FJ||LJF-------------7||F--7F--J|L7F7||F7L-J||L| L|L7JLF.F-L7|-F7L7|L7F7F-7F-7|F----------JL-JL--J|F-7||FJ||||7|F7F7FJL--7|L7F-J||FJ|L7|L7FJFJL7LJF7L-----7F-----7||LJF-JL-77L7LJLJLJ|7-F-F.| F|-|.-JFLLLLJ7||FJ|FLJLJFJL7LJL----7F7F-7F7F-7F-7|L7||||FJ|LJFJ|||LJF---JL7|L--J|L-JL||||||L-7|F-JL---7F7LJF-7F7||L-7L---7L-7|F--7F7L7-F-L-| J..L.J.|-LFLF-J|L7|F----JF-JJF-----J|||FJ|||FJ|FJL-JLJ||L7L-7L7||L7FL-7F-7||F7F7|F---JL7|L--7||L-7F7F7LJL--JLLJLJ|F7L7F7L|F-J|L-7LJL-J-|..-J FF.FF.----JJL-7L7LJL----7|F-7L-7F---J||L-JLJL-JL--7F7FJ|7L7FJ.LJL7|F--JL7LJ||LJLJ|F7F7FJ|F7FJLJF7LJLJL-------7FF7LJL7LJL7|L-7|F7L7J||JF7-|.7 -J--L|FJJ.|LL7L7|F7F7F-7LJL7L7FJ|F---JL7F-7F7F7F-7LJ|L-JF-JL-7F--J|L7F7FJF-JL---7||||LJFJ|LJF--J|-F-----7F7F-JFJL7F7L---J|F-JLJ|FJ|L|J-|7LJJ |.||LLJJ.F77LFFJLJLJ|L7|F-7L7LJFJL-----JL7|||||L7|F7|F7FL-7F-JL--7L7LJLJ|L7F-7F-J|||L-7L7L-7L--7L7|F-7F7LJLJLFJF7LJL----7|L--7J|L-7F7J7|-J.| L7LL77J.F-777LL----7L-J|L7|7L--JJF7F7F7F-J||||L-JLJ|LJL-7FJL7FFF-JFJLF7F--JL7|L7FJ||F7|FJF7|F-7L7||L7LJL-----JFJL----7F-JL--7L7|F-JF77F77-L| L7|LL-7.L7L-7.FF-7|L--7|FJL7F7F7FJLJLJ||F7LJ|L----7L----JL-7L7FJF7|.FJLJF-7FJ|FJL7|LJ||L-JLJL7|FJLJFJF7F7F7F7FJF7F--7|L-7F7FL-JLJF-J|-FJF-JL |.FJF||FF|F-JF7L7|F7FFJ||F7LJLJ|L---7FJLJL7FJF7F-7L7F7F7F7FJFJL7||L7L-7FJFJL7||F-JL-7|L7F----J|L7F7|FJ||LJLJ|L-JLJF-JL-7LJL-7F---JF7|JJF7L-J FF||FFF--J|F-JL-JLJL7L7|LJL7F-7L----JL----JL-J|L7L7LJLJLJ|L-JF7||L7|F-JL7L7FJ||L-7F-JL-JL----7||LJLJL7|L--7FJF----JF7F7L----JL-7F-JLJF77L7LJ |-F-7|L--7|L-------7L7||LF-J|JL---------7F---7L7L7L7F7F-7L---J|LJF||L7F-JFJL7LJ7FJ|F---7F--7J||F7F7F7|L---JL7L-7F--JLJL7LF7JF7FJL---7-JL-77J |LL7L---7||F7F7F7F7L7||L7L--JF7F--------J|F--JFL-JFJ||L7L----7|F--J|.||F7|F7L-7FJFJL--7LJF7|FJ|||||||L---7F7L--J|F-7F-7L-JL7|LJF--7FJFJ7LL-7 F--JF--7LJ|||||||||.||L7|F7F7||L---7F----JL7F7F7F7L7|L7|F7-F7LJL7F7L7||||LJL7FJL-JF7F7L-7|LJL7|||||||F7F7LJL-7F-JL7|L7L----J|F-JF7LJ.FJ|--J- |F-7|JLL-7||||||LJL-JL-JLJLJLJL7.F-J|F-----J|||LJ||LJFLJ|L-JL7F7||L7||LJL7F7||-LF7||||F-J|F-7|||LJLJLJLJ|F---J|F--JL-JFF7|F7|L--J|F-77-JL-|. LJFLJJ.LFJLJLJLJF7F-7F7F-7F7F-7L7L--JL---7F7|||F7L------JF7F-J|LJL7||L7F7LJ||L7FJLJ|||L-7|L7|||L7F7F---7LJF7F7|L---7F--JL7|||F---JL7|L|.|LJ- |L|-F7F7L-7F7F-7|||7||||FJ||L7L7L---7F7F7LJLJ|||L------7FJ|L-7L7F7||L7|||F7||FJL--7LJL--JL-JLJL-J|LJF--JF-JLJLJF7F7LJF---J|LJL7F7F-JL-7-|JJ. |JF-JLJL--J|LJFJ|||FJ|||L7||FJFL7F-7LJLJL---7LJL7F7F--7LJLL--JFJ||||FJ||||LJ||J.F-JF7F7F-----7F7FJ7FJF-7|F-7F-7|LJ|F7L-7F7|F--J|LJF---J||-FF ||L7F-7F-7FJF-JFJLJL-J||F||||F--JL7L-7F-7F77L--7LJLJF7L------7|FJ|||L7LJ||JLLJF-JF-J||LJLF---J|||F7L7|.LJ|LLJFJL7LLJL--J|LJL-7J|F-JF---7J7.| .-LLJFJL7LJJL7FJ.F----JL7||||L----JF-J|FJ|L---7|F7F-J|F-7F-7FJLJF||L7|J-||77.FL--J7F|L7F-JF--7||||L7LJF-7L--7L-7L-7F7F7FJF--7L-JL7FJF--JL7-7 |.|-LL7FJF--7LJF-JF7F-7FJLJLJF77F--JF-JL7|F---JLJLJF7LJFLJFJL---7LJFJL7JLJ-7-F----77L-JL--JF-J|LJ|FJF7L7|F--JF7L--J|||||FJF7L-7F7LJFJ|||JLF7 F.J7FLLJFL-7|F-JF7|||FJ|F7F7FJL7L---JF-7LJL7JF7F7F-JL7FF-7L----7||FL-7L7J.L-FL---7L-7|F----JF-JF7||FJL-JLJF-7|L----JLJLJL-JL-7|||F7L---77-FJ LF|-F7.F---J|L7FJ|||||FJ||||L-7L-----JFL7F-JFJLJ||F-7L7L7|F--7J||7JJL|FJL7|.LJ|F-JF7L-JF7F7FJF-JLJLJF--7F7|FJ|F---7F7F7F-----JLJLJ|F---J.LLJ .F||L|.L---7L7|||LJLJLJFJLJL-7L--------7|L--JF-7LJL7L7L-JLJF7||||JL--LJ7FJF.7FFL-7|L7F7||||L7L7F----JF7LJLJL-JL--7|||||L----7F7F-7|L---7F7JJ .L----F-J-FL7|LJF7F----JF7F-7L--7F-----JL----J.L-7FJ.L7F-7FJLJ-LJ||.L|J|J.LLJF-F-J|L|||||||FJ7LJF7F--JL----7F--7FJ||LJL7F7F-J|||FJL-7F7|FL|J .L7L7-J-LF--JL7L||L-----J||7L--7LJF---7F7F7F7F--7|L7F7LJ.LJF7F|FLJ-F.|7J|.77F77L-7L7||||||LJ7F7FJ|L-7F----7|L-7|L7|L-7FJ||L--JLJL-77LJLJ7F|J JLJ7||F||L-7F7L-JL7F7F7F7LJF7F7L-7|F--J|LJLJLJF-JL-J||F7F--JL-77|L7JFLF-L7LL7J||L|FJLJLJLJ-F7||L7L-7LJF---JL-7|L-JL--JL-JL7F-7F--7L-7-J||F7J L|L-7JFFF7-LJ|F7F7LJLJLJL-7|LJL-7LJL---JF7F---JF7JF7|LJ||F--7FJL7JL-7F||L.-FJ-|LFLJF|J|F77FJ||L-JF-JF7L-----7|L-----7|-F-7|L7||F7L7FJ|||-J|7 F||FF7FF|L--7LJLJL-------7|L---7|F7F----JLJF---JL-JLJF7LJL-7LJJ7|.|J|FF|FF7|L-|JF7F7F7FJ|FJFJL-7FJF7||F7-F--JL7F---7L7FJFJL-JLJ|L7LJJ-FF7L|7 LL-FL77JL--7|LF7F--7F----JL---7|||LJF7JF---JF--7F-7F7|L7F7FJF7JFF-LFF-7J-JL.|JL-|LJLJ|L7|L7|F--JL-JLJLJL7L---7|L-77L7|L7|JF7|F-JFJ-LL7|--7|J |7.-7.|7F--JL7|LJF7LJF7F-7F7F7LJ|L--JL-JF--7L-7||FJ|||FJ||L-JL-7--FFL7|.||.F-.LFL--7FJFJL-J|L-7F7F7F-7F7L---7|L7FJF7LJFJL-JL7|F-JF7J|FJ.|--7 F7L-|-LL|F--7|L7FJS7FJLJJ||||L-7L---7F-7|F7L--JLJL-JLJ|FJ|F----JFF--7||7J.7L|-F|-LFJ|7L---7L7.LJLJLJF|||F--7LJFJL7||F7|F---7LJL--J|LJJ..L77J 77LF-JFFLJF-JL-J|F-J|F---J|||F-JF7F7LJF|LJL--7F7F7F--7LJFJL--7F77|F7LJL7L--F7.-F77L7|F7F77L7L-7F7F--7||LJF7L-7L--J|||LJL--7L7F7F-7L7|7-|7L7. FFJ|L.FJ|F|F-7F-JL-7|L----JLJL--JLJL--7L--7F7LJLJLJF-JF7L---7LJL7LJL7F-J-|-JJ7.||-|||||||F7L-7|||L-7|LJF-JL--JF7F-JLJF7F--JFLJ|L7L-J7F7|JFL- LJFJ-LL7FLLJ.||F--7||F-----7F7F7F-7F-7L--7LJL--7F--JF7|L---7L7F-JF--JL7JJ|||LF-|L--JLJLJLJL--JLJL7FJL7-L------JLJF---J||F--7F7L7L7F-7J7J7-LJ ||LJ.|L7.|7F-|||F7LJ|L----7|||||L7|L7L7F7|7F7F7LJF7-|LJF7F-JLLJJ7L--7FJ.F-7J-LFL---7F7F----7F---7|L-7|F7F---7F---JF--7LJ|F-J||FL7LJFJ.|.--LF LL7.F|.|FFLJJLJLJL--JFF---JLJLJL-JL-JL|||L-JLJL-7|L7|F-JLJF-7F7F7F7FJL--JFJJ.|.F---J|||F---J|F--JL--JLJ|L--7LJ-F7||F7L--JL--JL-7|F-JLFF-L-7J FJ7.||-FJ||7.LF---7-F7L7F7F7F-7F7F---7LJL--7F---JL7||L7F7FJFJ|LJ||||F7F7FJL-77-L7F7FJLJL-7F7|L----7F--7L---JJF-JL-J|L7F-7F7F---JLJ||.L|.|.|7 FLFL-77.|FFJ.|L7F7L7||FJ|LJLJJLJ|L7F-JF7|F7||F--7FJ||FJ|||FJ7L-7||LJ|||LJJ|L.|LLLJLJF----J|||F-7F7||F7L----7FJF7F7FJJLJL|||L--7F7LF-7JJ-7F-7 J.JJ.|7F7LJ.LF7LJL7|||L-JJF----7L-JL-7||FJ|LJ|F-JL7LJL7|LJL7F7FJ||F-JLJF7||JF|.FF--7L-7F-7|LJL7LJLJ||L7F---J|FJLJ||F7JF7LJ|F--J|L-7JJJ..|LJ| LF|J|.FL77L||||F7FJLJ|F7F-JF7F7L-----J||L7L7L||F--JF7FJ|F7FJ||L7|||F7JFJL7F7FF7LL-7|F7LJ|LJFF7L---7|L7LJF7F-JL--7LJ|L-JL-7LJF-7|F-J.F77-J7.| .LJ-L-77FF---J|||L--7||||F-JLJL-----7FJ|FJFJFJLJF7FJLJF||LJL||||LJLJ|FJF-J|L7||F-7|LJL7F7F--JL---7LJ|L--JLJF----JF7|F----JJFJFJ||F7F7|F7LLFJ F||F|-F-LL---7LJL--7||||LJF-7F------J|FJL7|JL7F-JLJF---JL--7|L7L-7F-J|FJ-FJFJ||L7|L7F-J||L--7F7F7L---------JF-7F7||||F--7F7L7L7|LJLJL--7.|LJ F|77|-|LJF7F7L----7||||L7JL7|L-7F----JL--JL7FJL7F7FL-7F----JL7|F-JL7-|L-7|FJFJL-J|FJL-7||F7|LJLJL--------7F7L7||LJLJLJF-J|L-JFJ|F--7F7FJ.L7| FJ|L.F-7-|LJ|F---7|LJ|L7|F7|L-7LJF----7F7F7LJF-J||F7F|L--77F7||L7F7L-JF-J|L7|F--7LJF--J|||L-7F7F7F7-F7F--J|L-JLJF-7F--JF7|F-7L-JL-7LJ||J|.L. L-J-F7.J.L-7|L--7|L-7L7||||L-7|F7L---7LJ|||F7L7FJLJL-JF-7L7|LJL7LJ|F7FJF7|FJLJF7L-7|F7-|||F7LJLJLJ|FJ|L---JF7F7FJJ|L---JLJL7L-7F-7L-7LJ-7-|7 L77FFL7LF--JL-77|L7JL7LJLJ|F7||||F--7L-7LJLJL7LJF----7L7L-JL--7L7FJ|||7||||LF-J|7FJ|||FJ|LJL-----7||FJJF7F-JLJ|L-7|F-7F----JF7LJ7|F-J7JFL7|| .|FF7J7LL--7F7L7L7L77L7F-7LJ||LJ|L-7|F7L7F7FF|F7L---7|FJLF7LF7L7|L7|LJFJ||L7L-7L7L7|||L7L7F-7F---JLJL-7||L---7L--JLJ.|L-----JL7FFJL--7-J-L-7 |-FJ||F7.F7LJL7L7|FJF7LJFJF7|L-7|F-J||L7LJL7FJ|L7F7FJ||F7|L7|L7||-|L77L7LJFJF-JFJFJLJ|FJFJL7|L---7F--7LJL----JF---7F-JF7F7F--7L7|F7F-JJ-7L-J LLL7L-J|FJL--7L7LJL-JL--JFJ|L--JLJF7LJFL---JL-JJLJ|L7||||L7LJFJ|L-JFJF7L7FJJL-7|FJF--JL7|FFJ|F---J|F-JF7F--7F-JF--J|F7||||L-7L-JLJ|L-7F-JFJ| J.LL--7|L-7F7L7L7F----7F-J7L--7F7FJL----7JF7F----7L-JLJ|||L-7L7L-7FJFJ|FJL7F--J|L7|F7FFJL7L7|L----JL7FJLJF7LJF-JJF7LJLJLJL-7L---7L|F-JJF7.FJ |7|LF-JL-7||L7L-J|F---J|F-----J|||F-----JFJLJF---JF-7F7||F-7L7|F-JL7L7LJF-JL--7L-J||L7L-7|FJL7F7F7F-J|7F7|L--JF-7|L-------7|F--7|7LJ.|LLF7J7 |-LJL7F--JLJ|L---JL7F7FJ|F-7F-7|LJL7F7-F-JF--JF--7L7||||||FJFJ|L-7FJFJF7|F7F7-L-7FJL7|F7|||F7LJLJ|L-7|FJLJF7F-JFJ|F-------J|L-7LJJFL-7.|JF-- 7|LF-JL--7F7F-----7|||L7LJFLJLLJF-7LJL7|F-J-F7L7FJFJLJ||||L7L7L--JL7|FJLJ||||F7FJL7FJLJLJ|LJL--7FJF7LJL7F7|||F-JFJL7F---7F7L-7L7LJ77L|F|FJJ| L7.L-7F--J||L----7|LJL-JF----7F7L7L--7LJL---J|FJL7L--7|||L7L7|F7F-7||L-7FJ|||||L7FJL7F7F7L7F7LFJL-JL--7LJLJ||L--JF7LJF--J|L-7L-J.|LJ-L-JFJF| FFF--JL--7||F7F7FJL--7F7L---7LJL7L--7L7F7F-7FJ|F-JF7FJLJL7|FJLJ||FJ||F-JL7LJ|||FJ|F7LJLJL7||L7L7F7F---JF---J|F---JL--JF7FJF7L---7.|J|LL7F--7 |JL---7F-J||||||L--7FJ||F7F7L--7L---JJLJ||FLJF||F-J|L7F7FJ|L7F7LJL7LJL7F7|F-J||L7||L--7F7||L7|-LJ|L7F-7L----JL7F7F7F--JLJFJL----JF-.J|JF-FJ. L.|F--JL--JLJLJ|7F-JL-J|||||F-7|F7F7F7F7LJF---J|L7FJ-||LJ.L7LJ|LF7L7F7LJ|||F7|L7|LJF--J|LJL-J|F-7|FJL7|F7F-7F-J|||LJF--7FJF7F77F7-7-JF-L.J-7 F-LL-7F7F-7F7F7L7L7F7F7LJLJLJFJLJLJLJLJL-7L---7L-JL-7||F7F7|F-JFJL-J|L--J|LJ|L7||F-JF-7L-7F--JL7||L-7|LJLJ-LJF7|||F-JF7LJFJLJL-J|.F7LJL|FJF| F7.F-J|||FJ|LJL7|JLJLJL-----7|F7F77F7F---J|F7F|F7F7FJ|||LJ|||F7L---7|F7F-JF-JFJ|||F7L7|F-JL-7JFJ|L7FJ|F------JLJLJL--JL7||F-----J7JL7JFFJF-7 LJ-|F7|LJ|FJF--JL-----------JLJLJL-JLJF---7||FJ|LJ||FJ|L-7|||||F--7|LJ|L-7L7FL7||||L7|||F7F-JFJFJ.|L7LJ.F-----7F-------JFJL----7F77JLFFL-LJ| L|FJ|LJF-JL7|F7F----------7F7F-7F--7F7|F--J||L7|F7LJ|FJF7||||||L-7||F-JF7|FJF7|||||FJ||LJ||F7L7|F7|FJLF7L----7|L--------JF7F---J|L77F7JFFJJ7 FL|FJF7|F--JLJLJF---7F-7F-J|||FJ|F-J|||L-7FJ|FJ||L7FJ|FJ||LJ||L7FJLJL7FJ|||FJ|||||||FJL7FJ|||FJ||||L7FJL7F7F7||F-7F------JLJ|F--JFJF7J.L7F77 LLLJL||LJF7F-7F-JF7FJL7|L--JLJL7|L7FJ|L-7||JLJFJ|FJL7|L7LJF7||||L---7||L|||L7|||||||L-7||FJ||L7LJ|L7|L-7||||||LJFJL----------JF7FJFJL-7LLFJL L7FF7|L--J||FJL7FJ|||FJL----7F7||FJL7L7FJ|L-7|L7|L--J|FJJFJ||L7|F7F-J||FJ||FJ||||LJL7FJLJL-JL7|7FJFJ|F-JLJ||LJF7L-7F----7F-7F-JLJ7|F--J7.|.| F--JLJF--7LJ|F7LJFJL7L-----7LJLJ||F7|FJ|FJF7|F-JL7F-7LJF7L7LJFJLJ|L-7LJ|FJ|L7|||L7F7||F7F7F--JL7|FJFJL-7F-JL--J|F-JL77F7LJ|LJ-F---JL7.|7L77F |F---7|.FJF7LJL7FJF7L------JF7F-J||||L7|L7|||L-7FJL7L-7|L-JF7L--7L7FJF-JL7L7|||L7||LJLJLJ||F7F7||L7L7F7|L7F7F7FJL--7L-JL--7F--JF-7F7L-7-7.F| LJ-F-JL7L-JL--7LJFJ|F7F7F---J|L-7||LJFJL7||||F-JL-7|F-JL--7|L7F-JFJ|.L7F7L7||||FJ|L-7F7F-J||||||L7L7|||L7||LJ|L--7FL7F7F--J|F--J-LJL--J-|-LJ LLFJF--JF--7F-JF7L7LJ||LJF---JF7|||FFJF7|LJLJL7F-7LJL7F7FFJL7|L-7L7L7-||L7|||LJ|FJF-J||L-7||LJ||FJFJ|||FJ||F-JF-7|F-J||L-7|||F--------7--JL| F-L7L7..L-7LJF7|L7L-7LJF-JF7F7||||L7|FJLJFF---JL7L7F7LJL7L7FJ|F-JJL7L7LJLLJ|L7FJL7L-7||F-J|L-7LJL7||LJ||FJ|L-7L7||L7FJ|F7L-JLJF7F-----J7.L|| JJFL7|7LL7L7FJ|L7L7FJF-JF7|||LJ||L7||||F--JF7F--JFJ||F7FJF|L7|L-7F7L7|FF--7|FJL7FJF-J||L7FJF7L--7|L--7||L7L7FJFJ||FJL7||L7F7F7||L-7F-7LF-7-7 |7L7||J-LJ.|L7L7L7||FJF-J|||L7JLJL|||L7|F7FJ||F-7L7||||L-7L7||F-J||FJL7|F-J||F7LJFJF7||FJ|FJL-7FJL-7FJLJLL7|L7L7LJ|F7|||FJ|||LJL--J|FJJL7|L| JJ|FLJ|LJ7LL-J.L7|||L7|-FJ|L7L---7|||FJLJLJFJLJFJFJ||||F7L7||LJ7FJLJF7LJL7L|LJL-7L7|||||FJ|F--JL--7|L--7.FLJ-L7|F-J|||||L7||L---7F-JL7.|F|-J |.-J.F7LJJLLLF--J|||FJ|FJFJFJF7F7|LJ||F7F--JF-7L7L-J||||L7||L7F-JF-7|L7F7L7L7F7FJFJ|||LJ|FJL7F7F7FJ|F-7L7F----J|L7FJLJ||FJ||F7F7LJF-7|7FL7.L -J.|F|7-7.F-JL--7|||L7|L7||L7||||L-7|||LJF-7L7L7L7F-J||L7LJL7|L-7|.|L7|||FJFJ|||||FJ|L-7||F7LJ||LJ.||FJFJL7F--7|F||F7JLJ|FJ||LJ|F-J|LJ|F|L7J ...|LLJLL7.|.|LLLJLJFJ|FJ|F-J|||L-7|LJL--JJ|FJ7L7|L7FJ|FJF--JL7FJ|FJFJ|||L7L7||L7||FJF-J|||L--JL--7LJ|FJF7||F-J|FJLJL7F-JL7|L-7|L7LJ7JFFF.-. |-F7-FLL|-LJ77|.LJJJL7|L7|L7FJ|L-7LJF------J|FF7LJFJ|FJL7|F--7|L7|L7L7||L7|FJ|L7|LJL7L-7LJL7F-7F-7L-7LJJ|||||F7|L--7FJL7F7||F7||FJ-F|7J||FJ7 |F|J.L.F-7|LJ-LJJ.|.L|L7||FJ|FJF7L-7L-7F---7L7|L-7L-J|F7||L7FJL7|L7|FJ|L7LJL7|FJL7F-JF7L-7FJL7|L7|F7L---J|||LJ||JF7LJF-J|||LJ||LJJFLJJLFJLJJ |LJL-J--|L-F7JL7J-F7||FJ||L7|L7||F7L7FJ|F--JFJL-7L---J||||FJ|F7||FJLJ|L7L--7||L-7|L7FJ|F-JL7FJL7||||F7F7FJLJF-JL-JL7L|F-J|L7.|L7J.|J7FFJ-|L| FL7JLF.LF77.L-FJ7.777||LLJJLJ7||||L7||FJL-7FJF--JF---7|LJLJFJ|||||F-7F-JF--JLJF-J|FJL7|L--7||F-J|||LJ|||L-7|L7F7F-7L7LJF-JFJ-L7|77J|FFFJF--- -F.FJLF7L7|7|.FL|7J|-LJ-F-----J|LJ|LJLJF--JL7L7F7||F-JL--7FJFJ|||LJFJL-7L----7L7FJL-7||F-7|||L-7||L-7|||F7|F-J||L7L7|F7L-7L7JL||||7|FLFF7L7. .-|L7|F|-J--77JLJLF|7FJLL--7F-7L------7L--7FJFJ|||FJF7F7FJ|FJFJ|L-7L7F-JF-7F-J|LJF--J|||7LJLJ|FJ||F7|||||LJL7FJ|FJFJLJL-7L-JLFLJ77F77.||LFJJ .FL|.-JL7|.JL77|JF||-L7F---J||L7F-----JF--J|FJFJ||L-J||LJL||-L7L7FJFJL7FJFJL----7L-7FJ|L---7F-JFJLJ||LJ||F7FJ|FJL7|F-7F7L-7J7JFLJ77LL-FL-JJ| F|--7|7-|-7|7JLLJL7JF|-L---7|F-JL-----7L7F7|L7|.LJ-F-JL--7||F-JFJL7|F-JL7L7F7F7FJF-JL7|F-7FJL7FJFF-JL7FJLJ|L7||F7||L7LJ|F-JJ7.||-|F-L--F.|JF -7-L7LJ7|.F|L-J.F.L--77J|.FJ||F7F7F---JL||||FJL7JF-JF7F7FJLJL-7|F7LJ|F7FJF||||||FL7F-J||FJ|F-JL-7L--7||F--JJ|||||||FJJ.|L7|F7-JF-LJFF7L-7L-7 ||F7L77L7.-7-77L||J77LF-7F|FJ|||||L7|-|JLJ|||F7|FL--J|||L7F---JLJ|F7LJ|L-7LJ||||F7|L-7||L7||F7F7L7.FJ||L7-F-J|LJLJ||J--L-J7LJ--F-|LLJ-.F77LF --7.FL-FJ.L.|FFJ|7.|FFL7LLLJ.LJ||L7L-77-|JLJ||LJF----J|L-JL7F-7F7LJL-7L7FJLFJ||||LJF-J|L7||||||L7L7L7|L7|JL7FJ.LLL|L77L|J.|7|7.F--L7J-FF||.7 L|L7J.LJ-7F|7.F7.|FJ-|FL.LJJ.LFJ|FJF7L7J.-F-JL7FJF7F-7L-7F-JL7|||F--7L7LJF-JFJLJ|F-J.LL7|LJ||LJFJFJ-LJ.LJ|F||J7.|L|FJ7F|-J|-|--J.|.F7-|L|LJJ .L7JL7F||LL7LL7L7LJ|--7.|J|7F7L7|L7||FJ7FFL-7FJL7||L7L7FJ|F7FJ|||L-7L-J|.L--J7JF|L7.JJL||JFJ|LLL-JJ||-LLJ-FLJ.F--.LJJ|F|7F|J|7J7L|7|LJJF-7F- 7JFJLFFJ|JLJ|FL7.L-L-LLL-F-LL-FJ|J||LJ7L|JLL||J-LJL-JJ||FJ|||FJ|L-7L-7JL7|JJ-J-7L-J7J7FLJLL7|L|LL7.LF-7J|L77L|L|L7L|-J-7J7.F-JF|FLL7LF-J|.J| 7|F7.-J.||F|FJ.|.F-J.--7-F-|7FL-J-LJ|.JFJ.|LLJJL||F---J|L-J||L7L7FJF-J.L-J|7.L|7-J-JFL7LJ.LLJ7-JFJ7LFJJ-F-.F.7-|7F7|FJF|.F-7J.|LJ-||-7J.-F-| L|7-7|F7--FF7--JF-7L7.|77|L|FJL|.7LJFJ.|L7F|-L.F|FL---7L7F-J|J|FJL7L-77J|-|--.LL-J.F|7||.LL|F77.|-FF7JJF-7-|7||JFFL-|.FJ7.7LFF-FJLLJJ.L-7.7- LLF--FF|F7-JJF|.|FJJFL7LF7-|.J--.L-F7.FJF|-77|.FLLJ7.F|FJL-7|FJL-7|F7|JFJ|J|JL--.L7JLJ7|.L|L-JF7|.FJ|.L777FJ-77|-7J-J-JL77|-F|7.F-7JL7-|7|.L |-|7|.|F7L|JFF7-.L.||-L.FJ.L.J7|FFJ||.|--|-FJ-7LLLL|.FJL7F7||L7F-JLJLJLJ-J.J7F777.||7FFF7F7LLJL.L-J7L7F||7LL7LF-JL--L7.L-J|FFJ-|7FF7FL7-|7J| FF--7FLLJF|7FF-.|.-7|7LF7J-L7|L-JJ7|77JJ..LL7F|FL|.L-L7FJ|LJL7||.F7JJJ..L|7J-FF7F|||FLLFFF|.|7|-|.F-JF-LL-F7L-JF-J77F-|7J-F.|JJLJJ|F||L|.|-J F77|LF|7F7L77L|.J.|JL|-7||LLFFJJJ7FJ||--7F7.FL-|FJ77|-LJFJF7FJ|L-J|7FFJ7F-7--L|7F--|J.F---J-F7J--7|.F|J-7F7J.J.FL.FFFJ|7LF-7L7.J|F|L||-L-77| L-JJL-JJJL7JL-L-JJJFJJLF-L-.F7.|LLL--J7J-LFL7L|JJJF-J7..L-JLJJL---J-LF-LJJL7.LLJJJJJLJ.L|J-LFLJL-L--|JJ-LLJL|J-|.-J|.L|JL|JJ.FF--7L-FJ-LJ.J- """.trimIndent() }
0
Kotlin
0
0
660d1a5733dd533aff822f0e10166282b8e4bed9
25,151
AOC2023
Creative Commons Zero v1.0 Universal
src/main/kotlin/g2901_3000/s2959_number_of_possible_sets_of_closing_branches/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g2901_3000.s2959_number_of_possible_sets_of_closing_branches // #Hard #Bit_Manipulation #Heap_Priority_Queue #Graph #Enumeration #Shortest_Path // #2024_01_16_Time_231_ms_(87.50%)_Space_39.9_MB_(75.00%) import java.util.LinkedList import java.util.Queue class Solution { private fun get(n: Int, maxDis: Int, mask: Int, al: List<MutableList<IntArray>>): Int { var nodes = 0 val m = BooleanArray(n) for (i in 0 until n) { val `val` = mask and (1 shl i) if (`val` > 0) { m[i] = true nodes++ } } if (nodes == n) { return 1 } for (startVertex in 0 until n) { if (m[startVertex]) { continue } val q: Queue<IntArray> = LinkedList() q.add(intArrayOf(startVertex, 0)) val dis = IntArray(n) dis.fill(Int.MAX_VALUE) dis[startVertex] = 0 var nodeCount = 1 while (q.isNotEmpty()) { val curr = q.poll() for (adj in al[curr[0]]) { if (!m[adj[0]] && curr[1] + adj[1] <= dis[adj[0]]) { if (dis[adj[0]] == Int.MAX_VALUE) { nodeCount++ } dis[adj[0]] = curr[1] + adj[1] q.add(intArrayOf(adj[0], dis[adj[0]])) } } } for (i in 0 until n) { if (!m[i] && dis[i] > maxDis) { return 0 } } if (nodes != n - nodeCount) { return 0 } } return 1 } private fun solve(n: Int, maxDis: Int, al: List<MutableList<IntArray>>): Int { var res = 0 for (i in 0 until (1 shl n)) { res += get(n, maxDis, i, al) } return res } fun numberOfSets(n: Int, maxDistance: Int, roads: Array<IntArray>): Int { val al: MutableList<MutableList<IntArray>> = ArrayList() for (i in 0 until n) { al.add(ArrayList()) } for (edge in roads) { al[edge[0]].add(intArrayOf(edge[1], edge[2])) al[edge[1]].add(intArrayOf(edge[0], edge[2])) } return solve(n, maxDistance, al) } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
2,393
LeetCode-in-Kotlin
MIT License
AddStrings.kt
ncschroeder
604,822,497
false
{"Kotlin": 19399}
/* https://leetcode.com/problems/add-strings/ Given two non-negative integers, `num1` and `num2` represented as string, return the sum of `num1` and `num2` as a string. You must solve the problem without using any built-in library for handling large integers (such as BigInteger). You must also not convert the inputs to integers directly. */ /* To solve this, we do the same thing that we would do if we were adding these 2 numbers without using a calculator. Start with the rightmost digit of both numbers and get the sum of these. If this is < 10, then prepend it to the result. If the sum is >= 10, then prepend the last digit of it to the result. Then get the digits that are to the left and do the same thing but add 1 to this if the sum was >= 10. If the strings are the same length, then we just do this for all digits, add 1 if applicable, and we're done. If the strings are different lengths, once we get to the point where we've iterated through all the digits of 1 string but not the other, take the digits of the string that has those remaining digits, add 1 to this if applicable, and then prepend this to the result and we're done. */ fun addStrings(num1: String, num2: String): String { // Index variables for iterating backwards through the strings var i1: Int = num1.lastIndex var i2: Int = num2.lastIndex val answerBuilder = StringBuilder() var add1 = false while (i1 >= 0 && i2 >= 0) { val digitsSum: Int = num1[i1].digitToInt() + num2[i2].digitToInt() + (if (add1) 1 else 0) add1 = digitsSum >= 10 // Prepend last digit of digitsSum answerBuilder.insert(0, digitsSum % 10) i1-- i2-- } if (num1.length == num2.length) { if (add1) { answerBuilder.insert(0, 1) } } else { // Get remaining digits from the longer param string var remainingDigits: String = if (i1 >= 0) num1.substring(0..i1) else num2.substring(0..i2) if (add1) { /* This is similar as what to do for the Plus One challenge. 1st, find the index of the last digit that isn't a 9. This is a digit that needs to be incremented. If the string only contains 9s then set remainingDigits to a string that is 1 digit longer than it currently is and has 1 as its 1st digit and 0s for the rest. Otherwise, make remainingDigits have the same digits it currently has before incrementIndex followed by the digit at incrementIndex incremented followed by 0s. */ val incrementIndex: Int = remainingDigits.indexOfLast { it != '9' } remainingDigits = if (incrementIndex == -1) { "1".padEnd(length = remainingDigits.length + 1, padChar = '0') } else { remainingDigits.take(incrementIndex) .plus(remainingDigits[incrementIndex].digitToInt() + 1) .padEnd(length = remainingDigits.length, padChar = '0') } } answerBuilder.insert(0, remainingDigits) } return answerBuilder.toString() }
0
Kotlin
0
0
c77d0c8bb0595e61960193fc9b0c7a31952e8e48
3,200
Coding-Challenges
MIT License
src/main/kotlin/g1901_2000/s1947_maximum_compatibility_score_sum/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g1901_2000.s1947_maximum_compatibility_score_sum // #Medium #Array #Dynamic_Programming #Bit_Manipulation #Backtracking #Bitmask // #2023_06_20_Time_179_ms_(100.00%)_Space_37.5_MB_(100.00%) class Solution { private lateinit var dp: Array<IntArray> private var m = 0 private lateinit var memo: Array<IntArray> fun maxCompatibilitySum(students: Array<IntArray>, mentors: Array<IntArray>): Int { val n = students[0].size m = students.size dp = Array(m) { IntArray(m) } for (i in 0 until m) { for (j in 0 until m) { var tmp = 0 for (k in 0 until n) { tmp += if (students[i][k] == mentors[j][k]) 1 else 0 } dp[i][j] = tmp } } memo = Array(m) { IntArray((1 shl m) + 1) } for (x in memo) { x.fill(-1) } return dp(0, 0) } private fun dp(idx: Int, mask: Int): Int { if (idx == m) { return 0 } if (memo[idx][mask] != -1) { return memo[idx][mask] } var ans = 0 for (i in 0 until m) { if (mask and (1 shl i) == 0) { ans = Math.max(ans, dp[idx][i] + dp(idx + 1, mask or (1 shl i))) } } memo[idx][mask] = ans return ans } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,378
LeetCode-in-Kotlin
MIT License
src/year2021/02/Day02.kt
Vladuken
573,128,337
false
{"Kotlin": 327524, "Python": 16475}
package year2021.`02` import readInput private enum class Command { Forward, Down, Up; } private data class CommandWrapper( val command: Command, val amount: Int, ) fun main() { fun parse(input: List<String>): List<CommandWrapper> { return input .map { val (command, amount) = it.split(" ") val result = when (command) { "forward" -> Command.Forward "down" -> Command.Down "up" -> Command.Up else -> error("Illegal State $command") } CommandWrapper(result, amount.toInt()) } } fun part1(input: List<String>): Int { var horizontal = 0 var depth = 0 parse(input) .forEach { (command, amount) -> when (command) { Command.Forward -> { horizontal += amount } Command.Up -> { depth -= amount } Command.Down -> { depth += amount } } } return horizontal * depth } fun part2(input: List<String>): Int { var aim = 0 var horizontal = 0 var depth = 0 parse(input) .forEach { (command, amount) -> when (command) { Command.Forward -> { horizontal += amount depth += aim * amount } Command.Up -> { aim -= amount } Command.Down -> { aim += amount } } } return horizontal * depth } // test if implementation meets criteria from the description, like: val testInput = readInput("Day02_test") check(part1(testInput) == 150) val input = readInput("Day02") println(part1(input)) println(part2(input)) }
0
Kotlin
0
5
c0f36ec0e2ce5d65c35d408dd50ba2ac96363772
2,132
KotlinAdventOfCode
Apache License 2.0
src/Day05.kt
polbins
573,082,325
false
{"Kotlin": 9981}
fun main() { fun part1( input: List<String>, numberOfStacks: Int ): String { val stacks: MutableList<ArrayDeque<Char>> = buildList(numberOfStacks) { add(ArrayDeque<Char>()) }.toMutableList() val crateSize = 4 var i = 0 for (s in input) { // put on to stack while (s.indexOf('[', startIndex = i).also { i = it } != -1) { val stackIndex: Int = Math.floorDiv(i, crateSize) while (stacks.size - 1 < stackIndex) { stacks.add(stacks.size, ArrayDeque()) } val char = s[i + 1] stacks[stackIndex].addFirst(char) i += 3 } // follow movements if (s.contains("move")) { val groupValues = "move (\\d+) from (\\d+) to (\\d+)".toRegex().find(s)!!.groupValues var count = groupValues[1].toInt() val from = groupValues[2].toInt() val to = groupValues[3].toInt() while (count > 0) { val char = stacks[from - 1].removeLast() stacks[to - 1].addLast(char) count-- } } } // print out top of stack return stacks.map { it.last() }.joinToString("") } fun part2( input: List<String>, numberOfStacks: Int ): String { val stacks: MutableList<ArrayDeque<Char>> = buildList(numberOfStacks) { add(ArrayDeque<Char>()) }.toMutableList() val crateSize = 4 var i = 0 for (s in input) { // put on to stack while (s.indexOf('[', startIndex = i).also { i = it } != -1) { val stackIndex: Int = Math.floorDiv(i, crateSize) while (stacks.size - 1 < stackIndex) { stacks.add(stacks.size, ArrayDeque()) } val char = s[i + 1] stacks[stackIndex].addFirst(char) i += 3 } // follow movements if (s.contains("move")) { val groupValues = "move (\\d+) from (\\d+) to (\\d+)".toRegex().find(s)!!.groupValues val count = groupValues[1].toInt() val from = groupValues[2].toInt() val to = groupValues[3].toInt() val last = stacks[from - 1].takeLast(count) repeat(count) { stacks[from - 1].removeLast() } stacks[to - 1].addAll(last) } } // print out top of stack return stacks.map { it.last() }.joinToString("") } // test if implementation meets criteria from the description, like: val testInput1 = readInput("Day05_test") check(part1(testInput1, 3) == "CMZ") val input1 = readInput("Day05") println(part1(input1, 9)) val testInput2 = readInput("Day05_test") check(part2(testInput2, 3) == "MCD") val input2 = readInput("Day05") println(part2(input2, 9)) }
0
Kotlin
0
0
fb9438d78fed7509a4a2cf6c9ea9e2eb9d059f14
2,661
AoC-2022
Apache License 2.0
src/Day05.kt
mcdimus
572,064,601
false
{"Kotlin": 32343}
import util.readInput @OptIn(ExperimentalStdlibApi::class) fun main() { fun part1(input: List<String>): String { val stacks = parseStacks(input) val commands = parseCommands(input) for (command in commands) { for (i in 0..<command.amount) { val c = stacks[command.fromStackIndex].removeFirst() stacks[command.toStackIndex].addFirst(c) } } return stacks.fold("") { acc, stack -> acc + stack.first() } } fun part2(input: List<String>): String { val stacks = parseStacks(input) val commands = parseCommands(input) for (command in commands) { val crates = mutableListOf<Char>() for (i in 0..<command.amount) { crates.add(stacks[command.fromStackIndex].removeFirst()) } crates.reversed().forEach { stacks[command.toStackIndex].addFirst(it) } } return stacks.fold("") { acc, stack -> acc + stack.first() } } // 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)) } private fun parseStacks(input: List<String>): MutableList<ArrayDeque<Char>> { val stacks = mutableListOf<ArrayDeque<Char>>() input.takeWhile { !it[1].isDigit() } .map { it.windowed(size = 3, step = 4) } .forEach { strings -> strings.forEachIndexed { stackIndex, crate -> if (stackIndex + 1 > stacks.size) { stacks.add(ArrayDeque()) } if (crate.isNotBlank()) { stacks[stackIndex].add(crate[1]) } } } return stacks } private fun parseCommands(input: List<String>) = input .dropWhile { it.isNotBlank() } .drop(1) .map { Command.of(it) } private data class Command(val amount: Int, val fromStackIndex: Int, val toStackIndex: Int) { companion object { fun of(value: String): Command { val ints = value .replace("move ", "") .replace("from ", "") .replace("to ", "") .split(' ') .map { it.toInt() } return Command(amount = ints[0], fromStackIndex = ints[1] - 1, toStackIndex = ints[2] - 1) } } }
0
Kotlin
0
0
dfa9cfda6626b0ee65014db73a388748b2319ed1
2,530
aoc-2022
Apache License 2.0
src/Day19.kt
Kvest
573,621,595
false
{"Kotlin": 87988}
import kotlin.math.max import kotlin.math.min fun main() { val testInput = readInput("Day19_test") val testBlueprints = testInput.map(Blueprint.Companion::fromString) check(part1(testBlueprints) == 33) val input = readInput("Day19") val blueprints = input.map(Blueprint.Companion::fromString) println(part1(blueprints)) println(part2(blueprints)) } private fun part1(blueprints: List<Blueprint>): Int { return blueprints.sumOf { it.number * calculateMaxGeodes(it, 24) } } private fun part2(blueprints: List<Blueprint>): Int { return calculateMaxGeodes(blueprints[0], 32) * calculateMaxGeodes(blueprints[1], 32) * calculateMaxGeodes(blueprints[2], 32) } private fun calculateMaxGeodes( blueprint: Blueprint, minutesLeft: Int, memo: MutableMap<Long, Int> = mutableMapOf(), oreRobotsCount: Int = 1, clayRobotsCount: Int = 0, obsidianRobotsCount: Int = 0, geodesRobotsCount: Int = 0, oreCount: Int = 0, clayCount: Int = 0, obsidianCount: Int = 0, geodesCount: Int = 0, ): Int { if (minutesLeft == 0) { return geodesCount } //Throw out resources, which can't be potentially spend by the end of the minutesLeft. //This reduces a lot of recursive calls because it collapse overlapping states val oreForKey = min(oreCount, minutesLeft * blueprint.oreMax) val clayForKey = min(clayCount, minutesLeft * blueprint.clayMax) val obsidianForKey = min(obsidianCount, minutesLeft * blueprint.obsidianMax) val key = minutesLeft * 1_000_000_000_000_000_000L + oreRobotsCount * 10_000_000_000_000_000L + clayRobotsCount * 100_000_000_000_000L + obsidianRobotsCount * 1000_000_000_000L + geodesRobotsCount * 10_000_000_000L + oreForKey * 100_000_000L + clayForKey * 1_000_000L + obsidianForKey * 10_000L + geodesCount * 100L if (key in memo) { return memo.getValue(key) } var result = 0 val canBuildOreRobot = oreCount >= blueprint.oreForOreRobot && oreRobotsCount < blueprint.oreMax val canBuildClayRobot = oreCount >= blueprint.oreForClayRobot && clayRobotsCount < blueprint.clayMax val canBuildObsidianRobot = oreCount >= blueprint.oreForObsidianRobot && clayCount >= blueprint.clayForObsidianRobot && obsidianCount <= blueprint.obsidianMax val canBuildGeodeRobot = oreCount >= blueprint.oreForGeodeRobot && obsidianCount >= blueprint.obsidianForGeodeRobot if (canBuildGeodeRobot) { result = max( result, calculateMaxGeodes( blueprint = blueprint, minutesLeft = minutesLeft - 1, memo = memo, oreRobotsCount = oreRobotsCount, clayRobotsCount = clayRobotsCount, obsidianRobotsCount = obsidianRobotsCount, geodesRobotsCount = geodesRobotsCount + 1, oreCount = oreCount + oreRobotsCount - blueprint.oreForGeodeRobot, clayCount = clayCount + clayRobotsCount, obsidianCount = obsidianCount + obsidianRobotsCount - blueprint.obsidianForGeodeRobot, geodesCount = geodesCount + geodesRobotsCount ) ) } if (canBuildObsidianRobot) { result = max( result, calculateMaxGeodes( blueprint = blueprint, minutesLeft = minutesLeft - 1, memo = memo, oreRobotsCount = oreRobotsCount, clayRobotsCount = clayRobotsCount, obsidianRobotsCount = obsidianRobotsCount + 1, geodesRobotsCount = geodesRobotsCount, oreCount = oreCount + oreRobotsCount - blueprint.oreForObsidianRobot, clayCount = clayCount + clayRobotsCount - blueprint.clayForObsidianRobot, obsidianCount = obsidianCount + obsidianRobotsCount, geodesCount = geodesCount + geodesRobotsCount ) ) } if (canBuildClayRobot) { result = max( result, calculateMaxGeodes( blueprint = blueprint, minutesLeft = minutesLeft - 1, memo = memo, oreRobotsCount = oreRobotsCount, clayRobotsCount = clayRobotsCount + 1, obsidianRobotsCount = obsidianRobotsCount, geodesRobotsCount = geodesRobotsCount, oreCount = oreCount + oreRobotsCount - blueprint.oreForClayRobot, clayCount = clayCount + clayRobotsCount, obsidianCount = obsidianCount + obsidianRobotsCount, geodesCount = geodesCount + geodesRobotsCount ) ) } if (canBuildOreRobot) { result = max( result, calculateMaxGeodes( blueprint = blueprint, minutesLeft = minutesLeft - 1, memo = memo, oreRobotsCount = oreRobotsCount + 1, clayRobotsCount = clayRobotsCount, obsidianRobotsCount = obsidianRobotsCount, geodesRobotsCount = geodesRobotsCount, oreCount = oreCount + oreRobotsCount - blueprint.oreForOreRobot, clayCount = clayCount + clayRobotsCount, obsidianCount = obsidianCount + obsidianRobotsCount, geodesCount = geodesCount + geodesRobotsCount ) ) } result = max( result, calculateMaxGeodes( blueprint = blueprint, minutesLeft = minutesLeft - 1, memo = memo, oreRobotsCount = oreRobotsCount, clayRobotsCount = clayRobotsCount, obsidianRobotsCount = obsidianRobotsCount, geodesRobotsCount = geodesRobotsCount, oreCount = oreCount + oreRobotsCount, clayCount = clayCount + clayRobotsCount, obsidianCount = obsidianCount + obsidianRobotsCount, geodesCount = geodesCount + geodesRobotsCount ) ) memo[key] = result return result } private val BLUEPRINT_FORMAT = Regex("Blueprint (\\d+): Each ore robot costs (\\d+) ore. Each clay robot costs (\\d+) ore. Each obsidian robot costs (\\d+) ore and (\\d+) clay. Each geode robot costs (\\d+) ore and (\\d+) obsidian.") private class Blueprint( val number: Int, val oreForOreRobot: Int, val oreForClayRobot: Int, val oreForObsidianRobot: Int, val clayForObsidianRobot: Int, val oreForGeodeRobot: Int, val obsidianForGeodeRobot: Int, ) { val oreMax: Int by lazy { maxOf(oreForOreRobot, oreForClayRobot, oreForObsidianRobot, oreForGeodeRobot) } val clayMax: Int get() = clayForObsidianRobot val obsidianMax: Int get() = obsidianForGeodeRobot companion object { fun fromString(str: String): Blueprint { val match = BLUEPRINT_FORMAT.find(str) val (number, oreForOreRobot, oreForClayRobot, oreForObsidianRobot, clayForObsidianRobot, oreForGeodeRobot, obsidianForGeodeRobot) = requireNotNull( match ).destructured return Blueprint( number.toInt(), oreForOreRobot.toInt(), oreForClayRobot.toInt(), oreForObsidianRobot.toInt(), clayForObsidianRobot.toInt(), oreForGeodeRobot.toInt(), obsidianForGeodeRobot.toInt() ) } } }
0
Kotlin
0
0
6409e65c452edd9dd20145766d1e0ea6f07b569a
7,623
AOC2022
Apache License 2.0
src/test/kotlin/com/igorwojda/string/ispalindrome/tolerant/Solution.kt
igorwojda
159,511,104
false
{"Kotlin": 254856}
package com.igorwojda.string.ispalindrome.tolerant // iterative solution private object Solution1 { private fun isTolerantPalindrome(str: String): Boolean { var characterRemoved = false var leftIndex = 0 var rightIndex = str.lastIndex while (leftIndex <= rightIndex) { if (str[leftIndex] != str[rightIndex]) { if (characterRemoved) { return false } characterRemoved = true when { str[leftIndex + 1] == str[rightIndex] -> leftIndex++ str[leftIndex] == str[rightIndex - 1] -> rightIndex-- else -> return false } } leftIndex++ rightIndex-- } return true } } // Recursive solution private object Solution2 { private fun isTolerantPalindrome(str: String, characterRemoved: Boolean = false): Boolean { return if (str.isEmpty() || str.length == 1) { true } else { if (str.first() == str.last()) { isTolerantPalindrome( str.substring(1 until str.lastIndex), characterRemoved, ) } else { if (characterRemoved) { false } else { if (str.length == 2) { return true } val removeLeftResult = isTolerantPalindrome( str.substring(2 until str.lastIndex), true, ) val removeRightResult = isTolerantPalindrome( str.substring(1 until str.lastIndex - 1), true, ) return removeLeftResult || removeRightResult } } } } } // recursive solution 2 private object Solution3 { private fun isTolerantPalindrome(str: String, characterRemoved: Boolean = false): Boolean { val revStr = str.reversed() if (revStr == str) return true if (characterRemoved) return false // Remove a single non-matching character and re-compare val removeIndex = str.commonPrefixWith(revStr).length if (removeIndex + 1 > str.length) return false // reached end of string val reducedStr = str.removeRange(removeIndex, removeIndex + 1) return if (isTolerantPalindrome(reducedStr, true)) { true } else { val reducedRevStr = revStr.removeRange(removeIndex, removeIndex + 1) isTolerantPalindrome(reducedRevStr, true) } } }
9
Kotlin
225
895
b09b738846e9f30ad2e9716e4e1401e2724aeaec
2,738
kotlin-coding-challenges
MIT License
src/main/kotlin/com/jacobhyphenated/day12/Day12.kt
jacobhyphenated
572,119,677
false
{"Kotlin": 157591}
package com.jacobhyphenated.day12 import com.jacobhyphenated.Day import java.io.File import kotlin.math.absoluteValue // The N-Body Problem class Day12: Day<List<List<Int>>> { override fun getInput(): List<List<Int>> { return this.javaClass.classLoader.getResource("day12/input.txt")!! .readText() .lines() .map {line -> line .trim() .removeSuffix(">") .split(", ") .map { it.split("=")[1].toInt() } } } /** * Given a list of moons (4) and their x,y,z positions (the puzzle input) * Each position updates based on the velocity. * Velocity is computed by the differences to every other moon along each dimension. * * So moon1 with an x position of 3 and moon 2 with an x position of -1, * moon1 x velocity decreases by 1, and moon2 x velocity increases by 1. * * For each step, update the velocities for all dimensions by comparing all moons to each other. * Then update the positions by adding the velocity to the appropriate dimension. * * After 1000 steps, what is the total energy of the system? */ override fun part1(input: List<List<Int>>): Number { val (positions, velocities) = doSteps(1000, input) return totalEnergy(positions, velocities) } /** * Eventually, the state of the universe will repeat. At what step does that happen? * * Because the next state be computed as a function of itself, the first state to repeat must be the first state. * (you can calculate step n-1 from step n) * It can take a very long time to get a repeat, brute force wont do it. * * Each dimension can be calculated independently, x is not dependent on y or z. * Compute the periodic repeat of x, y, and z independently. * Then return the least common multiple of each period * * Performance note: Finding the repeat periods sequentially does a lot of duplicate computations. * We could improve this by doing all three at once - stepping until all 3 periods found. */ override fun part2(input: List<List<Int>>): Number { return findRepeatPeriods(input).reduce { a,b -> leastCommonMultiple(a, b)} } /** * Total energy for a moon is computed by * - adding the absolute values of each position value * - adding the absolute values of each velocity value * - multiplying these two numbers together. * * Do this for all moons and sum the results */ fun totalEnergy(positions: List<List<Int>>, velocities: List<List<Int>>): Int { return positions.zip(velocities) .sumOf { (position, velocity) -> position.sumOf { it.absoluteValue } * velocity.sumOf { it.absoluteValue } } } // Helper method to execute n number of steps and return the position and velocity information at the end fun doSteps(steps: Int, input: List<List<Int>>): Pair<List<List<Int>>, List<List<Int>>> { val positions = input.map { mutableListOf(*it.toTypedArray()) } val velocities = mutableListOf<MutableList<Int>>() repeat(positions.size) { velocities.add(mutableListOf(0,0,0)) } repeat(steps) { doStep(positions, velocities) } return Pair(positions, velocities) } /** * Each dimension repeats its state eventually, and x,y,z are independent. * do steps until we find the minimum steps to repeat each dimensions state * * @return a list of the number of steps required to repeat for each dimension */ private fun findRepeatPeriods(input: List<List<Int>>): List<Long> { val positions = input.map { mutableListOf(*it.toTypedArray()) } val velocities = mutableListOf<MutableList<Int>>() repeat(positions.size) { velocities.add(mutableListOf(0,0,0)) } val isolateDimension: (List<List<Int>>, List<List<Int>>, Int) -> List<Pair<Int,Int>> = {ps, vs, dimension -> ps.map { it[dimension] }.zip(vs.map { it[dimension]} ) } val initialStates = (0..2).map { isolateDimension(positions, velocities, it)} val periods = mutableListOf<Long?>(null, null, null) var count: Long = 0 do { doStep(positions, velocities) count++ for (dimension in 0..2) { if (periods[dimension] == null && isolateDimension(positions, velocities, dimension) == initialStates[dimension]) { periods[dimension] = count } } } while (periods.any { it == null }) return periods.filterNotNull() } // Helper method to compute the state after the next step private fun doStep(positions: List<MutableList<Int>>, velocities: List<MutableList<Int>>) { // This is unpleasant - the first two loops compare all moons to each other. The 3rd loop covers all 3 dimensions. for (position1 in 0 until positions.size - 1) { for (position2 in position1 until positions.size) { for (dimension in 0..2) { val p1 = positions[position1][dimension] val p2 = positions[position2][dimension] if (p1 < p2) { velocities[position1][dimension] += 1 velocities[position2][dimension] -= 1 } else if (p1 > p2) { velocities[position1][dimension] -= 1 velocities[position2][dimension] += 1 } } } } // After velocities have been properly calculated, update the positions for ((i, position) in positions.withIndex()) { for (dimension in 0..2) { position[dimension] += velocities[i][dimension] } } } private fun leastCommonMultiple(m: Long, n:Long): Long { return m*n / gcd(m,n) } // tailrec allows the compiler to optimize for tail recursion private tailrec fun gcd(a: Long, b: Long): Long { return if (b == 0L) a.absoluteValue else gcd(b, a % b) } }
0
Kotlin
0
0
1a0b9cb6e9a11750c5b3b5a9e6b3d63649bf78e4
6,256
advent2019
The Unlicense
src/day04/Day04.kt
voom
573,037,586
false
{"Kotlin": 12156}
package day04 import readInput /** * --- Day 4: Camp Cleanup --- */ fun main() { fun toIntRanges(sections: String) = sections.split(',') .map { range -> val (left, right) = range .split('-') .map { it.toInt() } (left..right).toSet() } fun part1(input: List<String>): Int { return input .map { toIntRanges(it) } .let { it.count { (a, b) -> a.containsAll(b) || b.containsAll(a) } } } fun part2(input: List<String>): Int { return input .map { toIntRanges(it) } .let { it.count { (a, b) -> a.intersect(b).isNotEmpty() } } } // test if implementation meets criteria from the description, like: val testInput = readInput("day04/test_input") check(part1(testInput) == 2) check(part2(testInput) == 4) val input = readInput("day04/input") println(part1(input)) println(part2(input)) }
0
Kotlin
0
1
a8eb7f7b881d6643116ab8a29177d738d6946a75
1,097
aoc2022
Apache License 2.0
src/main/kotlin/io/github/lawseff/aoc2023/range/NestedRangeMapProblemSolver.kt
lawseff
573,226,851
false
{"Kotlin": 37196}
package io.github.lawseff.aoc2023.range import io.github.lawseff.aoc2023.range.entity.AlmanacEntityMapping import io.github.lawseff.aoc2023.range.entity.Range import io.github.lawseff.aoc2023.range.entity.SourceDestinationRange import io.github.lawseff.aoclib.Day import io.github.lawseff.aoclib.PartOne import io.github.lawseff.aoclib.PartTwo @Day(5) class NestedRangeMapProblemSolver { private val parser = AlmanacParser() @PartOne fun findMinLocationIdFromSeedIds(input: List<String>): Long { val almanac = parser.parseAlmanac(input) val locations = almanac.initialSeeds.map { findLastCorrespondingId(it, almanac.entityMappings) } return locations.min() } // This is a brute-force solution @PartTwo fun findMinLocationIdFromSeedIdRanges(input: List<String>): Long { val almanac = parser.parseAlmanac(input) val entityMappings = invert(almanac.entityMappings) val seedRanges = almanac.initialSeeds.chunked(2) .map { Range(it[0], it[1]) } var locationId = 1L while (!contains(seedRanges, findLastCorrespondingId(locationId, entityMappings))) { locationId++ } return locationId } private fun findLastCorrespondingId(startId: Long, entityMappings: List<AlmanacEntityMapping>): Long { return entityMappings.fold(startId) { currentId, mapping -> findNextCorrespondingId(currentId, mapping) } } private fun findNextCorrespondingId(sourceId: Long, mapping: AlmanacEntityMapping): Long { var correspondingId = sourceId for (range in mapping.ranges) { val sourceStartId = range.sourceStartId val sourceEndId = sourceStartId + range.rangeLength - 1 if (correspondingId in sourceStartId..sourceEndId) { val destinationSourceDifference = range.destinationStartId - range.sourceStartId correspondingId += destinationSourceDifference break } } return correspondingId } private fun invert(mappings: List<AlmanacEntityMapping>): List<AlmanacEntityMapping> { return mappings.reversed().map { invert(it) } } private fun invert(mapping: AlmanacEntityMapping): AlmanacEntityMapping { val sourceType = mapping.destinationType val destinationType = mapping.sourceType val ranges = mapping.ranges.map { SourceDestinationRange(it.destinationStartId, it.sourceStartId, it.rangeLength) } return AlmanacEntityMapping(sourceType, destinationType, ranges) } private fun contains(ranges: List<Range>, id: Long): Boolean { return ranges.any { contains(it, id) } } private fun contains(range: Range, id: Long): Boolean { val startId = range.startId val endId = startId + range.rangeLength - 1 return id in startId..endId } }
0
Kotlin
0
0
b60ab611aec7bb332b8aa918aa7c23a43a3e61c8
2,939
advent-of-code-2023
MIT License
kotlin/0051-n-queens.kt
neetcode-gh
331,360,188
false
{"JavaScript": 473974, "Kotlin": 418778, "Java": 372274, "C++": 353616, "C": 254169, "Python": 207536, "C#": 188620, "Rust": 155910, "TypeScript": 144641, "Go": 131749, "Swift": 111061, "Ruby": 44099, "Scala": 26287, "Dart": 9750}
class Solution { fun solveNQueens(n: Int): List<List<String>> { val cols = HashSet<Int>() //keep track of used columns, we iterate rows val posDia = HashSet<Int>() //...of positive diagonals R+C val negDia = HashSet<Int>() //...of negative diagonals R-C val temp: ArrayList<ArrayList<String>> = arrayListOf() // to hold our temporary distinct solution val res: ArrayList<ArrayList<String>> = arrayListOf() // result with each distinct solutin where each input is a solution fillWithQueens(0,n,res,cols,posDia,negDia,temp) return res } private fun fillWithQueens( row: Int, n: Int, res: ArrayList<ArrayList<String>>, cols: HashSet<Int>, posDia: HashSet<Int>, negDia: HashSet<Int>, board: ArrayList<ArrayList<String>> ){ //if we have filled the whole board with queens if(row == n){ val complete: ArrayList<String> = arrayListOf() for(i in 0..n-1){ val joined = board[i].joinToString(separator = "") complete.add(joined) } res.add(complete) return } for(column in 0 until n){ if(cols.contains(column) || posDia.contains(row+column) || negDia.contains(row-column)) continue val temp = tempRow(n) board.add(temp) cols.add(column) posDia.add(row+column) negDia.add(row-column) board[row][column] = "Q" fillWithQueens(row+1,n,res,cols,posDia,negDia,board) cols.remove(column) posDia.remove(row+column) negDia.remove(row-column) board[row][column] = "." } } private fun tempRow(n: Int): ArrayList<String>{ val temp: ArrayList<String> = arrayListOf() repeat(n){ temp.add(".") } return temp } }
337
JavaScript
2,004
4,367
0cf38f0d05cd76f9e96f08da22e063353af86224
1,974
leetcode
MIT License
kotlin/src/katas/kotlin/skiena/graphs/DFSApplications.kt
dkandalov
2,517,870
false
{"Roff": 9263219, "JavaScript": 1513061, "Kotlin": 836347, "Scala": 475843, "Java": 475579, "Groovy": 414833, "Haskell": 148306, "HTML": 112989, "Ruby": 87169, "Python": 35433, "Rust": 32693, "C": 31069, "Clojure": 23648, "Lua": 19599, "C#": 12576, "q": 11524, "Scheme": 10734, "CSS": 8639, "R": 7235, "Racket": 6875, "C++": 5059, "Swift": 4500, "Elixir": 2877, "SuperCollider": 2822, "CMake": 1967, "Idris": 1741, "CoffeeScript": 1510, "Factor": 1428, "Makefile": 1379, "Gherkin": 221}
package katas.kotlin.skiena.graphs import katas.kotlin.skiena.graphs.UnweightedGraphs.diamondGraph import katas.kotlin.skiena.graphs.UnweightedGraphs.linearGraph import katas.kotlin.skiena.graphs.UnweightedGraphs.meshGraph import datsok.shouldEqual import org.junit.Test fun <T> Graph<T>.hasCycles(): Boolean { val fromVertex = vertices.first() val visited = HashSet<T>().apply { add(fromVertex) } dfsEdges(fromVertex).forEach { edge -> val justAdded = visited.add(edge.to) if (!justAdded) return true } return false } fun <T> Graph<T>.findCutVertices( vertex: T = vertices.first(), visited: MutableSet<T> = HashSet<T>().apply { add(vertex) }, parent: MutableMap<T, T> = HashMap(), depth: MutableMap<T, Int> = HashMap<T, Int>().apply { put(vertex, 1) }, low: MutableMap<T, Int> = HashMap<T, Int>().apply { put(vertex, 1) }, result: MutableSet<T> = HashSet() ): Set<T> { var isCutVertex = false var childCount = 0 edgesByVertex[vertex]?.forEach { (from, to) -> val justAdded = visited.add(to) if (justAdded) { childCount++ parent[to] = from depth[to] = depth[from]!! + 1 low[to] = depth[to]!! findCutVertices(to, visited, parent, depth, low, result) if (low[to]!! >= depth[from]!!) isCutVertex = true low[from] = minOf(low[from]!!, low[to]!!) } else if (to != parent[from]) { low[from] = minOf(low[from]!!, depth[to]!!) } } if (parent[vertex] != null && isCutVertex) result.add(vertex) if (parent[vertex] == null && childCount > 1) result.add(vertex) return result } class DFSApplicationsTests { @Test fun `find cycles in an undirected graph`() { linearGraph.hasCycles() shouldEqual false diamondGraph.hasCycles() shouldEqual true meshGraph.hasCycles() shouldEqual true } @Test fun `find cut vertices of undirected graph`() { linearGraph.findCutVertices() shouldEqual setOf(2) diamondGraph.findCutVertices() shouldEqual emptySet() meshGraph.findCutVertices() shouldEqual emptySet() // 3 // / \ // 2 4--5--6 // \ / // 1 Graph.readInts("1-2,1-4,2-3,3-4,4-5,5-6").findCutVertices() shouldEqual setOf(4, 5) // 2--3--6 // | | | // 1--4--5 Graph.readInts("1-2,1-4,2-3,3-4,4-5,5-6,6-3").findCutVertices() shouldEqual emptySet() // 2--3--4 // | | | // 1--6--5 Graph.readInts("1-2,1-6,2-3,3-4,4-5,5-6,3-6").findCutVertices() shouldEqual emptySet() Graph.readInts( "1-2,1-3,2-3,3-4,4-5,4-6,5-6," + "1-7,1-8,7-8,8-9,8-10,9-10,9-11,10-11" ).savedAsPng("exampleFromSkiena").findCutVertices() shouldEqual setOf(1, 3, 4, 8) } }
7
Roff
3
5
0f169804fae2984b1a78fc25da2d7157a8c7a7be
2,868
katas
The Unlicense
src/test/kotlin/nl/dirkgroot/adventofcode/year2022/Day07Test.kt
dirkgroot
317,968,017
false
{"Kotlin": 187862}
package nl.dirkgroot.adventofcode.year2022 import io.kotest.core.spec.style.StringSpec import io.kotest.matchers.shouldBe import nl.dirkgroot.adventofcode.util.input import nl.dirkgroot.adventofcode.util.invokedWith import java.util.* private fun solution1(input: String): Long { val directories = findDirectories(input) return directories.entries.map { (_, size) -> size }.filter { it <= 100000 }.sum() } private fun solution2(input: String): Long { val directories = findDirectories(input) val rootSize = directories.getValue("/") return directories.entries.map { (_, size) -> size }.sorted() .first { 70000000L - rootSize + it >= 30000000L } } private fun findDirectories(input: String): Map<String, Long> { val stack = Stack<Pair<String, Long>>() val directories = mutableMapOf<String, Long>() var currentDir = "/" var currentSize = 0L input.lineSequence().drop(1) .filter { it.matches("(\\$ cd|\\d+) .*".toRegex()) } .forEach { entry -> if (entry == "$ cd ..") { directories[currentDir] = currentSize val (dir, size) = stack.pop() currentDir = dir currentSize += size } else if (entry.startsWith("$ cd")) { val newDir = entry.substring(5) stack.push(currentDir to currentSize) currentSize = 0L currentDir += "/$newDir" } else currentSize += entry.takeWhile { it != ' ' }.toLong() } directories[currentDir] = currentSize while (stack.isNotEmpty()) { val (dir, size) = stack.pop() currentDir = dir currentSize += size directories[currentDir] = currentSize } return directories } //===============================================================================================\\ private const val YEAR = 2022 private const val DAY = 7 class Day07Test : StringSpec({ "example part 1" { ::solution1 invokedWith exampleInput shouldBe 95437L } "part 1 solution" { ::solution1 invokedWith input(YEAR, DAY) shouldBe 1611443L } "example part 2" { ::solution2 invokedWith exampleInput shouldBe 24933642L } "part 2 solution" { ::solution2 invokedWith input(YEAR, DAY) shouldBe 2086088L } }) private val exampleInput = """ ${'$'} cd / ${'$'} ls dir a 14848514 b.txt 8504156 c.dat dir d ${'$'} cd a ${'$'} ls dir e 29116 f 2557 g 62596 h.lst ${'$'} cd e ${'$'} ls 584 i ${'$'} cd .. ${'$'} cd .. ${'$'} cd d ${'$'} ls 4060174 j 8033020 d.log 5626152 d.ext 7214296 k """.trimIndent()
1
Kotlin
1
1
ffdffedc8659aa3deea3216d6a9a1fd4e02ec128
2,796
adventofcode-kotlin
MIT License
src/main/kotlin/com/hj/leetcode/kotlin/problem2369/Solution.kt
hj-core
534,054,064
false
{"Kotlin": 619841}
package com.hj.leetcode.kotlin.problem2369 /** * LeetCode page: [2369. Check if There is a Valid Partition For The Array](https://leetcode.com/problems/check-if-there-is-a-valid-partition-for-the-array/); */ class Solution { /* Complexity: * Time O(N) and Space O(N) where N is the size of nums; */ fun validPartition(nums: IntArray): Boolean { // dp[i] ::= validPartition(nums[i:]) val dp = BooleanArray(nums.size + 3) dp[nums.size] = true dp[nums.size + 1] = false dp[nums.size + 2] = false for (i in nums.indices.reversed()) { dp[i] = ((dp[i + 2] && nums.isAllEqual(i..i + 1)) || (dp[i + 3] && nums.isAllEqual(i..i + 2)) || (dp[i + 3] && nums.isConsecutiveIncreasing(i..i + 2))) } return dp[0] } private fun IntArray.isAllEqual(indexRange: IntRange): Boolean { return indexRange.all { index -> this[index] == this[indexRange.first] } } private fun IntArray.isConsecutiveIncreasing(indexRange: IntRange): Boolean { return indexRange.withIndex().all { (difference, index) -> this[index] == this[indexRange.first] + difference } } }
1
Kotlin
0
1
14c033f2bf43d1c4148633a222c133d76986029c
1,228
hj-leetcode-kotlin
Apache License 2.0
src/main/kotlin/day18/Day18.kt
dustinconrad
572,737,903
false
{"Kotlin": 100547}
package day18 import geometry.Coord3d import geometry.containedBy import geometry.neighbors import geometry.parseCoord3d import geometry.x import geometry.y import geometry.z import readResourceAsBufferedReader fun main() { println("part 1: ${part1(readResourceAsBufferedReader("18_1.txt").readLines())}") println("part 2: ${part2(readResourceAsBufferedReader("18_1.txt").readLines())}") } fun part1(input: List<String>): Int { val coords = input.map { parseCoord3d(it) } val droplets = LavaDroplets(coords) return droplets.totalSurfaceArea } fun part2(input: List<String>): Int { val coords = input.map { parseCoord3d(it) } val droplets = LavaDroplets(coords) return droplets.outerSurfaceArea() } class LavaDroplets(droplets: Collection<Coord3d>) { private val droplets = droplets.toSet() private val min: Coord3d private val max: Coord3d init { var minX = Int.MAX_VALUE var maxX = Int.MIN_VALUE var minY = Int.MAX_VALUE var maxY = Int.MIN_VALUE var minZ = Int.MAX_VALUE var maxZ = Int.MIN_VALUE droplets.forEach { minX = minOf(minX, it.x()) maxX = maxOf(maxX, it.x()) minY = minOf(minY, it.y()) maxY = maxOf(maxY, it.y()) minZ = minOf(minZ, it.z()) maxZ = maxOf(maxZ, it.z()) } min = Triple(minX, minY, minZ) max = Triple(maxX, maxY, maxZ) } private fun surfaceArea(droplets: Collection<Coord3d>, validate: (Coord3d) -> Boolean): Int { val surfaceAreas = droplets.associateWith { 6 }.toMutableMap() surfaceAreas.keys.forEach { val neighbors = neighbors(it, validate) neighbors.forEach { n -> surfaceAreas[n] = surfaceAreas[n]!! - 1 } } return surfaceAreas.values.sum() } private fun neighbors(droplet: Coord3d, validate: (Coord3d) -> Boolean): Set<Coord3d> { return droplet.neighbors() .filter { validate(it) } .toSet() } val totalSurfaceArea = surfaceArea(droplets) { droplets.contains(it) } fun outerSurfaceArea(): Int { val internalIslands = internalIslands() val internalSurfaceAreas = internalIslands.associateWith { island -> surfaceArea(island) { !droplets.contains(it) } } val internalSurfaceArea = internalSurfaceAreas.values.sum() return totalSurfaceArea - internalSurfaceArea } fun internalIslands(): Set<Set<Coord3d>> { val unvisited = mutableSetOf<Coord3d>() for (x in min.x()..max.x()) { for (y in min.y()..max.y()) { for (z in min.z()..max.z()) { val candidate = Triple(x, y, z) if (!droplets.contains(candidate)) { unvisited.add(candidate) } } } } val externalIslands = mutableSetOf<Set<Coord3d>>() val internalIslands = mutableSetOf<Set<Coord3d>>() while(unvisited.isNotEmpty()) { var isInternal = true val currIsland = mutableSetOf<Coord3d>() val q = ArrayDeque<Coord3d>() val start = unvisited.first() q.add(start) while(q.isNotEmpty()) { val next = q.removeFirst() if (!unvisited.remove(next)) { continue } currIsland.add(next) val neighbors = next.neighbors() if (neighbors.any { !it.containedBy(min, max)}) { isInternal = false } val unvisitedNeighbors = neighbors.filter { unvisited.contains(it) } q.addAll(unvisitedNeighbors) } if (isInternal) { internalIslands.add(currIsland) } else { externalIslands.add(currIsland) } } return internalIslands } }
0
Kotlin
0
0
1dae6d2790d7605ac3643356b207b36a34ad38be
4,040
aoc-2022
Apache License 2.0
src/main/kotlin/com/dvdmunckhof/aoc/event2021/Day02.kt
dvdmunckhof
318,829,531
false
{"Kotlin": 195848, "PowerShell": 1266}
package com.dvdmunckhof.aoc.event2021 import com.dvdmunckhof.aoc.splitOnce class Day02(private val input: List<String>) { fun solvePart1(): Int = solve { state, direction, distance -> when (direction) { "forward" -> state.copy(position = state.position + distance) "up" -> state.copy(depth = state.depth - distance) "down" -> state.copy(depth = state.depth + distance) else -> error("Invalid direction") } } fun solvePart2(): Int = solve { state, direction, distance -> when (direction) { "forward" -> state.copy(position = state.position + distance, depth = state.depth + state.aim * distance) "up" -> state.copy(aim = state.aim - distance) "down" -> state.copy(aim = state.aim + distance) else -> error("Invalid direction") } } private fun solve(move: (state: State, direction: String, distance: Int) -> State): Int { val state = input.fold(State(0, 0, 0)) { state, next -> val (direction, distance) = next.splitOnce(" ") move(state, direction, distance.toInt()) } return state.position * state.depth } private data class State(val position: Int, val depth: Int, val aim: Int) }
0
Kotlin
0
0
025090211886c8520faa44b33460015b96578159
1,291
advent-of-code
Apache License 2.0
src/main/kotlin/Day08.kt
AlmazKo
576,500,782
false
{"Kotlin": 26733}
typealias Map = Array<IntArray> object Day08 : Task { @JvmStatic fun main(args: Array<String>) = execute() override fun part1(input: Iterable<String>): Any { val map = parse(input) val copter = Copter(map) val visible = copter.launch() return visible.sumOf { it.count { it > 0 } } } override fun part2(input: Iterable<String>): Any { val map = parse(input) val copter = Copter2(map) val bestScore = copter.launch() return bestScore } class Copter(private val grid: Map) { private val visible: Map = Array(grid.size) { IntArray(grid.first().size) } private val width = grid.first().size private val height = grid.size private var highestTree: Int = -1 fun launch(): Array<IntArray> { repeat(height) { y -> highestTree = -1 toEast(y) highestTree = -1 toWest(y) } repeat(width) { x -> highestTree = -1 toSouth(x) highestTree = -1 toNorth(x) } return visible } private fun toEast(y: Int) = repeat(width) { onTree(it, y) } private fun toWest(y: Int) = repeat(width) { onTree(width - it - 1, y) } private fun toSouth(x: Int) = repeat(height) { onTree(x, it) } private fun toNorth(x: Int) = repeat(height) { onTree(x, height - it - 1) } private fun onTree(x: Int, y: Int) { val t = grid[y][x] if (t > highestTree) { visible[y][x] = 1 highestTree = t } } } class Copter2(private val grid: Map) { private val width = grid.first().size private val height = grid.size fun launch(): Int { return (0..(width * height)).iterator().asSequence() .map { lookup(it % width, it / height) } .max() } private fun lookup(x: Int, y: Int): Int { if (x == 0 || y == 0) return 0 val current = grid[y][x] val north = toNorth(x, y, current) val south = toSouth(x, y, current) val west = toWest(x, y, current) val east = toEast(x, y, current) return north * south * west * east } private fun toNorth(x: Int, y: Int, max: Int): Int { var distance = 0 for (y in (y - 1)downTo 0) { distance += 1 if (grid[y][x] >= max) break } return distance } private fun toSouth(x: Int, y: Int, max: Int): Int { var distance = 0 for (y in (y + 1) until height) { distance += 1 if (grid[y][x] >= max) break } return distance } private fun toEast(x: Int, y: Int, max: Int): Int { var distance = 0 for (x in (x + 1) until width) { distance += 1 if (grid[y][x] >= max) break } return distance } private fun toWest(x: Int, y: Int, max: Int): Int { var distance = 0 for (x in (x - 1) downTo 0) { distance += 1 if (grid[y][x] >= max) break } return distance } } // --- util fun parse(input: Iterable<String>): Map { return input.map { it.toCharArray().map { it.code - 48 }.toIntArray() }.toTypedArray() } }
0
Kotlin
0
1
109cb10927328ce296a6b0a3600edbc6e7f0dc9f
3,632
advent2022
MIT License
src/Day05_part1.kt
lowielow
578,058,273
false
{"Kotlin": 29322}
class Stack { val input = readInput("Day05") private val rawList = mutableListOf<MutableList<Char>>() private val newList = mutableListOf<MutableList<Char>>() fun addStack(str: String) { var raw = "" for (i in 1 until str.length step 4) { raw += str[i].toString() } rawList.add(raw.toMutableList()) } fun arrangeStack() { for (j in 0 until rawList[0].size) { var new = "" for (i in 0 until rawList.size) { if (rawList[i][j] == ' ') { continue } else { new = rawList[i][j] + new } } newList.add(new.toMutableList()) } } fun handleMove(regex: Regex, str: String) { val match = regex.find(str)!! val (a, b, c) = match.destructured var i = 0 while (i != a.toInt()) { newList[c.toInt() - 1].add(newList[b.toInt() - 1][newList[b.toInt() - 1].size - 1]) newList[b.toInt() - 1].removeAt(newList[b.toInt() - 1].size - 1) i++ } } fun printTopStack(): String { var str = "" for (i in newList.indices) { str += newList[i][newList[i].size - 1].toString() } return str } } fun main() { val stack = Stack() val regexStack = Regex(".*[A-Z].*") val regexMove = Regex("\\D*(\\d+)\\D*(\\d)\\D*(\\d)") fun part1(input: List<String>): String { for (i in input.indices) { if (regexStack.matches(input[i])) { stack.addStack(input[i]) } else if (input[i].isEmpty()) { stack.arrangeStack() } else if (regexMove.matches(input[i])) { stack.handleMove(regexMove, input[i]) } } return stack.printTopStack() } part1(stack.input).println() }
0
Kotlin
0
0
acc270cd70a8b7f55dba07bf83d3a7e72256a63f
1,926
aoc2022
Apache License 2.0
src/day22/day22.kt
kacperhreniak
572,835,614
false
{"Kotlin": 85244}
package day22 import readInput private fun Direction.rotateRight(): Direction = when (this) { Direction.LEFT -> Direction.UP Direction.RIGHT -> Direction.DOWN Direction.UP -> Direction.RIGHT Direction.DOWN -> Direction.LEFT } private fun Direction.rotateLeft(): Direction = when (this) { Direction.LEFT -> Direction.DOWN Direction.DOWN -> Direction.RIGHT Direction.RIGHT -> Direction.UP Direction.UP -> Direction.LEFT } private fun Direction.makeRotation(char: Char): Direction = when (char) { 'R' -> rotateRight() 'L' -> rotateLeft() else -> throw IllegalArgumentException() } private fun parseBoard(input: List<String>): Array<CharArray> { val maxSize = input.maxBy { it.length }.length val board = Array(input.size - 2) { CharArray(maxSize) { '|' } } input.forEachIndexed { rowIndex, line -> for ((colIndex, item) in line.withIndex()) { if (item == '.' || item == '#') board[rowIndex][colIndex] = item } } return board } private fun parseMovement(input: List<String>): List<Action> { val movements = mutableListOf<Action>() var startIndex = 0 val line = input.last() for ((index, item) in line.withIndex()) { if (item == 'R' || item == 'L') { movements.add( Action.Steps(value = line.substring(startIndex, index).toInt()) ) movements.add(Action.Rotate(item)) startIndex = index + 1 } } movements.add(Action.Steps(value = line.substring(startIndex).toInt())) return movements } private fun startPoint(input: List<String>): Pair<Int, Int> { for ((index, item) in input[0].withIndex()) { if (item == '.') { return Pair(0, index) } } throw IllegalStateException() } private fun calculateResult(position: Pair<Int, Int>, direction: Direction): Int { return 1000 * (position.first + 1) + 4 * (position.second + 1) + direction.ordinal } private fun Pair<Int, Int>.getItem(board: Array<CharArray>): Char = board[first][second] fun strategyPartOne( state: State, board: Array<CharArray>, move: Action.Steps ): State { fun newInEdge(point: Pair<Int, Int>): Pair<Int, Int> { return if (point.first < 0) { point.copy(first = board.size - 1) } else if (point.first >= board.size) { point.copy(first = 0) } else if (point.second < 0) { point.copy(second = board[0].size - 1) } else if (point.second >= board[0].size) { point.copy(second = 0) } else point } fun Pair<Int, Int>.next(direction: Direction): Pair<Int, Int> { val result = when (direction) { Direction.LEFT -> this.copy(second = this.second - 1) Direction.RIGHT -> this.copy(second = this.second + 1) Direction.UP -> this.copy(first = this.first - 1) Direction.DOWN -> this.copy(first = this.first + 1) } return newInEdge(result) } fun findNewStartPosition(startPoint: Pair<Int, Int>): Pair<Int, Int> { var next = startPoint while (next.getItem(board) == '|') { next = next.next(state.direction) } return next } var next = state.position var counter = move.value while (counter > 0) { val previous = next next = next.next(state.direction) if (next.getItem(board) == '|') { next = findNewStartPosition(next) } if (next.getItem(board) == '#') { next = previous break } counter-- } return state.copy( position = next ) } private fun solution( startPoint: Pair<Int, Int>, strategies: List<Action>, handleStrategy: (state: State, strategy: Action.Steps) -> State ): Int { var state = State( position = startPoint, direction = Direction.RIGHT ) for (strategy in strategies) { state = when (strategy) { is Action.Steps -> handleStrategy(state, strategy) is Action.Rotate -> state.copy( direction = state.direction.makeRotation(char = strategy.char) ) } println(state) } return calculateResult(state.position, state.direction) } private fun part1(input: List<String>): Int { val startPoint = startPoint(input) val board = parseBoard(input) val strategies = parseMovement(input) val handleStrategy = { state: State, move: Action.Steps -> strategyPartOne(state, board, move) } return solution(startPoint, strategies, handleStrategy) } private fun strategyPartTwo( state: State, board: Array<CharArray>, move: Action.Steps ): State { var direction = state.direction fun newInEdge(point: Pair<Int, Int>): Pair<Int, Int> { val bigRow = point.first / 50 val bigCol = point.second / 50 val smallRow = point.first - bigRow * 50 val smallCol = point.second - bigCol * 50 var next = point if (bigRow == 0 && bigCol == 0) { if (direction == Direction.LEFT) { direction = Direction.RIGHT next = Pair(3 * 50 - 1 - smallRow, 0) println("1: $point; $bigRow $bigCol $smallRow $smallCol Next $next") } else throw IllegalStateException("Point 0,0 shouldn't be here with this direction: $direction") } else if (bigCol == 1 && point.first < 0) { if (direction == Direction.UP) { direction = Direction.RIGHT next = Pair(3 * 50 + smallCol, 0) println("2: $point; $bigRow $bigCol $smallRow $smallCol Next $next") } else throw IllegalStateException("Point 0,0 shouldn't be here with this direction: $direction") } else if (bigCol == 2 && point.first < 0) { if (direction == Direction.UP) { // Potential place direction = Direction.UP next = Pair(4 * 50 - 1, smallCol) println("3: $point; $bigRow $bigCol $smallRow $smallCol Next $next") } else throw IllegalStateException("Point 0,0 shouldn't be here with this direction: $direction") } else if (bigRow == 0 && bigCol == 3) { // TODO CHANGE if (direction == Direction.RIGHT) { direction = Direction.LEFT next = Pair(3 * 50 - 1 - smallRow, 2 * 50 - 1) println("4: $point; $bigRow $bigCol $smallRow $smallCol Next $next") } else throw IllegalStateException("Point 0,0 shouldn't be here with this direction: $direction") } else if (bigRow == 1 && bigCol == 2) { if (direction == Direction.DOWN) { direction = Direction.LEFT next = Pair(1 * 50 + smallCol, 2 * 50 - 1) println("5: $point; $bigRow $bigCol $smallRow $smallCol Next $next") } else if (direction == Direction.RIGHT) { direction = Direction.UP next = Pair(1 * 50 - 1, 2 * 50 + smallRow) println("6: $point; $bigRow $bigCol $smallRow $smallCol Next $next") } else throw IllegalStateException("Point 0,0 shouldn't be here with this direction: $direction") } else if (bigRow == 1 && bigCol == 0) { if (direction == Direction.LEFT) { direction = Direction.DOWN next = Pair(2 * 50, smallRow) println("7: $point; $bigRow $bigCol $smallRow $smallCol Next $next") } else if (direction == Direction.UP) { direction = Direction.RIGHT next = Pair(1 * 50 + smallCol, 1 * 50) println("8: $point; $bigRow $bigCol $smallRow $smallCol Next $next") } else throw IllegalStateException("Point 0,0 shouldn't be here with this direction: $direction") } else if (bigRow == 2 && point.second < 0) { if (direction == Direction.LEFT) { direction = Direction.RIGHT next = Pair(1 * 50 - 1 - smallRow, 1 * 50) println("9: $point; $bigRow $bigCol $smallRow $smallCol Next $next") } else throw IllegalStateException("Point 0,0 shouldn't be here with this direction: $direction") } else if (bigRow == 2 && bigCol == 2) { if (direction == Direction.RIGHT) { direction = Direction.LEFT next = Pair(1 * 50 - 1 - smallRow, 3 * 50 - 1) println("10: $point; $bigRow $bigCol $smallRow $smallCol Next $next") } else throw IllegalStateException("Point 0,0 shouldn't be here with this direction: $direction") } else if (bigRow == 3 && bigCol == 1) { if (direction == Direction.DOWN) { direction = Direction.LEFT next = Pair(3 * 50 + smallCol, 1 * 50 - 1) println("11: $point; $bigRow $bigCol $smallRow $smallCol Next $next") } else if (direction == Direction.RIGHT) { direction = Direction.UP next = Pair(3 * 50 - 1, 1 * 50 + smallRow) println("12: $point; $bigRow $bigCol $smallRow $smallCol Next $next") } else throw IllegalStateException("Point 0,0 shouldn't be here with this direction: $direction") } else if (bigRow == 4 && bigCol == 0) { // TODO CHANGE if (direction == Direction.DOWN) { direction = Direction.DOWN next = Pair(0, 2 * 50 + smallCol) println("13: $point; $bigRow $bigCol $smallRow $smallCol Next $next") } else throw IllegalStateException("Point 0,0 shouldn't be here with this direction: $direction") } else if (bigRow == 3 && point.second < 0) { if (direction == Direction.LEFT) { direction = Direction.DOWN next = Pair(0, 1 * 50 + smallRow) println("14: $point; $bigRow $bigCol $smallRow $smallCol Next $next") } else throw IllegalStateException("Point 0,0 shouldn't be here with this direction: $direction") } return next } fun Pair<Int, Int>.next(direction: Direction): Pair<Int, Int> { val result = when (direction) { Direction.LEFT -> this.copy(second = this.second - 1) Direction.RIGHT -> this.copy(second = this.second + 1) Direction.UP -> this.copy(first = this.first - 1) Direction.DOWN -> this.copy(first = this.first + 1) } return newInEdge(result) } var counter = move.value var next = state.position while (counter > 0) { val previous = next val previousDirection = direction next = next.next(direction) if (next.getItem(board) == '#') { next = previous direction = previousDirection break } counter-- } return State( position = next, direction = direction ) } private fun part2(input: List<String>): Int { val startPoint = startPoint(input) val board = parseBoard(input) val strategies = parseMovement(input) val handleStrategy = { state: State, move: Action.Steps -> strategyPartTwo(state, board, move) } return solution(startPoint, strategies, handleStrategy) } sealed interface Action { data class Steps(val value: Int) : Action data class Rotate(val char: Char) : Action } enum class Direction { RIGHT, DOWN, LEFT, UP } data class State( val position: Pair<Int, Int>, val direction: Direction, ) fun main() { val input = readInput("day22/input") println("Part 1: ${part1(input)}") println("Part 2: ${part2(input)}") }
0
Kotlin
1
0
03368ffeffa7690677c3099ec84f1c512e2f96eb
11,788
aoc-2022
Apache License 2.0
src/exercises/Day05.kt
Njko
572,917,534
false
{"Kotlin": 53729}
// ktlint-disable filename package exercises import readInput data class Move(val quantity: Int, val from: Int, val to: Int) fun main() { fun extractStacks(lines: List<String>): List<MutableList<Char>> { val numberOfStacks = lines.last()[lines.last().length - 1].toString().toInt() val stacks = mutableListOf<MutableList<Char>>() for (u in 0 until numberOfStacks) { val stack = mutableListOf<Char>() stacks.add(stack) } for (i in lines.size - 2 downTo 0) { val numberOfBrackets = numberOfStacks * 2 val numberOfSpaces = numberOfStacks - 1 // fill the lines to have same size val line = lines[i].padEnd(numberOfStacks + numberOfBrackets + numberOfSpaces) for (j in line.indices) { if (!line[j].isWhitespace()) { when (j) { 1 -> stacks[0].add(line[j]) line.length - 2 -> stacks[numberOfStacks - 1].add(line[j]) else -> { if (j % 4 == 1) { stacks[(j - 1) / 4].add(line[j]) } } } } } } return stacks.toList() } fun extractMoves(data: List<String>): List<Move> { val pattern = "move (\\d*) from (\\d*) to (\\d*)".toRegex() val moves = mutableListOf<Move>() for (line in data) { pattern.findAll(line).forEach { matchResult -> moves.add( Move( quantity = matchResult.groupValues[1].toInt(), from = matchResult.groupValues[2].toInt(), to = matchResult.groupValues[3].toInt() ) ) } } return moves } fun executeMovesWithCrateMover9000( moves: List<Move>, stacks: List<MutableList<Char>> ) { for (move in moves) { val stackFrom = stacks[move.from - 1] val stackTo = stacks[move.to - 1] repeat(move.quantity) { stackTo.add(stackFrom.last()) stackFrom.removeLast() } } } fun readStacks(stacks: List<MutableList<Char>>): String { var answer = "" for (stack in stacks) { answer += stack.last().toString() } return answer } fun part1(input: List<String>): String { val splitIndex = input.indexOfFirst { line -> line.isEmpty() } val stacks = extractStacks(input.subList(0, splitIndex)) val moves = extractMoves(input.subList(splitIndex + 1, input.size)) executeMovesWithCrateMover9000(moves, stacks) return readStacks(stacks) } fun executeMovesWithCrateMover9001(moves: List<Move>, stacks: List<MutableList<Char>>) { for (move in moves) { val stackFrom = stacks[move.from - 1] val stackTo = stacks[move.to - 1] val stackToMove = stackFrom.takeLast(move.quantity) stackTo.addAll(stackToMove) repeat(move.quantity) { stackFrom.removeLast() } } } fun part2(input: List<String>): String { val splitIndex = input.indexOfFirst { line -> line.isEmpty() } val stacks = extractStacks(input.subList(0, splitIndex)) val moves = extractMoves(input.subList(splitIndex + 1, input.size)) executeMovesWithCrateMover9001(moves, stacks) return readStacks(stacks) } // test if implementation meets criteria from the description, like: val testInput = readInput("Day05_test") println("Test results:") println(part1(testInput)) check(part1(testInput) == "CMZ") println(part2(testInput)) check(part2(testInput) == "MCD") val input = readInput("Day05") println("Final results:") println(part1(input)) check(part1(input) == "FCVRLMVQP") println(part2(input)) check(part2(input) == "RWLWGJGFD") }
0
Kotlin
0
2
68d0c8d0bcfb81c183786dfd7e02e6745024e396
4,141
advent-of-code-2022
Apache License 2.0
src/Day02.kt
ajspadial
573,864,089
false
{"Kotlin": 15457}
fun main() { fun scoreShape(shape: String): Int { return when (shape) { "X" -> 1 "Y" -> 2 "Z" -> 3 else -> 0 } } fun scoreRound(opponent: String, response: String): Int { if (opponent == "A") { return when (response) { "X" -> 3 "Y" -> 6 "Z" -> 0 else -> 0 } } if (opponent == "B") { return when (response) { "X" -> 0 "Y" -> 3 "Z" -> 6 else -> 0 } } if (opponent == "C") { return when (response) { "X" -> 6 "Y" -> 0 "Z" -> 3 else -> 0 } } return 0 } fun response(opponent: String, result: String):String { if (opponent == "A") { return when (result) { "X" -> "Z" "Y" -> "X" "Z" -> "Y" else -> "" } } if (opponent == "B") { return when (result) { "X" -> "X" "Y" -> "Y" "Z" -> "Z" else -> "" } } if (opponent == "C") { return when (result) { "X" -> "Y" "Y" -> "Z" "Z" -> "X" else -> "" } } return "" } fun part1(input: List<String>): Int { var score = 0 for (line in input) { val symbols = line.split(" ") score += scoreShape(symbols[1]) + scoreRound(symbols[0], symbols[1]) } return score } fun part2(input: List<String>): Int { var score = 0 for (line in input) { val symbols = line.split(" ") val response = response(symbols[0], symbols[1]) score += scoreShape(response) + scoreRound(symbols[0], response) } return score } // 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
ed7a2010008be17fec1330b41adc7ee5861b956b
2,376
adventofcode2022
Apache License 2.0
src/main/kotlin/Excercise07.kt
underwindfall
433,989,850
false
{"Kotlin": 55774}
import kotlin.math.abs private fun part1() { getInputAsTest("07") { split(",") }.map { it.toInt() }.minFuel().let { println("Part 1 $it") } } private fun part2() { getInputAsTest("07") { split(",") }.map { it.toInt() }.maxFuel().let { println("Part 2 $it") } } private fun List<Int>.minFuel(): Int { val minValue = minOf { it } val maxValue = maxOf { it } return (minValue..maxValue).minOf { meetingPos -> sumOf { startPos -> abs(startPos - meetingPos) } } } private fun List<Int>.maxFuel(): Int { val minValue = minOf { it } val maxValue = maxOf { it } return (minValue..maxValue).minOf { meetingPos -> sumOf { startPos -> val diff = abs(startPos - meetingPos) (1 + diff) * diff / 2 } } } fun main() { part1() part2() }
0
Kotlin
0
0
4fbee48352577f3356e9b9b57d215298cdfca1ed
774
advent-of-code-2021
MIT License
src/main/kotlin/ru/spbstu/parse/Parsing.kt
belyaev-mikhail
192,383,116
false
null
package ru.spbstu.parse import ru.spbstu.map.* import ru.spbstu.sim.* data class Task(val name: String, val map: Shape, val initial: Point, val obstacles: List<Shape>, val boosters: List<Booster>) fun parsePoint(point: String): Point { val coordinates = point.replace('(', ' ').replace(')', ' ').split(',').map { it.trim() }.map { Integer.valueOf(it) } return Point(coordinates.first(), coordinates.last()) } fun parseMap(map: String): Shape { return map.split("),(").map { parsePoint(it) } } fun parseObstacles(obstacles: String): List<Obstacle> { if (obstacles.trim().isEmpty()) return emptyList() return obstacles.split(';').map { parseMap(it) }.map { it } } fun parseBoosters(boosters: String): List<Booster> { if (boosters.trim().isEmpty()) return emptyList() return boosters.split(';').map { it.trim() }.map { Booster(parsePoint(it.drop(1)), BoosterType.from("${it[0]}")) } } fun parseFile(name: String, data: String): Task { val (map, point, obstacles, boosters) = data.split('#') return Task( name, parseMap(map), parsePoint(point), parseObstacles(obstacles), parseBoosters(boosters) ) } fun parseAnswer(data: String): List<List<Command>> { val newData = data.split("#").map { it.trim() } val newRes = mutableListOf<StringBuilder>() val botNum = data.split("#").size var curBotNum = 1 repeat(botNum) { newRes.add(StringBuilder()) } var offsets = mutableListOf(0) while (!offsets.mapIndexed { index, i -> index to i }.all { newData[it.first].length <= it.second }) { for (i in offsets.size until botNum) { newRes[i].append('N') } for (i in 0 until offsets.size) { if (offsets[i] >= newData[i].length) continue if (newData[i][offsets[i]] == 'C' && curBotNum < botNum) { offsets.add(-1) curBotNum++ } } offsets = offsets.map { it + 1 }.toMutableList() } newRes.mapIndexed { ind, el -> el.append(newData[ind]) } return newRes.map { parseAnswer1(it.toString()) } } private fun parseAnswer1(data: String): List<Command> { val splData = data.split(Regex("[() ]")) val result = mutableListOf<Command>() splData.mapIndexed { index, s -> s.map { when (it) { 'R' -> RESET 'W' -> MOVE_UP 'S' -> MOVE_DOWN 'A' -> MOVE_LEFT 'D' -> MOVE_RIGHT 'Z' -> NOOP 'E' -> TURN_CW 'Q' -> TURN_CCW 'B' -> ATTACH_MANUPULATOR(parsePoint(splData[index + 1])) 'F' -> USE_FAST_WHEELS 'L' -> USE_DRILL 'T' -> SHIFT_TO(parsePoint(splData[index + 1])) 'C' -> CLONE 'N' -> NOT_EXIST else -> null } }.filterNotNull().forEach { result.add(it) } } return result }
1
Kotlin
0
0
cd5c7d668bf6615fd7e639ddfce0c135c138de42
3,004
icfpc-2019
MIT License
src/Day05.kt
chrisjwirth
573,098,264
false
{"Kotlin": 28380}
fun main() { fun parsedInstructions(input: List<String>): MutableList<Map<String, Int>> { val parsedInstructions = mutableListOf<Map<String, Int>>() val instructions = input.subList( input.indexOfFirst { it.isEmpty() } + 1, input.size ) instructions.forEach { val splitInstruction = it.split(" ") val instructionMap = mapOf( "count" to splitInstruction[1].toInt(), "origin" to splitInstruction[3].toInt(), "destination" to splitInstruction[5].toInt() ) parsedInstructions.add(instructionMap) } return parsedInstructions } fun parsedStacks(input: List<String>): MutableList<MutableList<Char>> { val stacks = mutableListOf<MutableList<Char>>() run stackLoop@ { input.forEach { if (it.isEmpty()) return@stackLoop var index = 1 var stack = 0 while (it.length > index) { if (stack >= stacks.size) stacks.add(mutableListOf()) if (it[index].isLetter()) { stacks[stack].add(it[index]) } index += 4 stack++ } } } return stacks } fun moveItems9000(stacks: MutableList<MutableList<Char>>, count: Int, origin: Int, destination: Int) { val originStack = stacks[origin - 1] val destinationStack = stacks[destination - 1] repeat (count) { destinationStack.add(0, originStack.removeFirst()) } } fun moveItems9001(stacks: MutableList<MutableList<Char>>, count: Int, origin: Int, destination: Int) { val originStack = stacks[origin - 1] val destinationStack = stacks[destination - 1] destinationStack.addAll(0, originStack.subList(0, count)) originStack.subList(0, count).clear() } fun topItems(stacks: MutableList<MutableList<Char>>): String { val topItems = StringBuilder() stacks.forEach { topItems.append(it.first()) } return topItems.toString() } fun part1(input: List<String>): String { val stacks = parsedStacks(input) val instructions = parsedInstructions(input) instructions.forEach { moveItems9000(stacks, it["count"]!!, it["origin"]!!, it["destination"]!!) } return topItems(stacks) } fun part2(input: List<String>): String { val stacks = parsedStacks(input) val instructions = parsedInstructions(input) instructions.forEach { moveItems9001(stacks, it["count"]!!, it["origin"]!!, it["destination"]!!) } return topItems(stacks) } // Test val testInput = readInput("Day05_test") check(part1(testInput) == "CMZ") check(part2(testInput) == "MCD") // Final val input = readInput("Day05") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
d8b1f2a0d0f579dd23fa1dc1f7b156f728152c2d
3,079
AdventOfCode2022
Apache License 2.0
src/day03/Day03.kt
xxfast
572,724,963
false
{"Kotlin": 32696}
package day03 import readLines fun main() { fun Sequence<Set<Char>>.scored() = this .map { it.map { char -> if (char.isLowerCase()) char - 'a' else char - 'A' + 26 } + 1 } .flatten() .sum() fun part1(input: List<String>) = input.asSequence() .map { rucksack -> rucksack.chunked(rucksack.length / 2) { it.toSet()} } .map { (first, second) -> first intersect second } .scored() fun part2(input: List<String>) = input.asSequence() .chunked(3) { group -> group.map { it.toSet() } } .map { (first, second, third) -> first intersect second intersect third } .scored() // test if implementation meets criteria from the description, like: val testInput: List<String> = readLines("day03/test.txt") check(part1(testInput) == 157) check(part2(testInput) == 70) val input: List<String> = readLines("day03/input.txt") println(part1(input)) println(part2(input)) }
0
Kotlin
0
1
a8c40224ec25b7f3739da144cbbb25c505eab2e4
914
advent-of-code-22
Apache License 2.0
src/main/kotlin/io/github/kmakma/adventofcode/y2020/Y2020Day18.kt
kmakma
225,714,388
false
null
package io.github.kmakma.adventofcode.y2020 import io.github.kmakma.adventofcode.utils.Day import io.github.kmakma.adventofcode.utils.product fun main() { Y2020Day18().solveAndPrint() } private enum class Operation { ADDITION, MULTIPLICATION } class Y2020Day18 : Day(2020, 18, "Operation Order") { private lateinit var inputLines: List<List<Char>> override fun initializeDay() { inputLines = inputInStringLines().map { line -> line.toList().filter { it != ' ' } } } override suspend fun solveTask1(): Any? { return inputLines.map { line -> parseSimple(line.toMutableList()) }.sum() } override suspend fun solveTask2(): Any? { return inputLines.map { line -> parseAdvanced(line.toMutableList()) }.sum() } private fun parseSimple(expr: MutableList<Char>): Long { var value: Long? = null var operation: Operation? = null while (expr.isNotEmpty()) { when (val char = expr.removeFirst()) { '(' -> value = calculate(value, operation, parseSimple(expr)) ')' -> return value!! '+' -> operation = Operation.ADDITION '*' -> operation = Operation.MULTIPLICATION else -> value = calculate(value, operation, Character.getNumericValue(char).toLong()) } } return value!! } private fun calculate(first: Long?, operation: Operation?, second: Long): Long { return when { first == null -> second operation == Operation.ADDITION -> first + second operation == Operation.MULTIPLICATION -> first * second else -> throw IllegalArgumentException("missing operator: $first, $operation, $second") } } private fun parseAdvanced(expr: MutableList<Char>, subExpr: StringBuilder = StringBuilder()): Long { while (expr.isNotEmpty()) { when (val char = expr.removeFirst()) { '(' -> subExpr.append(parseAdvanced(expr)) ')' -> return calculate(subExpr) else -> subExpr.append(char) } } return calculate(subExpr) } private fun calculate(expr: StringBuilder): Long { return expr .split("*") .map { sumString -> sumString .split("+") .map { it.toLong() } .sum() } .product() } }
0
Kotlin
0
0
7e6241173959b9d838fa00f81fdeb39fdb3ef6fe
2,478
adventofcode-kotlin
MIT License
codeforces/kotlinheroes6/practice/g.kt
mikhail-dvorkin
93,438,157
false
{"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408}
package codeforces.kotlinheroes6.practice fun main() { val (_, m) = readInts() val a = readLongs() val capital = a.withIndex().minByOrNull { it.value }!!.index data class Edge(val u: Int, val v: Int, val weight: Long) val edges = List(m) { val (uIn, vIn, weight) = readLongs() Edge((uIn - 1).toInt(), (vIn - 1).toInt(), weight) } + List(a.size) { Edge(it, capital, a[it] + a[capital]) } val dsu = DisjointSetUnion(a.size) var ans = 0L for (edge in edges.sortedBy { it.weight }) { if (dsu[edge.u] == dsu[edge.v]) continue dsu.unite(edge.u, edge.v) ans += edge.weight } println(ans) } class DisjointSetUnion(n: Int) { val p: IntArray = IntArray(n) { it } val r = java.util.Random(566) operator fun get(v: Int): Int = if (p[v] == v) v else { p[v] = get(p[v]); p[v] } fun unite(v: Int, u: Int) = if (r.nextBoolean()) p[get(v)] = get(u) else p[get(u)] = get(v) } private fun readLn() = readLine()!! private fun readStrings() = readLn().split(" ") private fun readInts() = readStrings().map { it.toInt() } private fun readLongs() = readStrings().map { it.toLong() }
0
Java
1
9
30953122834fcaee817fe21fb108a374946f8c7c
1,091
competitions
The Unlicense
2017/src/main/kotlin/Day23.kt
dlew
498,498,097
false
{"Kotlin": 331659, "TypeScript": 60083, "JavaScript": 262}
import utils.splitNewlines import utils.splitWhitespace object Day23 { fun part1(input: String): Int { val instructions = input.splitNewlines().map(this::parseInstruction) var pointer = 0 val registers = mutableMapOf<Char, Long>().withDefault { 0 } var mulCount = 0 while (pointer < instructions.size) { val instruction = instructions[pointer] when (instruction) { is Instruction.Modify -> { val curr = registers.getValue(instruction.target) val value = instruction.source.getValue(registers) registers[instruction.target] = when (instruction.operation) { Operation.SET -> value Operation.SUBTRACT -> curr - value Operation.MULTIPLY -> { mulCount++ curr * value } } pointer++ } is Instruction.Jump -> { if (instruction.check.getValue(registers) != 0L) { pointer += instruction.offset.getValue(registers).toInt() } else { pointer++ } } } } return mulCount } // The secret is that the code is just counting prime numbers in a range fun part2(input: String, initialAValue: Int): Int { var start = if (initialAValue == 0) 93 else 109300 var end = if (initialAValue == 0) 93 else 126300 return (start..end step 17).count { it.isPrime() } } // Forgive me for this incredibly stupid prime tester private fun Int.isPrime(): Boolean { return (2 until this).any { this % it == 0 } } private sealed class Instruction { class Modify(val operation: Operation, val target: Char, val source: ValueSource) : Instruction() class Jump(val check: ValueSource, val offset: ValueSource) : Instruction() } private sealed class ValueSource { abstract fun getValue(registers: Map<Char, Long>): Long class Number(val number: Long) : ValueSource() { override fun getValue(registers: Map<Char, Long>) = number } class Register(val register: Char) : ValueSource() { override fun getValue(registers: Map<Char, Long>) = registers.getValue(register) } } private enum class Operation { SET, SUBTRACT, MULTIPLY } private fun parseInstruction(input: String): Instruction { val split = input.splitWhitespace() val arg1 = split[1] val arg2 = if (split.size == 3) split[2] else "" fun parseSource(source: String): ValueSource { return if (source[0] in 'a'..'z') ValueSource.Register(source[0]) else ValueSource.Number(source.toLong()) } return when (input.take(3)) { "set" -> Instruction.Modify(Operation.SET, arg1[0], parseSource(arg2)) "sub" -> Instruction.Modify(Operation.SUBTRACT, arg1[0], parseSource(arg2)) "mul" -> Instruction.Modify(Operation.MULTIPLY, arg1[0], parseSource(arg2)) "jnz" -> Instruction.Jump(parseSource(arg1), parseSource(arg2)) else -> throw IllegalArgumentException("Cannot parse $input") } } }
0
Kotlin
0
0
6972f6e3addae03ec1090b64fa1dcecac3bc275c
3,025
advent-of-code
MIT License
src/Day10.kt
vladislav-og
573,326,483
false
{"Kotlin": 27072}
fun main() { fun calculateSignalStrength(cycleCount: Int, signalStrength: Int, xValue: Int): Int { var signalStrength1 = signalStrength if (cycleCount % 40 == 20) { signalStrength1 += xValue * cycleCount } return signalStrength1 } fun part1(input: List<String>): Int { var cycleCount = 0 var xValue = 1 var signalStrength = 0 for (command in input) { val row = command.split(" ") if (row.size == 2) { for (i in 0..1) { cycleCount++ signalStrength = calculateSignalStrength(cycleCount, signalStrength, xValue) } xValue += row[1].toInt() } else { cycleCount++ signalStrength = calculateSignalStrength(cycleCount, signalStrength, xValue) } } return signalStrength } fun part2(input: List<String>): Int { return 1 } // test if implementation meets criteria from the description, like: val testInput = readInput("Day10_test") println(part1(testInput)) check(part1(testInput) == 13140) // println(part2(testInput1)) // check(part2(testInput1) == 36) val input = readInput("Day10") println(part1(input)) // 5981 // println(part2(input)) }
0
Kotlin
0
0
b230ebcb5705786af4c7867ef5f09ab2262297b6
1,204
advent-of-code-2022
Apache License 2.0
src/main/kotlin/aoc2022/Day08.kt
lukellmann
574,273,843
false
{"Kotlin": 175166}
@file:Suppress("DuplicatedCode") // I know... package aoc2022 import AoCDay import kotlin.math.max // https://adventofcode.com/2022/day/8 object Day08 : AoCDay<Int>( title = "Treetop Tree House", part1ExampleAnswer = 21, part1Answer = 1533, part2ExampleAnswer = 8, part2Answer = 345744, ) { private class Map(private val grid: String) { val xSize = grid.indexOf('\n') val ySize = (grid.length + 1) / (xSize + 1) operator fun get(x: Int, y: Int) = grid[(y * (xSize + 1)) + x] inline fun <T> foldInteriorTrees(initial: T, operation: (acc: T, tree: Char, x: Int, y: Int) -> T): T { var acc = initial for (y in 1..ySize - 2) { for (x in 1..xSize - 2) { acc = operation(acc, get(x, y), x, y) } } return acc } } override fun part1(input: String): Int { val map = Map(input) return map.foldInteriorTrees( initial = map.xSize * 2 + (map.ySize - 2) * 2 // edges are always visible ) fold@{ visibleFromOutside, tree, x, y -> // run from x y into all directions while trees are smaller, if we run out of the map, the tree is visible var up = y - 1 while (up >= 0 && map[x, up] < tree) up-- // note difference in comparison operator compared to part2 if (up < 0) return@fold visibleFromOutside + 1 var down = y + 1 while (down < map.ySize && map[x, down] < tree) down++ if (down >= map.ySize) return@fold visibleFromOutside + 1 var left = x - 1 while (left >= 0 && map[left, y] < tree) left-- if (left < 0) return@fold visibleFromOutside + 1 var right = x + 1 while (right < map.xSize && map[right, y] < tree) right++ if (right >= map.xSize) visibleFromOutside + 1 else visibleFromOutside } } override fun part2(input: String): Int { val map = Map(input) return map.foldInteriorTrees( initial = 0 // scenic score for all edges is 0 ) { maxScenicScore, tree, x, y -> // run from x y into all directions while trees are smaller, score can be calculated by subtracting indices var up = y - 1 while (up > 0 && map[x, up] < tree) up-- // note difference in comparison operator compared to part1 var down = y + 1 while (down < map.ySize - 1 && map[x, down] < tree) down++ var left = x - 1 while (left > 0 && map[left, y] < tree) left-- var right = x + 1 while (right < map.xSize - 1 && map[right, y] < tree) right++ max(maxScenicScore, (y - up) * (down - y) * (x - left) * (right - x)) } } }
0
Kotlin
0
1
344c3d97896575393022c17e216afe86685a9344
2,827
advent-of-code-kotlin
MIT License
src/main/kotlin/days/Day5.kt
teunw
573,164,590
false
{"Kotlin": 20073}
package days import chunkBy class Day5 : Day(5) { fun parseInput(): Pair<List<MutableList<Char>>, Array<Array<Int>>> { val (stackText, instructionText) = inputList.chunkBy { it.isBlank() } val stackIndexes = stackText .last() .mapIndexed { index, s -> if (s.isDigit()) index else null } .filterNotNull() val stacks = stackIndexes .map { index -> stackText.map { line -> line[index] } } .map { stack -> stack.filter { it.isLetter() }.toMutableList() } val instructionRegex = Regex("move ([0-9]+) from ([0-9]+) to ([0-9]+)") val instructions = instructionText.map { instruction -> instructionRegex.find(instruction)!!.groupValues.drop(1).map { it.toInt() }.toTypedArray() }.toTypedArray() return Pair(stacks, instructions) } override fun partOne(): String { val (stackss, instructions) = parseInput() return instructions.fold(stackss) { stacks, instruction -> val stackCopy = stacks.toMutableList() val stackFrom = stackCopy[instruction[1] - 1] val stackTo = stackCopy[instruction[2] - 1] val elements = stackFrom.take(instruction[0]) repeat(elements.size) { stackFrom.removeFirst() } stackTo.addAll(0, elements.reversed()) return@fold stackCopy } .map { it.firstOrNull() ?: "" } .joinToString("") } override fun partTwo(): String { val (stackss, instructions) = parseInput() return instructions.fold(stackss) { stacks, instruction -> val stackCopy = stacks.toMutableList() val stackFrom = stackCopy[instruction[1] - 1] val stackTo = stackCopy[instruction[2] - 1] val elements = stackFrom.take(instruction[0]) repeat(elements.size) { stackFrom.removeFirst() } stackTo.addAll(0, elements) return@fold stackCopy } .map { it.firstOrNull() ?: "" } .joinToString("") } }
0
Kotlin
0
0
149219285efdb1a4d2edc306cc449cce19250e85
2,090
advent-of-code-22
Creative Commons Zero v1.0 Universal
src/main/kotlin/ru/timakden/aoc/year2016/Day08.kt
timakden
76,895,831
false
{"Kotlin": 321649}
package ru.timakden.aoc.year2016 import ru.timakden.aoc.util.measure import ru.timakden.aoc.util.readInput /** * [Day 8: Two-Factor Authentication](https://adventofcode.com/2016/day/8). */ object Day08 { @JvmStatic fun main(args: Array<String>) { measure { val input = readInput("year2016/Day08") val screen = createScreen() println("Part One: ${part1(screen, input)}") printScreen(screen) } } fun part1(screen: Array<CharArray>, input: List<String>): Int { input.forEach { line -> if (line.startsWith("rect")) { val (width, height) = line.substringAfter(' ').split('x').map { it.toInt() } rect(screen, width, height) } else { val index = line.substringAfter('=').substringBefore(' ').toInt() val pixels = line.substringAfterLast(' ').toInt() if ("row" in line) rotateRow(screen, index, pixels) else rotateColumn(screen, index, pixels) } } return countLitPixels(screen) } private fun createScreen(width: Int = 50, height: Int = 6): Array<CharArray> { val screen = Array(height) { CharArray(width) } screen.forEach { row -> row.indices.forEach { row[it] = '.' } } return screen } private fun rect(screen: Array<CharArray>, width: Int, height: Int) { (0..<height).forEach { row -> (0..<width).forEach { column -> screen[row][column] = '#' } } } private fun rotateRow(screen: Array<CharArray>, row: Int, pixels: Int) { repeat(pixels) { screen[row] = shift(screen[row]) } } private fun rotateColumn(screen: Array<CharArray>, column: Int, pixels: Int) { var columnStr = "" (0..screen.lastIndex).forEach { columnStr += screen[it][column] } var array = columnStr.toCharArray() repeat(pixels) { array = shift(array) } (0..screen.lastIndex).forEach { screen[it][column] = array[it] } } private fun shift(array: CharArray): CharArray { val newArray = array.clone() newArray[0] = array[array.lastIndex] (0..<array.lastIndex).forEach { newArray[it + 1] = array[it] } return newArray } private fun countLitPixels(screen: Array<CharArray>) = screen.fold(0) { acc, chars -> acc + chars.count { it == '#' } } private fun printScreen(screen: Array<CharArray>) { println() screen.forEach(::println) println() } }
0
Kotlin
0
3
acc4dceb69350c04f6ae42fc50315745f728cce1
2,554
advent-of-code
MIT License
src/Day04.kt
ambrosil
572,667,754
false
{"Kotlin": 70967}
fun main() { fun part1(input: List<String>) = input .readRanges() .count { (first, second) -> first contains second || second contains first } fun part2(input: List<String>) = input .readRanges() .count { (first, second) -> first overlaps second } val input = readInput("inputs/Day04") println(part1(input)) println(part2(input)) } fun List<String>.readRanges() = this.map { it.split(",").map { s -> val (start, end) = s.split("-") start.toInt()..end.toInt() } } infix fun IntRange.contains(second: IntRange) = this.first <= second.first && this.last >= second.last infix fun IntRange.overlaps(second: IntRange) = (this intersect second).isNotEmpty()
0
Kotlin
0
0
ebaacfc65877bb5387ba6b43e748898c15b1b80a
845
aoc-2022
Apache License 2.0
src/main/kotlin/solutions/day08/Day8.kt
Dr-Horv
570,666,285
false
{"Kotlin": 115643}
package solutions.day08 import solutions.Solver import utils.Coordinate import kotlin.math.max class Day8 : Solver { override fun solve(input: List<String>, partTwo: Boolean): String { val map = mutableMapOf<Coordinate, Int>() val WIDTH = input[0].length val HEIGHT = input.size for ((y, line) in input.withIndex()) { for ((x, char) in line.toList().withIndex()) { val coord = Coordinate(x = x, y = y) val height = char.digitToInt() map[coord] = height } } if (!partTwo) { var visible = 0 //WIDTH * 2 + HEIGHT * 2 - 4 for (y in 0 until HEIGHT) { for (x in 0 until WIDTH) { val c = Coordinate(x, y) if (isVisible(c, map, WIDTH, HEIGHT)) { visible++ } } } return visible.toString() } else { var maxScenicScore = 0 for (y in 0 until HEIGHT) { for (x in 0 until WIDTH) { val c = Coordinate(x, y) val score = calculateScenicScore(c, map, WIDTH, HEIGHT) maxScenicScore = max(maxScenicScore, score) } } return maxScenicScore.toString() } } private fun calculateScenicScore(coordinate: Coordinate, map: Map<Coordinate, Int>, width: Int, height: Int): Int { val treeHeight = map[coordinate]!! var upScore = 0 for (y in (coordinate.y - 1 downTo 0)) { val c = coordinate.copy(y = y) val currTreeHeight = map[c]!! upScore++ if (currTreeHeight >= treeHeight) { break } } var leftScore = 0 for (x in (coordinate.x - 1 downTo 0)) { val currTreeHeight = map[coordinate.copy(x = x)]!! leftScore++ if (currTreeHeight >= treeHeight) { break } } var rightScore = 0 for (x in (coordinate.x + 1 until width)) { val currTreeHeight = map[coordinate.copy(x = x)]!! rightScore++ if (currTreeHeight >= treeHeight) { break } } var downScore = 0 for (y in (coordinate.y + 1 until height)) { val currTreeHeight = map[coordinate.copy(y = y)]!! downScore++ if (currTreeHeight >= treeHeight) { break } } return leftScore * rightScore * downScore * upScore } private fun isVisible(coordinate: Coordinate, map: Map<Coordinate, Int>, width: Int, height: Int): Boolean { val treeHeight = map[coordinate]!! if ((0 until coordinate.x).map { map.getOrElse(Coordinate(it, coordinate.y)) { throw Error("Not found: " + it + "," + coordinate.y) } }.all { it < treeHeight }) { return true } if ((width - 1 downTo (coordinate.x + 1)).map { map.getOrElse(Coordinate(it, coordinate.y)) { throw Error("Not found: " + it + "," + coordinate.y) } }.all { it < treeHeight }) { return true } if ((0 until coordinate.y).map { map.getOrElse(Coordinate(coordinate.x, it)) { throw Error("Not found: " + it + "," + coordinate.y) } }.all { it < treeHeight }) { return true } if ((height - 1 downTo (coordinate.y + 1)).map { map.getOrElse(Coordinate(coordinate.x, it)) { throw Error("Not found: " + it + "," + coordinate.y) } }.all { it < treeHeight }) { return true } return false } }
0
Kotlin
0
2
6c9b24de2fe2a36346cb4c311c7a5e80bf505f9e
3,835
Advent-of-Code-2022
MIT License
src/main/kotlin/Day10.kt
dliszewski
573,836,961
false
{"Kotlin": 57757}
import java.lang.StringBuilder class Day10 { fun part1(input: List<String>): Int { val cyclesToCheck = (20..220 step 40).toList() var result = 0 val instructions = listOf(1) + input.flatMap { it.toOperation() } instructions.reduceIndexed { cycle, acc, instruction -> if (cycle in cyclesToCheck) { result += cycle * acc } acc + instruction } return result } fun part2(input: List<String>): String { val crtCyclesToCheck = (40..220 step 40).toList() var spritePosition = 0 val instructions = listOf(1) + input.flatMap { it.toOperation() } val crtScreen = StringBuilder() instructions.reduceIndexed { cycle, acc, instruction -> crtScreen.append(if ((cycle - 1) % 40 in spritePosition - 1 .. spritePosition + 1) '#' else '.') if (cycle in crtCyclesToCheck) { crtScreen.appendLine() } spritePosition = acc + instruction acc + instruction } val screen = crtScreen.toString() println("====== Result ======") println(screen) println("====================") return screen } private fun String.toOperation(): List<Int> { return when { this == "noop" -> listOf(0) this.startsWith("addx") -> listOf(0, this.substringAfter("addx ").toInt()) else -> error("wrong operation $this") } } }
0
Kotlin
0
0
76d5eea8ff0c96392f49f450660220c07a264671
1,522
advent-of-code-2022
Apache License 2.0
src/day5/Day5.kt
quinlam
573,215,899
false
{"Kotlin": 31932}
package day5 import utils.Day import java.util.Stack /** * Actual answers after submitting; * part1: QGTHFZBHV * part2: MGDMPSZTM */ class Day5 : Day<String, StackInput>( testPart1Result = "CMZ", testPart2Result = "MCD" ) { override fun part1Answer(input: StackInput): String { return moveStacks(input, true) } override fun part2Answer(input: StackInput): String { return moveStacks(input) } private fun moveStacks(input: StackInput, reverse: Boolean = false): String { input.instructions.forEach { val tempStack = Stack<Char>() for (i in 1..it.number) { val value = input.stacks[it.stackFrom]?.pop() tempStack.push(value) } if (reverse) { tempStack.reverse() } while (!tempStack.isEmpty()) { input.stacks[it.stackTo]?.push(tempStack.pop()) } } val stringBuilder = StringBuilder() input.stacks.values.forEach { stringBuilder.append(it.peek()) } return stringBuilder.toString() } override fun modifyInput(input: List<String>): StackInput { val parts = input .map { parseLine(it) } .groupBy({ it.type }, { it.line }) val stackId = parts[ParseLineType.STACK_ID]?.first() ?: "" val contents = parts[ParseLineType.STACK_CONTENTS] ?: emptyList() val stacks = createStacks(stackId, contents) val instructions = parts[ParseLineType.INSTRUCTION] ?.map { createInstructions(it) } ?: emptyList() return StackInput(stacks, instructions) } private fun createInstructions(input: String): Instruction { val instructionString = input.split(" ") return Instruction( stackFrom = instructionString[3].toInt(), stackTo = instructionString[5].toInt(), number = instructionString[1].toInt() ) } private fun createStacks(stackIds: String, contents: List<String>): Map<Int, Stack<Char>> { val numOfStacks = stackIds.split("\\s+".toRegex()) val stacks = (1 until numOfStacks.size) .associateBy({ it }, { Stack<Char>() }) contents.forEach { it.toCharArray().forEachIndexed { index, element -> if (element.isLetter()) { val stack = (index / 4) + 1 stacks[stack]?.push(element) } } } stacks.values.forEach { it.reverse() } return stacks } private fun parseLine(input: String): IdentifiedLine { return when { input.startsWith(" 1") -> { IdentifiedLine(ParseLineType.STACK_ID, input) } input.isBlank() -> { IdentifiedLine(ParseLineType.BLANK, input) } input.startsWith("move") -> { IdentifiedLine(ParseLineType.INSTRUCTION, input) } else -> IdentifiedLine(ParseLineType.STACK_CONTENTS, input) } } }
0
Kotlin
0
0
d304bff86dfecd0a99aed5536d4424e34973e7b1
3,127
advent-of-code-2022
Apache License 2.0
2022/src/day08/Day08.kt
scrubskip
160,313,272
false
{"Kotlin": 198319, "Python": 114888, "Dart": 86314}
package day08 import java.io.File fun main() { val input = File("src/day08/day08input.txt").readLines() val grid = TreeGrid(input) println(grid.getVisibleCells().size) println(grid.getMaxScenicScore()) } typealias Cell = Pair<Int, Int> class TreeGrid { private var _values: List<List<Int>> private var _width: Int private var _height: Int constructor(input: List<String>) { _values = input.map { it.toCharArray().map { char -> char.toString().toInt() } } _width = _values[0].size _height = _values.size } fun getVisibleCells(): List<Cell> { val returnSet = mutableSetOf<Cell>() // Go left to right for (x in 0 until _width) { addVisibleCells(Cell(x, 0), 0, 1, returnSet) addVisibleCells(Cell(x, _height - 1), 0, -1, returnSet) } // Go top to bottom for (y in 0 until _height) { addVisibleCells(Cell(0, y), 1, 0, returnSet) addVisibleCells(Cell(_width - 1, y), -1, 0, returnSet) } return returnSet.toList() } fun getValue(cell: Cell): Int { return _values[cell.second][cell.first] } fun getWidth(): Int { return _width } fun getHeight(): Int { return _height } /** * Adds all the visible cells in a direction starting at an edge cell. */ private fun addVisibleCells(cellStart: Cell, deltaX: Int, deltaY: Int, set: MutableSet<Cell>) { set.add(cellStart) var currentCell = cellStart var candidateCell: Cell var lastMaxValue = getValue(cellStart) while (inbounds(currentCell)) { candidateCell = Cell(currentCell.first + deltaX, currentCell.second + deltaY) if (inbounds(candidateCell) && getValue(candidateCell) > lastMaxValue) { set.add(candidateCell) lastMaxValue = getValue(candidateCell) } currentCell = candidateCell } } fun getMaxScenicScore(): Int { var maxScore = 0 for (x in 0 until _width) { for (y in 0 until _height) { val scenicScore = getScenicScore(Cell(x, y)) if (scenicScore > maxScore) { maxScore = scenicScore } } } return maxScore } fun getScenicScore(cellStart: Cell): Int { val topTrees = getViewDistance(cellStart, 0, -1) val leftTrees = getViewDistance(cellStart, -1, 0) val rightTrees = getViewDistance(cellStart, 1, 0) val bottomTrees = getViewDistance(cellStart, 0, 1) return topTrees * bottomTrees * rightTrees * leftTrees } private fun getViewDistance(cellStart: Cell, deltaX: Int, deltaY: Int): Int { val value = getValue(cellStart) var treeCount = 0 var candidateCell = Cell(cellStart.first + deltaX, cellStart.second + deltaY) while (inbounds(candidateCell)) { treeCount++ if (getValue(candidateCell) >= value) { break } else { candidateCell = Cell(candidateCell.first + deltaX, candidateCell.second + deltaY) } } return treeCount } private fun inbounds(cell: Cell): Boolean { return cell.first >= 0 && cell.second >= 0 && cell.first <= _width - 1 && cell.second <= _height - 1 } private fun isEdge(cell: Cell): Boolean { return cell.first == 0 || cell.second == 0 || cell.first == _width - 1 || cell.second == _height - 1 } }
0
Kotlin
0
0
a5b7f69b43ad02b9356d19c15ce478866e6c38a1
3,600
adventofcode
Apache License 2.0
src/main/kotlin/day11/GalaxyMap.kt
limelier
725,979,709
false
{"Kotlin": 48112}
package day11 import kotlin.math.max import kotlin.math.min internal class GalaxyMap( inputLines: Iterable<String> ) { private val galaxies = inputLines.flatMapIndexed { row, line -> line.mapIndexedNotNull { col, char -> if (char == '#') Galaxy(row, col) else null } } val emptyRows = let { val galaxyRows = galaxies.map { it.row }.toSortedSet() val galaxyRowDomain = galaxyRows.min()..galaxyRows.max() (galaxyRowDomain - galaxyRows).toSet() } val emptyCols = let { val galaxyCols = galaxies.map { it.col }.toSortedSet() val galaxyColDomain = galaxyCols.min().. galaxyCols.max() (galaxyColDomain - galaxyCols).toSet() } inner class Galaxy( val row: Int, val col: Int, ) { /** * Calculate the taxicab distance to the [other] galaxy. Each empty row and column in-between will add * be counted [gapMultiplier] times. */ fun distanceTo(other: Galaxy, gapMultiplier: Int): Long { val minRow = min(row, other.row) val maxRow = max(row, other.row) val minCol = min(col, other.col) val maxCol = max(col, other.col) return maxRow - minRow + maxCol - minCol + (minRow..maxRow).intersect(emptyRows).count().toLong() * (gapMultiplier - 1) + (minCol..maxCol).intersect(emptyCols).count().toLong() * (gapMultiplier - 1) } } fun pairwiseDistanceSum(gapMultiplier: Int): Long { var sum = 0L for (i in galaxies.indices) { for (j in i+1..<galaxies.size) { sum += galaxies[i].distanceTo(galaxies[j], gapMultiplier) } } return sum } }
0
Kotlin
0
0
0edcde7c96440b0a59e23ec25677f44ae2cfd20c
1,782
advent-of-code-2023-kotlin
MIT License
src/Day04.kt
mr-cell
575,589,839
false
{"Kotlin": 17585}
fun main() { fun part1(input: List<String>): Int { return input .map { it.asRanges() } .count { it.first fullyOverlaps it.second || it.second fullyOverlaps it.first } } fun part2(input: List<String>): Int { return input .map { it.asRanges() } .count { it.first overlaps it.second } } // 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)) } private infix fun IntRange.fullyOverlaps(other: IntRange): Boolean = first <= other.first && last >= other.last private infix fun IntRange.overlaps(other: IntRange): Boolean = first <= other.last && last >= other.first private fun String.asIntRange(): IntRange = substringBefore("-").toInt()..substringAfter("-").toInt() private fun String.asRanges(): Pair<IntRange, IntRange> = substringBefore(",").asIntRange() to substringAfter(",").asIntRange()
0
Kotlin
0
0
2528bf0f72bcdbe7c13b6a1a71e3d7fe1e81e7c9
1,107
advent-of-code-2022
Apache License 2.0
src/Day09/Day09.kt
AllePilli
572,859,920
false
{"Kotlin": 47397}
package Day09 import Direction import checkAndPrint import directionsTo import measureAndPrintTimeMillis import move import readInput import touches import touchesDiagonally fun main() { fun List<String>.prepareInput() = map { line -> line.split(" ") .let { (first, second) -> val direction = when (val dir = first.first()) { 'U' -> Direction.Up 'R' -> Direction.Right 'D' -> Direction.Down 'L' -> Direction.Left else -> error("unknown direction $dir") } direction to second.toInt() } } fun simulateRope(tailSize: Int, steps: List<Pair<Direction, Int>>): Int { val rope = List(tailSize + 1) { Pair(0, 0) }.toMutableList() return steps.flatMap { (dir, amt) -> buildList { repeat(amt) { rope[0] = rope[0].move(dir) for (idx in 1 until rope.size) { if (rope[idx - 1] != rope[idx] && !rope[idx].touches(rope[idx - 1]) && !rope[idx].touchesDiagonally(rope[idx - 1])) { rope[idx].directionsTo(rope[idx - 1]).forEach { direction -> rope[idx] = rope[idx].move(direction) } } } add(rope.last()) } } }.distinct().size } fun part1(input: List<Pair<Direction, Int>>): Int = simulateRope(1, input) fun part2(input: List<Pair<Direction, Int>>): Int = simulateRope(9, input) val testInputPart1 = readInput("Day09_part1_test").prepareInput() check(part1(testInputPart1) == 13) val testInputPart2 = readInput("Day09_part2_test").prepareInput() check(part2(testInputPart2) == 36) val input = readInput("Day09").prepareInput() measureAndPrintTimeMillis { checkAndPrint(part1(input), 6243) } measureAndPrintTimeMillis { checkAndPrint(part2(input), 2630) } }
0
Kotlin
0
0
614d0ca9cc925cf1f6cfba21bf7dc80ba24e6643
2,156
AdventOfCode2022
Apache License 2.0
src/main/kotlin/day03/Day03.kt
TheSench
572,930,570
false
{"Kotlin": 128505}
package day03 import runDay fun main() { fun part1(input: List<String>): Int { return input.mapToRucksacks() .map { rucksack -> rucksack.first.find { rucksack.second.contains(it) }!! } .map(Char::priority) .sum() } fun part2(input: List<String>): Int { return input .asSequence() .map { it.toSet() } .chunked(3) .map { it.reduce(Set<Char>::intersect).first() } .map { it.priority } .sum() } (object {}).runDay( part1 = ::part1, part1Check = 157, part2 = ::part2, part2Check = 70 ) } private fun List<String>.mapToRucksacks() = map(String::toRucksack) private fun String.toRucksack() = length.let { length -> val half = length / 2 chunked(half).let { Pair(it[0], it[1]) } } private val Char.priority: Int get() = when (this) { in 'a'..'z' -> code - ('a'.code) + 1 in 'A'..'Z' -> code - ('A'.code) + 27 else -> throw IllegalArgumentException() }
0
Kotlin
0
0
c3e421d75bc2cd7a4f55979fdfd317f08f6be4eb
1,133
advent-of-code-2022
Apache License 2.0
src/questions/LengthOfLongestIncreasingSubSeq.kt
realpacific
234,499,820
false
null
package questions import _utils.UseCommentAsDocumentation import utils.shouldBe /** * Given an integer array nums, return the length of the longest strictly increasing subsequence. * A subsequence is a sequence that can be derived from an array by deleting some or no elements * without changing the order of the remaining elements. * * [Source](https://leetcode.com/problems/longest-increasing-subsequence/) | [Explanation](https://www.youtube.com/watch?v=mouCn3CFpgg) * * @see LongestIncreasingSubSeq */ @UseCommentAsDocumentation private object LengthOfLongestIncreasingSubSeq private fun lengthOfLIS(nums: IntArray): Int { if (nums.size == 1) return 1 var maxSubsequenceSize = 1 val increasingSeq = IntArray(nums.size) { 1 } for (i in 1..nums.lastIndex) { for (j in 0 until i) { // (Is still increasing?) && (choose the best i.e. larger answer) if (nums[i] > nums[j] && increasingSeq[i] <= increasingSeq[j]) { increasingSeq[i] = 1 + increasingSeq[j] } } maxSubsequenceSize = maxOf(maxSubsequenceSize, increasingSeq[i]) } return maxSubsequenceSize } fun main() { val solutionFns: List<(IntArray) -> Int> = listOf(::lengthOfLIS) for (fn in solutionFns) { fn(intArrayOf(5, 8, 7, 1, 9)) shouldBe 3 fn(intArrayOf(10, 9, 2, 5, 3, 7, 101, 18)) shouldBe 4 fn(intArrayOf(0, 1, 0, 3, 2, 3)) shouldBe 4 fn(intArrayOf(7, 7, 7, 7, 7, 7, 7)) shouldBe 1 fn((10 downTo 1).toList().toIntArray()) shouldBe 1 } }
4
Kotlin
5
93
22eef528ef1bea9b9831178b64ff2f5b1f61a51f
1,562
algorithms
MIT License
kotlin/src/main/kotlin/Saddlepoint.kt
funfunStudy
93,757,087
false
null
fun main(args: Array<String>) { val test1 = listOf( listOf(9, 8, 7), listOf(5, 3, 2), listOf(6, 6, 7)) val test2 = listOf( listOf(1, 2, 3), listOf(3, 1, 2), listOf(2, 3, 1)) val test3 = listOf( listOf(4, 5, 4), listOf(3, 5, 5), listOf(1, 5, 4)) val test4 = listOf( listOf(8, 7, 9), listOf(6, 7, 6), listOf(3, 2, 5) ) println(solve(test1).filterNotNull()) println(solve(test2).filterNotNull()) println(solve(test3).filterNotNull()) println(solve(test4).filterNotNull()) } private fun solve(list: List<List<Int>>): List<Pair<Int, Int>?> { val xResult = list.map { it.max()!! }.min() val yResult = transfer(list, listOf()).map { it.min()!! }.max() return if (xResult == yResult) { list.foldIndexed(listOf()) { index, acc, lista -> acc.plus(lista.mapIndexed { indexa, i -> if(i == xResult) index to indexa else null }) } } else { listOf() } } tailrec fun transfer(list: List<List<Int>>, acc: List<List<Int>>): List<List<Int>> { return when { list.isEmpty() || list.first().isEmpty() -> acc else -> { transfer(list.map { it.drop(1) }, acc.plusElement(list.map { it.first() })) } } }
0
Kotlin
3
14
a207e4db320e8126169154aa1a7a96a58c71785f
1,363
algorithm
MIT License
src/test/kotlin/com/igorwojda/list/minsublistlength/solution.kt
handiism
455,862,994
true
{"Kotlin": 218721}
package com.igorwojda.list.minsublistlength // Time complexity: O(n) // Space complexity O(n) // Use sliding window private object Solution1 { fun minSubListLength(list: List<Int>, sum: Int): Int { var total = 0 var start = 0 var end = 0 var minLen: Int? = null while (start < list.size) { // if current window doesn't add up to the given numElements then move the window to right if (total < sum && end < list.size) { total += list[end] end++ } // if current window adds up to at least the numElements given then we can shrink the window else if (total >= sum) { minLen = min(minLen, end - start) total -= list[start] start++ } // current total less than required total but we reach the end, need this or else we'll be in an infinite loop else { break } } return minLen ?: 0 } private fun min(i1: Int?, i2: Int?): Int? { return when { i1 != null && i2 != null -> Math.min(i1, i2) i1 != null && i2 == null -> i1 i1 == null && i2 != null -> i2 else -> null } } } // Time complexity: O(n^2) // Loop through all the elements and then loop through all sublists private object Solution2 { fun minSubListLength(list: List<Int>, sum: Int): Int { var minListLength: Int? = null repeat(list.size) { index -> var subListSum = 0 var numItems = 0 val subList = list.subList(index, list.size) for (item in subList) { subListSum += item numItems++ if (subListSum >= sum) { minListLength = min(minListLength, numItems) break } } } return minListLength ?: 0 } private fun min(i1: Int?, i2: Int?): Int? { return when { i1 != null && i2 != null -> Math.min(i1, i2) i1 != null && i2 == null -> i1 i1 == null && i2 != null -> i2 else -> null } } } private object KtLintWillNotComplain
1
Kotlin
2
1
413316e0e9de2f237d9768cfa68db3893e72b48c
2,292
kotlin-coding-challenges
MIT License
kotlin/src/main/kotlin/com/github/jntakpe/aoc2022/days/Day13.kt
jntakpe
572,853,785
false
{"Kotlin": 72329, "Rust": 15876}
package com.github.jntakpe.aoc2022.days import com.github.jntakpe.aoc2022.shared.Day import com.github.jntakpe.aoc2022.shared.readInputSplitOnBlank object Day13 : Day { override val input = parse() override fun part1(): Int { return input.mapIndexedNotNull { index, (a, b) -> index.takeIf { a <= b } }.sumOf { it + 1 } } override fun part2(): Int { val a = Packets(listOf(2)) val b = Packets(listOf(6)) val packets = (input.flatMap { (a, b) -> listOf(a, b) } + a + b).sorted() return (packets.indexOf(a) + 1) * (packets.indexOf(b) + 1) } @JvmInline value class Packets(val value: Any) : Comparable<Packets> { override fun compareTo(other: Packets): Int { return when { value is Int && other.value is Int -> value - other.value value is Int -> Packets(listOf(value)).compareTo(other) other.value is Int -> compareTo(Packets(listOf(other.value))) else -> { value as List<*> other.value as List<*> for (i in 0 until minOf(value.size, other.value.size)) { val a = value[i]!! val b = other.value[i]!! Packets(a).compareTo(Packets(b)).let { if (it != 0) return it } } value.size.compareTo(other.value.size) } } } } private fun parse(): List<Pair<Packets, Packets>> { return readInputSplitOnBlank(13) .map { it.lines() } .map { (l1, l2) -> parsePair(l1) to parsePair(l2) } } private fun parsePair(input: String): Packets { val raw = input.drop(1).dropLast(1) if (raw.isEmpty()) return Packets(emptyList<Any>()) val list = buildList { var inside = "" var brackets = 0 fun parseInside(): Any { return if (inside.toIntOrNull() != null) inside.toInt() else parsePair(inside).value } for (c in raw) { if (c == '[') brackets++ if (c == ']') brackets-- if (c == ',' && brackets == 0) { add(parseInside()) inside = "" } else { inside += c } } add(parseInside()) } return Packets(list) } }
1
Kotlin
0
0
63f48d4790f17104311b3873f321368934060e06
2,474
aoc2022
MIT License
kotlin/saddle-points/src/main/kotlin/Matrix.kt
enolive
96,409,842
false
{"Haskell": 220732, "TypeScript": 92672, "Kotlin": 78063, "Java": 28701, "C#": 1346}
class Matrix(val points: List<List<Int>>) { val saddlePoints: Set<MatrixCoordinate> init { val allPoints = allPoints() saddlePoints = maxInRow(allPoints) intersect minInColumn(allPoints) } fun allPoints(): List<Pair<MatrixCoordinate, Int>> { return points.mapIndexed { rowIndex, row -> row.mapIndexed { columnIndex, value -> Pair(MatrixCoordinate(rowIndex, columnIndex), value) } }.flatMap { it } } fun minInColumn(allPoints: List<Pair<MatrixCoordinate, Int>>): Set<MatrixCoordinate> { val columns = allPoints.groupBy { it.first.col } return findCoordinates(columns, { column -> minimumValueIn(column) }) } fun maxInRow(allPoints: List<Pair<MatrixCoordinate, Int>>): Set<MatrixCoordinate> { val rows = allPoints.groupBy { it.first.row } return findCoordinates(rows, { row -> maximumValueIn(row) }) } private fun findCoordinates(group: Map<Int, List<Pair<MatrixCoordinate, Int>>>, aggregate: (Map.Entry<Int, List<Pair<MatrixCoordinate, Int>>>) -> Int): Set<MatrixCoordinate> { return group .map { items -> Pair(items, aggregate(items)) } .map { (items, aggregatedValue) -> items.value.filter { (_, value) -> value == aggregatedValue } } .flatten() .map { (coordinate, _) -> coordinate } .toSet() } private fun minimumValueIn(column: Map.Entry<Int, List<Pair<MatrixCoordinate, Int>>>) = column.value.minBy { it.second }!!.second private fun maximumValueIn(row: Map.Entry<Int, List<Pair<MatrixCoordinate, Int>>>) = row.value.maxBy { it.second }!!.second }
81
Haskell
0
0
61a64a04a257b02145310dc6ac2342f986ca0672
1,756
exercism
MIT License
year2023/day11/expansion/src/main/kotlin/com/curtislb/adventofcode/year2023/day11/expansion/ExpandedUniverse.kt
curtislb
226,797,689
false
{"Kotlin": 2146738}
package com.curtislb.adventofcode.year2023.day11.expansion import com.curtislb.adventofcode.common.collection.mapToSet import com.curtislb.adventofcode.common.geometry.Point import com.curtislb.adventofcode.common.io.forEachLineIndexed import com.curtislb.adventofcode.common.iteration.uniquePairs import java.io.File import kotlin.math.abs /** * A representation of a universe containing one or more galaxies, in which the empty space between * galaxies has increased by a given expansion factor. * * @property galaxies A list of point positions of all galaxies in the universe, before accounting * for expansion. * @param expansionFactor The factor by which the space between galaxies should increase to account * for expansion. */ class ExpandedUniverse(private val galaxies: List<Point>, expansionFactor: Long) { /** * A map from each row index in [galaxies] to the distance between that row and the row at index * 0, after accounting for expansion. */ private val rowDistanceMap: Map<Int, Long> = expandedDistanceMap(galaxies.mapToSet { it.matrixRow }, expansionFactor) /** * A map from each column index in [galaxies] to the distance between that column and the column * at index 0, after accounting for expansion. */ private val colDistanceMap: Map<Int, Long> = expandedDistanceMap(galaxies.mapToSet { it.matrixCol }, expansionFactor) /** * Returns the sum of distances between all unique pairs of galaxies in the universe, after * accounting for expansion. */ fun sumGalaxyDistances(): Long = galaxies.uniquePairs().sumOf { (pointA, pointB) -> val rowDistanceA = rowDistanceMap[pointA.matrixRow] ?: error("Not in row map: $pointA") val rowDistanceB = rowDistanceMap[pointB.matrixRow] ?: error("Not in row map: $pointB") val colDistanceA = colDistanceMap[pointA.matrixCol] ?: error("Not in column map: $pointA") val colDistanceB = colDistanceMap[pointB.matrixCol] ?: error("Not in column map: $pointB") abs(rowDistanceA - rowDistanceB) + abs(colDistanceA - colDistanceB) } companion object { /** * Returns an [ExpandedUniverse] with the specified [expansionFactor] and galaxy positions * read from the given input [file], representing an unexpanded image of the universe. * * The [file] should contain a 2D grid of *only* the following characters: * - `#`: A galaxy contained in the universe * - `.`: An empty (unexpanded) space in the universe image */ fun fromFile(file: File, expansionFactor: Long): ExpandedUniverse { val galaxies = mutableListOf<Point>() file.forEachLineIndexed { rowIndex, line -> line.forEachIndexed { colIndex, char -> if (char == '#') { galaxies.add(Point.fromMatrixCoordinates(rowIndex, colIndex)) } } } return ExpandedUniverse(galaxies, expansionFactor) } /** * Returns a map from each index in [galaxyIndices] to the distance between that index and * index 0, assuming all excluded indices expand in size by the given [expansionFactor]. */ private fun expandedDistanceMap( galaxyIndices: Set<Int>, expansionFactor: Long ): Map<Int, Long> { // Calculate distance for each galaxy index in order val distanceMap = mutableMapOf(0 to 0L) var prevIndex = 0 for (index in galaxyIndices.sorted()) { // Skip index 0, since it's fixed at a distance of 0 if (index == 0) { continue } // Add expanded distance (plus 1 for this index) to the previous distance val prevDistance = distanceMap[prevIndex] ?: error("Index not in map: $prevIndex") val expandedDistance = (index - prevIndex - 1) * expansionFactor distanceMap[index] = prevDistance + expandedDistance + 1L prevIndex = index } return distanceMap } } }
0
Kotlin
1
1
6b64c9eb181fab97bc518ac78e14cd586d64499e
4,224
AdventOfCode
MIT License
src/Day11.kt
achugr
573,234,224
false
null
import java.math.BigInteger class ItemRouter(private val router: (BigInteger) -> Monkey) { fun send(item: BigInteger) { router.invoke(item).offer(item) } } class Monkey( private val items: MutableList<BigInteger>, private val operation: (BigInteger) -> BigInteger, private val stressReduces: Boolean, val divisibleBy: BigInteger, val firstMate: Int, val secondMate: Int ) { lateinit var router: ItemRouter lateinit var mod: BigInteger var itemsCounter: Int = 0 fun playRound() { items.forEach { item -> var value = operation.invoke(item.mod(mod)) if (stressReduces) { value = value.divide(BigInteger.valueOf(3)) } router.send(value) itemsCounter++ } items.clear() } fun offer(item: BigInteger) { items.add(item) } override fun toString(): String { return "Monkey(items=$items)" } companion object MonkeyInitializer { val monkeyRegex = """ Monkey \d+: Starting items: (?<startingItems>[\d,\s]+) Operation: new = old (?<operation>[+*] (?<operand>\w+)) Test: divisible by (?<divisibleBy>\d+) If true: throw to monkey (?<throwTo1>\d+) If false: throw to monkey (?<throwTo2>\d+) """.trimIndent().toRegex() fun init(str: String, stressReduces: Boolean): Monkey { val match = monkeyRegex.find(str) ?: throw IllegalArgumentException("Failed to parse monkey definition") val startingItems = match.getValue("startingItems").split(",").map { it.trim().toBigInteger() }.toMutableList() val operand = match.getValue("operand") val itemOperation = with(match.getValue("operation")) { when { startsWith("* old") -> { i: BigInteger -> i * i } startsWith("*") -> { i: BigInteger -> i * operand.toBigInteger() } startsWith("+") -> { i: BigInteger -> i + operand.toBigInteger() } startsWith("-") -> { i: BigInteger -> i - operand.toBigInteger() } else -> throw IllegalArgumentException("Unexpected input") } } val divisibleBy = match.getValue("divisibleBy").toBigInteger() return Monkey( startingItems, itemOperation, stressReduces, divisibleBy, match.getValue("throwTo1").toInt(), match.getValue("throwTo2").toInt() ) } } } fun main() { fun readMonkeys(input: String, stressReduces: Boolean): List<Monkey> { val monkeys = input.split("\n\n") .map { Monkey.init(it, stressReduces) } .toList() val mod = monkeys .map { it.divisibleBy } .reduce { acc, value -> acc * value } monkeys.forEach { monkey -> monkey.mod = mod monkey.router = ItemRouter { i: BigInteger -> if (i.mod(monkey.divisibleBy).equals(BigInteger.ZERO)) { monkeys[monkey.firstMate] } else { monkeys[monkey.secondMate] } } } return monkeys } fun getAnswer(monkeys: List<Monkey>) = monkeys .map { it.itemsCounter.toLong() } .sortedByDescending { it } .take(2) .reduce { acc, value -> acc * value } fun playGame(input: String, rounds: Int, stressReduces: Boolean): Long { val monkeys = readMonkeys(input, stressReduces) (0 until rounds).forEach { idx -> monkeys.forEach { monkey -> monkey.playRound() } } return getAnswer(monkeys) } fun part1(input: String): Long { return playGame(input, 20, true) } fun part2(input: String): Long { return playGame(input, 10_000, false) } // test if implementation meets criteria from the description, like: println(part1(readInputText("Day11"))) println(part2(readInputText("Day11"))) } fun MatchResult.getValue(name: String): String = this.groups[name]?.value ?: throw IllegalArgumentException("Group for name $name not found")
0
Kotlin
0
0
d91bda244d7025488bff9fc51ca2653eb6a467ee
4,300
advent-of-code-kotlin-2022
Apache License 2.0
app/src/test/java/com/terencepeh/leetcodepractice/RecursiveSum.kt
tieren1
560,012,707
false
{"Kotlin": 26346}
package com.terencepeh.leetcodepractice fun sum(arr: IntArray): Int { println("Size = ${arr.size}") return when { arr.isEmpty() -> 0 else -> arr[0] + sum(arr.copyOfRange(1, arr.size)) } } fun count(list: List<Any>): Int { return when { list.isEmpty() -> 0 else -> 1 + count(list.subList(1, list.size)) } } private fun max(list: IntArray): Int = when { list.size == 2 -> if (list[0] > list[1]) list[0] else list[1] else -> { val subMax = max(list.copyOfRange(1, list.size)) if (list[0] > subMax) list[0] else subMax } } fun main() { println(sum(intArrayOf(1, 2, 3, 4, 5))) println(count(listOf(1, 2, 3, 4, 5))) println(max(intArrayOf(1, 5, 10, 25, 16, 1))) // 25 }
0
Kotlin
0
0
427fa2855c01fbc1e85a840d0be381cbb4eec858
760
LeetCodePractice
MIT License
src/main/kotlin/day15/Day15.kt
Ostkontentitan
434,500,914
false
{"Kotlin": 73563}
package day15 import readInput fun puzzle() { val inputs = readInput(15).toRiskMap() // val bestPartOne = RecursivePathfinder().searchOptimalPath(inputs) // println("Best way found in runs: $bestPartOne") // 4246 val revealed = revealActualCave(inputs) val bestPartTwo = BacktrackingPathfinder().searchOptimalPath(revealed) println("Hardmode: Best way has risk: $bestPartTwo") } fun revealActualCave(incompleteMap: CaveRiskMap): CaveRiskMap { val size = incompleteMap.size * 5 return (0 until size).map { y -> (0 until size).map { x -> val xShift = x / incompleteMap.size val yShift = y / incompleteMap.size val xMod = x % incompleteMap.size val yMod = y % incompleteMap.size val shift = xShift + yShift val baseVal = incompleteMap[yMod][xMod] val new = baseVal + shift if (new > 9) new - 9 else new }.toTypedArray() }.toTypedArray() } fun List<String>.toRiskMap(): Array<Array<Int>> = map { it.map { char -> Integer.parseInt(char.toString()) }.toTypedArray() }.toTypedArray() typealias CaveRiskMap = Array<Array<Int>>
0
Kotlin
0
0
e0e5022238747e4b934cac0f6235b92831ca8ac7
1,185
advent-of-kotlin-2021
Apache License 2.0
src/main/kotlin/asaad/DayFour.kt
Asaad27
573,138,684
false
{"Kotlin": 23483}
package asaad import java.io.File private fun IntRange.containsOneAnother(intRange: IntRange): Boolean { return this.intersect(intRange).size == minOf(intRange.size, this.size) } private fun IntRange.overlap(intRange: IntRange): Boolean { return this.intersect(intRange).isNotEmpty() } private val IntRange.size: Int get() { return this.last - this.first + 1 } class DayFour(filePath: String) { private val file = File(filePath) private val input = readInput(file).map { it.asRanges() } private fun readInput(file: File) = file.readLines() private fun String.asRanges(): List<IntRange> { return this.split(",").map { getFieldRange(it) } } private fun solve(func: IntRange.(IntRange) -> Boolean) = input.count { it[0].func(it[1]) } fun result() { println("\tpart 1: ${solve(IntRange::containsOneAnother)}") println("\tpart 2: ${solve(IntRange::overlap)}") } /** * @param section: field section expression : "a-b" */ private fun getFieldRange(section: String): IntRange { val (first, second) = section.split("-") .map { it.toInt() } return first..second } }
0
Kotlin
0
0
16f018731f39d1233ee22d3325c9933270d9976c
1,205
adventOfCode2022
MIT License
app/src/main/java/com/itscoder/ljuns/practise/algorithm/MergeSort.kt
ljuns
148,606,057
false
{"Java": 26841, "Kotlin": 25458}
package com.itscoder.ljuns.practise.algorithm /** * Created by ljuns at 2019/1/8. * I am just a developer. * 归并排序 * 1、先将数组中间分割,直到无法分割 * 3, 1, 1, 6, 2, 4, 19 * 3, 1, 1, 6 * 3, 1 * 3 1 * 2、对最小的部分开始排序 1 3 1, 6 * 1 3 1 6 * 1 1 3 6 2, 4, 19 * 1 1 3 6 2, 4 19 * 1 1 3 6 2 4 * 1 1 2 3 4 6 19 * 1 1 2 3 4 6 19 * 3、合并上层的分割 */ fun main(args: Array<String>) { val arr = intArrayOf(3, 1, 1, 6, 2, 4, 19) val temp = intArrayOf(0, 0, 0, 0, 0, 0, 0) mergeSort(arr, 0, arr.size - 1, temp) arr.forEach { println(it) } } fun mergeSort(arr: IntArray, left: Int, right: Int, temp: IntArray) { if (left < right) { val mid = (left + right) / 2 // 分割左边 mergeSort(arr, left, mid, temp) // 分割右边 mergeSort(arr, mid + 1, right, temp) // 合并排序 merge(arr, left, mid, right, temp) } } fun merge(arr: IntArray, left: Int, mid: Int, right: Int, temp: IntArray) { var l = left // 从右边的第一个开始 var r = mid + 1 var i = 0 while (l <= mid && r <= right) { if (arr[l] <= arr[r]) { // 将左边的元素给临时数组,并把左边指向下一个 temp[i++] = arr[l++] } else { // 将右边的元素给临时数组,并把右边指向下一个 temp[i++] = arr[r++] } } // 将左边剩余的元素放到临时数组 while (l <= mid) { temp[i++] = arr[l++] } // 将右边剩余的元素放到临时数组 while (r <= right) { temp[i++] = arr[r++] } // 此时的临时数组已经是个有序数组了 var left = left i = 0 // 将临时数组的元素复制到原数组,原数组的起始位置是合并前左半部分的第一个位置,即 left while (left <= right) { arr[left++] = temp[i++] } }
0
Java
0
0
365062b38a7ac55468b202ebeff1b760663fc676
2,515
Practise
Apache License 2.0
src/day05/Day05.kt
Klaus-Anderson
572,740,347
false
{"Kotlin": 13405}
package day05 import readInput import java.util.* import kotlin.NoSuchElementException import kotlin.collections.ArrayDeque import kotlin.collections.ArrayList fun main() { fun part1(input: List<String>): String { val stacksIndexLine = input.first { line -> line.all { it.isDigit() or (it.toString() == " ") } } val stackList = input.take( input.indexOf(stacksIndexLine) ).map { line -> line.chunked(4).map { item -> item.filter { it.isLetter() } } }.let { listListString -> ArrayList(List(stacksIndexLine.last { it.isDigit() }.toString().toInt()) { index -> ArrayDeque(listListString.map { it[index] }.filterNot { it == "" }.reversed()) }) } val instructionList = input.slice( input.indexOf(stacksIndexLine)+2 until input.size ) instructionList.map { instruction -> val instructionNumbers = instruction.filter { it.isDigit() or (it.toString() == " ") }.also { it.replace(" ", " ") }.split(" ").filterNot { it == "" }.map { it.toInt() } val howManyToMove = instructionNumbers[0] val fromWhichStack = instructionNumbers[1] - 1 val toWhichStack = instructionNumbers[2] - 1 repeat(howManyToMove) { try { stackList[toWhichStack].add(stackList[fromWhichStack].removeLast()) } catch (_: NoSuchElementException){ } } } return stackList.joinToString(separator = "") { it.removeLast() } } fun part2(input: List<String>): String { val stacksIndexLine = input.first { line -> line.all { it.isDigit() or (it.toString() == " ") } } val stackList = input.take( input.indexOf(stacksIndexLine) ).map { line -> line.chunked(4).map { item -> item.filter { it.isLetter() } } }.let { listListString -> ArrayList(List(stacksIndexLine.last { it.isDigit() }.toString().toInt()) { index -> ArrayDeque(listListString.map { it[index] }.filterNot { it == "" }.reversed()) }) } val instructionList = input.slice( input.indexOf(stacksIndexLine)+2 until input.size ) instructionList.map { instruction -> val instructionNumbers = instruction.filter { it.isDigit() or (it.toString() == " ") }.also { it.replace(" ", " ") }.split(" ").filterNot { it == "" }.map { it.toInt() } val howManyToMove = instructionNumbers[0] val fromWhichStack = instructionNumbers[1] - 1 val toWhichStack = instructionNumbers[2] - 1 val toAdd = mutableListOf<String>() repeat(howManyToMove) { try { toAdd.add(stackList[fromWhichStack].removeLast()) } catch (_: NoSuchElementException){ } } toAdd.reversed().forEach { stackList[toWhichStack].add(it) } } return stackList.joinToString(separator = "") { it.removeLast() } } // test if implementation meets criteria from the description, like: val testInput = readInput("day05", "Day05_test") check(part1(testInput) == "CMZ") check(part2(testInput) == "MCD") val input = readInput("day05", "day05") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
faddc2738011782841ec20475171909e9d4cee84
4,123
harry-advent-of-code-kotlin-template
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/BinaryGapStrategy.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 private const val MAX_SIZE = 32 /** * 868. Binary Gap * @see <a href="https://leetcode.com/problems/binary-gap/">Source</a> */ fun interface BinaryGapStrategy { fun binaryGap(n: Int): Int } /** * Approach 1: Store Indexes * Time Complexity: O(log N). * Space Complexity: O(log N). */ class BGStoreIndexes : BinaryGapStrategy { override fun binaryGap(n: Int): Int { val a = IntArray(MAX_SIZE) var t = 0 for (i in 0 until MAX_SIZE) if (n shr i and 1 != 0) a[t++] = i var ans = 0 for (i in 0 until t - 1) ans = ans.coerceAtLeast(a[i + 1] - a[i]) return ans } } /** * Approach 2: One Pass * Time Complexity: O(log N). * Space Complexity: O(1). */ class BGOnePass : BinaryGapStrategy { override fun binaryGap(n: Int): Int { var last = -1 var ans = 0 for (i in 0 until MAX_SIZE) if (n shr i and 1 > 0) { if (last >= 0) ans = ans.coerceAtLeast(i - last) last = i } return ans } } class BGOther : BinaryGapStrategy { override fun binaryGap(n: Int): Int { var max = 0 var pos = 0 var lastPos = -1 var changed = n while (changed != 0) { pos++ if (changed and 1 == 1) { if (lastPos != -1) { max = max.coerceAtLeast(pos - lastPos) } lastPos = pos } changed = changed shr 1 } return max } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
2,149
kotlab
Apache License 2.0
2021/src/main/kotlin/com/github/afranken/aoc/Day202103.kt
afranken
434,026,010
false
{"Kotlin": 28937}
package com.github.afranken.aoc import kotlin.math.pow object Day202103 { fun part1(inputs: Array<String>): Int { //every input is expected to have the same size. Take inputs[0] to initialize. val inputLength = inputs[0].length val zeroes = IntArray(inputLength) val ones = IntArray(inputLength) //count up ones and zeroes for (input in inputs) { for (i in 0 until inputLength) { when (input[i].digitToInt()) { 0 -> zeroes[i]++ 1 -> ones[i]++ } } } val gammaBinary = Array(inputLength) { "" } val epsilonBinary = Array(inputLength) { "" } //construct gamma and epsilon binary numbers for (i in 0 until inputLength) { if (zeroes[i] > ones[i]) { gammaBinary[i] = "0" epsilonBinary[i] = "1" } else { gammaBinary[i] = "1" epsilonBinary[i] = "0" } } //convert to String representing binary code, then to decimal val gamma = toDecimal(gammaBinary.joinToString("")) val epsilon = toDecimal(epsilonBinary.joinToString("")) return gamma * epsilon } fun part2(inputs: Array<String>): Int { //all inputs are expected to have the same length val inputLength = inputs[0].length //iterate over initial list //split list into 1s and 0s for the first bit position val splitted = splitListByBit(inputs, 0) var oxygenBinary = if (splitted[1].size >= splitted[0].size) splitted[1] else splitted[0] var co2Binary = if (splitted[0].size <= splitted[1].size) splitted[0] else splitted[1] //process both lists: larger list for oxygen, smaller list for co2. Given equal size, // process 1s for oxygen. for (i in 1 until inputLength) { if (oxygenBinary.size > 1) { //oxygen: go through list for every bit position in 1 until length, always keep the larger list val oxygenSplit = splitListByBit(oxygenBinary, i) oxygenBinary = findNext(oxygenSplit[1], oxygenSplit[0], true) } if (co2Binary.size > 1) { //co2: go through list for every bit position in 1 until length, always keep smaller list. val co2Split = splitListByBit(co2Binary, i) co2Binary = findNext(co2Split[1], co2Split[0], false) } } //convert to String representing binary code, then to decimal val oxygen = toDecimal(oxygenBinary.joinToString("")) val co2 = toDecimal(co2Binary.joinToString("")) return oxygen * co2 } private fun findNext(ones: Array<String>, zeroes: Array<String>, oxygen: Boolean): Array<String> { return if (oxygen) { if (ones.size >= zeroes.size) { //oxygen prefers 1s over 0s when sizes are equal ones } else { zeroes } } else { if (zeroes.size <= ones.size) { //co2 prefers 0s over 1s when sizes are equal zeroes } else { ones } } } private fun splitListByBit(inputs: Array<String>, position: Int): Array<Array<String>> { val ones = arrayListOf<String>() val zeroes = arrayListOf<String>() for (input in inputs) { val c = input[position].toString() when (c) { "0" -> zeroes.add(input) "1" -> ones.add(input) } } //returns zeroes array with index 0 and ones array with index 1. return arrayOf(zeroes.toTypedArray(), ones.toTypedArray()) } private fun toDecimal(binaryNumber: String): Int { var sum = 0 binaryNumber.reversed().forEachIndexed { k, v -> sum += v.toString().toInt() * 2.0.pow(k.toDouble()).toInt() } return sum } }
0
Kotlin
0
0
0140f68e60fa7b37eb7060ade689bb6634ba722b
4,054
advent-of-code-kotlin
Apache License 2.0
src/main/kotlin/dp/MaxQuality.kt
yx-z
106,589,674
false
null
package dp import util.OneArray import util.get import util.toCharOneArray // given a method quality: T[1..k] -> Int that taking O(k) time and a string // S[1..n] find the max sum of qualities of each contiguous substring of S fun main(args: Array<String>) { val S = "acejfop".toCharOneArray() // sample method val quality: (OneArray<Char>) -> Int = { var sum = 0 it.asSequence().forEach { sum += ('r' - it) * (it - 'b') } sum } println(S.maxQ(quality)) } fun OneArray<Char>.maxQ(quality: (OneArray<Char>) -> Int): Int { val S = this val n = S.size // dp(i) = max sum of qualities of S[1..i] // memoization structure: 1d array dp[1..n] : dp[i] = dp(i) val dp = OneArray(n) { 0 } // space complexity: O(n) // base case: // dp(1) = quality(S[1..1]) dp[1] = quality(S[1..1]) // time complexity: O(1) // recursive case: // dp(i) = max{ dp(k) + S[k + 1..i] }, 1 <= k < i // dependency: dp(i) depends on dp[k] : k < i, that is entries to the left // evaluation order: outer loop for i from 2 to n (left to right) for (i in 2..n) { // inner loop for k from 1 until i dp[i] = (1 until i) .map { k -> dp[k] + quality(S[k..i]) } .max()!! } // time complexity: O(n^3) dp.prettyPrintln() // we want dp(n) return dp[n] // overall space complexity: O(n) // overall runtime complexity: O(n^3) }
0
Kotlin
0
1
15494d3dba5e5aa825ffa760107d60c297fb5206
1,333
AlgoKt
MIT License
src/main/kotlin/PuzzleModels.kt
Kyle-Falconer
671,044,954
false
null
sealed class PuzzleSolutionResult(val words: List<String>) { fun print() { when (this) { is ValidPuzzleSolution -> { println("${words.stringify()} ✅ valid solution in ${words.size} words") } is IncompletePuzzleSolution -> { println("${words.stringify()} ❌ incomplete solution; remaining letters= $remainingLetters") } is InvalidPuzzleSolution -> { println("${words.stringify()} ❌ invalid solution, $message") } } } } class ValidPuzzleSolution(words: List<String>) : PuzzleSolutionResult(words), Comparable<ValidPuzzleSolution> { private val solutionCharacterCount = words.joinToString().length private fun countCharacterOverlap(): Int { return solutionCharacterCount - words.joinToString().toSet().size } override fun compareTo(other: ValidPuzzleSolution): Int { return if (this.countCharacterOverlap() < other.countCharacterOverlap()) { -1 } else if (this.countCharacterOverlap() > other.countCharacterOverlap()) { 1 } else { solutionCharacterCount.compareTo(other.solutionCharacterCount) } } } class IncompletePuzzleSolution(words: List<String>, val remainingLetters: Set<Char>) : PuzzleSolutionResult(words) class InvalidPuzzleSolution(words: List<String>, val message: String) : PuzzleSolutionResult(words) sealed class CheckedWordResult(val word: String) { fun print() { when (this) { is ValidWord -> { println("\"$word\" ✅ valid word; remaining letters= $remainingLetters") } is InvalidWord -> { println("\"$word\" ❌ invalid word: $message") } } } } class ValidWord(word: String, val remainingLetters: Set<Char>) : CheckedWordResult(word) class InvalidWord(word: String, val message: String) : CheckedWordResult(word)
0
Kotlin
0
0
32f65f18067d686bb79cf84bdbb30bc880319124
2,038
LetterBoxedPuzzleSolver
Apache License 2.0
module-tool/src/main/kotlin/de/twomartens/adventofcode/day15/CustomHashMap.kt
2martens
729,312,999
false
{"Kotlin": 89431}
package de.twomartens.adventofcode.day15 import java.util.LinkedList data class Lens(val label: String, val focalLength: Int, val boxNumber: Int, val slotNumber: Int) enum class Operation { INSERT, REMOVAL } class CustomHashMap(private val hashAlgorithm: HashAlgorithm) { private val boxLensLabels: MutableMap<Int, MutableMap<String, Int>> = mutableMapOf() val boxes: MutableMap<Int, MutableList<Lens>> = mutableMapOf() fun sumTotalFocusingPower(): Int { return boxes.values.flatten().sumOf { calculateFocusingPower(it) } } fun calculateFocusingPower(lens: Lens): Int { return (1 + lens.boxNumber) * lens.slotNumber * lens.focalLength } fun handleInputs(inputs: List<String>) { inputs.forEach { handleInput(it) } } private fun handleInput(input: String) { val operation = parseOperation(input) when (operation) { Operation.INSERT -> insert(input) Operation.REMOVAL -> remove(input) } } private fun parseOperation(input: String): Operation { return when { input.contains('=') -> Operation.INSERT input.endsWith('-') -> Operation.REMOVAL else -> throw IllegalArgumentException("Input must contain = or -") } } private fun insert(input: String) { val (label, focalLengthString) = input.split('=') val boxNumber = hashAlgorithm.calculateHash(label) val lenses = boxes.getOrDefault(boxNumber, LinkedList()) val lensLabels = boxLensLabels.getOrDefault(boxNumber, mutableMapOf()) .toMutableMap() if (lensLabels.containsKey(label)) { val index = lensLabels[label]!! val lens = Lens(label, focalLengthString.toInt(), boxNumber, index + 1) lenses[index] = lens } else { val lens = Lens(label, focalLengthString.toInt(), boxNumber, lenses.lastIndex + 2) lenses.addLast(lens) lensLabels[label] = lenses.lastIndex } boxes[boxNumber] = lenses boxLensLabels[boxNumber] = lensLabels } private fun remove(input: String) { val label = input.substringBefore('-') val boxNumber = hashAlgorithm.calculateHash(label) var lenses = boxes.getOrDefault(boxNumber, mutableListOf()) val lensLabels = boxLensLabels.getOrDefault(boxNumber, mutableMapOf()) .toMutableMap() if (lensLabels.containsKey(label)) { val index = lensLabels[label]!! lenses = lenses.mapIndexed { existingIndex, lens -> val newLens = if (existingIndex > index) { Lens(lens.label, lens.focalLength, lens.boxNumber, lens.slotNumber - 1) } else { lens } newLens }.toMutableList() lenses.removeAt(index) lensLabels.remove(label) lensLabels.forEach { (existingLabel, existingIndex) -> if (existingIndex > index) { lensLabels[existingLabel] = existingIndex - 1 } } } boxes[boxNumber] = lenses boxLensLabels[boxNumber] = lensLabels } }
0
Kotlin
0
0
03a9f7a6c4e0bdf73f0c663ff54e01daf12a9762
3,343
advent-of-code
Apache License 2.0
domain/src/main/kotlin/com/seanshubin/condorcet/backend/domain/Ranking.kt
SeanShubin
238,518,165
false
null
package com.seanshubin.condorcet.backend.domain import kotlin.math.max import kotlin.random.Random data class Ranking(val candidateName: String, val rank: Int?) { companion object { fun List<Ranking>.prefers(a: String, b: String): Boolean = rankingFor(a) < rankingFor(b) private fun List<Ranking>.rankingFor(candiateName: String): Int = find { ranking -> ranking.candidateName == candiateName }?.rank ?: Int.MAX_VALUE fun List<Ranking>.listToString() = joinToString(" ") { (candidateName, rank) -> "$rank $candidateName" } fun List<Ranking>.voterBiasedOrdering(random: Random): List<Ranking> { val rankAscending = Comparator<Ranking> { o1, o2 -> val rank1 = o1?.rank ?: Int.MAX_VALUE val rank2 = o2?.rank ?: Int.MAX_VALUE rank1.compareTo(rank2) } val grouped = groupBy { it.rank } val groupedValues = grouped.values val shuffled = groupedValues.flatMap { it.shuffled(random) } val sorted = shuffled.sortedWith(rankAscending) return sorted } fun List<Ranking>.addMissingCandidates(allCandidates: List<String>): List<Ranking> { val existingCandidates = this.map { it.candidateName } val isMissing = { candidate: String -> !existingCandidates.contains(candidate) } val missingCandidates = allCandidates.filter(isMissing) val newRankings = missingCandidates.map { Ranking(it, null) } return this + newRankings } fun List<Ranking>.normalizeRankingsReplaceNulls(): List<Ranking> { val distinctOrderedRanks = this.mapNotNull { it.rank }.distinct().sorted() val normalized = (1..distinctOrderedRanks.size) val newRankMap = distinctOrderedRanks.zip(normalized).toMap() val lastRank = distinctOrderedRanks.size + 1 val result = map { (name, rank) -> val newRank = newRankMap[rank] ?: lastRank Ranking(name, newRank) } return result } fun List<Ranking>.normalizeRankingsKeepNulls(): List<Ranking> { val distinctOrderedRanks = this.mapNotNull { it.rank }.distinct().sorted() val normalized = (1..distinctOrderedRanks.size) val newRankMap = distinctOrderedRanks.zip(normalized).toMap() val result = map { (name, rank) -> val newRank = newRankMap[rank] Ranking(name, newRank) } return result } fun List<Ranking>.effectiveRankings(candidateNames: List<String>): List<Ranking> = addMissingCandidates(candidateNames).normalizeRankingsReplaceNulls() fun List<Ranking>.matchOrderToCandidates(candidateNames: List<String>): List<Ranking> { val byCandidate = this.associateBy { it.candidateName } return candidateNames.map { byCandidate.getValue(it) } } object RankingListComparator : Comparator<List<Ranking>> { override fun compare(firstRankingList: List<Ranking>, secondRankingList: List<Ranking>): Int { val firstRankList = firstRankingList.mapNotNull { it.rank } val secondRankList = secondRankingList.mapNotNull { it.rank } return RankListComparator.compare(firstRankList, secondRankList) } } object RankListComparator : Comparator<List<Int>> { override fun compare(firstList: List<Int>, secondList: List<Int>): Int { val maxSize = max(firstList.size, secondList.size) var compareResult = 0 var index = 0 while (index < maxSize) { val firstValue = firstList[index] val secondValue = secondList[index] compareResult = RankComparator.compare(firstValue, secondValue) if (compareResult != 0) break index++ } return compareResult } } object RankComparator : Comparator<Int> { override fun compare(first: Int, second: Int): Int = first.compareTo(second) } } }
0
Kotlin
0
0
c6dd3e86d9f722829c57d215fcfa7cb18b7955cd
4,309
condorcet-backend
The Unlicense
src/main/kotlin/com/github/wakingrufus/aoc/Day2.kt
wakingrufus
159,674,364
false
null
package com.github.wakingrufus.aoc import mu.KLogging val letters = ('a'..'z') class Day2 { companion object : KLogging() fun processInput(): List<String> = inputFileToLines("input-day2.txt") fun checksum(boxIds: List<String>): Int { val twos = boxIds.count { id -> letters.any { letter -> id.containsNOf(times = 2, letter = letter) } } val threes = boxIds.count { id -> letters.any { letter -> id.containsNOf(times = 3, letter = letter) } } return twos * threes } fun part2(boxIds: List<String>): String { return boxIds.allCombinations() .first(this@Day2::stringsMatch) .let { logger.info("found match: " + it.first + " and " + it.second) it.first.toCharArray() .filterIndexed { i, c -> it.second.toCharArray()[i] == c } .toCharArray() }.let { String(it) } } fun stringsMatch(strings: Pair<String, String>): Boolean { return strings.first.length == strings.second.length && strings.first.toCharArray() .zip(strings.second.toCharArray()) .count { it.first != it.second } == 1 } } fun String.containsNOf(times: Int, letter: Char): Boolean = this.count { it == letter } == times fun <T> List<T>.allCombinations(): Sequence<Pair<T, T>> { val collection = this return sequence { for (i in 0 until collection.size) { for (s in i + 1 until collection.size) { yield(collection[i] to collection[s]) } } } }
0
Kotlin
0
0
bdf846cb0e4d53bd8beda6fdb3e07bfce59d21ea
1,771
advent-of-code-2018
MIT License
src/Day04.kt
colund
573,040,201
false
{"Kotlin": 10244}
fun fullyContained(min1: Int, max1: Int, min2: Int, max2: Int): Boolean { return (min1 <= min2 && max1 >= max2) || (min2 <= min1 && max2 >= max1) } fun partiallyOverlap(min1: Int, max1: Int, min2: Int, max2: Int): Boolean { return (max1 in min2..max2) || (max2 in min1..max1) } fun main() { println("Day4 part 1: " + day4 { fullyContained(it[0].toInt(), it[1].toInt(), it[2].toInt(), it[3].toInt()) }) println("Day4 part 2: " + day4 { partiallyOverlap(it[0].toInt(), it[1].toInt(), it[2].toInt(), it[3].toInt()) }) } fun day4(fn: (List<String>) -> Boolean): Int { val input = readInput("Day04") val regex = "(\\d+)-(\\d+),(\\d+)-(\\d+)".toRegex() val count = input.map { line -> regex.findAll(line).map { it.groupValues.drop(1) } }.flatMap { it.map(fn) }.count { it } // Count the number of invocations that returned true return count }
0
Kotlin
0
0
49dcd2fccad0e54ee7b1a9cb99df2acdec146759
885
aoc-kotlin-2022
Apache License 2.0
src/Day01.kt
OskarWalczak
573,349,185
false
{"Kotlin": 22486}
fun main() { fun generateListOfSums(lines: List<String>): List<Int> { var currentSum: Int = 0 val sums : MutableList<Int> = ArrayList<Int>() lines.forEach{line -> if(line.isEmpty()){ sums.add(currentSum) currentSum = 0 } else{ val cals: Int = Integer.parseInt(line) currentSum += cals } } sums.sortDescending() return sums } fun part1(input: List<String>): Int { return generateListOfSums(input)[0] } fun part2(input: List<String>): Int { val sums = generateListOfSums(input) return sums[0] + sums[1] + sums[2] } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") check(part1(testInput) == 24000) val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
d34138860184b616771159984eb741dc37461705
972
AoC2022
Apache License 2.0
instantsearch/src/commonMain/kotlin/com/algolia/instantsearch/filter/facet/dynamic/internal/FacetsOrder.kt
algolia
55,971,521
false
{"Kotlin": 689459}
package com.algolia.instantsearch.filter.facet.dynamic.internal import com.algolia.instantsearch.filter.facet.dynamic.AttributedFacets import com.algolia.search.model.Attribute import com.algolia.search.model.rule.FacetOrdering import com.algolia.search.model.rule.FacetValuesOrder import com.algolia.search.model.rule.SortRule import com.algolia.search.model.search.Facet /** * Apply the algorithm transforming the received facets and facet ordering rules to the list of ordered facet attributes * and ordered values. * * @param facets facets per attribute * @param facetOrdering facets ordering rule */ internal fun facetsOrder(facets: Map<Attribute, List<Facet>>, facetOrdering: FacetOrdering): List<AttributedFacets> { val orderedAttributes = facetOrdering.facets.order.mapNotNull { attribute -> facets.keys.firstOrNull { it.raw == attribute } } return orderedAttributes.map { attribute -> val facetValues = facets[attribute] ?: emptyList() val orderedFacetValues = facetOrdering.values[attribute]?.let { order(facetValues, it) } ?: facetValues AttributedFacets(attribute, orderedFacetValues) } } /** * Order facet values. * * @param facets the list of facets to order * @param rule the ordering rule for facets * @return list of ordered facets */ private fun order(facets: List<Facet>, rule: FacetValuesOrder): List<Facet> { if (facets.size <= 1) return facets val pinnedFacets = rule.order.mapNotNull { value -> facets.firstOrNull { it.value == value } } val remainingFacets = facets.filter { !pinnedFacets.contains(it) } val facetsTail: List<Facet> = when (rule.sortRemainingBy ?: SortRule.Count) { SortRule.Alpha -> remainingFacets.sortedBy { it.value } SortRule.Count -> remainingFacets.sortedByDescending { it.count } SortRule.Hidden -> emptyList() } return pinnedFacets + facetsTail }
15
Kotlin
32
155
cb068acebbe2cd6607a6bbeab18ddafa582dd10b
1,895
instantsearch-android
Apache License 2.0
src/problems/day8/part1/part1.kt
klnusbaum
733,782,662
false
{"Kotlin": 43060}
package problems.day8.part1 import java.io.File //private const val test1file = "input/day8/test1.txt" //private const val test2file = "input/day8/test2.txt" private const val inputFile = "input/day8/input.txt" fun main() { val stepsCount = File(inputFile).bufferedReader().useLines { numSteps(it) } println("Number of steps $stepsCount") } private fun numSteps(lines: Sequence<String>): Int { val (instructions, rules) = lines.fold(RuleSetBuilder()) { builder, line -> builder.nextLine(line) }.build() var currentLocation = "AAA" while (currentLocation != "ZZZ") { val nextDirection = instructions.next() val nextRule = rules[currentLocation] ?: throw IllegalArgumentException("No such location: $currentLocation") currentLocation = if (nextDirection == 'L') { nextRule.left } else { nextRule.right } } return instructions.directionCount } private class Instructions(val directions: String) : Iterator<Char> { var directionCount = 0 override fun hasNext() = true override fun next(): Char { val next = directions[directionCount % directions.count()] directionCount++ return next } } private data class Rule(val left: String, val right: String) private fun String.toRule(): Rule { val left = this.substringBefore(", ").trimStart { it == '(' } val right = this.substringAfter(", ").trimEnd { it == ')' } return Rule(left, right) } private data class ParseResult(val instructions: Instructions, val rules: Map<String, Rule>) private class RuleSetBuilder { private var state = State.INSTRUCTIONS private var instructions: Instructions? = null private val rules = mutableMapOf<String, Rule>() private enum class State { INSTRUCTIONS, BLANK, RULES, } fun nextLine(line: String): RuleSetBuilder { when (state) { State.INSTRUCTIONS -> { instructions = Instructions(line) state = State.BLANK } State.BLANK -> { state = State.RULES } State.RULES -> { rules[line.substringBefore(" =")] = line.substringAfter("= ").toRule() } } return this } fun build() = ParseResult( instructions ?: throw IllegalArgumentException("missing instructions"), rules ) }
0
Kotlin
0
0
d30db2441acfc5b12b52b4d56f6dee9247a6f3ed
2,438
aoc2023
MIT License
src/main/kotlin/com/staricka/adventofcode2023/days/Day16.kt
mathstar
719,656,133
false
{"Kotlin": 107115}
package com.staricka.adventofcode2023.days import com.staricka.adventofcode2023.framework.Day import com.staricka.adventofcode2023.util.Grid import com.staricka.adventofcode2023.util.GridCell import com.staricka.adventofcode2023.util.StandardGrid import java.util.LinkedList import kotlin.math.max class MirrorGridTile(private val type: Char): GridCell { private val visited = HashSet<BeamDirection>() override val symbol = type fun energized() = visited.isNotEmpty() fun reset() = visited.clear() fun processBeam(direction: BeamDirection): List<BeamDirection> { if (visited.contains(direction)) return emptyList() visited.add(direction) return when (type) { '.' -> listOf(direction) '|' -> if (direction in listOf(BeamDirection.LEFT, BeamDirection.RIGHT)) listOf(BeamDirection.UP, BeamDirection.DOWN) else listOf(direction) '-' -> if (direction in listOf(BeamDirection.UP, BeamDirection.DOWN)) listOf(BeamDirection.LEFT, BeamDirection.RIGHT) else listOf(direction) '\\'-> when (direction) { BeamDirection.UP -> listOf(BeamDirection.LEFT) BeamDirection.RIGHT -> listOf(BeamDirection.DOWN) BeamDirection.DOWN -> listOf(BeamDirection.RIGHT) BeamDirection.LEFT -> listOf(BeamDirection.UP) } '/' -> when (direction) { BeamDirection.UP -> listOf(BeamDirection.RIGHT) BeamDirection.RIGHT -> listOf(BeamDirection.UP) BeamDirection.DOWN -> listOf(BeamDirection.LEFT) BeamDirection.LEFT -> listOf(BeamDirection.DOWN) } else -> throw Exception() } } } enum class BeamDirection { RIGHT, DOWN, LEFT, UP } data class Beam(val direction: BeamDirection, val x: Int, val y: Int) { fun translate(newDirection: BeamDirection): Beam { val newX = when(newDirection) { BeamDirection.UP -> x - 1 BeamDirection.DOWN -> x + 1 else -> x } val newY = when(newDirection) { BeamDirection.LEFT -> y - 1 BeamDirection.RIGHT -> y + 1 else -> y } return Beam(newDirection, newX, newY) } } fun Grid<MirrorGridTile>.energizedFromStart(direction: BeamDirection = BeamDirection.RIGHT, x: Int = 0, y: Int = 0): Int { val beams = LinkedList<Beam>() beams.add(Beam(direction, x, y)) while (beams.isNotEmpty()) { val beam = beams.pop() this[beam.x, beam.y]!!.processBeam(beam.direction) .map { beam.translate(it) } .filter { it.x in minX..maxX && it.y in minY..maxY } .forEach { beams.add(it) } } return cells().count { (_,_,t) -> t.energized() } } fun Grid<MirrorGridTile>.reset() { cells().forEach { (_,_,v) -> v.reset() } } class Day16: Day { override fun part1(input: String): Int { val grid = StandardGrid.build(input, ::MirrorGridTile) return grid.energizedFromStart() } override fun part2(input: String): Int { val grid = StandardGrid.build(input, ::MirrorGridTile) var max = 0 for (y in grid.minY..grid.maxY) { grid.reset() max = max(max, grid.energizedFromStart(BeamDirection.DOWN, 0, y)) grid.reset() max = max(max, grid.energizedFromStart(BeamDirection.UP, grid.maxX, y)) } for (x in grid.minX..grid.maxX) { grid.reset() max = max(max, grid.energizedFromStart(BeamDirection.RIGHT, x, 0)) grid.reset() max = max(max, grid.energizedFromStart(BeamDirection.LEFT, x, grid.maxY)) } return max } }
0
Kotlin
0
0
8c1e3424bb5d58f6f590bf96335e4d8d89ae9ffa
3,780
adventOfCode2023
MIT License
src/Day05.kt
marosseleng
573,498,695
false
{"Kotlin": 32754}
import java.util.ArrayDeque import java.util.Deque fun main() { fun part1(input: List<String>): String { val stacks = parseStacks(input.takeWhile { it.isNotBlank() }) val instructions = input.dropWhile { it.isNotBlank() }.drop(1) applyInstructions(instructions) { howMany, from, to -> move(stacks, howMany, from, to, inBatch = false) } return stacks.joinToString(separator = "") { try { it.pop() } catch (e: NoSuchElementException) { "" } } } fun part2(input: List<String>): String { val stacks = parseStacks(input.takeWhile { it.isNotBlank() }) val instructions = input.dropWhile { it.isNotBlank() }.drop(1) applyInstructions(instructions) { howMany, from, to -> move(stacks, howMany, from, to, inBatch = true) } return stacks.joinToString(separator = "") { try { it.pop() } catch (e: NoSuchElementException) { "" } } } val testInput = readInput("Day05_test") check(part1(testInput) == "CMZ") check(part2(testInput) == "MCD") val input = readInput("Day05") println(part1(input)) println(part2(input)) } fun parseStacks(stacks: List<String>): MutableList<Deque<String>> { val stacksFromBottom = stacks.reversed() val stackCount = stacksFromBottom.first().filter { it.isDigit() }.map { it.toString().toInt() }.max() val onlyStacks = stacksFromBottom.drop(1) val result = mutableListOf<Deque<String>>() repeat(stackCount) { result.add(ArrayDeque()) } onlyStacks.forEach { stack -> for (i in 0 until stackCount) { val characterIndex = 4 * i + 1 val number = stack.getOrNull(characterIndex)?.toString()?.takeUnless { it.isBlank() } ?: continue result[i].push(number) } } return result } fun applyInstructions(instructions: List<String>, callback: (howMany: Int, from: Int, to: Int) -> Unit) { instructions.forEachIndexed { index, instruction -> val values = """move (\d+) from (\d+) to (\d+)""".toRegex().matchEntire(instruction)?.groupValues ?: return@forEachIndexed callback(values[1].toInt(), values[2].toInt(), values[3].toInt()) } } fun move(stacks: MutableList<Deque<String>>, howMany: Int, from: Int, to: Int, inBatch: Boolean) { if (!inBatch) { repeat(howMany) { stacks[to - 1].push(stacks[from - 1].pop()) } } else { (0 until howMany) .map { stacks[from - 1].pop() } .reversed() .forEach { stacks[to - 1].push(it) } } }
0
Kotlin
0
0
f13773d349b65ae2305029017490405ed5111814
2,770
advent-of-code-2022-kotlin
Apache License 2.0
2021/kotlin/src/main/kotlin/com/pietromaggi/aoc2021/day16/Day16.kt
pfmaggi
438,378,048
false
{"Kotlin": 113883, "Zig": 18220, "C": 7779, "Go": 4059, "CMake": 386, "Awk": 184}
/* * Copyright 2021 <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 com.pietromaggi.aoc2021.day16 import com.pietromaggi.aoc2021.readInput data class PacketInfo(val version: Int, val value: Long, val position: Int) fun compute(operation: Int, factors: List<Long>): Long = when (operation) { 0 -> { // Sum factors.fold(0L) { sum, element -> sum + element } } 1 -> { // Product factors.fold(1L) { product, element -> product * element } } 2 -> { // Minimum factors.minOrNull()!! } 3 -> { // Maximum factors.maxOrNull()!! } 5 -> { // Greater Than if (factors.first() > factors.last()) 1L else 0L } 6 -> { // Lesser Than if (factors.first() < factors.last()) 1L else 0L } 7 -> { // Equal to if (factors.first() == factors.last()) 1L else 0L } else -> 0L } fun parseCalc(code: String): PacketInfo { var pos = 0 var version = code.substring(pos..pos + 2).toInt(radix = 2) pos += 3 val type = code.substring(pos..pos + 2).toInt(radix = 2) pos += 3 val result = when (type) { 4 -> { // Literal value var number = code.substring(pos+1..pos+4) while (code[pos] != '0') { pos += 5 number += code.substring(pos+1..pos + 4) } pos += 5 number.toLong(radix = 2) } else -> { val lengthType = code.substring(pos..pos).toInt(radix = 2) val length: Int val numbers = mutableListOf<Long>() pos += 1 if (lengthType == 0) { // length is 15 bits length = code.substring(pos..pos + 14).toInt(radix = 2) pos += 15 val start = pos while (pos < start + length) { val (partialVersion, partialValue, digested) = parseCalc(code.substring(pos)) numbers.add(partialValue) version += partialVersion pos += digested } compute(type, numbers) } else { // number of sub-packets is 11 bits val subPackets = code.substring(pos..pos + 10).toInt(radix = 2) pos += 11 repeat(subPackets) { val (partialVersion, partialValue, digested) = parseCalc(code.substring(pos)) numbers.add(partialValue) version += partialVersion pos += digested } compute(type, numbers) } } } return PacketInfo(version, result, pos) } fun part1(input: List<String>): Int { val line = input[0].chunked(1).joinToString("") { (it.toInt(radix = 16)).toString(radix = 2).padStart(4, '0') } val (result, _, _) = parseCalc(line) return result } fun part2(input: List<String>): Long { val line = input[0].chunked(1).joinToString("") { (it.toInt(radix = 16)).toString(radix = 2).padStart(4, '0') } val (_, result, _) = parseCalc(line) return result } fun main() { val input = readInput("Day16") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
7c4946b6a161fb08a02e10e99055a7168a3a795e
3,858
AdventOfCode
Apache License 2.0
puzzles/kotlin/src/skynet-revolution2/skynet-revolution2.kt
charlesfranciscodev
179,561,845
false
{"Python": 141140, "Java": 34848, "Kotlin": 33981, "C++": 27526, "TypeScript": 22844, "C#": 22075, "Go": 12617, "JavaScript": 11282, "Ruby": 6255, "Swift": 3911, "Shell": 3090, "Haskell": 1375, "PHP": 1126, "Perl": 667, "C": 493}
import java.util.Scanner import java.util.ArrayDeque fun main(args : Array<String>) { val graph = Graph() graph.readInitInput() graph.gameLoop() } class Node(val index:Int) { val links = ArrayList<Node>() var isGateway = false var isMarked = false fun nbGatewayLinks() : Int { return links.count { it.isGateway } } fun gatewayLink(): Node? { return links.firstOrNull { it.isGateway } } } class Graph { val input = Scanner(System.`in`) val nodes = ArrayList<Node>() val targetGateways = ArrayList<Node>() fun updateTargets(gateway: Node) { if (gateway.links.isEmpty()) { targetGateways.remove(gateway) } } fun reset() { for (node in nodes) { node.isMarked = false } } /** n1 and n2 are the indices of the nodes you wish to sever the link between */ fun sever(n1: Int, n2: Int) { val builder = StringBuilder() builder.append(n1) builder.append(" ") builder.append(n2) println(builder.toString()) } fun readInitInput() { val nbNodes = input.nextInt() // the total number of nodes in the level, including the gateways val nbLinks = input.nextInt() // the number of links val nbGateways = input.nextInt() // the number of exit gateways (0 until nbNodes).mapTo(nodes) { Node(it) } for (i in 0 until nbLinks) { val n1 = input.nextInt() // n1 and n2 defines a link between these nodes val n2 = input.nextInt() val node1 = nodes[n1] val node2 = nodes[n2] node1.links.add(node2) node2.links.add(node1) } for (i in 0 until nbGateways) { val index = input.nextInt() // the index of a gateway node val gateway = nodes[index] gateway.isGateway = true targetGateways.add(gateway) } } fun gameLoop() { while (true) { val agentIndex = input.nextInt() // The index of the node on which the Skynet agent is positioned this turn if (!blockNearbyAgent(agentIndex)) { if (!blockDoubleGateway(agentIndex)) { blockGateway() } } } } /** If the agent is linked to an exit, sever the link and return True. Otherwise, return False */ fun blockNearbyAgent(agentIndex: Int): Boolean { val agentNode = nodes[agentIndex] for (node in agentNode.links) { if (node.isGateway) { sever(agentIndex, node.index) agentNode.links.remove(node) node.links.remove(agentNode) updateTargets(node) return true } } return false } /** * Slice the last link on the shortest path between the virus and a gateway using BFS. * Only danger nodes are considered in possible paths. * A danger node is a node with 1 or more gateway links. * The link is severed if the node is linked to 2 gateways. * */ fun blockDoubleGateway(agentIndex: Int): Boolean { val agentNode = nodes[agentIndex] val queue = ArrayDeque<Node>() reset() agentNode.isMarked = true queue.add(agentNode) while(!queue.isEmpty()) { val currentNode = queue.pollFirst() for (neighbor in currentNode.links) { val nbGatewayLinks = neighbor.nbGatewayLinks() if (!neighbor.isGateway && nbGatewayLinks >= 1 && !neighbor.isMarked) { neighbor.isMarked = true if (nbGatewayLinks == 2) { val gateway = neighbor.gatewayLink() if (gateway != null) { sever(neighbor.index, gateway.index) neighbor.links.remove(gateway) gateway.links.remove(neighbor) updateTargets(gateway) return true } } else { queue.add(neighbor) } } } } return false } /** Slice a random gateway link. */ fun blockGateway() { val gateway = targetGateways[0] val node = gateway.links[0] sever(gateway.index, node.index) gateway.links.remove(node) node.links.remove(gateway) updateTargets(gateway) } }
0
Python
19
45
3ec80602e58572a0b7baf3a2829a97e24ca3460c
3,989
codingame
MIT License
src/main/kotlin/tw/gasol/aoc/aoc2022/Day7.kt
Gasol
574,784,477
false
{"Kotlin": 70912, "Shell": 1291, "Makefile": 59}
package tw.gasol.aoc.aoc2022 import java.util.Scanner import kotlin.math.abs interface Filesystem { val name: String val size: Int } data class File( override val name: String, override val size: Int, val parent: Directory? = null ) : Filesystem data class Directory( override val name: String, val children: MutableList<Filesystem> = mutableListOf(), val parent: Directory? = null ) : Filesystem { override val size = 0 private fun findChildren(name: String): Filesystem? { return children.firstOrNull { it.name == name } } fun findChildrenRecursively(predicate: (Filesystem) -> Boolean): List<Filesystem> { return children.filter(predicate) + children.filterIsInstance<Directory>() .flatMap { it.findChildrenRecursively(predicate) } } fun getDirectory(name: String): Directory? { return findChildren(name) as Directory? } fun getTotalSize(): Int { return size + children.sumOf { if (it is Directory) it.getTotalSize() else it.size } } } class Day7 { private fun buildFilesystem(input: String): Filesystem { var currentDir: Directory? = null var rootDir: Directory? = null input.lineSequence() .filterNot { it.isBlank() } .forEach { line -> if (line.startsWith("$")) { Scanner(line).use { scanner -> scanner.next() when (val command = scanner.next()) { "cd" -> { val path = scanner.next() currentDir = when (path) { ".." -> { assert(currentDir != null && currentDir?.parent != null) { "Cannot go up from root directory" } currentDir!!.parent } "/" -> { Directory("/").also { rootDir = it } } else -> { currentDir!!.getDirectory(path).also { childDir -> assert(childDir != null) { "Directory $childDir does not exist" } } } } } "ls" -> { // no-op } else -> error("Unknown command: $command") } } } else { assert(currentDir != null) { "Current directory can't be null" } Scanner(line).use { scanner -> val firstToken = scanner.next() if (firstToken == "dir") { val name = scanner.next() val dir = Directory(name, parent = currentDir) currentDir!!.children.add(dir) } else { val size = firstToken.toInt() val name = scanner.next() val file = File(name, size, parent = currentDir) currentDir!!.children.add(file) } } } } return rootDir!! } private fun printDir(dir: Directory, indent: Int = 0) { print(" ".repeat(indent)) println("- ${dir.name} (dir)") val childIndent = indent + 2 dir.children.forEach { child -> when (child) { is Directory -> printDir(child, childIndent) is File -> { print(" ".repeat(childIndent)) println("- ${child.name} (file, size=${child.size})") } } } } fun part1(input: String): Int { val filesystem = buildFilesystem(input) as Directory // printDir(filesystem) return filesystem .findChildrenRecursively { it is Directory && it.getTotalSize() < 100_000 } .map { it as Directory } .sumOf { it.getTotalSize() } } fun part2(input: String): Int { val totalSpaceAvailable = 70_000_000 val filesystem = buildFilesystem(input) as Directory val totalUsedSpace = filesystem.getTotalSize() val unusedSpace = totalSpaceAvailable - totalUsedSpace val atLeastSpaceNeedsToBeDelete = 30_000_000 - unusedSpace return filesystem .findChildrenRecursively { it is Directory } .map { it as Directory } .sortedWith(compareBy { abs(it.getTotalSize() - atLeastSpaceNeedsToBeDelete) }) .first().getTotalSize() } }
0
Kotlin
0
0
a14582ea15f1554803e63e5ba12e303be2879b8a
5,162
aoc2022
MIT License
src/Day22.kt
flex3r
572,653,526
false
{"Kotlin": 63192}
suspend fun main() { val testInput = readInput("Day22_test") check(part1(testInput) == 6032) check(part2(testInput) == 5031) val input = readInput("Day22") measureAndPrintResult { part1(input) } measureAndPrintResult { part2(input) } } private fun part1(input: List<String>): Int { val (mapInput, instructionInput) = input.partitionBy { it.isEmpty() } val grid = parseGrid(mapInput) val instructions = parseInstructions(instructionInput.first()) return walkGrid(grid, instructions) } private fun part2(input: List<String>): Int { val (mapInput, instructionInput) = input.partitionBy { it.isEmpty() } val grid = parseGrid(mapInput) val instructions = parseInstructions(instructionInput.first()) val isTest = grid.width == 16 val cubeSides: Map<Vec2, Int> = buildMap { if (isTest) { putAll((0..3).flatMap { x -> (4..7).map { y -> Vec2(x, y) to 1 } }) putAll((4..7).flatMap { x -> (4..7).map { y -> Vec2(x, y) to 2 } }) putAll((8..11).flatMap { x -> (4..7).map { y -> Vec2(x, y) to 3 } }) putAll((8..11).flatMap { x -> (0..3).map { y -> Vec2(x, y) to 4 } }) putAll((8..11).flatMap { x -> (8..11).map { y -> Vec2(x, y) to 5 } }) putAll((12..15).flatMap { x -> (8..11).map { y -> Vec2(x, y) to 6 } }) } else { putAll((100..149).flatMap { x -> (0..49).map { y -> Vec2(x, y) to 1 } }) putAll((50..99).flatMap { x -> (0..49).map { y -> Vec2(x, y) to 2 } }) putAll((50..99).flatMap { x -> (50..99).map { y -> Vec2(x, y) to 3 } }) putAll((50..99).flatMap { x -> (100..149).map { y -> Vec2(x, y) to 4 } }) putAll((0..49).flatMap { x -> (100..149).map { y -> Vec2(x, y) to 5 } }) putAll((0..49).flatMap { x -> (150..199).map { y -> Vec2(x, y) to 6 } }) } } val rules = buildList { if (isTest) { add(Rule(cubeSide = 1, direction = Direction.Left, newDirection = Direction.Up, transformPosition = { pos -> Vec2(12 + (7 - pos.y), 11) })) add(Rule(cubeSide = 1, direction = Direction.Up, newDirection = Direction.Down, transformPosition = { pos -> Vec2(8 + (3 - pos.x), 0) })) add(Rule(cubeSide = 1, direction = Direction.Down, newDirection = Direction.Up, transformPosition = { pos -> Vec2(8 + (3 - pos.x), 11) })) add(Rule(cubeSide = 2, direction = Direction.Up, newDirection = Direction.Right, transformPosition = { pos -> Vec2(8, pos.x - 4) })) add(Rule(cubeSide = 2, direction = Direction.Down, newDirection = Direction.Right, transformPosition = { pos -> Vec2(8, 4 + pos.x) })) add(Rule(cubeSide = 3, direction = Direction.Right, newDirection = Direction.Down, transformPosition = { pos -> Vec2(15 - (pos.y - 4), 8) })) add(Rule(cubeSide = 4, direction = Direction.Left, newDirection = Direction.Down, transformPosition = { pos -> Vec2(4 + pos.y, 4) })) add(Rule(cubeSide = 4, direction = Direction.Up, newDirection = Direction.Down, transformPosition = { pos -> Vec2(3 - (pos.x - 8), 4) })) add(Rule(cubeSide = 4, direction = Direction.Right, newDirection = Direction.Left, transformPosition = { pos -> Vec2(15, 8 + (3 - pos.y)) })) add(Rule(cubeSide = 5, direction = Direction.Left, newDirection = Direction.Up, transformPosition = { pos -> Vec2(4 + (3 - (pos.y - 8)), 7) })) add(Rule(cubeSide = 5, direction = Direction.Down, newDirection = Direction.Up, transformPosition = { pos -> Vec2(3 - (pos.x - 8), 7) })) add(Rule(cubeSide = 6, direction = Direction.Up, newDirection = Direction.Left, transformPosition = { pos -> Vec2(11, 4 + (3 - (pos.x - 12))) })) add(Rule(cubeSide = 6, direction = Direction.Right, newDirection = Direction.Left, transformPosition = { pos -> Vec2(11, 3 - (pos.y - 8)) })) add(Rule(cubeSide = 6, direction = Direction.Down, newDirection = Direction.Right, transformPosition = { pos -> Vec2(0, 4 + (3 - (12 - pos.x))) })) } else { add(Rule(cubeSide = 1, direction = Direction.Up, newDirection = Direction.Up, transformPosition = { pos -> Vec2(pos.x - 100, 199) })) // -> 6 add(Rule(cubeSide = 1, direction = Direction.Right, newDirection = Direction.Left, transformPosition = { pos -> Vec2(99, 100 + (49 - pos.y)) })) // -> 4 add(Rule(cubeSide = 1, direction = Direction.Down, newDirection = Direction.Left, transformPosition = { pos -> Vec2(99, 50 + (pos.x - 100)) })) // -> 3 add(Rule(cubeSide = 2, direction = Direction.Up, newDirection = Direction.Right, transformPosition = { pos -> Vec2(0, 150 + (pos.x - 50)) })) // -> 6 add(Rule(cubeSide = 2, direction = Direction.Left, newDirection = Direction.Right, transformPosition = { pos -> Vec2(0, 149 - pos.y) })) // -> 5 add(Rule(cubeSide = 3, direction = Direction.Right, newDirection = Direction.Up, transformPosition = { pos -> Vec2(100 + (pos.y - 50), 49) })) // -> 1 add(Rule(cubeSide = 3, direction = Direction.Left, newDirection = Direction.Down, transformPosition = { pos -> Vec2(pos.y - 50, 100) })) // -> 5 add(Rule(cubeSide = 4, direction = Direction.Right, newDirection = Direction.Left, transformPosition = { pos -> Vec2(149, 149 - pos.y) })) // -> 1 add(Rule(cubeSide = 4, direction = Direction.Down, newDirection = Direction.Left, transformPosition = { pos -> Vec2(49, 150 + (pos.x - 50)) })) // -> 6 add(Rule(cubeSide = 5, direction = Direction.Up, newDirection = Direction.Right, transformPosition = { pos -> Vec2(50, pos.x + 50) })) // -> 3 add(Rule(cubeSide = 5, direction = Direction.Left, newDirection = Direction.Right, transformPosition = { pos -> Vec2(50, 149 - pos.y) })) // -> 2 add(Rule(cubeSide = 6, direction = Direction.Left, newDirection = Direction.Down, transformPosition = { pos -> Vec2(50 + (pos.y - 150), 0) })) // -> 2 add(Rule(cubeSide = 6, direction = Direction.Down, newDirection = Direction.Down, transformPosition = { pos -> Vec2(pos.x + 100, 0) })) // -> 1 add(Rule(cubeSide = 6, direction = Direction.Right, newDirection = Direction.Up, transformPosition = { pos -> Vec2(50 + (pos.y - 150), 149) })) // -> 4 } } return walkGrid(grid, instructions, cubeSides, rules) } private data class Rule(val cubeSide: Int, val direction: Direction, val newDirection: Direction, val transformPosition: (Vec2) -> Vec2) private fun walkGrid( grid: Grid<Char>, instructions: List<Instruction>, cubeSides: Map<Vec2, Int> = emptyMap(), rules: List<Rule> = emptyList(), ): Int { val start = grid.getRowCells(0).first { (_, c) -> c == '.'}.first val state = instructions.fold(GridState(start, Direction.Right)) { state, instruction -> doInstruction(grid, state, instruction, cubeSides, rules) } return 1000 * (state.position.y + 1) + 4 * (state.position.x + 1) + state.direction.score } private fun doInstruction( grid: Grid<Char>, state: GridState, instruction: Instruction, cubeSides: Map<Vec2, Int>, rules: List<Rule> ): GridState { val ruleMap = rules.associate { (cubeSide, direction, newDirection, transform) -> (cubeSide to direction) to (newDirection to transform) } return when (instruction) { RotateRight -> state.copy(direction = Direction.values().first { it.ordinal == (state.direction.ordinal + 1) % 4 }) RotateLeft -> state.copy(direction = Direction.values().first { it.ordinal == (state.direction.ordinal + 3) % 4 }) is Move -> { var position = state.position var direction = state.direction repeat(instruction.amount) { var newPosition = position + direction.vector var newDirection = direction if (newPosition !in grid || grid[newPosition] == ' ') { val cubeSide = cubeSides[position] if (cubeSide == null) { newPosition = when (direction) { Direction.Right -> grid.getRowCells(newPosition.y).first { (_, c) -> c != ' ' }.first Direction.Down -> grid.getColumnCells(newPosition.x).first { (_, c) -> c != ' ' }.first Direction.Left -> grid.getRowCells(newPosition.y).last { (_, c) -> c != ' ' }.first Direction.Up -> grid.getColumnCells(newPosition.x).last { (_, c) -> c != ' ' }.first } } else { val (newDirectionFromRule, transform) = ruleMap.getValue(cubeSide to direction) newDirection = newDirectionFromRule newPosition = transform(position) } } if (grid[newPosition] == '#') { return@repeat } position = newPosition direction = newDirection } state.copy(position = position, direction = direction) } } } private fun parseGrid(input: List<String>): Grid<Char> { val width = input.maxOf { it.length } val height = input.size return Grid.fromInput(width, height) { (x, y) -> input.getOrNull(y)?.getOrNull(x) ?: ' ' } } private fun parseInstructions(input: String): List<Instruction> { var currentMoveCount = 0 return buildList { input.forEach { c -> if (c.isDigit()) { currentMoveCount = currentMoveCount * 10 + c.digitToInt() return@forEach } if (currentMoveCount != 0) { add(Move(currentMoveCount)) currentMoveCount = 0 } when (c) { 'L' -> add(RotateLeft) 'R' -> add(RotateRight) else -> error("xd") } } // last char is digit if (currentMoveCount != 0) { add(Move(currentMoveCount)) } } } enum class Direction(val vector: Vec2, val score: Int) { Right(Vec2(1, 0), 0), Down(Vec2(0, 1), 1), Left(Vec2(-1, 0), 2), Up(Vec2(0, -1), 3), } sealed class Instruction data class Move(val amount: Int): Instruction() object RotateRight : Instruction() object RotateLeft : Instruction() data class GridState(val position: Vec2, val direction: Direction)
0
Kotlin
0
0
8604ce3c0c3b56e2e49df641d5bf1e498f445ff9
10,542
aoc-22
Apache License 2.0
day08/src/main/kotlin/Main.kt
rstockbridge
225,212,001
false
null
import extensions.charCounts fun main() { val input = resourceFile("input.txt") .readText() val image = parseInput(input, 25, 6) println("Part I: the solution is ${solvePartI(image)}.") println("Part II: the solution is:") solvePartII(image) } fun parseInput(input: String, width: Int, height: Int): List<List<String>> { val result = mutableListOf<List<String>>() val numberOfLayers = input.length / (width * height) val layerSize = height * width for (layerIndex in 0 until numberOfLayers) { val layer = mutableListOf<String>() for (rowIndex in 0 until height) { val row = input.substring( layerIndex * layerSize + width * rowIndex, layerIndex * layerSize + width * (1 + rowIndex) ) layer.add(row) } result.add(layer) } return result } fun solvePartI(image: List<List<String>>): Int { return validateImage(image) } fun solvePartII(image: List<List<String>>) { val height = image[0].size val width = image[0][0].length for (heightIndex in 0 until height) { for (widthIndex in 0 until width) { var layerIndex = 0 var layerPixel = image[layerIndex][heightIndex][widthIndex] while (layerPixel == '2') { layerIndex++ layerPixel = image[layerIndex][heightIndex][widthIndex] } if (layerPixel == '0') { print(" ") } else { print("█") } } println() } } fun validateImage(image: List<List<String>>): Int { val layerWithMin0Digits = image.minBy { convertLayerToSingleString(it).charCounts()['0']!! }!! val numberOf1Digits = convertLayerToSingleString(layerWithMin0Digits).charCounts().getOrElse('1') { 0 } val numberOf2Digits = convertLayerToSingleString(layerWithMin0Digits).charCounts().getOrElse('2') { 0 } return numberOf1Digits * numberOf2Digits } fun convertLayerToSingleString(layer: List<String>): String { var result = "" layer.forEach { row -> result += row } return result }
0
Kotlin
0
0
bcd6daf81787ed9a1d90afaa9646b1c513505d75
2,185
AdventOfCode2019
MIT License
src/day08/Day08.kt
Longtainbin
573,466,419
false
{"Kotlin": 22711}
package day08 import readInput import kotlin.math.max fun main() { val input = readInput("inputDay08") val matrix = createMatrix(input) println(processPart1(matrix)) println(processPart2(matrix)) } private fun createMatrix(input: List<String>): Array<IntArray> { val row = input.size val col = input.first().length val result = Array(row) { IntArray(col) } for (i in input.indices) { for (j in 0 until col) { result[i][j] = input[i][j] - '0' } } return result } // For Part_1 private fun processPart1(matrix: Array<IntArray>): Int { val row = matrix.size val col = matrix.first().size val matList = mutableListOf<Array<IntArray>>( upLookMatrix(matrix), downLookMatrix(matrix), leftLookMatrix(matrix), rightLookMatrix(matrix) ) var count = 0 for (i in 0 until row) { for (j in 0 until col) { if (isVisable(matrix, i, j, matList)) { count++ } } } return count } private fun isVisable(matrix: Array<IntArray>, i: Int, j: Int, matList: List<Array<IntArray>>): Boolean { if (isOnEdge(matrix, i, j)) { return true } for (mat in matList) { if (matrix[i][j] > mat[i][j]) { return true } } return false } // For Part_2 private fun processPart2(matrix: Array<IntArray>): Int { val row = matrix.size val col = matrix.first().size var maxScore = 0 for (i in 0 until row) { for (j in 0 until col) { maxScore = max(maxScore, getScore(matrix, i, j)) } } return maxScore } private fun getScore(matrix: Array<IntArray>, i: Int, j: Int): Int { if (isOnEdge(matrix, i, j)) { return 0 } var upScore = 0 for (index in (j - 1) downTo 0) { upScore++ if (matrix[i][index] >= matrix[i][j]) { break } } var downScore = 0 for (index in (j + 1) until matrix.size) { downScore++ if (matrix[i][index] >= matrix[i][j]) { break } } var leftScore = 0 for (index in (i - 1) downTo 0) { leftScore++ if (matrix[index][j] >= matrix[i][j]) { break } } var rightScore = 0 for (index in (i + 1) until matrix.first().size) { rightScore++ if (matrix[index][j] >= matrix[i][j]) { break } } return upScore * leftScore * downScore * rightScore }
0
Kotlin
0
0
48ef88b2e131ba2a5b17ab80a0bf6a641e46891b
2,527
advent-of-code-2022
Apache License 2.0
codeforces/round773/b.kt
mikhail-dvorkin
93,438,157
false
{"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408}
package codeforces.round773 private fun solve() { readInt() val a = readInts().toIntArray() val groups = a.groupBy { it } if (groups.values.any { it.size % 2 != 0 }) return println(-1) var start = 0 val insertions = mutableListOf<Pair<Int, Int>>() val tandems = mutableListOf<Int>() var x = 0 while (start < a.size) { val repeat = a.drop(start + 1).indexOf(a[start]) + start + 1 val rev = mutableListOf<Int>() for (i in start + 1 until repeat) { insertions.add(x + (repeat - start) + (i - start) to a[i]) rev.add(a[i]) } tandems.add((repeat - start) * 2) x += (repeat - start) * 2 rev.reverse() for (i in rev.indices) { a[start + 2 + i] = rev[i] } start += 2 } println(insertions.size) for (insertion in insertions) { println("${insertion.first} ${insertion.second}") } println(tandems.size) println(tandems.joinToString(" ")) } fun main() = repeat(readInt()) { solve() } private fun readLn() = readLine()!! private fun readInt() = readLn().toInt() private fun readStrings() = readLn().split(" ") private fun readInts() = readStrings().map { it.toInt() }
0
Java
1
9
30953122834fcaee817fe21fb108a374946f8c7c
1,104
competitions
The Unlicense
src/main/kotlin/g2201_2300/s2251_number_of_flowers_in_full_bloom/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g2201_2300.s2251_number_of_flowers_in_full_bloom // #Hard #Array #Hash_Table #Sorting #Binary_Search #Prefix_Sum #Ordered_Set // #2023_06_28_Time_973_ms_(100.00%)_Space_88.6_MB_(100.00%) import java.util.Arrays import java.util.PriorityQueue class Solution { fun fullBloomFlowers(flowers: Array<IntArray>, persons: IntArray): IntArray { Arrays.sort(flowers, { a: IntArray, b: IntArray -> a[0].compareTo(b[0]) }) val ans = IntArray(persons.size) val pq = PriorityQueue({ a: Pair, b: Pair -> a.j.compareTo(b.j) }) var j = 0 val t = Array(persons.size) { IntArray(2) } for (i in persons.indices) { t[i][0] = persons[i] t[i][1] = i } Arrays.sort(t, { a: IntArray, b: IntArray -> a[0].compareTo(b[0]) }) for (ints in t) { while (pq.isNotEmpty()) { if (pq.peek().j < ints[0]) { pq.poll() } else { break } } while (j < flowers.size) { if (flowers[j][0] <= ints[0] && flowers[j][1] >= ints[0]) { pq.add(Pair(flowers[j][0], flowers[j][1])) j++ continue } if (flowers[j][1] < ints[0]) { j++ continue } break } ans[ints[1]] = pq.size } return ans } private class Pair(var i: Int, var j: Int) }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,547
LeetCode-in-Kotlin
MIT License
cz.wrent.advent/Day14.kt
Wrent
572,992,605
false
{"Kotlin": 206165}
package cz.wrent.advent fun main() { println(partOne(test)) val result = partOne(input) println("14a: $result") println(partTwo(test)) println("14b: ${partTwo(input)}") } private fun partOne(input: String): Int { return simulate(input, withFloor = false) } private fun simulate(input: String, withFloor: Boolean): Int { val map = input.split("\n").map { it.toShape() }.flatten().map { it to Material.ROCK }.toMap().toMutableMap() val cave = if (withFloor) CaveWithFloor(map) else Cave(map) var i = 0 try { while (true) { cave.sandfall() i++ if (cave.map[500 to 0] == Material.SAND) { return i } } } catch (e: EndlessFallException) { println("Finished") } return i } private fun partTwo(input: String): Int { return simulate(input, withFloor = true) } private open class Cave(val map: MutableMap<Pair<Int, Int>, Material>) { fun add(coord: Pair<Int, Int>, material: Material) { map[coord] = material } fun sandfall() { val next = this.fall(500 to 0) add(next, Material.SAND) } fun fall(from: Pair<Int, Int>): Pair<Int, Int> { val bellow = findBellow(from) return if (get(bellow.first - 1 to bellow.second) == null) { this.fall(bellow.first - 1 to bellow.second) } else if (get(bellow.first + 1 to bellow.second) == null) { this.fall(bellow.first + 1 to bellow.second) } else { bellow.first to bellow.second - 1 } } open fun get(coord: Pair<Int, Int>): Material? { return map[coord] } open fun findBellow(from: Pair<Int, Int>): Pair<Int, Int> { return this.map.entries.filter { it.key.first == from.first }.filter { it.key.second > from.second } .minByOrNull { it.key.second }?.key ?: throw EndlessFallException() } } private class CaveWithFloor(map: MutableMap<Pair<Int, Int>, Material>) : Cave(map) { val floorY = map.keys.maxByOrNull { it.second }!!.second + 2 override fun get(coord: Pair<Int, Int>): Material? { return if (coord.second == floorY) return Material.ROCK else super.get(coord) } override fun findBellow(from: Pair<Int, Int>): Pair<Int, Int> { return try { super.findBellow(from) } catch (e: EndlessFallException) { from.first to floorY } } } private class EndlessFallException() : Exception() private enum class Material { ROCK, SAND, } private fun String.toShape(): Set<Pair<Int, Int>> { val set = mutableSetOf<Pair<Int, Int>>() val points = this.split(" -> ").map { it.split(",") }.map { it.first().toInt() to it.get(1).toInt() } points.windowed(2).forEach { (first, second) -> var current = first if (first.first == second.first) { while (current != second) { set.add(current) val diff = if (current.second < second.second) 1 else (-1) current = current.first to current.second + diff } } else { while (current != second) { set.add(current) val diff = if (current.first < second.first) 1 else (-1) current = current.first + diff to current.second } } set.add(second) } return set } private const val test = """498,4 -> 498,6 -> 496,6 503,4 -> 502,4 -> 502,9 -> 494,9""" private const val input = """503,53 -> 503,50 -> 503,53 -> 505,53 -> 505,51 -> 505,53 -> 507,53 -> 507,52 -> 507,53 -> 509,53 -> 509,50 -> 509,53 539,105 -> 539,98 -> 539,105 -> 541,105 -> 541,100 -> 541,105 -> 543,105 -> 543,103 -> 543,105 -> 545,105 -> 545,101 -> 545,105 -> 547,105 -> 547,95 -> 547,105 -> 549,105 -> 549,104 -> 549,105 -> 551,105 -> 551,99 -> 551,105 -> 553,105 -> 553,97 -> 553,105 -> 555,105 -> 555,96 -> 555,105 545,125 -> 549,125 536,172 -> 536,168 -> 536,172 -> 538,172 -> 538,164 -> 538,172 -> 540,172 -> 540,168 -> 540,172 -> 542,172 -> 542,163 -> 542,172 -> 544,172 -> 544,164 -> 544,172 -> 546,172 -> 546,171 -> 546,172 -> 548,172 -> 548,165 -> 548,172 -> 550,172 -> 550,170 -> 550,172 -> 552,172 -> 552,170 -> 552,172 500,34 -> 500,37 -> 496,37 -> 496,40 -> 506,40 -> 506,37 -> 504,37 -> 504,34 527,147 -> 527,139 -> 527,147 -> 529,147 -> 529,142 -> 529,147 -> 531,147 -> 531,138 -> 531,147 -> 533,147 -> 533,137 -> 533,147 -> 535,147 -> 535,140 -> 535,147 -> 537,147 -> 537,146 -> 537,147 -> 539,147 -> 539,142 -> 539,147 -> 541,147 -> 541,140 -> 541,147 527,147 -> 527,139 -> 527,147 -> 529,147 -> 529,142 -> 529,147 -> 531,147 -> 531,138 -> 531,147 -> 533,147 -> 533,137 -> 533,147 -> 535,147 -> 535,140 -> 535,147 -> 537,147 -> 537,146 -> 537,147 -> 539,147 -> 539,142 -> 539,147 -> 541,147 -> 541,140 -> 541,147 539,150 -> 539,152 -> 534,152 -> 534,159 -> 544,159 -> 544,152 -> 543,152 -> 543,150 500,34 -> 500,37 -> 496,37 -> 496,40 -> 506,40 -> 506,37 -> 504,37 -> 504,34 527,147 -> 527,139 -> 527,147 -> 529,147 -> 529,142 -> 529,147 -> 531,147 -> 531,138 -> 531,147 -> 533,147 -> 533,137 -> 533,147 -> 535,147 -> 535,140 -> 535,147 -> 537,147 -> 537,146 -> 537,147 -> 539,147 -> 539,142 -> 539,147 -> 541,147 -> 541,140 -> 541,147 558,119 -> 563,119 536,172 -> 536,168 -> 536,172 -> 538,172 -> 538,164 -> 538,172 -> 540,172 -> 540,168 -> 540,172 -> 542,172 -> 542,163 -> 542,172 -> 544,172 -> 544,164 -> 544,172 -> 546,172 -> 546,171 -> 546,172 -> 548,172 -> 548,165 -> 548,172 -> 550,172 -> 550,170 -> 550,172 -> 552,172 -> 552,170 -> 552,172 539,131 -> 543,131 527,147 -> 527,139 -> 527,147 -> 529,147 -> 529,142 -> 529,147 -> 531,147 -> 531,138 -> 531,147 -> 533,147 -> 533,137 -> 533,147 -> 535,147 -> 535,140 -> 535,147 -> 537,147 -> 537,146 -> 537,147 -> 539,147 -> 539,142 -> 539,147 -> 541,147 -> 541,140 -> 541,147 536,172 -> 536,168 -> 536,172 -> 538,172 -> 538,164 -> 538,172 -> 540,172 -> 540,168 -> 540,172 -> 542,172 -> 542,163 -> 542,172 -> 544,172 -> 544,164 -> 544,172 -> 546,172 -> 546,171 -> 546,172 -> 548,172 -> 548,165 -> 548,172 -> 550,172 -> 550,170 -> 550,172 -> 552,172 -> 552,170 -> 552,172 526,82 -> 530,82 527,147 -> 527,139 -> 527,147 -> 529,147 -> 529,142 -> 529,147 -> 531,147 -> 531,138 -> 531,147 -> 533,147 -> 533,137 -> 533,147 -> 535,147 -> 535,140 -> 535,147 -> 537,147 -> 537,146 -> 537,147 -> 539,147 -> 539,142 -> 539,147 -> 541,147 -> 541,140 -> 541,147 548,122 -> 553,122 539,105 -> 539,98 -> 539,105 -> 541,105 -> 541,100 -> 541,105 -> 543,105 -> 543,103 -> 543,105 -> 545,105 -> 545,101 -> 545,105 -> 547,105 -> 547,95 -> 547,105 -> 549,105 -> 549,104 -> 549,105 -> 551,105 -> 551,99 -> 551,105 -> 553,105 -> 553,97 -> 553,105 -> 555,105 -> 555,96 -> 555,105 500,34 -> 500,37 -> 496,37 -> 496,40 -> 506,40 -> 506,37 -> 504,37 -> 504,34 539,105 -> 539,98 -> 539,105 -> 541,105 -> 541,100 -> 541,105 -> 543,105 -> 543,103 -> 543,105 -> 545,105 -> 545,101 -> 545,105 -> 547,105 -> 547,95 -> 547,105 -> 549,105 -> 549,104 -> 549,105 -> 551,105 -> 551,99 -> 551,105 -> 553,105 -> 553,97 -> 553,105 -> 555,105 -> 555,96 -> 555,105 523,84 -> 527,84 536,172 -> 536,168 -> 536,172 -> 538,172 -> 538,164 -> 538,172 -> 540,172 -> 540,168 -> 540,172 -> 542,172 -> 542,163 -> 542,172 -> 544,172 -> 544,164 -> 544,172 -> 546,172 -> 546,171 -> 546,172 -> 548,172 -> 548,165 -> 548,172 -> 550,172 -> 550,170 -> 550,172 -> 552,172 -> 552,170 -> 552,172 551,119 -> 556,119 529,84 -> 533,84 505,62 -> 509,62 503,53 -> 503,50 -> 503,53 -> 505,53 -> 505,51 -> 505,53 -> 507,53 -> 507,52 -> 507,53 -> 509,53 -> 509,50 -> 509,53 527,147 -> 527,139 -> 527,147 -> 529,147 -> 529,142 -> 529,147 -> 531,147 -> 531,138 -> 531,147 -> 533,147 -> 533,137 -> 533,147 -> 535,147 -> 535,140 -> 535,147 -> 537,147 -> 537,146 -> 537,147 -> 539,147 -> 539,142 -> 539,147 -> 541,147 -> 541,140 -> 541,147 527,147 -> 527,139 -> 527,147 -> 529,147 -> 529,142 -> 529,147 -> 531,147 -> 531,138 -> 531,147 -> 533,147 -> 533,137 -> 533,147 -> 535,147 -> 535,140 -> 535,147 -> 537,147 -> 537,146 -> 537,147 -> 539,147 -> 539,142 -> 539,147 -> 541,147 -> 541,140 -> 541,147 539,105 -> 539,98 -> 539,105 -> 541,105 -> 541,100 -> 541,105 -> 543,105 -> 543,103 -> 543,105 -> 545,105 -> 545,101 -> 545,105 -> 547,105 -> 547,95 -> 547,105 -> 549,105 -> 549,104 -> 549,105 -> 551,105 -> 551,99 -> 551,105 -> 553,105 -> 553,97 -> 553,105 -> 555,105 -> 555,96 -> 555,105 539,105 -> 539,98 -> 539,105 -> 541,105 -> 541,100 -> 541,105 -> 543,105 -> 543,103 -> 543,105 -> 545,105 -> 545,101 -> 545,105 -> 547,105 -> 547,95 -> 547,105 -> 549,105 -> 549,104 -> 549,105 -> 551,105 -> 551,99 -> 551,105 -> 553,105 -> 553,97 -> 553,105 -> 555,105 -> 555,96 -> 555,105 527,147 -> 527,139 -> 527,147 -> 529,147 -> 529,142 -> 529,147 -> 531,147 -> 531,138 -> 531,147 -> 533,147 -> 533,137 -> 533,147 -> 535,147 -> 535,140 -> 535,147 -> 537,147 -> 537,146 -> 537,147 -> 539,147 -> 539,142 -> 539,147 -> 541,147 -> 541,140 -> 541,147 526,86 -> 530,86 548,128 -> 552,128 500,34 -> 500,37 -> 496,37 -> 496,40 -> 506,40 -> 506,37 -> 504,37 -> 504,34 504,19 -> 504,23 -> 503,23 -> 503,31 -> 512,31 -> 512,23 -> 507,23 -> 507,19 503,53 -> 503,50 -> 503,53 -> 505,53 -> 505,51 -> 505,53 -> 507,53 -> 507,52 -> 507,53 -> 509,53 -> 509,50 -> 509,53 523,88 -> 527,88 551,131 -> 555,131 541,122 -> 546,122 536,172 -> 536,168 -> 536,172 -> 538,172 -> 538,164 -> 538,172 -> 540,172 -> 540,168 -> 540,172 -> 542,172 -> 542,163 -> 542,172 -> 544,172 -> 544,164 -> 544,172 -> 546,172 -> 546,171 -> 546,172 -> 548,172 -> 548,165 -> 548,172 -> 550,172 -> 550,170 -> 550,172 -> 552,172 -> 552,170 -> 552,172 539,105 -> 539,98 -> 539,105 -> 541,105 -> 541,100 -> 541,105 -> 543,105 -> 543,103 -> 543,105 -> 545,105 -> 545,101 -> 545,105 -> 547,105 -> 547,95 -> 547,105 -> 549,105 -> 549,104 -> 549,105 -> 551,105 -> 551,99 -> 551,105 -> 553,105 -> 553,97 -> 553,105 -> 555,105 -> 555,96 -> 555,105 536,172 -> 536,168 -> 536,172 -> 538,172 -> 538,164 -> 538,172 -> 540,172 -> 540,168 -> 540,172 -> 542,172 -> 542,163 -> 542,172 -> 544,172 -> 544,164 -> 544,172 -> 546,172 -> 546,171 -> 546,172 -> 548,172 -> 548,165 -> 548,172 -> 550,172 -> 550,170 -> 550,172 -> 552,172 -> 552,170 -> 552,172 503,53 -> 503,50 -> 503,53 -> 505,53 -> 505,51 -> 505,53 -> 507,53 -> 507,52 -> 507,53 -> 509,53 -> 509,50 -> 509,53 517,88 -> 521,88 504,19 -> 504,23 -> 503,23 -> 503,31 -> 512,31 -> 512,23 -> 507,23 -> 507,19 536,172 -> 536,168 -> 536,172 -> 538,172 -> 538,164 -> 538,172 -> 540,172 -> 540,168 -> 540,172 -> 542,172 -> 542,163 -> 542,172 -> 544,172 -> 544,164 -> 544,172 -> 546,172 -> 546,171 -> 546,172 -> 548,172 -> 548,165 -> 548,172 -> 550,172 -> 550,170 -> 550,172 -> 552,172 -> 552,170 -> 552,172 527,147 -> 527,139 -> 527,147 -> 529,147 -> 529,142 -> 529,147 -> 531,147 -> 531,138 -> 531,147 -> 533,147 -> 533,137 -> 533,147 -> 535,147 -> 535,140 -> 535,147 -> 537,147 -> 537,146 -> 537,147 -> 539,147 -> 539,142 -> 539,147 -> 541,147 -> 541,140 -> 541,147 527,147 -> 527,139 -> 527,147 -> 529,147 -> 529,142 -> 529,147 -> 531,147 -> 531,138 -> 531,147 -> 533,147 -> 533,137 -> 533,147 -> 535,147 -> 535,140 -> 535,147 -> 537,147 -> 537,146 -> 537,147 -> 539,147 -> 539,142 -> 539,147 -> 541,147 -> 541,140 -> 541,147 562,122 -> 567,122 539,150 -> 539,152 -> 534,152 -> 534,159 -> 544,159 -> 544,152 -> 543,152 -> 543,150 532,82 -> 536,82 505,58 -> 509,58 539,105 -> 539,98 -> 539,105 -> 541,105 -> 541,100 -> 541,105 -> 543,105 -> 543,103 -> 543,105 -> 545,105 -> 545,101 -> 545,105 -> 547,105 -> 547,95 -> 547,105 -> 549,105 -> 549,104 -> 549,105 -> 551,105 -> 551,99 -> 551,105 -> 553,105 -> 553,97 -> 553,105 -> 555,105 -> 555,96 -> 555,105 536,172 -> 536,168 -> 536,172 -> 538,172 -> 538,164 -> 538,172 -> 540,172 -> 540,168 -> 540,172 -> 542,172 -> 542,163 -> 542,172 -> 544,172 -> 544,164 -> 544,172 -> 546,172 -> 546,171 -> 546,172 -> 548,172 -> 548,165 -> 548,172 -> 550,172 -> 550,170 -> 550,172 -> 552,172 -> 552,170 -> 552,172 502,60 -> 506,60 539,105 -> 539,98 -> 539,105 -> 541,105 -> 541,100 -> 541,105 -> 543,105 -> 543,103 -> 543,105 -> 545,105 -> 545,101 -> 545,105 -> 547,105 -> 547,95 -> 547,105 -> 549,105 -> 549,104 -> 549,105 -> 551,105 -> 551,99 -> 551,105 -> 553,105 -> 553,97 -> 553,105 -> 555,105 -> 555,96 -> 555,105 535,88 -> 539,88 554,134 -> 558,134 539,150 -> 539,152 -> 534,152 -> 534,159 -> 544,159 -> 544,152 -> 543,152 -> 543,150 500,34 -> 500,37 -> 496,37 -> 496,40 -> 506,40 -> 506,37 -> 504,37 -> 504,34 539,105 -> 539,98 -> 539,105 -> 541,105 -> 541,100 -> 541,105 -> 543,105 -> 543,103 -> 543,105 -> 545,105 -> 545,101 -> 545,105 -> 547,105 -> 547,95 -> 547,105 -> 549,105 -> 549,104 -> 549,105 -> 551,105 -> 551,99 -> 551,105 -> 553,105 -> 553,97 -> 553,105 -> 555,105 -> 555,96 -> 555,105 503,53 -> 503,50 -> 503,53 -> 505,53 -> 505,51 -> 505,53 -> 507,53 -> 507,52 -> 507,53 -> 509,53 -> 509,50 -> 509,53 503,53 -> 503,50 -> 503,53 -> 505,53 -> 505,51 -> 505,53 -> 507,53 -> 507,52 -> 507,53 -> 509,53 -> 509,50 -> 509,53 503,53 -> 503,50 -> 503,53 -> 505,53 -> 505,51 -> 505,53 -> 507,53 -> 507,52 -> 507,53 -> 509,53 -> 509,50 -> 509,53 508,56 -> 512,56 540,91 -> 540,92 -> 547,92 -> 547,91 539,105 -> 539,98 -> 539,105 -> 541,105 -> 541,100 -> 541,105 -> 543,105 -> 543,103 -> 543,105 -> 545,105 -> 545,101 -> 545,105 -> 547,105 -> 547,95 -> 547,105 -> 549,105 -> 549,104 -> 549,105 -> 551,105 -> 551,99 -> 551,105 -> 553,105 -> 553,97 -> 553,105 -> 555,105 -> 555,96 -> 555,105 540,91 -> 540,92 -> 547,92 -> 547,91 521,65 -> 521,67 -> 513,67 -> 513,72 -> 526,72 -> 526,67 -> 523,67 -> 523,65 539,105 -> 539,98 -> 539,105 -> 541,105 -> 541,100 -> 541,105 -> 543,105 -> 543,103 -> 543,105 -> 545,105 -> 545,101 -> 545,105 -> 547,105 -> 547,95 -> 547,105 -> 549,105 -> 549,104 -> 549,105 -> 551,105 -> 551,99 -> 551,105 -> 553,105 -> 553,97 -> 553,105 -> 555,105 -> 555,96 -> 555,105 499,62 -> 503,62 536,172 -> 536,168 -> 536,172 -> 538,172 -> 538,164 -> 538,172 -> 540,172 -> 540,168 -> 540,172 -> 542,172 -> 542,163 -> 542,172 -> 544,172 -> 544,164 -> 544,172 -> 546,172 -> 546,171 -> 546,172 -> 548,172 -> 548,165 -> 548,172 -> 550,172 -> 550,170 -> 550,172 -> 552,172 -> 552,170 -> 552,172 536,172 -> 536,168 -> 536,172 -> 538,172 -> 538,164 -> 538,172 -> 540,172 -> 540,168 -> 540,172 -> 542,172 -> 542,163 -> 542,172 -> 544,172 -> 544,164 -> 544,172 -> 546,172 -> 546,171 -> 546,172 -> 548,172 -> 548,165 -> 548,172 -> 550,172 -> 550,170 -> 550,172 -> 552,172 -> 552,170 -> 552,172 536,172 -> 536,168 -> 536,172 -> 538,172 -> 538,164 -> 538,172 -> 540,172 -> 540,168 -> 540,172 -> 542,172 -> 542,163 -> 542,172 -> 544,172 -> 544,164 -> 544,172 -> 546,172 -> 546,171 -> 546,172 -> 548,172 -> 548,165 -> 548,172 -> 550,172 -> 550,170 -> 550,172 -> 552,172 -> 552,170 -> 552,172 548,134 -> 552,134 536,172 -> 536,168 -> 536,172 -> 538,172 -> 538,164 -> 538,172 -> 540,172 -> 540,168 -> 540,172 -> 542,172 -> 542,163 -> 542,172 -> 544,172 -> 544,164 -> 544,172 -> 546,172 -> 546,171 -> 546,172 -> 548,172 -> 548,165 -> 548,172 -> 550,172 -> 550,170 -> 550,172 -> 552,172 -> 552,170 -> 552,172 536,172 -> 536,168 -> 536,172 -> 538,172 -> 538,164 -> 538,172 -> 540,172 -> 540,168 -> 540,172 -> 542,172 -> 542,163 -> 542,172 -> 544,172 -> 544,164 -> 544,172 -> 546,172 -> 546,171 -> 546,172 -> 548,172 -> 548,165 -> 548,172 -> 550,172 -> 550,170 -> 550,172 -> 552,172 -> 552,170 -> 552,172 542,134 -> 546,134 518,76 -> 518,77 -> 530,77 -> 530,76 539,105 -> 539,98 -> 539,105 -> 541,105 -> 541,100 -> 541,105 -> 543,105 -> 543,103 -> 543,105 -> 545,105 -> 545,101 -> 545,105 -> 547,105 -> 547,95 -> 547,105 -> 549,105 -> 549,104 -> 549,105 -> 551,105 -> 551,99 -> 551,105 -> 553,105 -> 553,97 -> 553,105 -> 555,105 -> 555,96 -> 555,105 539,105 -> 539,98 -> 539,105 -> 541,105 -> 541,100 -> 541,105 -> 543,105 -> 543,103 -> 543,105 -> 545,105 -> 545,101 -> 545,105 -> 547,105 -> 547,95 -> 547,105 -> 549,105 -> 549,104 -> 549,105 -> 551,105 -> 551,99 -> 551,105 -> 553,105 -> 553,97 -> 553,105 -> 555,105 -> 555,96 -> 555,105 544,119 -> 549,119 527,147 -> 527,139 -> 527,147 -> 529,147 -> 529,142 -> 529,147 -> 531,147 -> 531,138 -> 531,147 -> 533,147 -> 533,137 -> 533,147 -> 535,147 -> 535,140 -> 535,147 -> 537,147 -> 537,146 -> 537,147 -> 539,147 -> 539,142 -> 539,147 -> 541,147 -> 541,140 -> 541,147 493,15 -> 493,16 -> 504,16 -> 504,15 536,172 -> 536,168 -> 536,172 -> 538,172 -> 538,164 -> 538,172 -> 540,172 -> 540,168 -> 540,172 -> 542,172 -> 542,163 -> 542,172 -> 544,172 -> 544,164 -> 544,172 -> 546,172 -> 546,171 -> 546,172 -> 548,172 -> 548,165 -> 548,172 -> 550,172 -> 550,170 -> 550,172 -> 552,172 -> 552,170 -> 552,172 542,128 -> 546,128 527,147 -> 527,139 -> 527,147 -> 529,147 -> 529,142 -> 529,147 -> 531,147 -> 531,138 -> 531,147 -> 533,147 -> 533,137 -> 533,147 -> 535,147 -> 535,140 -> 535,147 -> 537,147 -> 537,146 -> 537,147 -> 539,147 -> 539,142 -> 539,147 -> 541,147 -> 541,140 -> 541,147 539,105 -> 539,98 -> 539,105 -> 541,105 -> 541,100 -> 541,105 -> 543,105 -> 543,103 -> 543,105 -> 545,105 -> 545,101 -> 545,105 -> 547,105 -> 547,95 -> 547,105 -> 549,105 -> 549,104 -> 549,105 -> 551,105 -> 551,99 -> 551,105 -> 553,105 -> 553,97 -> 553,105 -> 555,105 -> 555,96 -> 555,105 540,91 -> 540,92 -> 547,92 -> 547,91 511,58 -> 515,58 500,34 -> 500,37 -> 496,37 -> 496,40 -> 506,40 -> 506,37 -> 504,37 -> 504,34 527,147 -> 527,139 -> 527,147 -> 529,147 -> 529,142 -> 529,147 -> 531,147 -> 531,138 -> 531,147 -> 533,147 -> 533,137 -> 533,147 -> 535,147 -> 535,140 -> 535,147 -> 537,147 -> 537,146 -> 537,147 -> 539,147 -> 539,142 -> 539,147 -> 541,147 -> 541,140 -> 541,147 527,147 -> 527,139 -> 527,147 -> 529,147 -> 529,142 -> 529,147 -> 531,147 -> 531,138 -> 531,147 -> 533,147 -> 533,137 -> 533,147 -> 535,147 -> 535,140 -> 535,147 -> 537,147 -> 537,146 -> 537,147 -> 539,147 -> 539,142 -> 539,147 -> 541,147 -> 541,140 -> 541,147 538,86 -> 542,86 521,65 -> 521,67 -> 513,67 -> 513,72 -> 526,72 -> 526,67 -> 523,67 -> 523,65 539,105 -> 539,98 -> 539,105 -> 541,105 -> 541,100 -> 541,105 -> 543,105 -> 543,103 -> 543,105 -> 545,105 -> 545,101 -> 545,105 -> 547,105 -> 547,95 -> 547,105 -> 549,105 -> 549,104 -> 549,105 -> 551,105 -> 551,99 -> 551,105 -> 553,105 -> 553,97 -> 553,105 -> 555,105 -> 555,96 -> 555,105 539,105 -> 539,98 -> 539,105 -> 541,105 -> 541,100 -> 541,105 -> 543,105 -> 543,103 -> 543,105 -> 545,105 -> 545,101 -> 545,105 -> 547,105 -> 547,95 -> 547,105 -> 549,105 -> 549,104 -> 549,105 -> 551,105 -> 551,99 -> 551,105 -> 553,105 -> 553,97 -> 553,105 -> 555,105 -> 555,96 -> 555,105 536,172 -> 536,168 -> 536,172 -> 538,172 -> 538,164 -> 538,172 -> 540,172 -> 540,168 -> 540,172 -> 542,172 -> 542,163 -> 542,172 -> 544,172 -> 544,164 -> 544,172 -> 546,172 -> 546,171 -> 546,172 -> 548,172 -> 548,165 -> 548,172 -> 550,172 -> 550,170 -> 550,172 -> 552,172 -> 552,170 -> 552,172 504,19 -> 504,23 -> 503,23 -> 503,31 -> 512,31 -> 512,23 -> 507,23 -> 507,19 536,172 -> 536,168 -> 536,172 -> 538,172 -> 538,164 -> 538,172 -> 540,172 -> 540,168 -> 540,172 -> 542,172 -> 542,163 -> 542,172 -> 544,172 -> 544,164 -> 544,172 -> 546,172 -> 546,171 -> 546,172 -> 548,172 -> 548,165 -> 548,172 -> 550,172 -> 550,170 -> 550,172 -> 552,172 -> 552,170 -> 552,172 527,147 -> 527,139 -> 527,147 -> 529,147 -> 529,142 -> 529,147 -> 531,147 -> 531,138 -> 531,147 -> 533,147 -> 533,137 -> 533,147 -> 535,147 -> 535,140 -> 535,147 -> 537,147 -> 537,146 -> 537,147 -> 539,147 -> 539,142 -> 539,147 -> 541,147 -> 541,140 -> 541,147 539,105 -> 539,98 -> 539,105 -> 541,105 -> 541,100 -> 541,105 -> 543,105 -> 543,103 -> 543,105 -> 545,105 -> 545,101 -> 545,105 -> 547,105 -> 547,95 -> 547,105 -> 549,105 -> 549,104 -> 549,105 -> 551,105 -> 551,99 -> 551,105 -> 553,105 -> 553,97 -> 553,105 -> 555,105 -> 555,96 -> 555,105 508,60 -> 512,60 517,62 -> 521,62 536,172 -> 536,168 -> 536,172 -> 538,172 -> 538,164 -> 538,172 -> 540,172 -> 540,168 -> 540,172 -> 542,172 -> 542,163 -> 542,172 -> 544,172 -> 544,164 -> 544,172 -> 546,172 -> 546,171 -> 546,172 -> 548,172 -> 548,165 -> 548,172 -> 550,172 -> 550,170 -> 550,172 -> 552,172 -> 552,170 -> 552,172 518,76 -> 518,77 -> 530,77 -> 530,76 539,105 -> 539,98 -> 539,105 -> 541,105 -> 541,100 -> 541,105 -> 543,105 -> 543,103 -> 543,105 -> 545,105 -> 545,101 -> 545,105 -> 547,105 -> 547,95 -> 547,105 -> 549,105 -> 549,104 -> 549,105 -> 551,105 -> 551,99 -> 551,105 -> 553,105 -> 553,97 -> 553,105 -> 555,105 -> 555,96 -> 555,105 539,105 -> 539,98 -> 539,105 -> 541,105 -> 541,100 -> 541,105 -> 543,105 -> 543,103 -> 543,105 -> 545,105 -> 545,101 -> 545,105 -> 547,105 -> 547,95 -> 547,105 -> 549,105 -> 549,104 -> 549,105 -> 551,105 -> 551,99 -> 551,105 -> 553,105 -> 553,97 -> 553,105 -> 555,105 -> 555,96 -> 555,105 493,15 -> 493,16 -> 504,16 -> 504,15 536,172 -> 536,168 -> 536,172 -> 538,172 -> 538,164 -> 538,172 -> 540,172 -> 540,168 -> 540,172 -> 542,172 -> 542,163 -> 542,172 -> 544,172 -> 544,164 -> 544,172 -> 546,172 -> 546,171 -> 546,172 -> 548,172 -> 548,165 -> 548,172 -> 550,172 -> 550,170 -> 550,172 -> 552,172 -> 552,170 -> 552,172 521,65 -> 521,67 -> 513,67 -> 513,72 -> 526,72 -> 526,67 -> 523,67 -> 523,65 536,172 -> 536,168 -> 536,172 -> 538,172 -> 538,164 -> 538,172 -> 540,172 -> 540,168 -> 540,172 -> 542,172 -> 542,163 -> 542,172 -> 544,172 -> 544,164 -> 544,172 -> 546,172 -> 546,171 -> 546,172 -> 548,172 -> 548,165 -> 548,172 -> 550,172 -> 550,170 -> 550,172 -> 552,172 -> 552,170 -> 552,172 527,147 -> 527,139 -> 527,147 -> 529,147 -> 529,142 -> 529,147 -> 531,147 -> 531,138 -> 531,147 -> 533,147 -> 533,137 -> 533,147 -> 535,147 -> 535,140 -> 535,147 -> 537,147 -> 537,146 -> 537,147 -> 539,147 -> 539,142 -> 539,147 -> 541,147 -> 541,140 -> 541,147 539,105 -> 539,98 -> 539,105 -> 541,105 -> 541,100 -> 541,105 -> 543,105 -> 543,103 -> 543,105 -> 545,105 -> 545,101 -> 545,105 -> 547,105 -> 547,95 -> 547,105 -> 549,105 -> 549,104 -> 549,105 -> 551,105 -> 551,99 -> 551,105 -> 553,105 -> 553,97 -> 553,105 -> 555,105 -> 555,96 -> 555,105 503,53 -> 503,50 -> 503,53 -> 505,53 -> 505,51 -> 505,53 -> 507,53 -> 507,52 -> 507,53 -> 509,53 -> 509,50 -> 509,53 539,105 -> 539,98 -> 539,105 -> 541,105 -> 541,100 -> 541,105 -> 543,105 -> 543,103 -> 543,105 -> 545,105 -> 545,101 -> 545,105 -> 547,105 -> 547,95 -> 547,105 -> 549,105 -> 549,104 -> 549,105 -> 551,105 -> 551,99 -> 551,105 -> 553,105 -> 553,97 -> 553,105 -> 555,105 -> 555,96 -> 555,105 547,116 -> 552,116 504,19 -> 504,23 -> 503,23 -> 503,31 -> 512,31 -> 512,23 -> 507,23 -> 507,19 539,150 -> 539,152 -> 534,152 -> 534,159 -> 544,159 -> 544,152 -> 543,152 -> 543,150 539,105 -> 539,98 -> 539,105 -> 541,105 -> 541,100 -> 541,105 -> 543,105 -> 543,103 -> 543,105 -> 545,105 -> 545,101 -> 545,105 -> 547,105 -> 547,95 -> 547,105 -> 549,105 -> 549,104 -> 549,105 -> 551,105 -> 551,99 -> 551,105 -> 553,105 -> 553,97 -> 553,105 -> 555,105 -> 555,96 -> 555,105 504,19 -> 504,23 -> 503,23 -> 503,31 -> 512,31 -> 512,23 -> 507,23 -> 507,19 527,147 -> 527,139 -> 527,147 -> 529,147 -> 529,142 -> 529,147 -> 531,147 -> 531,138 -> 531,147 -> 533,147 -> 533,137 -> 533,147 -> 535,147 -> 535,140 -> 535,147 -> 537,147 -> 537,146 -> 537,147 -> 539,147 -> 539,142 -> 539,147 -> 541,147 -> 541,140 -> 541,147 527,147 -> 527,139 -> 527,147 -> 529,147 -> 529,142 -> 529,147 -> 531,147 -> 531,138 -> 531,147 -> 533,147 -> 533,137 -> 533,147 -> 535,147 -> 535,140 -> 535,147 -> 537,147 -> 537,146 -> 537,147 -> 539,147 -> 539,142 -> 539,147 -> 541,147 -> 541,140 -> 541,147 539,105 -> 539,98 -> 539,105 -> 541,105 -> 541,100 -> 541,105 -> 543,105 -> 543,103 -> 543,105 -> 545,105 -> 545,101 -> 545,105 -> 547,105 -> 547,95 -> 547,105 -> 549,105 -> 549,104 -> 549,105 -> 551,105 -> 551,99 -> 551,105 -> 553,105 -> 553,97 -> 553,105 -> 555,105 -> 555,96 -> 555,105 536,172 -> 536,168 -> 536,172 -> 538,172 -> 538,164 -> 538,172 -> 540,172 -> 540,168 -> 540,172 -> 542,172 -> 542,163 -> 542,172 -> 544,172 -> 544,164 -> 544,172 -> 546,172 -> 546,171 -> 546,172 -> 548,172 -> 548,165 -> 548,172 -> 550,172 -> 550,170 -> 550,172 -> 552,172 -> 552,170 -> 552,172 536,172 -> 536,168 -> 536,172 -> 538,172 -> 538,164 -> 538,172 -> 540,172 -> 540,168 -> 540,172 -> 542,172 -> 542,163 -> 542,172 -> 544,172 -> 544,164 -> 544,172 -> 546,172 -> 546,171 -> 546,172 -> 548,172 -> 548,165 -> 548,172 -> 550,172 -> 550,170 -> 550,172 -> 552,172 -> 552,170 -> 552,172 521,65 -> 521,67 -> 513,67 -> 513,72 -> 526,72 -> 526,67 -> 523,67 -> 523,65 518,76 -> 518,77 -> 530,77 -> 530,76 503,53 -> 503,50 -> 503,53 -> 505,53 -> 505,51 -> 505,53 -> 507,53 -> 507,52 -> 507,53 -> 509,53 -> 509,50 -> 509,53 541,88 -> 545,88 504,19 -> 504,23 -> 503,23 -> 503,31 -> 512,31 -> 512,23 -> 507,23 -> 507,19 536,172 -> 536,168 -> 536,172 -> 538,172 -> 538,164 -> 538,172 -> 540,172 -> 540,168 -> 540,172 -> 542,172 -> 542,163 -> 542,172 -> 544,172 -> 544,164 -> 544,172 -> 546,172 -> 546,171 -> 546,172 -> 548,172 -> 548,165 -> 548,172 -> 550,172 -> 550,170 -> 550,172 -> 552,172 -> 552,170 -> 552,172 555,122 -> 560,122 521,65 -> 521,67 -> 513,67 -> 513,72 -> 526,72 -> 526,67 -> 523,67 -> 523,65 527,147 -> 527,139 -> 527,147 -> 529,147 -> 529,142 -> 529,147 -> 531,147 -> 531,138 -> 531,147 -> 533,147 -> 533,137 -> 533,147 -> 535,147 -> 535,140 -> 535,147 -> 537,147 -> 537,146 -> 537,147 -> 539,147 -> 539,142 -> 539,147 -> 541,147 -> 541,140 -> 541,147 532,86 -> 536,86 539,150 -> 539,152 -> 534,152 -> 534,159 -> 544,159 -> 544,152 -> 543,152 -> 543,150 536,172 -> 536,168 -> 536,172 -> 538,172 -> 538,164 -> 538,172 -> 540,172 -> 540,168 -> 540,172 -> 542,172 -> 542,163 -> 542,172 -> 544,172 -> 544,164 -> 544,172 -> 546,172 -> 546,171 -> 546,172 -> 548,172 -> 548,165 -> 548,172 -> 550,172 -> 550,170 -> 550,172 -> 552,172 -> 552,170 -> 552,172 536,172 -> 536,168 -> 536,172 -> 538,172 -> 538,164 -> 538,172 -> 540,172 -> 540,168 -> 540,172 -> 542,172 -> 542,163 -> 542,172 -> 544,172 -> 544,164 -> 544,172 -> 546,172 -> 546,171 -> 546,172 -> 548,172 -> 548,165 -> 548,172 -> 550,172 -> 550,170 -> 550,172 -> 552,172 -> 552,170 -> 552,172 539,150 -> 539,152 -> 534,152 -> 534,159 -> 544,159 -> 544,152 -> 543,152 -> 543,150 550,113 -> 555,113 554,116 -> 559,116 521,65 -> 521,67 -> 513,67 -> 513,72 -> 526,72 -> 526,67 -> 523,67 -> 523,65 527,147 -> 527,139 -> 527,147 -> 529,147 -> 529,142 -> 529,147 -> 531,147 -> 531,138 -> 531,147 -> 533,147 -> 533,137 -> 533,147 -> 535,147 -> 535,140 -> 535,147 -> 537,147 -> 537,146 -> 537,147 -> 539,147 -> 539,142 -> 539,147 -> 541,147 -> 541,140 -> 541,147 514,60 -> 518,60 539,105 -> 539,98 -> 539,105 -> 541,105 -> 541,100 -> 541,105 -> 543,105 -> 543,103 -> 543,105 -> 545,105 -> 545,101 -> 545,105 -> 547,105 -> 547,95 -> 547,105 -> 549,105 -> 549,104 -> 549,105 -> 551,105 -> 551,99 -> 551,105 -> 553,105 -> 553,97 -> 553,105 -> 555,105 -> 555,96 -> 555,105 535,84 -> 539,84 521,65 -> 521,67 -> 513,67 -> 513,72 -> 526,72 -> 526,67 -> 523,67 -> 523,65 511,62 -> 515,62 503,53 -> 503,50 -> 503,53 -> 505,53 -> 505,51 -> 505,53 -> 507,53 -> 507,52 -> 507,53 -> 509,53 -> 509,50 -> 509,53 536,172 -> 536,168 -> 536,172 -> 538,172 -> 538,164 -> 538,172 -> 540,172 -> 540,168 -> 540,172 -> 542,172 -> 542,163 -> 542,172 -> 544,172 -> 544,164 -> 544,172 -> 546,172 -> 546,171 -> 546,172 -> 548,172 -> 548,165 -> 548,172 -> 550,172 -> 550,170 -> 550,172 -> 552,172 -> 552,170 -> 552,172 539,105 -> 539,98 -> 539,105 -> 541,105 -> 541,100 -> 541,105 -> 543,105 -> 543,103 -> 543,105 -> 545,105 -> 545,101 -> 545,105 -> 547,105 -> 547,95 -> 547,105 -> 549,105 -> 549,104 -> 549,105 -> 551,105 -> 551,99 -> 551,105 -> 553,105 -> 553,97 -> 553,105 -> 555,105 -> 555,96 -> 555,105 527,147 -> 527,139 -> 527,147 -> 529,147 -> 529,142 -> 529,147 -> 531,147 -> 531,138 -> 531,147 -> 533,147 -> 533,137 -> 533,147 -> 535,147 -> 535,140 -> 535,147 -> 537,147 -> 537,146 -> 537,147 -> 539,147 -> 539,142 -> 539,147 -> 541,147 -> 541,140 -> 541,147 529,80 -> 533,80 545,131 -> 549,131 503,53 -> 503,50 -> 503,53 -> 505,53 -> 505,51 -> 505,53 -> 507,53 -> 507,52 -> 507,53 -> 509,53 -> 509,50 -> 509,53 527,147 -> 527,139 -> 527,147 -> 529,147 -> 529,142 -> 529,147 -> 531,147 -> 531,138 -> 531,147 -> 533,147 -> 533,137 -> 533,147 -> 535,147 -> 535,140 -> 535,147 -> 537,147 -> 537,146 -> 537,147 -> 539,147 -> 539,142 -> 539,147 -> 541,147 -> 541,140 -> 541,147 504,19 -> 504,23 -> 503,23 -> 503,31 -> 512,31 -> 512,23 -> 507,23 -> 507,19 539,150 -> 539,152 -> 534,152 -> 534,159 -> 544,159 -> 544,152 -> 543,152 -> 543,150 536,172 -> 536,168 -> 536,172 -> 538,172 -> 538,164 -> 538,172 -> 540,172 -> 540,168 -> 540,172 -> 542,172 -> 542,163 -> 542,172 -> 544,172 -> 544,164 -> 544,172 -> 546,172 -> 546,171 -> 546,172 -> 548,172 -> 548,165 -> 548,172 -> 550,172 -> 550,170 -> 550,172 -> 552,172 -> 552,170 -> 552,172 554,110 -> 563,110 539,105 -> 539,98 -> 539,105 -> 541,105 -> 541,100 -> 541,105 -> 543,105 -> 543,103 -> 543,105 -> 545,105 -> 545,101 -> 545,105 -> 547,105 -> 547,95 -> 547,105 -> 549,105 -> 549,104 -> 549,105 -> 551,105 -> 551,99 -> 551,105 -> 553,105 -> 553,97 -> 553,105 -> 555,105 -> 555,96 -> 555,105 493,15 -> 493,16 -> 504,16 -> 504,15 529,88 -> 533,88 527,147 -> 527,139 -> 527,147 -> 529,147 -> 529,142 -> 529,147 -> 531,147 -> 531,138 -> 531,147 -> 533,147 -> 533,137 -> 533,147 -> 535,147 -> 535,140 -> 535,147 -> 537,147 -> 537,146 -> 537,147 -> 539,147 -> 539,142 -> 539,147 -> 541,147 -> 541,140 -> 541,147 536,134 -> 540,134 500,34 -> 500,37 -> 496,37 -> 496,40 -> 506,40 -> 506,37 -> 504,37 -> 504,34 520,86 -> 524,86"""
0
Kotlin
0
0
8230fce9a907343f11a2c042ebe0bf204775be3f
28,910
advent-of-code-2022
MIT License