path
stringlengths
5
169
owner
stringlengths
2
34
repo_id
int64
1.49M
755M
is_fork
bool
2 classes
languages_distribution
stringlengths
16
1.68k
content
stringlengths
446
72k
issues
float64
0
1.84k
main_language
stringclasses
37 values
forks
int64
0
5.77k
stars
int64
0
46.8k
commit_sha
stringlengths
40
40
size
int64
446
72.6k
name
stringlengths
2
64
license
stringclasses
15 values
src/main/kotlin/dev/shtanko/algorithms/leetcode/RangeSum.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2023 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import dev.shtanko.algorithms.MOD import kotlin.math.max /** * 1508. Range Sum of Sorted Subarray Sums * @see <a href="https://leetcode.com/problems/range-sum-of-sorted-subarray-sums/">Source</a> */ fun interface RangeSum { operator fun invoke(nums: IntArray, n: Int, left: Int, right: Int): Int } class RangeSumPrefixSum : RangeSum { override operator fun invoke(nums: IntArray, n: Int, left: Int, right: Int): Int { var res: Long = 0 var sum: Long = 0 val sums: MutableList<Long> = ArrayList() val pSum: MutableList<Long> = ArrayList() // sums - all sums of subarrays, pSum - prefix sums; var l = left pSum.add(0L) for (i in 0 until n) { sum += nums[i] pSum.add(sum) for (j in 0 until pSum.size - 1) sums.add(sum - pSum[j]) } sums.sort() while (l <= right) res = (res + sums[l++ - 1]) % MOD return res.toInt() } } class RangeSumBinarySearch : RangeSum { override operator fun invoke(nums: IntArray, n: Int, left: Int, right: Int): Int { val maxLeft = findMax(nums, left) val maxRight = findMax(nums, right) val rangeSumLeft = rangeSum(nums, maxLeft) val rangeSumRight = rangeSum(nums, maxRight) var ans = Math.floorMod(rangeSumRight[0] + (right - rangeSumRight[1]) * (maxRight + 1), MOD) ans = Math.floorMod(ans - (rangeSumLeft[0] + (left - rangeSumLeft[1] - 1) * (maxLeft + 1)), MOD) return ans } private fun findMax(nums: IntArray, cnt: Int): Int { var lo = 0 var hi = 0 for (v in nums) hi += v while (lo < hi) { val mid = lo + (hi - lo + 1) / 2 val sum = rangeSum(nums, mid) if (sum[1] >= cnt) { hi = mid - 1 } else { lo = mid } } return lo } // sum of various rangesums, including only those rangesum that are below max private fun rangeSum(nums: IntArray, max: Int): IntArray { var rangeSum = 0 var rangeCnt = 0 var lo = 0 var hi = 0 val n = nums.size var sum = 0 var sumsum = 0 while (lo < n) { while (hi < n && sum + nums[hi] <= max) { sum += nums[hi] sumsum = (sumsum + sum) % MOD ++hi } rangeSum = (rangeSum + sumsum) % MOD if (hi > lo) { sum -= nums[lo] sumsum = (sumsum - (hi - lo) * nums[lo] + MOD) % MOD rangeCnt += hi - lo } ++lo hi = max(hi, lo) } return intArrayOf(rangeSum, rangeCnt) } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
3,378
kotlab
Apache License 2.0
src/Day04.kt
mzlnk
573,124,510
false
{"Kotlin": 14876}
fun main() { fun part1(input: List<String>): Int { var pairs = 0 for (line: String in input) { val rawData = line.split(',').flatMap { it.split('-') }.map { it.toInt() } val firstPair = Pair(rawData[0], rawData[1]) val secondPair = Pair(rawData[2], rawData[3]) val isFirstPairOverlapping = firstPair.first <= secondPair.first && firstPair.second >= secondPair.second val isSecondPairOverlapping = secondPair.first <= firstPair.first && secondPair.second >= firstPair.second val isOverlapping = isFirstPairOverlapping || isSecondPairOverlapping if(isOverlapping) { pairs++ } } return pairs } fun part2(input: List<String>): Int { var pairs = 0 for(line: String in input) { val rawData = line.split(',').flatMap { it.split('-') }.map { it.toInt() } val firstPair = Pair(rawData[0], rawData[1]) val secondPair = Pair(rawData[2], rawData[3]) if(!(firstPair.second < secondPair.first || secondPair.second < firstPair.first)) { pairs++ } } return pairs } // test if implementation meets criteria from the description, like: val testInput = readInput("Day04_test") check(part1(testInput) == 2) check(part2(testInput) == 4) val input = readInput("Day04") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
3a8ec82e9a8b4640e33fdd801b1ef87a06fa5cd5
1,497
advent-of-code-2022
Apache License 2.0
src/com/kingsleyadio/adventofcode/y2021/day18/Solution.kt
kingsleyadio
435,430,807
false
{"Kotlin": 134666, "JavaScript": 5423}
package com.kingsleyadio.adventofcode.y2021.day18 import com.kingsleyadio.adventofcode.util.readInput fun part1(input: List<String>): Int { return input.map(::parseMath).reduce { acc, math -> acc + math }.score() } fun part2(input: List<String>): Int { return sequence { for (i in input.indices) for (j in input.indices) { if (i != j) { // Parsing on-demand since DS is mutable, which makes reuse impossible val left = parseMath(input[i]) val right = parseMath(input[j]) yield((left + right).score()) } } }.maxOrNull()!! } fun main() { val input = readInput(2021, 18).readLines() println(part1(input)) println(part2(input)) } fun parseMath(input: String): SnailMath { fun parse(reader: StringReader): SnailMath { return when (val char = reader.read(1)) { "[" -> { val left = parse(reader) reader.read(1) val right = parse(reader) reader.read(1) SnailMath.Pair(left, right) } else -> SnailMath.Literal(char.toInt()) } } return parse(StringReader(input)) } class StringReader(private val string: String) { private var index = 0 fun read(size: Int): String { val result = string.substring(index, index + size) index += size return result } } fun explode(math: SnailMath, depth: Int): Diff { if (math !is SnailMath.Pair) return Diff(0, 0) val (left, right) = math if (depth == 5 && left is SnailMath.Literal && right is SnailMath.Literal) { return Diff(left.value, right.value) } // Left val diffL = explode(left, depth + 1) if (depth + 1 == 5 && math.left is SnailMath.Pair) math.left = SnailMath.Literal(0) math.right.addLeft(diffL.right) // Right val diffR = explode(right, depth + 1) if (depth + 1 == 5 && math.right is SnailMath.Pair) math.right = SnailMath.Literal(0) math.left.addRight(diffR.left) return Diff(diffL.left, diffR.right) } fun split(math: SnailMath) { var split = false // To ensure we only split 1 fun splitToPair(value: Int): SnailMath.Pair { split = true val low = value / 2 val high = value - low return SnailMath.Pair(SnailMath.Literal(low), SnailMath.Literal(high)) } fun split(math: SnailMath) { if (split || math !is SnailMath.Pair) return val (left, right) = math if (left is SnailMath.Literal && left.value > 9) math.left = splitToPair(left.value) else split(left) if (split) return if (right is SnailMath.Literal && right.value > 9) math.right = splitToPair(right.value) else split(right) } split(math) } operator fun SnailMath.plus(other: SnailMath): SnailMath { return SnailMath.Pair(this, other).also { pair -> while (true) { val score = pair.toString() explode(pair, 1) split(pair) if (score == pair.toString()) break } } } sealed interface SnailMath { fun addLeft(value: Int) fun addRight(value: Int) fun score(): Int class Literal(var value: Int) : SnailMath { override fun addLeft(value: Int) = run { this.value += value } override fun addRight(value: Int) = run { this.value += value } override fun score() = value override fun toString() = value.toString() } data class Pair(var left: SnailMath, var right: SnailMath) : SnailMath { override fun addLeft(value: Int) = left.addLeft(value) override fun addRight(value: Int) = right.addRight(value) override fun score() = 3 * left.score() + 2 * right.score() override fun toString() = "[$left,$right]" } } data class Diff(val left: Int, val right: Int)
0
Kotlin
0
1
9abda490a7b4e3d9e6113a0d99d4695fcfb36422
3,879
adventofcode
Apache License 2.0
src/y2022/Day07.kt
a3nv
574,208,224
false
{"Kotlin": 34115, "Java": 1914}
package y2022 import utils.readInput import java.util.function.Predicate fun main() { fun parse(input: List<String>): Folder { val rootFolderName = input.first().split(" ")[2] var currentFolder = Folder(rootFolderName) val rootFolder = currentFolder input.drop(1).forEach { when { isBack(it) -> { currentFolder = currentFolder.parent!! } isCd(it) -> { val currentFolderName = it.split(" ")[2] val folder = currentFolder.subFolders.first { sub -> sub.name == currentFolderName } currentFolder = folder } isDir(it) -> { val folderName = it.split(" ")[1] val f = Folder(folderName) f.parent = currentFolder currentFolder.subFolders.add(f) } isFile(it) -> { val size = it.split(" ")[0].toInt() fun add(current: Folder?, size: Int) { if (current != null) { current.size += size add(current.parent, size) } } add(currentFolder, size) } } } return rootFolder } fun count(root: Folder, predicate: Predicate<Folder>): List<Int> { val q = mutableListOf<Folder>() val result = mutableListOf<Int>() q.add(root) while (q.isNotEmpty()) { val candidate = q.removeFirst() if (predicate.test(candidate)) { result.add(candidate.size) } q.addAll(candidate.subFolders) } return result } fun part1(input: List<String>): Int { val rootFolder = parse(input) return count(rootFolder) { it: Folder -> it.size <= 100000 }.sum() } fun part2(input: List<String>): Int { val rootFolder = parse(input) val required = 30000000 - (70000000 - rootFolder.size) return count(rootFolder) { it: Folder -> it.size >= required }.min() } // test if implementation meets criteria from the description, like: val testInput = readInput("y2022", "Day07_test") println(part1(testInput)) check(part1(testInput) == 95437) println(part2(testInput)) check(part2(testInput) == 24933642) val input = readInput("y2022", "Day07") println(part1(input)) check(part1(input) == 2031851) println(part2(input)) check(part2(input) == 2568781) } fun isFile(line: String): Boolean { return line[0].isDigit() } fun isCd(line: String): Boolean { return line.startsWith("\$ cd") } fun isBack(line: String): Boolean { return line == "\$ cd .." } fun isDir(line: String): Boolean { return line.startsWith("dir") } class Folder( var name: String, var parent: Folder? = null, var subFolders: MutableList<Folder> = mutableListOf(), var size: Int = 0 )
0
Kotlin
0
0
ab2206ab5030ace967e08c7051becb4ae44aea39
3,101
advent-of-code-kotlin
Apache License 2.0
src/day02/Day02.kt
Xlebo
572,928,568
false
{"Kotlin": 10125}
package day02 import getOrFetchInputData import readInput import kotlin.math.abs fun main() { val enemyInput = mapOf('A' to 1, 'B' to 2, 'C' to 3) val playerInput = mapOf('X' to 1, 'Y' to 2, 'Z' to 3) val incrementBasedOnResult = mapOf('X' to -1, 'Y' to 0, 'Z' to 1) fun determinePlayerInput(enemy: Char, result: Char): Int { var playerScore = enemyInput[enemy]!! + incrementBasedOnResult[result]!! playerScore = playerScore.mod(3) return if (playerScore == 0) { 3 } else { playerScore } } fun calculateScore(enemy: Char, player: Char): Int { val selectionScore = playerInput[player]!! var score = selectionScore - enemyInput[enemy]!! if (abs(score) > 1) score /= -2 return (score + 1) * 3 + selectionScore } fun part1(input: List<String>): Int { return input .map { it .split(" ") .map { play -> play[0] } }.sumOf { calculateScore(it[0], it[1]) } } fun part2(input: List<String>): Int { return input .map { it .split(" ") .map { play -> play[0] } } .sumOf { determinePlayerInput(it[0], it[1]) + (incrementBasedOnResult[it[1]]!! + 1) * 3 } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day02_test", "day02") val result1 = part1(testInput) val result2 = part2(testInput) check(result1 == 15) { "Got: $result1" } check(result2 == 12) { "Got: $result2" } val input = getOrFetchInputData(2) println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
cd718c2c7cb59528080d2aef599bd93e0919d2d9
1,772
aoc2022
Apache License 2.0
src/main/kotlin/adventofcode2023/day13/day13_2.kt
dzkoirn
725,682,258
false
{"Kotlin": 133478}
package adventofcode2023.day13 import adventofcode2023.readInput import kotlin.math.min import kotlin.time.measureTime fun main() { println("Day 13") val input = readInput("day13") val puzzle2Duration = measureTime { println("Puzzle 2 ${puzzle2(input)}") } println("Puzzle 2 took $puzzle2Duration") } fun mutateInput(input: List<String>): List<List<String>> { return buildList { input.subList(0, input.lastIndex).forEachIndexed { index, s1 -> input.subList(index + 1, input.size).forEachIndexed { index2, s2 -> var difference = 1 var diffI = 0 for ((i, c) in s1.withIndex()) { if (s2[i] != c) { diffI = i difference-- } if (difference < 0) { break } } if (difference == 0) { fun Char.change() = if (this == '#') { '.' } else { '#' } add(with(input.toMutableList()) { set(index, String(s1.toCharArray().let { arr -> arr.also { it[diffI] = it[diffI].change() } })) toList() }) add(with(input.toMutableList()) { set(index2 + index + 1, String(s2.toCharArray().let { arr -> arr.also { it[diffI] = it[diffI].change() } })) toList() }) } } } } // .also { // println( // "Mutated candidates:\n${ // it.joinToString("\n\n") { l -> l.asString() } // }") // } } fun findIndex2(input: List<String>): Set<Int> { val candidates = input.windowed(2).mapIndexedNotNull { index, (a, b) -> // println("findIndex: $index, $a, $b, ${a == b}") if (a == b) { if (index > 0) { val range = min(index, (input.lastIndex - (index + 1))) val isReflection = (0..range).all { i -> // println("all $range, $index, $i, ${input[index - i]}, ${input[index + 1 + i]}, ${input[index - i] == input[index + 1 + i]}") input[index - i] == input[index + 1 + i] } // println("isReflection = $isReflection, $index, $a, $b") if (isReflection) { println("isReflection = $isReflection, $index, $a, $b") return@mapIndexedNotNull index + 1 } } else { println("isReflection = true, $index, $a, $b") return@mapIndexedNotNull index + 1 } } null } return candidates.toSet() // .also { // println("Reflections: $it") // } } fun rotateInput(input: List<String>): List<String> { return buildList { input.first.indices.forEach { i -> add(buildString { input.forEach { l -> append(l[i]) } }) } } // .also { newInput -> // println("Rotated Input:\n${newInput.joinToString(separator = "\n") { it }}") // } } fun findReflection2(input: List<String>): Int { val original = buildSet { findIndex2(input).forEach { add(it * 100) } findIndex2(rotateInput(input)).forEach { add(it) } } val calculated = buildSet { mutateInput(input).forEach { newInput -> findIndex2(newInput).forEach { add(it * 100) } findIndex2(rotateInput(newInput)).forEach { add(it) } } mutateInput(rotateInput(input)).forEach { newInput -> val newInputRotated = rotateInput(newInput) findIndex2(newInputRotated).forEach { add(it * 100) } findIndex2(rotateInput(newInputRotated)).forEach { add(it) } } } return (calculated - original).sum() } fun List<String>.asString(): String { return this.mapIndexed { index, s -> String.format("%02d %s", index, s) }.joinToString("\n") { it } } fun puzzle2(source: List<String>): Int = parseInput(source).sumOf { input -> findReflection2(input).also { println("Input:\n${input.asString()}\nResult:$it") } }
0
Kotlin
0
0
8f248fcdcd84176ab0875969822b3f2b02d8dea6
4,632
adventofcode2023
MIT License
src/Day05.kt
shepard8
573,449,602
false
{"Kotlin": 73637}
data class Move(val count: Int, val fromStack: Int, val toStack: Int) val stacks = listOf( listOf(), listOf('D', 'H', 'R', 'Z', 'S', 'P', 'W', 'Q'), listOf('F', 'H', 'Q', 'W', 'R', 'B', 'V'), listOf('H', 'S', 'V', 'C'), listOf('G', 'F', 'H'), listOf('Z', 'B', 'J', 'G', 'P'), listOf('L', 'F', 'W', 'H', 'J', 'T', 'Q'), listOf('N', 'J', 'V', 'L', 'D', 'W', 'T', 'Z'), listOf('F', 'H', 'G', 'J', 'C', 'Z', 'T', 'D'), listOf('H', 'B', 'M', 'V', 'P', 'W'), ) fun main() { fun part1(moves: List<Move>): String { val stacks = stacks.toMutableList() moves.forEach { move -> val items = stacks[move.fromStack].take(move.count) stacks[move.fromStack] = stacks[move.fromStack].drop(move.count) stacks[move.toStack] = items.reversed() + stacks[move.toStack] } return stacks.drop(1).map { it.first() }.joinToString("") } fun part2(moves: List<Move>): String { val stacks = stacks.toMutableList() moves.forEach { move -> val items = stacks[move.fromStack].take(move.count) stacks[move.fromStack] = stacks[move.fromStack].drop(move.count) stacks[move.toStack] = items + stacks[move.toStack] } return stacks.drop(1).map { it.first() }.joinToString("") } val input = readInput("Day05").drop(10) val moves = sequence { input.forEach { line -> val ints = line.split(" ") yield(Move(ints[1].toInt(), ints[3].toInt(), ints[5].toInt())) } }.toList() println(part1(moves)) println(part2(moves)) }
0
Kotlin
0
1
81382d722718efcffdda9b76df1a4ea4e1491b3c
1,632
aoc2022-kotlin
Apache License 2.0
src/main/kotlin/d2/d2.kt
LaurentJeanpierre1
573,454,829
false
{"Kotlin": 118105}
package d2 import readInput data class Res( val ABC : Char, val XYZ: Char) fun part1(input: List<String>): Int { var score = 0 val rules = mapOf( Res('A', 'X') to 3, Res('B', 'X') to 0, Res('C', 'X') to 6, Res('A', 'Y') to 6, Res('B', 'Y') to 3, Res('C', 'Y') to 0, Res('A', 'Z') to 0, Res('B', 'Z') to 6, Res('C', 'Z') to 3, ) val value = mapOf( 'X' to 1, 'Y' to 2, 'Z' to 3) for(line in input) { if (line.isNotBlank()) { val match = rules.get(Res(line[0], line[2])) ?: -99999 val bet = value.get(line[2]) ?: -99999 score += match + bet } } return score } fun part2(input: List<String>): Int { var score = 0 val rules = mapOf( Res('A', 'X') to 3, Res('B', 'X') to 0, Res('C', 'X') to 6, Res('A', 'Y') to 6, Res('B', 'Y') to 3, Res('C', 'Y') to 0, Res('A', 'Z') to 0, Res('B', 'Z') to 6, Res('C', 'Z') to 3, ) val expect = mapOf( 'X' to 0, 'Y' to 3, 'Z' to 6) val value = mapOf( 'X' to 1, 'Y' to 2, 'Z' to 3) for(line in input) { if (line.isNotBlank()) { var item : Char = ' ' for ((K,V) in rules) { if (K.ABC == line[0]) if (V == expect[line[2]]) item = K.XYZ } val match = rules.get(Res(line[0], item)) ?: -99999 val bet = value.get(item) ?: -99999 score += match + bet } } return score } fun main() { val input = readInput("d2/input1") println(part2(input)) }
0
Kotlin
0
0
5cf6b2142df6082ddd7d94f2dbde037f1fe0508f
1,682
aoc2022
Creative Commons Zero v1.0 Universal
src/Day05.kt
bendh
573,833,833
false
{"Kotlin": 11618}
fun main() { fun readInitialSupplyStackData(input: List<String>): List<ArrayDeque<String>> { // Create deque val supplyStackData = input.subList(0, input.indexOf("")) val lastStackNumber = supplyStackData.last().last().digitToInt() val supplyStacks = (1..lastStackNumber).map { ArrayDeque<String>() } val initialSupplyPositionData = supplyStackData.subList(0,supplyStackData.lastIndex) initialSupplyPositionData.forEach { val chuncks = it.chunked(4) chuncks.forEachIndexed { index, data -> if (data.isNotBlank()) { supplyStacks[index].addLast(data[1].toString()) } } } return supplyStacks } fun List<ArrayDeque<String>>.moveSupply(from: Int, to: Int){ val supply = this[from-1].removeFirst() this[to-1].addFirst(supply) } fun List<ArrayDeque<String>>.getTopSupplies(): String { return this.filter { it.isNotEmpty() } .map { it.first() } .reduce { acc, s -> acc+s } } fun List<ArrayDeque<String>>.moveMultipleSupply(noOfSupplies: Int, from: Int, to: Int){ val fromList = this[from-1] val toList = this[to-1] val supplies = this[from-1].take(noOfSupplies) val newFromContent = fromList.slice(noOfSupplies..fromList.lastIndex) fromList.clear() fromList.addAll(newFromContent) toList.addAll(0, supplies) } fun String.getMove(): Triple<Int, Int, Int> { val moveRegex = Regex("""^move (\d+) from (\d+) to (\d+)$""") val match = moveRegex.find(this) if (this.matches(moveRegex)) { val move = match?.destructured?.toList()?.map { it.toInt() } if (move != null) { return Triple(move[0], move[1], move[2] ) } } return Triple(0, 0, 0) } fun part1(input: List<String>): String { val stacks = readInitialSupplyStackData(input) val moves = input.subList(input.indexOf("")+1, input.lastIndex+1) moves.forEach { val (count, from, to) = it.getMove() if (count == 1) { stacks.moveSupply(from, to) } else { (1..count).forEach { _ -> stacks.moveSupply(from, to) } } } return stacks.getTopSupplies() } fun part2(input: List<String>): String { val stacks = readInitialSupplyStackData(input) val moves = input.subList(input.indexOf("")+1, input.lastIndex+1) moves.forEach { val (noOfSupplies, from, to) = it.getMove() stacks.moveMultipleSupply(noOfSupplies, from, to) } return stacks.getTopSupplies() } // test if implementation meets criteria from the description, like: val testInput = readLines("Day05_test") check(part1(testInput) == "CMZ") check(part2(testInput) == "MCD") // val input = readLines("Day05") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
e3ef574441b63a99a99a095086a0bf025b8fc475
3,122
advent-of-code-2022-kotlin
Apache License 2.0
day6/src/main/kotlin/Main.kt
joshuabrandes
726,066,005
false
{"Kotlin": 47373}
import java.io.File fun main() { println("------ Advent of Code 2023 - Day 6 -----") val puzzleInput = getPuzzleInput() val races = getRaces(puzzleInput) val waysToWin = races .map { it.numberOfWaysToWin() } .reduce { acc, i -> acc * i } println("Task 1: Number of ways to win all Races: $waysToWin") val actualRace = getRace(puzzleInput) val waysToWinActualRace = actualRace.numberOfWaysToWin() println("Task 2: Number of Ways to win actual Race: $waysToWinActualRace") println("----------------------------------------") } fun getRaces(puzzleInput: List<String>): List<Race> { val times = puzzleInput.first() .substringAfter("Time: ") .split(" ") .map { it.trim() } .filter { it.isNotEmpty() } .map { it.toLong() } val distances = puzzleInput.last() .substringAfter("Distance: ") .split(" ") .map { it.trim() } .filter { it.isNotEmpty() } .map { it.toLong() } assert(times.size == distances.size) val races = mutableListOf<Race>() for (i in times.indices) { races.add(Race(times[i], distances[i])) } return races } fun getRace(puzzleInput: List<String>) : Race { val time = puzzleInput.first() .substringAfter("Time: ") .split("") .map { it.trim() } .filter { it.isNotEmpty() } .reduce { acc, s -> acc + s } .toLong() val distance = puzzleInput.last() .substringAfter("Distance: ") .split("") .map { it.trim() } .filter { it.isNotEmpty() } .reduce { acc, s -> acc + s } .toLong() return Race(time, distance) } fun getPuzzleInput(): List<String> { val fileUrl = ClassLoader.getSystemResource("input.txt") return File(fileUrl.toURI()).readLines() } data class Race(val time: Long, val distance: Long) { fun numberOfWaysToWin(): Int { var ways = 0 for (i in 1..<time) { if (distanceAfter(i) > distance) { ways++ } } return ways } private fun distanceAfter(time: Long): Long { return time * (this.time - time) } }
0
Kotlin
0
1
de51fd9222f5438efe9a2c45e5edcb88fd9f2232
2,209
aoc-2023-kotlin
The Unlicense
src/days/day3/Day3.kt
Riven-Spell
113,698,657
false
{"Kotlin": 25729}
package days.day3 import kotlin.math.* fun day3p1(s: String) : String { val x = s.toInt() val upper = (1..x step 2).first { it * it >= x } val xdist = abs((x % upper) - ((upper / 2) + 1)) - if(sqrt(x.toFloat()).toInt().toFloat().pow(2).toInt() == x) 1 else 0 val ydist = upper / 2 return (xdist + ydist).toString() } typealias point2D = Pair<Int,Int> operator fun point2D.plus(p: point2D): point2D = point2D(this.first + p.first, this.second + p.second) operator fun point2D.minus(p: point2D): point2D = point2D(this.first - p.first, this.second - p.second) operator fun List<point2D>.plus(p: point2D): List<point2D> = this.map { it + p } operator fun List<point2D>.minus(p: point2D): List<point2D> = this.map { it - p } infix fun Int.pow(x: Int): Int = this.toFloat().pow(x).toInt() fun List<Int>.extend(n: Int): List<Int> = this + (1..n).map { this.last() } typealias Memblock = HashMap<point2D, Int> fun Memblock.around(p: point2D): Int = (-1..1).map { x -> (-1..1).map { y -> point2D(x,y) } }.map { b -> b.filter { it != point2D(0,0) } }.map { it + p }.map { b -> b.map { this[it] ?: 0 }.sum() }.sum() fun Memblock.getZero(p: point2D): Int = this[p] ?: 0 fun day3p2(s: String) : String { val moves = listOf(point2D(0,1), point2D(-1,0), point2D(0,-1), point2D(1,0)) var croot = 3 var cursor = point2D(1,0) var mblck = Memblock() mblck[point2D(0,0)] = 1 mblck[point2D(1,0)] = 1 var max = s.toInt() //(1..((croot pow 2) - ((croot - 2) pow 2))).map { it - 1 }.map { it / (croot - 1) }.drop(1).extend(1).map { moves [it] } -- one liner to snake around while (true) { (1..((croot pow 2) - ((croot - 2) pow 2))).map { it - 1 }.map { it / (croot - 1) }.drop(1).extend(1).map { moves[it] }.map { cursor += it; cursor }.forEachIndexed { i, pos -> mblck[pos] = mblck.around(pos) if (mblck.getZero(pos) > max) { val ntimes = i + ((croot - 2) pow 2) println("found result after $ntimes iterations") return mblck.getZero(pos).toString() } } croot += 2 } }
0
Kotlin
0
1
dbbdb390a0addee98c7876647106af208c3d9bc7
2,124
Kotlin-AdventOfCode-2017
MIT License
src/Day07.kt
ajspadial
573,864,089
false
{"Kotlin": 15457}
abstract class DirectoryElement(val name: String) { abstract fun getSize(): Int } class Directory(name: String, val parent: Directory?) : DirectoryElement(name) { val elements = mutableListOf<DirectoryElement>() override fun getSize(): Int { return elements.sumOf { it.getSize()} } } class File(name: String, private val size: Int): DirectoryElement(name) { override fun getSize(): Int { return size } } fun main() { fun findSmaller(root: Directory, limitSize: Int, list: MutableList<Directory>) { if (root.getSize()<=limitSize) { list.add(root) } for (e in root.elements) { if (e is Directory) { findSmaller(e, limitSize, list) } } } fun findBigger(root: Directory, limitSize: Int, list: MutableList<Directory>) { val s = root.getSize() if (s >=limitSize) { list.add(root) } for (e in root.elements) { if (e is Directory) { findBigger(e, limitSize, list) } } } fun loadDirectory(input: List<String>): Directory { var ls = false val rootDirectory = Directory("/", null) var currentDirectory = rootDirectory for (line in input) { if (line.startsWith("$ cd")) { ls = false val dirname = line.substring(5) if (dirname == "/") { currentDirectory = rootDirectory } else if (dirname == "..") { currentDirectory = currentDirectory.parent!! } else { for (d in currentDirectory.elements) { if (d.name == dirname && d is Directory) { currentDirectory = d break } } } } else if (line.startsWith("$ ls")) { ls = true } else if (ls) { val elements = line.split(" ") val name = elements[1] if (elements[0] == "dir") { currentDirectory.elements.add(Directory(name, currentDirectory)) } else { val size = elements[0].toInt() currentDirectory.elements.add(File(name, size)) } } } return rootDirectory } fun part1(input: List<String>): Int { val rootDirectory = loadDirectory(input) val candidates = mutableListOf<Directory>() findSmaller(rootDirectory, 100000, candidates) var sum = 0 for (d in candidates) { sum += d.getSize() } return sum } fun part2(input: List<String>): Int { val rootDirectory = loadDirectory(input) val unusedSpace = 70000000 - rootDirectory.getSize() val neededSpace = 30000000 - unusedSpace val candidates = mutableListOf<Directory>() findBigger(rootDirectory, neededSpace, candidates) var result = candidates[0].getSize() for (c in candidates) { val s = c.getSize() if (s < result) { result = s } } return result } // test if implementation meets criteria from the description, like: val testInput = readInput("Day07_test") check(part1(testInput) == 95437) check(part2(testInput) == 24933642) val input = readInput("Day07") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
ed7a2010008be17fec1330b41adc7ee5861b956b
3,642
adventofcode2022
Apache License 2.0
day4/src/main/kotlin/day4/Main.kt
ErikHellman
433,722,039
false
{"Kotlin": 9432}
package day4 import java.io.File import java.util.regex.Pattern fun main(args: Array<String>) { val lines = loadFile("input.txt") val numbersDrawn = lines[0] val boards = lines.drop(1) .chunked(5) .map { board -> board.map { line -> line.map { it to false }.toMutableList() }.toMutableList() } traverseBoards(numbersDrawn, boards) } private fun traverseBoards( numbersDrawn: MutableList<Int>, boards: List<MutableList<MutableList<Pair<Int, Boolean>>>> ) { var lastWinningBoard = boards[0] var lastWinningNumber = -1 var mutableBoards = boards numbersDrawn.forEach { numberDrawn -> mutableBoards = mutableBoards.filter { board -> updateBoard(numberDrawn, board) val didWin = checkBoard(board) if (didWin) { lastWinningBoard = board lastWinningNumber = numberDrawn } !didWin } } println("Last board won at $lastWinningNumber") lastWinningBoard.forEach { line -> println(line) } val sum = sumOfUnmarked(lastWinningBoard) println("Result: $sum x $lastWinningNumber = ${sum * lastWinningNumber}") } fun sumOfUnmarked(board: MutableList<MutableList<Pair<Int, Boolean>>>): Int { return board.flatten().fold(0 to false) { acc, pair -> if (!pair.second) { acc.copy(acc.first + pair.first) } else acc }.first } fun checkBoard(board: MutableList<MutableList<Pair<Int, Boolean>>>): Boolean { board.forEach { line -> val win = line.reduce { acc, next -> acc.copy(second = acc.second && next.second) }.second if (win) return true } for (column in board[0].indices) { val win = board.indices .map { line -> board[line][column].second } .reduce { acc, marked -> acc && marked } if (win) return true } return false } fun updateBoard(numberDrawn: Int, board: MutableList<MutableList<Pair<Int, Boolean>>>) { for (line in board.indices) { for (column in board[line].indices) { if (board[line][column].first == numberDrawn) { board[line][column] = numberDrawn to true } } } } fun loadFile(input: String): MutableList<MutableList<Int>> { val regex = Pattern.compile(" +|,") return File(input) .useLines { sequence -> sequence.filter { line -> line.isNotBlank() } .map { line -> line.split(regex) .map { entry -> entry.trim() } .filter { it.isNotBlank() } .map { it.toInt() } .toMutableList() } .toMutableList() } }
0
Kotlin
0
1
37f54d52633fff5f6fdd9e66926c57421fc721d2
2,815
advent-of-code-2021
Apache License 2.0
src/Day02.kt
iProdigy
572,297,795
false
{"Kotlin": 33616}
fun main() { fun part1(input: List<String>): Int = input .map { (it.first() - 'A') to (it.last() - 'X') } .sumOf { (first, second) -> val move = second + 1 // [1, 3] val round = when (second - first) { 0 -> 3 // draw 1, -2 -> 6 // win else -> 0 // loss } move + round } fun part2(input: List<String>): Int = input .map { (it.first() - 'A') to (it.last() - 'X') } .sumOf { (first, second) -> val round = second * 3 // 0, 3, 6 val move = when (round) { 0 -> first - 1 // lose 6 -> first + 1 // win else -> first // draw }.mod(3) + 1 // put in [1, 3] move + round } // 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)) // 11150 println(part2(input)) // 8295 }
0
Kotlin
0
1
784fc926735fc01f4cf18d2ec105956c50a0d663
1,109
advent-of-code-2022
Apache License 2.0
2023/src/main/kotlin/sh/weller/aoc/Day07.kt
Guruth
328,467,380
false
{"Kotlin": 188298, "Rust": 13289, "Elixir": 1833}
package sh.weller.aoc object Day07 : SomeDay<Pair<String, Int>, Int> { override fun partOne(input: List<Pair<String, Int>>): Int { return input .map { (handString, bet) -> Hand.fromString(handString) to bet } .sortedBy { it.first.handValue } .mapIndexed { index, (_, bet) -> (index + 1) * bet } .sum() } override fun partTwo(input: List<Pair<String, Int>>): Int { return input .map { (handString, bet) -> JokerHand(handString) to bet } .sortedBy { it.first.valueOf() } .mapIndexed { index, (hand, bet) -> println("${hand.rawHand} - ${hand.valueOf()} - ${hand.handType()} ") (index + 1) * bet } .sum() } } enum class HandType(val value: Int) { FiveOfAKind(7), FourOfAKind(6), FullHouse(5), ThreeOfAKind(4), TwoPair(3), OnePair(2), HighCard(1) } data class Hand( val type: HandType, val handValue: Long, val rawHand: String, ) { companion object { fun fromString(value: String): Hand { val chars = value.toCharArray() val groupedChars = chars.groupBy { it } val type = when { groupedChars.size == 1 -> HandType.FiveOfAKind groupedChars.size == 2 && groupedChars.any { it.value.size == 4 } -> HandType.FourOfAKind groupedChars.size == 2 && groupedChars.any { it.value.size == 3 } && groupedChars.any { it.value.size == 2 } -> HandType.FullHouse groupedChars.size == 3 && groupedChars.any { it.value.size == 3 } && groupedChars.any { it.value.size == 3 } -> HandType.ThreeOfAKind groupedChars.size == 3 && groupedChars.count { it.value.size == 2 } == 2 -> HandType.TwoPair groupedChars.size == 4 && groupedChars.count { it.value.size == 2 } == 1 -> HandType.OnePair groupedChars.size == 5 -> HandType.HighCard else -> throw IllegalArgumentException("Unknown Hand Type") } val stringValue = "${type.value}" + chars.map { when (it) { 'A' -> "13" 'K' -> "12" 'Q' -> "11" 'J' -> "10" 'T' -> "09" '9' -> "08" '8' -> "07" '7' -> "06" '6' -> "05" '5' -> "04" '4' -> "03" '3' -> "02" '2' -> "01" else -> throw IllegalArgumentException("Unknown Card Type") } }.joinToString("") return Hand(type, stringValue.toLong(), value) } } } data class JokerHand( val rawHand: String, ) { fun valueOf(): Long = "${handType().value}${handValue()}".toLong() fun handType(): HandType { val chars = rawHand.toCharArray() val groupedChars = chars.groupBy { it }.mapValues { it.value.size } val numberOfJokers = groupedChars['J'] ?: 0 return when { numberOfJokers == 0 -> { when { groupedChars.size == 1 -> HandType.FiveOfAKind groupedChars.size == 2 && groupedChars.any { it.value == 4 } -> HandType.FourOfAKind groupedChars.size == 2 && groupedChars.any { it.value == 3 } && groupedChars.any { it.value == 2 } -> HandType.FullHouse groupedChars.size == 3 && groupedChars.any { it.value == 3 } && groupedChars.any { it.value == 3 } -> HandType.ThreeOfAKind groupedChars.size == 3 && groupedChars.count { it.value == 2 } == 2 -> HandType.TwoPair groupedChars.size == 4 && groupedChars.count { it.value == 2 } == 1 -> HandType.OnePair groupedChars.size == 5 -> HandType.HighCard else -> throw IllegalArgumentException("Unknown Hand Type: $rawHand") } } numberOfJokers == 5 -> HandType.FiveOfAKind numberOfJokers == 4 -> HandType.FiveOfAKind numberOfJokers == 3 -> { when { // JJJAA groupedChars.size == 2 -> HandType.FiveOfAKind // JJJAB groupedChars.size == 3 -> HandType.FourOfAKind else -> throw IllegalArgumentException("Unknown Hand Type: $rawHand") } } numberOfJokers == 2 -> { when { // JJABC groupedChars.size == 4 -> HandType.ThreeOfAKind // JJAAB groupedChars.size == 3 -> HandType.FourOfAKind // JJAAA groupedChars.size == 2 -> HandType.FiveOfAKind else -> throw IllegalArgumentException("Unknown Hand Type: $rawHand") } } numberOfJokers == 1 -> { when { // JABCD groupedChars.size == 5 -> HandType.OnePair // JAABC groupedChars.size == 4 -> HandType.ThreeOfAKind // JAAAB groupedChars.size == 3 && groupedChars.count { it.value == 3 } == 1 -> HandType.FourOfAKind // JAABB groupedChars.size == 3 && groupedChars.count { it.value == 2 } == 2 -> HandType.FullHouse // JAAAA groupedChars.size == 2 -> HandType.FiveOfAKind else -> throw IllegalArgumentException("Unknown Hand Type: $rawHand") } } else -> throw IllegalArgumentException("Unknown Hand Type: $rawHand") } } fun handValue(): String = rawHand.toCharArray().joinToString("") { when (it) { 'A' -> "13" 'K' -> "12" 'Q' -> "11" 'T' -> "10" '9' -> "09" '8' -> "08" '7' -> "07" '6' -> "06" '5' -> "05" '4' -> "04" '3' -> "03" '2' -> "02" 'J' -> "01" else -> throw IllegalArgumentException("Unknown Card Type") } } }
0
Kotlin
0
0
69ac07025ce520cdf285b0faa5131ee5962bd69b
6,470
AdventOfCode
MIT License
src/_2022/Day02.kt
albertogarrido
572,874,945
false
{"Kotlin": 36434}
package _2022 import readInput import java.lang.IllegalArgumentException fun main() { val input = readInput("2022", "day02") println(part1(input)) println(part2(input)) } // part 1 private fun part1(input: List<String>): Int { var points = 0 input.forEach { round -> val (opponent, player) = round.split(" ") points += symbolUsagePoints(player) points += determineRoundPoints(opponent, player) } return points } fun determineRoundPoints(opponent: String, player: String): Int { val isDraw = (player == Player.rock && opponent == Opponent.rock) || (player == Player.paper && opponent == Opponent.paper) || (player == Player.scissors && opponent == Opponent.scissors) if (isDraw) return 3 val isPlayerWinner = (player == Player.rock && opponent == Opponent.scissors) || (player == Player.paper && opponent == Opponent.rock) || (player == Player.scissors && opponent == Opponent.paper) return if (isPlayerWinner) 6 else 0 } fun symbolUsagePoints(player: String) = when (player) { "X" -> 1 "Y" -> 2 "Z" -> 3 else -> { throw IllegalArgumentException("player played wrong symbol") } } // part 2 private fun part2(input: List<String>): Int { var points = 0 input.forEach { round -> val (opponent, result) = round.split(" ") points += calculateStrategy( opponentPlays = mapPlays(opponent), resultNeeded = mapResult(result) ) } return points } fun calculateStrategy(opponentPlays: Plays, resultNeeded: Result) = when (resultNeeded) { Result.Win -> { 6 + when (opponentPlays) { Plays.Rock -> 2 Plays.Paper -> 3 Plays.Scissors -> 1 } } Result.Draw -> { 3 + when (opponentPlays) { Plays.Rock -> 1 Plays.Paper -> 2 Plays.Scissors -> 3 } } Result.Lose -> { when (opponentPlays) { Plays.Rock -> 3 Plays.Paper -> 1 Plays.Scissors -> 2 } } } fun mapResult(result: String) = when (result) { "X" -> Result.Lose "Y" -> Result.Draw "Z" -> Result.Win else -> throw IllegalArgumentException("wrong result") } fun mapPlays(opponent: String) = when (opponent) { "A" -> Plays.Rock "B" -> Plays.Paper "C" -> Plays.Scissors else -> throw IllegalArgumentException("played the wrong symbol") } //second part enum class Result { Win, Draw, Lose } //second part enum class Plays { Rock, Paper, Scissors } //first part object Player { val rock = "X" val paper = "Y" val scissors = "Z" } //first part object Opponent { val rock: String = "A" val paper: String = "B" val scissors: String = "C" }
0
Kotlin
0
0
ef310c5375f67d66f4709b5ac410d3a6a4889ca6
2,970
AdventOfCode.kt
Apache License 2.0
src/Day05.kt
iam-afk
572,941,009
false
{"Kotlin": 33272}
typealias Stacks = Array<MutableList<Char>> data class Move(val count: Int, val from: Int, val to: Int) typealias Moves = List<Move> data class Input(val stacks: Stacks, val moves: Moves) { companion object { fun parse(input: List<String>): Input { val at = input.indexOf("") val count = input[at - 1].split(Regex("\\s+")).count() - 1 val stacks = Array(count) { mutableListOf<Char>() } for (line in input.subList(0, at - 1).asReversed()) { for ((stack, i) in stacks.zip(1 until line.length step 4)) { if (line[i].isLetter()) { stack.add(line[i]) } } } val moves = input.subList(at + 1, input.size) .map { it.split(' ') } .map { Move(it[1].toInt(), it[3].toInt() - 1, it[5].toInt() - 1) } return Input(stacks, moves) } } } fun main() { fun part1(input: List<String>): String { val (stacks, moves) = Input.parse(input) for ((count, fromIndex, toIndex) in moves) { val from = stacks[fromIndex] val to = stacks[toIndex] repeat(count) { to.add(from.removeLast()) } } return buildString { stacks.forEach { append(it.last()) } } } fun part2(input: List<String>): String { val (stacks, moves) = Input.parse(input) for ((count, fromIndex, toIndex) in moves) { val from = stacks[fromIndex] val to = stacks[toIndex] repeat(count) { to.add(from[from.size - count + it]) } repeat(count) { from.removeLast() } } return buildString { stacks.forEach { append(it.last()) } } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day05_test") check(part1(testInput) == "CMZ") check(part2(testInput) == "MCD") val input = readInput("Day05") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
b30c48f7941eedd4a820d8e1ee5f83598789667b
2,116
aockt
Apache License 2.0
src/Day02.kt
niltsiar
572,887,970
false
{"Kotlin": 16548}
fun main() { fun part1(input: List<String>): Int { val game = mapOf( "A X" to 1 + 3, "A Y" to 2 + 6, "A Z" to 3 + 0, "B X" to 1 + 0, "B Y" to 2 + 3, "B Z" to 3 + 6, "C X" to 1 + 6, "C Y" to 2 + 0, "C Z" to 3 + 3, ) return input.sumOf { line -> game[line] ?: 0 } } fun part2(input: List<String>): Int { val game = mapOf( "A X" to 3 + 0, "A Y" to 1 + 3, "A Z" to 2 + 6, "B X" to 1 + 0, "B Y" to 2 + 3, "B Z" to 3 + 6, "C X" to 2 + 0, "C Y" to 3 + 3, "C Z" to 1 + 6, ) return input.sumOf { line -> game[line] ?: 0 } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day02_test") check(part1(testInput) == 15) check(part2(testInput) == 12) val input = readInput("Day02") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
766b3e168fc481e4039fc41a90de4283133d3dd5
1,112
advent-of-code-kotlin-2022
Apache License 2.0
src/day18/Day18.kt
gr4cza
572,863,297
false
{"Kotlin": 93944}
package day18 import readInput import kotlin.math.abs fun main() { data class Cube( val x: Int, val y: Int, val z: Int, ) { fun getPosition(): List<Int> { return listOf(x, y, z) } } fun Cube.checkTouching(to: Cube): Boolean { return (this.x == to.x && this.y == to.y && (abs(this.z - to.z) == 1)) || (this.x == to.x && this.z == to.z && (abs(this.y - to.y) == 1)) || (this.y == to.y && this.z == to.z && (abs(this.x - to.x) == 1)) } fun parse(input: List<String>): List<Cube> { return input.map { it.split(",").map { it.toInt() }.let { (x, y, z) -> Cube(x, y, z) } } } fun Cube.countTouching(cubes: List<Cube>): Int { var freeSides = 6 cubes.forEach { cube2 -> if (this != cube2) { if (this.checkTouching(cube2)) { freeSides-- } } } return freeSides } fun countSides(cubes: List<Cube>): Int { val freeSidesPerCube = cubes.map { cube -> cube.countTouching(cubes) } return freeSidesPerCube.sum() } fun part1(input: List<String>): Int { val cubes = parse(input) return countSides(cubes) } fun Cube.getNeighbours(): MutableList<Cube> { val neighbours = mutableListOf<Cube>() this.copy(x = this.x - 1).let { neighbours.add(it) } this.copy(x = this.x + 1).let { neighbours.add(it) } this.copy(y = this.y - 1).let { neighbours.add(it) } this.copy(y = this.y + 1).let { neighbours.add(it) } this.copy(z = this.z - 1).let { neighbours.add(it) } this.copy(z = this.z + 1).let { neighbours.add(it) } return neighbours } fun maxDimension(cubes: List<Cube>): Int { return cubes.maxOfOrNull { maxOf(it.x, it.y, it.z) } ?: 0 } fun countOutside(cubes: List<Cube>): Int { val maxDim = maxDimension(cubes) + 1 val minDim = -1 var faceCount = 0 val visited = mutableListOf<Cube>() val queue = ArrayDeque(listOf(Cube(-1, -1, -1))) while (queue.isNotEmpty()) { val currentPos = queue.removeFirst() currentPos.getNeighbours().forEach { n -> if (n.getPosition().all { it in minDim..maxDim } && currentPos !in visited) { if (n in cubes) { faceCount++ } else { queue.add(n) } } } visited.add(currentPos) } return faceCount } fun part2(input: List<String>): Int { val cubes = parse(input) return countOutside(cubes) } // test if implementation meets criteria from the description, like: val testInput = readInput("day18/Day18_test") val input = readInput("day18/Day18") check((part1(testInput)).also { println(it) } == 64) check((part1(input)).also { println(it) } == 3374) check(part2(testInput).also { println(it) } == 58) check(part2(input).also { println(it) } == 2010) }
0
Kotlin
0
0
ceca4b99e562b4d8d3179c0a4b3856800fc6fe27
3,262
advent-of-code-kotlin-2022
Apache License 2.0
src/Day11.kt
f1qwase
572,888,869
false
{"Kotlin": 33268}
private data class Monkey( val id: Int, val items: MutableList<Long>, val op: (Long) -> Long, val testDivisibleBy: Long, val successReceiverIndex: Int, val failureReceiverIndex: Int, ) { var inspectedItemsCount: Long = 0 } private fun parseOperation(input: String): (Long) -> Long { val (_, operand1Str, opStr, operand2Str) = Regex("(\\S+) ([+*]) (\\S+)").find(input)!! .groupValues val op: (Long, Long) -> Long = when (opStr) { "+" -> Long::plus "*" -> Long::times else -> throw IllegalArgumentException("Unknown operation: $input") } return { x: Long -> op(parseOperand(operand1Str, x), parseOperand(operand2Str, x)) } } private fun parseOperand(operandString: String, oldValue: Long): Long = when (operandString) { "old" -> oldValue else -> operandString.toLong() } private fun parseMonkey(input: List<String>): Monkey { val id = Regex("Monkey (\\d+):").find(input[0])!!.groupValues[1].toInt() val items = input[1].substringAfter("Starting items: ") .split(", ") .map { it.toLong() } val operation = input[2].substringAfter("Operation: new = ").let(::parseOperation) val testDivisibleBy = input[3].substringAfter("Test: divisible by ").toLong() val successReceiver = input[4].substringAfter("If true: throw to monkey ").toInt() val failureReceiverReceiver = input[5].substringAfter("If false: throw to monkey ").toInt() return Monkey( id, items.toMutableList(), operation, testDivisibleBy, successReceiver, failureReceiverReceiver ) } private fun List<Monkey>.playRound(worryReducer: (Long) -> Long) { forEach {monkey -> monkey.items.forEach { worryLevel -> monkey.inspectedItemsCount++ val nextWorryLevel = worryReducer(monkey.op(worryLevel)) val monkeyToThrowItemIndex = if (nextWorryLevel % monkey.testDivisibleBy == 0L) { monkey.successReceiverIndex } else { monkey.failureReceiverIndex } this[monkeyToThrowItemIndex].items.add(nextWorryLevel) } monkey.items.clear() } } fun main() { fun part1(input: List<String>): Long { val monkeys = input.chunked(7, ::parseMonkey) repeat(20) { monkeys.playRound { it / 3} } return monkeys .map { it.inspectedItemsCount } .sortedDescending() .take(2) .reduce(Long::times) } fun part2(input: List<String>): Long { val monkeys = input.chunked(7, ::parseMonkey) val commonDivider = monkeys.map { it.testDivisibleBy }.reduce(Long::times) repeat(10000) { monkeys.playRound { it % commonDivider } } println(monkeys.map { it.inspectedItemsCount }) return monkeys .map { it.inspectedItemsCount } .sortedDescending() .take(2) .reduce(Long::times) } // test if implementation meets criteria from the description, like: val testInput = readInput("Day11_test") part1(testInput).let { check(it == 10605L) { it } } val input = readInput("Day11") println(part1(input)) part2(testInput).let { check(it == 2713310158) { it } } println(part2(input)) }
0
Kotlin
0
0
3fc7b74df8b6595d7cd48915c717905c4d124729
3,357
aoc-2022
Apache License 2.0
src/main/kotlin/days/Day11.kt
hughjdavey
725,972,063
false
{"Kotlin": 76988}
package days import xyz.hughjd.aocutils.Coords.Coord class Day11 : Day(11) { override fun partOne(): Any { return sumOfShortestPaths(2) } override fun partTwo(): Any { val factors = listOf( sumOfShortestPaths(1), sumOfShortestPaths(10), sumOfShortestPaths(100) ).map { it.toLong() } // borrow line from day 9 val diffs = factors.windowed(2) { (l, r) -> r - l } // 4 more x10s to get to a million (1000 -> 10000 -> 100000 -> 1000000) val projectedDiffs = (0 until 4).fold(diffs) { acc, _ -> acc + acc.last() * 10 }.takeLast(4) // add all projected differences onto the value we got from factor 100 return projectedDiffs.fold(factors.last()) { acc, elem -> acc + elem } } fun sumOfShortestPaths(expansionFactor: Int): Int { val expanded = spaceExpansion(expansionFactor) return getAllPairs(expanded).sumOf { shortestPath(it.first, it.second) } } fun shortestPath(start: Coord, end: Coord): Int { return start.manhattan(end) } fun getAllPairs(space: List<String>): List<Pair<Coord, Coord>> { val galaxies = space.flatMapIndexed { y, row -> row.mapIndexedNotNull { x, char -> if (char == '#') Coord(x, y) else null } } return galaxies.flatMapIndexed { index, c1 -> galaxies.drop(index).mapNotNull { c2 -> if (c1 != c2) c1 to c2 else null } } } fun spaceExpansion(scaleFactor: Int = 2): List<String> { val rowsToDuplicate = inputList.mapIndexedNotNull { index, row -> if (row.all { it == '.' }) index else null } val columns = (0..inputList.lastIndex).map { x -> inputList.map { row -> row[x] } } val columnsToDuplicate = columns.mapIndexedNotNull { index, column -> if (column.all { it == '.' }) index else null } return inputList.flatMapIndexed { y, row -> fun xFn(x: Int, char: Char): List<Char> { return if (columnsToDuplicate.contains(x)) List(scaleFactor) { char } else listOf(char) } if (rowsToDuplicate.contains(y)) { List(scaleFactor) { row.flatMapIndexed { x, char -> xFn(x, char) } } } else { listOf(row.flatMapIndexed { x, char -> xFn(x, char) }) } }.map { it.joinToString("") } } }
0
Kotlin
0
0
330f13d57ef8108f5c605f54b23d04621ed2b3de
2,347
aoc-2023
Creative Commons Zero v1.0 Universal
src/main/kotlin/Day02.kt
alex859
573,174,372
false
{"Kotlin": 80552}
import Choice.* import FixedResult.* fun main() { val testInput = readInput("Day02_test.txt") check(testInput.total { it.toRound().myScore } == 15) check(testInput.total { it.toRoundFixing().toRound().myScore } == 12) val input = readInput("Day02.txt") println(input.total { it.toRound().myScore }) println(input.total { it.toRoundFixing().toRound().myScore }) } internal fun String.toRound(): Round { val (opponentChoiceStr, myChoiceStr) = split(" ") return Round( myChoice = myChoiceStr.toChoice(myChoices), opponentChoice = opponentChoiceStr.toChoice(opponentChoices) ) } internal fun String.toRoundFixing(): RoundFixing { val (opponentChoiceStr, fixedResultStr) = split(" ") return opponentChoiceStr.toChoice(opponentChoices) to fixedResultStr.toFixingResult() } internal data class Round( val myChoice: Choice, val opponentChoice: Choice ) internal enum class Choice { ROCK, SCISSORS, PAPER } internal enum class FixedResult { WIN, LOSE, DRAW } internal typealias RoundFixing = Pair<Choice, FixedResult> internal fun RoundFixing.toRound(): Round { val (opponentChoice, fixedResult) = this val myChoice = when (fixedResult) { DRAW -> opponentChoice WIN -> results.values.first { it.loser == opponentChoice }.winner LOSE -> results.values.first { it.winner == opponentChoice }.loser } return Round(myChoice = myChoice, opponentChoice = opponentChoice) } private sealed interface Result { object Draw : Result data class NonDraw( val winner: Choice, val loser: Choice ) : Result } private val Round.result: Result get() { val (choice1, choice2) = this return if (choice1 == choice2) Result.Draw else results[choice1 vs choice2] ?: results[choice2 vs choice1] ?: error("unable to find result for $this") } private val results = mapOf( (ROCK vs PAPER) to Result.NonDraw(winner = PAPER, loser = ROCK), (ROCK vs SCISSORS) to Result.NonDraw(winner = ROCK, loser = SCISSORS), (SCISSORS vs PAPER) to Result.NonDraw(winner = SCISSORS, loser = PAPER), ) private fun Result.scoreFor(choice: Choice) = when (this) { is Result.Draw -> 3 is Result.NonDraw -> { with(this) { if (choice == winner) 6 else 0 } } } internal val Round.myScore: Int get() = myChoice.score + result.scoreFor(myChoice) private val Choice.score: Int get() = when (this) { ROCK -> 1 PAPER -> 2 SCISSORS -> 3 } private infix fun Choice.vs(that: Choice): Round = Round(myChoice = this, opponentChoice = that) private fun String.toFixingResult() = when (this) { "X" -> LOSE "Y" -> DRAW "Z" -> WIN else -> error("unrecognised result $this") } private fun String.toChoice(map: Map<String, Choice>) = map[this] ?: error("unrecognised choice code: $this") private val opponentChoices = mapOf( "A" to ROCK, "B" to PAPER, "C" to SCISSORS, ) private val myChoices = mapOf( "X" to ROCK, "Y" to PAPER, "Z" to SCISSORS, ) internal fun String.total(f: (String) -> Int): Int = lines().sumOf { f(it) }
0
Kotlin
0
0
fbbd1543b5c5d57885e620ede296b9103477f61d
3,205
advent-of-code-kotlin-2022
Apache License 2.0
src/main/kotlin/days/Solution11.kt
Verulean
725,878,707
false
{"Kotlin": 62395}
package days import adventOfCode.InputHandler import adventOfCode.Solution import adventOfCode.util.PairOf object Solution11 : Solution<List<CharArray>>(AOC_YEAR, 11) { override fun getInput(handler: InputHandler) = handler.getInput("\n").map(String::toCharArray) private fun getDistanceSum( galaxies: List<PairOf<Int>>, blankXs: Set<Int>, blankYs: Set<Int>, expansionFactors: List<Long> ): List<Long> { val ret = List(expansionFactors.size) { 0L }.toMutableList() galaxies.asSequence() .forEachIndexed { i, start -> val (x1, y1) = start galaxies.asSequence().drop(i + 1) .forEach { (x2, y2) -> val (sx1, sx2) = if (x1 < x2) x1 to x2 else x2 to x1 val (sy1, sy2) = if (y1 < y2) y1 to y2 else y2 to y1 val manhattan = sx2 - sx1 + sy2 - sy1 val crosses = blankXs.filter { it in sx1..sx2 }.size + blankYs.filter { it in sy1..sy2 }.size expansionFactors.forEachIndexed { j, expansion -> ret[j] += manhattan + (expansion - 1) * crosses } } } return ret } override fun solve(input: List<CharArray>): PairOf<Long> { val galaxies = input.withIndex() .flatMap { (i, row) -> row.withIndex() .filter { (_, c) -> c == '#' } .map { (j, _) -> i to j } } val xs = input.indices.filter { i -> !input[i].contains('#') }.toSet() val ys = input[0].indices.filter { j -> input.all { row -> row[j] != '#' } }.toSet() val (ans1, ans2) = getDistanceSum(galaxies, xs, ys, listOf(2, 1000000)) return ans1 to ans2 } }
0
Kotlin
0
1
99d95ec6810f5a8574afd4df64eee8d6bfe7c78b
1,840
Advent-of-Code-2023
MIT License
src/Day03.kt
dcbertelsen
573,210,061
false
{"Kotlin": 29052}
import java.io.File fun main() { fun part1(input: List<String>): Int { return input.map { sack -> sack.bisect() } .map { parts -> parts.first.intersect(parts.second).first() } .sumOf { it.toScore() } } fun part2(input: List<String>): Int { return input.chunked(3) .map { sacks -> sacks[0].intersect(sacks[1]).toString().intersect(sacks[2]).firstOrNull() } .sumOf { it?.toScore() ?: 0 } } val testInput = listOf<String>( "vJrwpWtwJgWrhcsFMMfFFhFp", "jqHRNqRjqzjGDLGLrsFMfFZSrLrFZsSL", "PmmdzqPrVvPwwTWBwg", "wMqvLMZHhHMvwLHjbvcjnnSBnvTQFn", "ttgJtRGJQctTZtZT", "CrZsJsPPZsGzwwsLwLmpwMDw" ) // test if implementation meets criteria from the description, like: println(part1(testInput)) check(part1(testInput) == 157) check(part2(testInput) == 70) val input = File("./src/resources/Day03a.txt").readLines() println(part1(input)) println(part2(input)) } fun Char.toScore() : Int = (if (this.isLowerCase()) this - 'a' else this - 'A' + 26) + 1 fun CharSequence.intersect(list2: CharSequence) : List<Char> { return this.filter { list2.contains(it) }.toList() } fun String.bisect() : Pair<String, String> = Pair(this.substring(0, this.length/2), this.substring(this.length/2, this.length))
0
Kotlin
0
0
9d22341bd031ffbfb82e7349c5684bc461b3c5f7
1,395
advent-of-code-2022-kotlin
Apache License 2.0
src/main/kotlin/mirecxp/aoc23/day08/Day08.kt
MirecXP
726,044,224
false
{"Kotlin": 42343}
package mirecxp.aoc23.day08 import mirecxp.aoc23.readInput //https://adventofcode.com/2023/day/8 class Day08(private val inputPath: String) { private var lines: List<String> = readInput(inputPath).toMutableList() val keys = lines[0] var keyIndex = 0 fun getNextKey(): Char { val key = keys[keyIndex] keyIndex++ if (keyIndex > keys.length - 1) { keyIndex = 0 } return key } fun solve(part2: Boolean): String { println("Solving day 8 for ${lines.size} line [$inputPath]") val navMap = mutableMapOf<String, Pair<String, String>>() lines.drop(2).forEach { line -> line.split("=").apply { val key = first().trim() get(1).trim().substring(1, 9).split(", ").apply { navMap[key] = get(0) to get(1) } } } var countMoves = 0L if (!part2) { var actualKey = "AAA" while (actualKey != "ZZZ") { countMoves++ var actualNav = navMap[actualKey] if (actualNav != null) { actualKey = if (getNextKey() == 'L') { actualNav.first } else { actualNav.second } } else { println("Error: No nav for $actualKey") } } } else { var allDirsCounts = mutableListOf<Long>() navMap.keys.filter { it.endsWith("A") }.forEach { key -> var actualKey = key countMoves = 0 while (!actualKey.endsWith("Z")) { countMoves++ var actualNav = navMap[actualKey] if (actualNav != null) { actualKey = if (getNextKey() == 'L') { actualNav.first } else { actualNav.second } } else { println("Error: No nav for $actualKey") } } println(countMoves) allDirsCounts.add(countMoves) } countMoves = lcmForList(allDirsCounts) } val result = countMoves val solution = "$result" println(solution) return solution } } fun main(args: Array<String>) { val testProblem = Day08("test/day08t") check(testProblem.solve(part2 = false) == "6") check(testProblem.solve(part2 = true) == "6") val problem = Day08("real/day08a") problem.solve(part2 = false) problem.solve(part2 = true) } fun lcm(a: Long, b: Long): Long { val larger = if (a > b) a else b val worst = a * b var lcm = larger while (lcm <= worst) { if (lcm % a == 0L && lcm % b == 0L) { return lcm } lcm += larger } return worst } fun lcmForList(numList: List<Long>): Long { var result = numList[0] for (i in 1 until numList.size) { result = lcm(result, numList[i]) } return result }
0
Kotlin
0
0
6518fad9de6fb07f28375e46b50e971d99fce912
3,209
AoC-2023
MIT License
src/Day02.kt
atsvetkov
572,711,515
false
{"Kotlin": 10892}
fun main() { fun part1(input: List<String>): Int { return input.sumOf { Shape.parse(it.split(' ')[0]).play(Shape.parse(it.split(' ')[1])) } } fun part2(input: List<String>): Int { return input.sumOf { Shape.parse(it.split(' ')[0]).play(Shape.parse(it.split(' ')[0]).counterpartByOutcome(Outcome.parse(it.split(' ')[1]))) } } // val testInput = readInput("Day02_test") // println("Testing part 1: " + part1(testInput)) val input = readInput("Day02") println("Part 1: " + part1(input)) println("Part 2: " + part2(input)) } fun Shape.play(myShape: Shape): Int { val result = myShape.score + when { this < myShape -> 6 this > myShape -> 0 else -> 3 } return result } fun Shape.counterpartByOutcome(outcome: Outcome): Shape = when(outcome) { is Outcome.Win -> this.beatenBy() is Outcome.Loss -> this.beats() is Outcome.Draw -> this } sealed class Outcome(val value: Int, val score: Int) { companion object { fun parse(outcome: String) = when(outcome) { "X" -> Loss() "Y" -> Draw() "Z" -> Win() else -> throw Exception("Unknown outcome: $outcome") } } class Win : Outcome(1, 6) class Loss : Outcome(-1, 0) class Draw : Outcome(0, 3) } sealed class Shape(val score: Int) : Comparable<Shape> { companion object { fun parse(shape: String) = when(shape) { "A", "X" -> Rock() "B", "Y" -> Paper() "C", "Z" -> Scissors() else -> throw Exception("Unknown shape: $shape") } } abstract fun beatenBy(): Shape abstract fun beats(): Shape class Rock : Shape(1) { override fun beatenBy() = Paper() override fun beats() = Scissors() override fun compareTo(other: Shape): Int { return when (other) { is Rock -> 0 is Paper -> -1 is Scissors -> 1 } } } class Paper : Shape(2) { override fun beatenBy() = Scissors() override fun beats() = Rock() override fun compareTo(other: Shape): Int { return when (other) { is Rock -> 1 is Paper -> 0 is Scissors -> -1 } } } class Scissors : Shape(3) { override fun beatenBy() = Rock() override fun beats() = Paper() override fun compareTo(other: Shape): Int { return when (other) { is Rock -> -1 is Paper -> 1 is Scissors -> 0 } } } }
0
Kotlin
0
0
01c3bb6afd658a2e30f0aee549b9a3ac4da69a91
2,662
advent-of-code-2022
Apache License 2.0
src/aoc2022/day03/Day03.kt
svilen-ivanov
572,637,864
false
{"Kotlin": 53827}
package aoc2022.day03 import readInput fun priority(char: Char): Int { return when { ('a'..'z').contains(char) -> 1 + char.code - 'a'.code ('A'..'Z').contains(char) -> 27 + char.code - 'A'.code else -> error("") } } fun main() { fun part1(input: List<String>) { var sum = 0 for (line in input) { val item = line .chunked(line.length / 2) .map(String::toSortedSet) .reduce { acc, items -> acc.apply { retainAll(items) } } .single() sum += priority(item) } println(sum) check(sum == 7967) } fun part2(input: List<String>) { var sum = 0 for (group in input.chunked(3)) { val item = group .map(String::toSortedSet) .reduce { acc, items -> acc.apply { retainAll(items) } } .single() sum += priority(item) } println(sum) check(sum == 2716) } fun part2fp(input: List<String>) { val sum = input .chunked(3) .sumOf { group -> group.map(String::toSortedSet) .reduce { acc, items -> acc.apply { retainAll(items) } } .map { priority(it) } .single() } println(sum) check(sum == 2716) } val testInput = readInput("day03/day03") part1(testInput) part2(testInput) part2fp(testInput) }
0
Kotlin
0
0
456bedb4d1082890d78490d3b730b2bb45913fe9
1,525
aoc-2022
Apache License 2.0
src/Day02.kt
dominik003
573,083,805
false
{"Kotlin": 9376}
fun main() { fun part1(input: List<String>): Int { val scoreMap = mapOf("X" to 1, "Y" to 2, "Z" to 3) val winMap = mapOf("X" to "C", "Y" to "A", "Z" to "B") val drawMap = mapOf("X" to "A", "Y" to "B", "Z" to "C") var score = 0 input.forEach { val parts = it.split(" ") val enemyChoice = parts[0] val myChoice = parts[1] score += scoreMap[myChoice]!! score += if (winMap[myChoice] == enemyChoice) 6 else 0 score += if (drawMap[myChoice] == enemyChoice) 3 else 0 } return score } fun part2(input: List<String>): Int { val resultScoreMap = mapOf("X" to 0, "Y" to 3, "Z" to 6) val winMap = mapOf("A" to 2, "B" to 3, "C" to 1) val drawMap = mapOf("A" to 1, "B" to 2, "C" to 3) val loseMap = mapOf("A" to 3, "B" to 1, "C" to 2) var score = 0 input.forEach { val parts = it.split(" ") val enemyChoice = parts[0] val result = parts[1] score += resultScoreMap[result]!! score += when (result) { "X" -> loseMap[enemyChoice]!! "Y" -> drawMap[enemyChoice]!! "Z" -> winMap[enemyChoice]!! else -> 0 } } return score } // test if implementation meets criteria from the description, like: val testInput = readInput(2, true) check(part1(testInput) == 15) print(part2(testInput)) check(part2(testInput) == 12) val input = readInput(2) println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
b64d1d4c96c3dd95235f604807030970a3f52bfa
1,645
advent-of-code-2022
Apache License 2.0
src/Day11.kt
buongarzoni
572,991,996
false
{"Kotlin": 26251}
fun solveDay11() { val input = readInputString("Day11") val monkeys = parseMonkeys(input) solve( monkeys = parseMonkeys(input), rounds = 20, message = "Solution for part 1: ", worryLevelOperation = { it / 3 }, ) val gcd = monkeys.map { it.testDivisibleBy }.reduce { acc, l -> acc*l } solve( monkeys = parseMonkeys(input), rounds = 10_000, message = "Solution for part 2: ", worryLevelOperation = { it % gcd }, ) } private fun solve( monkeys: List<Monkey>, rounds: Int, message: String, worryLevelOperation: (Long) -> Long, ) { repeat(rounds) { for (monkey in monkeys) { while (monkey.items.isNotEmpty()) { monkey.inspectedItems++ val item = monkey.items.removeFirst() val operator = if (monkey.operator == "old") item else monkey.operator.toLong() val result = when(monkey.operation) { "*" -> worryLevelOperation(item * operator) "+" -> worryLevelOperation(item + operator) else -> error("unexpected operation $operator") } if (result % monkey.testDivisibleBy == 0L) { monkeys[monkey.ifTrueThrowToMonkey].items.add(result) } else { monkeys[monkey.ifFalseThrowToMonkey].items.add(result) } } } } val sortedMonkeys = monkeys.sortedByDescending { it.inspectedItems } val monkeyBusiness = sortedMonkeys[0].inspectedItems * sortedMonkeys[1].inspectedItems println(message + monkeyBusiness) } private fun parseMonkeys(input: String) = input.split("\n\n").map { monkeyInput -> val monkey = Monkey() val lines = monkeyInput.split("\n") lines.forEach { line -> if (line.contains("Monkey")) { val monkeyNumber = line.substringAfter("Monkey ").removeSuffix(":").toInt() monkey.number = monkeyNumber } else if (line.contains("Starting")) { val startingItems = line.substringAfter("Starting items: ").split(", ") startingItems.forEach { monkey.items.add(it.toLong()) } } else if (line.contains("Operation")) { val (operation, operator) = line.substringAfter("Operation: new = old ").split(" ") monkey.operation = operation monkey.operator = operator } else if (line.contains("Test")) { val divisibleBy = line.substringAfter("Test: divisible by ").toLong() monkey.testDivisibleBy = divisibleBy } else if (line.contains("If true")) { val toMonkey = line.substringAfter("If true: throw to monkey ").toInt() monkey.ifTrueThrowToMonkey = toMonkey } else if (line.contains("If false")) { val toMonkey = line.substringAfter("If false: throw to monkey ").toInt() monkey.ifFalseThrowToMonkey = toMonkey } } monkey } data class Monkey( var number: Int = -1, var inspectedItems: Long = 0, val items: MutableList<Long> = mutableListOf(), var operation: String = "", var operator: String = "", var testDivisibleBy: Long = 0, var ifTrueThrowToMonkey: Int = 0, var ifFalseThrowToMonkey: Int = 0, )
0
Kotlin
0
0
96aadef37d79bcd9880dbc540e36984fb0f83ce0
3,335
AoC-2022
Apache License 2.0
src/Day05.kt
StephenVinouze
572,377,941
false
{"Kotlin": 55719}
fun main() { fun <T> List<List<T>>.rowToColumn(): List<List<T>> = first().indices .map { row -> indices.map { col -> this[col][row] } } fun List<List<Char>>.toTopStack(): String = map { it.last() }.joinToString("") fun parse(input: List<String>): Pair<List<MutableList<Char>>, List<List<String>>> { val (unformattedStacks, unformattedInstructions) = input.partition { it.contains('[') } val stackSize = unformattedInstructions.first() .last { it.isDigit() } .toString() .toInt() val stacks = unformattedStacks .dropLastWhile { !it.contains('[') } .map { // Drop first whitespace then take only stack char val stack = it.toCharArray().toList() .drop(1) .filterIndexed { index, _ -> index % 4 == 0 } .toMutableList() // Fill shorter stack lines with whitespaces so that we can flip the rows into columns // (we need each row to have same size) repeat((stackSize - stack.size)) { stack.add(' ') } stack } .rowToColumn() .map { // Reverse stacks to have top stack at the end of the list then remove useless whitespaces it.reversed() .filterNot { stack -> stack.isWhitespace() } .toMutableList() } val instructions = unformattedInstructions .drop(2) .map { instruction -> instruction .filter { it.isDigit() || it.isWhitespace() } .split(" ") .filter { it.isNotBlank() } } return Pair(stacks, instructions) } fun part1(input: List<String>): String { val (stacks, instructions) = parse(input) instructions.forEach { instruction -> val stacksToMove = instruction[0].toInt() val fromStack = stacks[instruction[1].toInt() - 1] val toStack = stacks[instruction[2].toInt() - 1] val movedItems = mutableListOf<Char>() val movingStacksCount = stacksToMove.coerceIn(0, fromStack.size) repeat(movingStacksCount) { val movedItem = fromStack[fromStack.lastIndex - it] toStack.add(movedItem) movedItems.add(movedItem) } repeat(movingStacksCount) { fromStack.removeLast() } } return stacks.toTopStack() } fun part2(input: List<String>): String { val (stacks, instructions) = parse(input) instructions.forEach { instruction -> val stacksToMove = instruction[0].toInt() val fromStack = stacks[instruction[1].toInt() - 1] val toStack = stacks[instruction[2].toInt() - 1] val movingStacksCount = stacksToMove.coerceIn(0, fromStack.size) val movingStacks = fromStack.slice((fromStack.size - movingStacksCount).. fromStack.lastIndex) toStack.addAll(movingStacks) repeat(movingStacksCount) { fromStack.removeLast() } } return stacks.toTopStack() } val testInput = readInput("Day05_test") check(part1(testInput) == "CMZ") check(part2(testInput) == "MCD") val input = readInput("Day05") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
11b9c8816ded366aed1a5282a0eb30af20fff0c5
3,547
AdventOfCode2022
Apache License 2.0
archive/src/main/kotlin/com/grappenmaker/aoc/year21/Day04.kt
770grappenmaker
434,645,245
false
{"Kotlin": 409647, "Python": 647}
package com.grappenmaker.aoc.year21 import com.grappenmaker.aoc.PuzzleSet import kotlin.math.floor // 5x5 const val BOARD_SIZE = 5 val spacePattern = """\s+""".toRegex() fun PuzzleSet.day4() = puzzle(day = 4) { // Part one val lines = inputLines // Read numbers val numbers = lines.first().split(",").map { it.toInt() } // Read boards val boardsText = lines.joinToString("\n").substringAfter("\n\n").split("\n\n") val boards = boardsText.asSequence() .map { b -> b.trim().lines() .flatMap { it.trim().split(spacePattern) } .mapIndexed { i, s -> Cell(s.toInt(), i) } } .map { Board(it.toTypedArray()) }.toSet() // Simulate game val game = Game(numbers, boards) partOne = (game.getEventualWinner()!!.score * game.lastNumber).s() // Part two game.reset() val lastWinner = game.getRanking().last() partTwo = (game.lastNumber * lastWinner.score).s() } class Game(private val numbers: List<Int>, private val boards: Set<Board>) { var lastNumber = 0 private set private var index = 0 private fun step() { if (index >= numbers.size) return this.lastNumber = numbers[index] boards.forEach { it.mark(lastNumber) } index++ } fun getEventualWinner(): Board? { for (i in numbers) { step() val winner = getWinners().firstOrNull() if (winner != null) return winner } return null } fun getRanking(): List<Board> { val boardsLeft = boards.toMutableSet() val result = mutableListOf<Board>() for (i in numbers) { step() val newWinners = boardsLeft.filter { it.hasWon() } result.addAll(newWinners) boardsLeft.removeAll(newWinners.toSet()) if (boardsLeft.isEmpty()) break } return result } fun reset() { this.index = 0 boards.forEach { it.reset() } } private fun getWinners() = boards.filter { it.hasWon() } } class Board(private val cells: Array<Cell>) { private val rows get() = (0 until BOARD_SIZE).map { i -> cells.filter { it.getX() == i } } private val cols get() = (0 until BOARD_SIZE).map { i -> cells.filter { it.getY() == i } } val score get() = cells.filter { !it.marked }.sumOf { it.number } fun hasWon(): Boolean { val checkAll: (List<Cell>) -> Boolean = { it.all { c -> c.marked } } return rows.any(checkAll) || cols.any(checkAll) } fun mark(num: Int) = cells.filter { it.number == num }.forEach { it.marked = true } fun reset() = cells.forEach { it.marked = false } } data class Cell(val number: Int, val index: Int, var marked: Boolean = false) { fun getX() = index % BOARD_SIZE fun getY() = floor(index / BOARD_SIZE.toDouble()).toInt() }
0
Kotlin
0
7
92ef1b5ecc3cbe76d2ccd0303a73fddda82ba585
2,894
advent-of-code
The Unlicense
src/main/kotlin/com/ginsberg/advent2019/Day12.kt
tginsberg
222,116,116
false
null
/* * Copyright (c) 2019 by <NAME> */ /** * Advent of Code 2019, Day 12 - The N-Body Problem * Problem Description: http://adventofcode.com/2019/day/12 * Blog Post/Commentary: https://todd.ginsberg.com/post/advent-of-code/2019/day12/ */ package com.ginsberg.advent2019 import org.apache.commons.math3.util.ArithmeticUtils.lcm class Day12(input: List<String>) { private val moons: List<Moon> = parseInput(input) private val moonPairs: List<Pair<Moon, Moon>> = moons.everyPair() fun solvePart1(steps: Int): Int { repeat(steps) { step() } return moons.sumBy { it.energy() } } fun solvePart2(): Long { val startingX: List<Pair<Int, Int>> = moons.map { it.position.x to it.velocity.x } val startingY: List<Pair<Int, Int>> = moons.map { it.position.y to it.velocity.y } val startingZ: List<Pair<Int, Int>> = moons.map { it.position.z to it.velocity.z } var foundX: Long? = null var foundY: Long? = null var foundZ: Long? = null var stepCount = 0L do { stepCount += 1 step() foundX = if (foundX == null && startingX == moons.map { it.position.x to it.velocity.x }) stepCount else foundX foundY = if (foundY == null && startingY == moons.map { it.position.y to it.velocity.y }) stepCount else foundY foundZ = if (foundZ == null && startingZ == moons.map { it.position.z to it.velocity.z }) stepCount else foundZ } while (foundX == null || foundY == null || foundZ == null) return lcm(foundX, lcm(foundY, foundZ)) } private fun step() { moonPairs.forEach { it.first.applyGravity(it.second) it.second.applyGravity(it.first) } moons.forEach { it.applyVelocity() } } private fun parseInput(input: List<String>): List<Moon> = input.map { line -> line.replace("""[^-\d,]""".toRegex(), "") .split(",") .map { it.toInt() } }.map { Moon(Vector3D(it[0], it[1], it[2])) } data class Moon(var position: Vector3D, var velocity: Vector3D = Vector3D.ZERO) { fun applyGravity(other: Moon) { this.velocity += (this.position diff other.position) } fun applyVelocity() { position += velocity } fun energy(): Int = position.abs * velocity.abs } }
0
Kotlin
2
23
a83e2ecdb6057af509d1704ebd9f86a8e4206a55
2,451
advent-2019-kotlin
Apache License 2.0
src/Day01.kt
ChristianNavolskyi
573,154,881
false
{"Kotlin": 29804}
import kotlin.math.max import kotlin.time.ExperimentalTime import kotlin.time.measureTime @ExperimentalTime fun main() { fun part1(input: List<String>): Int { return input.toMutableList().apply { add("") }.fold(listOf(-1, 0)) { acc, calories -> if (calories.isEmpty()) { listOf(max(acc[0], acc[1]), 0) } else { listOf(acc[0], acc[1] + (calories.toIntOrNull() ?: 0)) } }[0] } fun part2(input: List<String>): Int { val output = input.toMutableList().apply { add("") }.fold(listOf(-1, -1, -1, 0)) { acc, calories -> if (calories.isEmpty()) { val sum = acc[3] if (sum > acc[0]) { listOf(sum, acc[0], acc[1], 0) } else if (sum > acc[1]) { listOf(acc[0], sum, acc[1], 0) } else if (sum > acc[2]) { listOf(acc[0], acc[1], sum, 0) } else { listOf(acc[0], acc[1], acc[2], 0) } } else { listOf(acc[0], acc[1], acc[2], acc[3] + (calories.toIntOrNull() ?: 0)) } } return output[0] + output[1] + output[2] } // test if implementation meets criteria from the description, like: val testInput = readLines("Day01_test") check(part1(testInput) == 24000) check(part2(testInput) == 45000) val input = readLines("Day01") val first: Int val second: Int val taskTime = measureTime { first = part1(input) second = part2(input) } println("Task took: $taskTime to compute part 1 ($first) and part 2 ($second)") val times = 1 val firstTime = measureTime { repeat(times) { part1(input) } }.div(times) val secondTime = measureTime { repeat(times) { part2(input) } }.div(times) println("Times") println("First part took: $firstTime") println("Second part took: $secondTime") }
0
Kotlin
0
0
222e25771039bdc5b447bf90583214bf26ced417
1,990
advent-of-code-2022
Apache License 2.0
src/exercises/Day15.kt
Njko
572,917,534
false
{"Kotlin": 53729}
// ktlint-disable filename package exercises import readInput import kotlin.math.abs data class Scan( val sensorAtX: Int, val sensorAtY: Int, val closestBeaconAtX: Int, val closestBeaconAtY: Int, val distance: Int ) fun main() { fun extractScans(data: List<String>): List<Scan> { val pattern = "^.* x=(-?\\d*), y=(-?\\d*).* x=(-?\\d*), y=(-?\\d*)\$".toRegex() val scans = mutableListOf<Scan>() for (line in data) { pattern.findAll(line).forEach { matchResult -> val sensorAtX = matchResult.groupValues[1].toInt() val sensorAtY = matchResult.groupValues[2].toInt() val closestBeaconAtX = matchResult.groupValues[3].toInt() val closestBeaconAtY = matchResult.groupValues[4].toInt() val distanceX = abs(closestBeaconAtX - sensorAtX) val distanceY = abs(closestBeaconAtY - sensorAtY) scans.add( Scan( sensorAtX = sensorAtX, sensorAtY = sensorAtY, closestBeaconAtX = closestBeaconAtX, closestBeaconAtY = closestBeaconAtY, distance = distanceX + distanceY ) ) } } return scans } fun part1(input: List<String>, lineScanned: Int): Int { val scans = extractScans(input) val beaconsRangeIntersectsLine = scans.filter { (it.sensorAtY - it.distance..it.sensorAtY + it.distance).contains(lineScanned) } val intersection = mutableSetOf<Int>() beaconsRangeIntersectsLine.forEach { scan -> val xDistance = scan.distance - abs(lineScanned - scan.sensorAtY) val xRange = scan.sensorAtX - xDistance..scan.sensorAtX + xDistance xRange.forEach { intersection.add(it) } } return intersection.size - 1 } fun findLineWithHole(scans: List<Scan>, gridSize: Int): Int { for (lineIndex in 0..gridSize) { val beaconsRangeIntersectsLine = scans.filter { (it.sensorAtY - it.distance..it.sensorAtY + it.distance).contains(lineIndex) } val intersection = mutableSetOf<Int>() beaconsRangeIntersectsLine.forEach { scan -> val xDistance = (scan.distance - abs(lineIndex - scan.sensorAtY)) val xMin = (scan.sensorAtX - xDistance).coerceIn(0..gridSize) val xMax = (scan.sensorAtX + xDistance).coerceIn(0..gridSize) val xRange = xMin..xMax xRange.forEach { intersection.add(it) } } if (intersection.size - 1 != gridSize) { return lineIndex } } return -1 } fun findPositionOfHole(scans: List<Scan>, gridSize: Int, y: Int): Int { return 14 } fun part2(input: List<String>, gridSize: Int): Int { val scans = extractScans(input) val y = findLineWithHole(scans, gridSize) // too slow val x = findPositionOfHole(scans, gridSize, y) return y } // test if implementation meets criteria from the description, like: val testInput = readInput("Day15_test") println("Test results:") // println(part1(testInput, 10)) // check(part1(testInput) == 26) // println(part2(testInput, 20)) // check(part2(testInput) == 56000011) val input = readInput("Day15") val startTime = System.currentTimeMillis() println("Final results:") println(part1(input, 2000000)) val endOfPart1 = System.currentTimeMillis() println("ended part 1 in ${endOfPart1 - startTime} ms") // check(part1(input) == 5525990) println(part2(input, 4000000)) // check(part2(input) == 0) println("End") }
0
Kotlin
0
2
68d0c8d0bcfb81c183786dfd7e02e6745024e396
3,933
advent-of-code-2022
Apache License 2.0
src/Day04.kt
asm0dey
572,860,747
false
{"Kotlin": 61384}
fun main() { fun rangeToSet(textRange: List<String>) = (textRange[0].toInt()..textRange[1].toInt()).toSet() fun part1(input: List<String>): Int { return input .asSequence() .map { it.split(',') } .filter { it.size == 2 } .map { it.map { range -> range.split('-') } } .map { (r1, r2) -> rangeToSet(r1) to rangeToSet(r2) } .count { (x, y) -> x.containsAll(y) || y.containsAll(x) } } fun part2(input: List<String>): Int { return input .asSequence() .map { it.split(',') } .filter { it.size == 2 } .map { it.map { range -> range.split('-') } } .map { (r1, r2) -> rangeToSet(r1) to rangeToSet(r2) } .count { (x, y) -> (x intersect y).isNotEmpty() } } val testInput = readInput("Day04_test") check(part1(testInput) == 2) val input = readInput("Day04") println(part1(input)) println(part2(input)) }
1
Kotlin
0
1
f49aea1755c8b2d479d730d9653603421c355b60
996
aoc-2022
Apache License 2.0
2023/src/main/kotlin/day10.kt
madisp
434,510,913
false
{"Kotlin": 388138}
import utils.Grid import utils.MutableIntGrid import utils.Parser import utils.Solution import utils.Vec2i import utils.borderWith import utils.expand import utils.map import utils.toMutable fun main() { Day10.run() } private fun guessStart(g: Grid<Char>, s: Vec2i): List<Char> { val up = s.y > 2 && g[s.x][s.y - 2] == '|' val down = s.y < g.height - 2 && g[s.x][s.y + 2] == '|' val left = s.x > 2 && g[s.x - 2][s.y] == '-' val right = s.x < g.width - 2 && g[s.x + 2][s.y] == '-' return buildList { if (up && down) add('|') if (left && right) add('-') if (up && right) add('L') if (up && left) add('J') if (left && down) add('7') if (right && down) add('F') } } private val EXPAND = mapOf( '|' to Parser.charGrid(".|.\n.|.\n.|."), '-' to Parser.charGrid("...\n---\n..."), 'L' to Parser.charGrid(".|.\n.L-\n..."), 'J' to Parser.charGrid(".|.\n-J.\n..."), '7' to Parser.charGrid("...\n-7.\n.|."), 'F' to Parser.charGrid("...\n.F-\n.|."), '.' to Parser.charGrid("...\n...\n..."), 'S' to Parser.charGrid("SSS\nSSS\nSSS"), ) object Day10 : Solution<Pair<Vec2i, Grid<Char>>>() { override val name = "day10" override val parser: Parser<Pair<Vec2i, Grid<Char>>> = Parser.charGrid .map { g -> g.expand(3) { _, c -> EXPAND[c]!! } } .map { g -> val startLocation = (0 until g.width / 3).asSequence().flatMap { x -> (0 until g.height / 3).asSequence().map { y -> Vec2i(x, y) } }.map { (it * 3) + 1 }.first { g[it] == 'S' } val startOpts = guessStart(g, startLocation) require(startOpts.size == 1) { //TODO(madis) what if this doesn't hold true? "Grid has more than 1 start options: $startOpts" } val ret = g.toMutable() val start = EXPAND[startOpts.first()]!! start.cells.forEach { (p, c) -> ret[p + startLocation + Vec2i(-1, -1)] = c } startLocation to ret } private val NEXT = mapOf( '|' to listOf(Vec2i.UP, Vec2i.DOWN), '-' to listOf(Vec2i.LEFT, Vec2i.RIGHT), 'L' to listOf(Vec2i.UP, Vec2i.RIGHT), 'J' to listOf(Vec2i.UP, Vec2i.LEFT), '7' to listOf(Vec2i.LEFT, Vec2i.DOWN), 'F' to listOf(Vec2i.DOWN, Vec2i.RIGHT), ) data class QueueItem( val p: Vec2i, val c: Char, val s: Int ) private fun computeVisited(): MutableIntGrid { val (start, g) = input val visited = MutableIntGrid(IntArray(g.width * g.height / 9) { -1 }, g.width / 3, g.height / 3) val q = ArrayDeque(listOf(QueueItem(start, g[start], 0))) while (q.isNotEmpty()) { val p = q.removeFirst() visited[p.p / 3] = p.s NEXT[p.c]?.map { p.p + it * 3 } ?.filter { it.x >= 0 && it.y >= 0 && it.x < g.width && it.y < g.height } ?.filter { visited[it / 3] == -1 } ?.forEach { q.add(QueueItem(it, g[it], p.s + 1)) } } return visited } override fun part1(input: Pair<Vec2i, Grid<Char>>): Int { return computeVisited().values.max() } override fun part2(input: Pair<Vec2i, Grid<Char>>): Int { val visited = computeVisited().borderWith(-1) val expandedInput = input.second.borderWith('.', 3).map(Grid.OobBehaviour.Throw()) { p, c -> if (visited[p / 3] == -1) '.' else c }.toMutable() val start = Vec2i(0, 0) val q = ArrayDeque(listOf(start)) while (q.isNotEmpty()) { val p = q.removeLast() expandedInput[p] = 'x' p.adjacent .filter { it.x >= 0 && it.y >= 0 && it.x < expandedInput.width && it.y < expandedInput.height } .filter { expandedInput[it] == '.' } .forEach { q.add(it) } } var count = 0 (0 until expandedInput.width / 3).forEach { x -> (0 until expandedInput.height / 3).forEach { y -> val expandedCoords = (3 * x until 3 * x + 3).flatMap { ex -> (3 * y until 3 * y + 3).map { ey -> Vec2i(ex, ey) } } if (expandedCoords.all { expandedInput[it] == '.' }) { count++ } } } return count } }
0
Kotlin
0
1
3f106415eeded3abd0fb60bed64fb77b4ab87d76
4,056
aoc_kotlin
MIT License
y2021/src/main/kotlin/adventofcode/y2021/Day08.kt
Ruud-Wiegers
434,225,587
false
{"Kotlin": 503769}
package adventofcode.y2021 import adventofcode.io.AdventSolution object Day08 : AdventSolution(2021, 8, "Seven Segment Search") { override fun solvePartOne(input: String) = parseInput(input).flatMap(DecodingProblem::message).count { it.size in listOf(2, 3, 4, 7) } override fun solvePartTwo(input: String) = parseInput(input).sumOf { (digits, message) -> val patterns = digits.sortDigitPatterns() message.map(patterns::indexOf).joinToString("").toInt() } private fun parseInput(input: String) = input.lineSequence().map { val (digits, message) = it.split(" | ").map { list -> list.split(" ").map(String::toSet) } DecodingProblem(digits, message) } private fun Collection<Set<Char>>.sortDigitPatterns(): List<SegmentEncodedDigit> { val one = single { it.size == 2 } val four = single { it.size == 4 } val seven = single { it.size == 3 } val eight = single { it.size == 7 } val bottomLeftSegment = ('a'..'g').single { segment -> count { segment in it } == 4 } val fiveSegments = filter { it.size == 5 } val two = fiveSegments.single { bottomLeftSegment in it } val three = fiveSegments.single { (it intersect one).size == 2 } val five = fiveSegments.single { it != two && it != three } val sixSegments = filter { it.size == 6 } val six = sixSegments.single { (it intersect one).size == 1 } val nine = sixSegments.single { bottomLeftSegment !in it } val zero = sixSegments.single { it != six && it != nine } return listOf(zero, one, two, three, four, five, six, seven, eight, nine) } } private data class DecodingProblem(val digitPatterns: List<SegmentEncodedDigit>, val message: List<SegmentEncodedDigit>) private typealias SegmentEncodedDigit = Set<Char>
0
Kotlin
0
3
fc35e6d5feeabdc18c86aba428abcf23d880c450
1,844
advent-of-code
MIT License
y2023/src/main/kotlin/adventofcode/y2023/Day21.kt
Ruud-Wiegers
434,225,587
false
{"Kotlin": 503769}
package adventofcode.y2023 import adventofcode.io.AdventSolution import adventofcode.util.vector.Vec2 import adventofcode.util.vector.neighbors fun main() { Day21.solve() } object Day21 : AdventSolution(2023, 21, "Step Counter") { override fun solvePartOne(input: String): Int { val path = parse(input) return solve(path.keys, path.filterValues { it == 'S' }.keys.first(), 64) } fun brute(input: String, steps: Int): Int { val path = parse(input) return solve(path.keys, path.filterValues { it == 'S' }.keys.first(), steps) } override fun solvePartTwo(input: String): Long { /* notes on the input: S is in the middle of a 131*131 plot S has a clear view NESW the outer edge is clear too so we can disregard the interior so you can draw a diamond with radius 2mid013mid, and that's more or less correct use checkerboarding to count filled squares use pathfinding for the perimeter */ val steps = 26501365L val length = 131 return solve(input, length, steps) } fun solve(input: String, length: Int, steps: Long): Long { val path = parse(input).keys val pos = SidePositions(length) var count = 0L val evens = solve(path, pos.middle, length * 2 + 2).toLong() val odds = solve(path, pos.middle, length * 2 + 1).toLong() val countInner = ((steps + length) / length / 2 * 2 - 1).let { it * it } val countOuter = ((steps) / length / 2 * 2).let { it * it } val stepParity = steps % 2 == 0L count += countInner * if (stepParity) evens else odds count += countOuter * if (stepParity) odds else evens //this only works if we're beyond halfway traversing an endpoint (otherwise the block just before the endpoint is also incomplete) val a = (steps % length + length / 2).toInt() val endpoints = listOf(pos.n, pos.e, pos.s, pos.w).map { solve(path, it, a).toLong() } count += endpoints.sum() val b = ((steps + length - 1) % (length * 2)).toInt() val diagonals1 = listOf(pos.nw, pos.ne, pos.se, pos.sw).map { solve(path, it, b).toLong() } val diagonal1Count = (steps + length - 1) / length / 2 * 2 - 1 count += diagonal1Count * diagonals1.sum() val c = ((steps - 1) % (length * 2)).toInt() val diagonals2 = listOf(pos.nw, pos.ne, pos.se, pos.sw).map { solve(path, it, c).toLong() } val diagonal2Count = (steps - 1) / length / 2 * 2 count += diagonal2Count * diagonals2.sum() return count } } data class SidePositions(val length: Int) { private val f = 0 private val m = length / 2 private val l = length - 1 val middle = Vec2(m, m) val nw = Vec2(f, f) val n = Vec2(m, f) val ne = Vec2(l, f) val e = Vec2(l, m) val se = Vec2(l, l) val s = Vec2(m, l) val sw = Vec2(f, l) val w = Vec2(f, m) } private fun solve(path: Set<Vec2>, initial: Vec2, steps: Int): Int { val reached = mutableSetOf<Vec2>() generateSequence(setOf(initial)) { open -> open .flatMap { it.neighbors().filter { it in path } }.filter { it !in reached }.toSet().also { reached += it } }.takeWhile { it.isNotEmpty() }.take(steps+1).count() return reached.count { (it.x + it.y + initial.x + initial.y + steps) %2 ==0 } } private fun parse(input: String): Map<Vec2, Char> = input.lines() .flatMapIndexed { y, line -> line.withIndex() .map { (x, value) -> Vec2(x, y) to value } } .toMap().filterValues { it != '#' }
0
Kotlin
0
3
fc35e6d5feeabdc18c86aba428abcf23d880c450
3,676
advent-of-code
MIT License
src/Day06.kt
paul-matthews
433,857,586
false
{"Kotlin": 18652}
fun List<String>.getLanternfish(): Shoal = fold(mutableListOf()) {acc, s -> acc.addAll(s.split(",").toInts()) acc } typealias GroupedShoal = Map<Int, Long> fun Shoal.toGroupedShoal(): GroupedShoal = fold(mutableMapOf()) { acc, fish -> acc[fish] = (acc.get(fish) ?: 0L) + 1 acc } fun GroupedShoal.newDay(): GroupedShoal { val day = mutableMapOf<Int, Long>() map {(k, v) -> var newK = k - 1 if(newK < 0) { newK = 6 day[8] = v } day[newK] = (day.get(newK) ?: 0L) + v } return day } fun GroupedShoal.applyDays(numDays: Int): GroupedShoal { var newShoal = this for (d in 1..numDays) { newShoal = newShoal.newDay() } return newShoal } typealias Fish = Int typealias Shoal = List<Fish> fun main() { fun part1(input: List<String>) = input.getLanternfish().toGroupedShoal().applyDays(80).values.sum() fun part2(input: List<String>): Long = input.getLanternfish().toGroupedShoal().applyDays(256).values.sum() val testInput = readFileContents("Day06_test") val part1Result = part1(testInput) check(part1Result == 5934L) { "Expected: 5934 but found $part1Result" } val part2Result = part2(testInput) check((part2Result) == 26984457539) { "Expected 26984457539 but is: $part2Result" } val input = readFileContents("Day06") println("Part1: " + part1(input)) println("Part2: " + part2(input)) }
0
Kotlin
0
0
2f90856b9b03294bc279db81c00b4801cce08e0e
1,459
advent-of-code-kotlin-template
Apache License 2.0
src/Day04.kt
Akaneiro
572,883,913
false
null
fun main() { fun List<String>.makeIntervals() = this .map {// convert to list of intervals like listOf([2,3,4], [6,7,8]) it.split(",") .map { val values = it.split("-") val intRange = values.first().toInt()..values.last().toInt() val array = intRange.toList() array } } .map { it.first() to it.last() } // make pairs like ([2,3,4] to [6,7,8]) fun part1(input: List<String>): Int { return input .makeIntervals() .count { (firstInterval, secondInterval) -> val intersection = firstInterval.intersect(secondInterval.toSet()) intersection.size == firstInterval.size || intersection.size == secondInterval.size } } fun part2(input: List<String>): Int { return input .makeIntervals() .count { it.first.intersect(it.second.toSet()).isNotEmpty() } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day04_test") check(part1(testInput) == 2) check(part2(testInput) == 4) val input = readInput("Day04") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
f987830a70a2a1d9b88696271ef668ba2445331f
1,343
aoc-2022
Apache License 2.0
src/aoc2022/day02/AoC02.kt
Saxintosh
576,065,000
false
{"Kotlin": 30013}
package aoc2022.day02 import readLines enum class Hand { Rock, Paper, Scissors; val value = ordinal + 1 companion object { infix fun from(ch: Char) = when (ch) { 'A', 'X' -> Rock 'B', 'Y' -> Paper else -> Scissors } } fun circularNext() = values()[(ordinal + 1) % values().size] fun circularPrev() = values()[(ordinal + values().size - 1) % values().size] fun winningHand() = circularNext() fun loosingHand() = circularPrev() } const val LOSE = 0 const val DRAW = 3 const val WIN = 6 fun game1(a: Char, b: Char): Int { val elfHand = Hand from a val myHand = Hand from b val res = when { elfHand == myHand -> DRAW elfHand.winningHand() == myHand -> WIN else -> LOSE } return res + myHand.value } fun game2(a: Char, b: Char): Int { val sx = Hand from a var res = 0 res += when (b) { 'X' -> LOSE + sx.loosingHand().value 'Y' -> DRAW + sx.value else -> WIN + sx.winningHand().value } return res } fun main() { operator fun String.component1() = this[0] operator fun String.component2() = this[2] fun part1(list: List<String>): Int { return list.sumOf { val (a, b) = it game1(a, b) } } fun part2(list: List<String>): Int { return list.sumOf { val (a, b) = it game2(a, b) } } readLines(15, 12, ::part1, ::part2) }
0
Kotlin
0
0
877d58367018372502f03dcc97a26a6f831fc8d8
1,347
aoc2022
Apache License 2.0
src/year_2022/day_05/Day05.kt
scottschmitz
572,656,097
false
{"Kotlin": 240069}
package year_2022.day_05 import readInput data class Rearrangement( val quantity: Int, val from: Int, val to: Int ) object Day05 { /** * @return */ fun solutionOne(text: List<String>): String { val stacks = parseContainers(text) val rearrangements = parseRearrangements(text) rearrangements.forEach { rearrangement -> for (i in 0 until rearrangement.quantity) { val topContainer = stacks[rearrangement.from]!!.removeLast() stacks[rearrangement.to]!!.add(topContainer) } } var message = "" stacks.forEach { (_, containers) -> message += containers.last() } return message } /** * @return */ fun solutionTwo(text: List<String>): String { val stacks = parseContainers(text) val rearrangements = parseRearrangements(text) rearrangements.forEach { rearrangement -> val fromStack = stacks[rearrangement.from]!! val toStack = stacks[rearrangement.to]!! val toMove = mutableListOf<Char>() for (i in 0 until rearrangement.quantity) { toMove.add(fromStack.removeLast()) } toStack.addAll(toMove.reversed()) } var message = "" stacks.forEach { (_, containers) -> message += containers.last() } return message } private fun parseContainers(text: List<String>): Map<Int, MutableList<Char>> { val blankLine = text.indexOfFirst { it.isEmpty() } val stacksText = text[blankLine -1] val stackPositions = stacksText.mapIndexedNotNull { index, c -> if (c.isDigit()) { c.digitToInt() to index } else { null } }.toMap() val stacks = mutableMapOf<Int, MutableList<Char>>() for (i in blankLine - 1 downTo 0) { val line = text[i] stackPositions.forEach { (stackId, index) -> if (line.length >= index) { val container = line[index] if (container.isLetter()) { if (stacks[stackId] == null) { stacks[stackId] = mutableListOf<Char>() } stacks[stackId]!!.add(container) } } } } return stacks } private fun parseRearrangements(text: List<String>): List<Rearrangement> { val rearrangements = mutableListOf<Rearrangement>() text.forEach { line -> if (line.startsWith("move")) { // is a rearrangement val parts = line.split(" ") rearrangements.add( Rearrangement( quantity = parts[1].toInt(), from = parts[3].toInt(), to = parts[5].toInt() ) ) } } return rearrangements } } fun main() { val inputText = readInput("year_2022/day_05/Day06.txt") val solutionOne = Day05.solutionOne(inputText) println("Solution 1: $solutionOne") val solutionTwo = Day05.solutionTwo(inputText) println("Solution 2: $solutionTwo") }
0
Kotlin
0
0
70efc56e68771aa98eea6920eb35c8c17d0fc7ac
3,362
advent_of_code
Apache License 2.0
dcp_kotlin/src/main/kotlin/dcp/day264/day264.kt
sraaphorst
182,330,159
false
{"C++": 577416, "Kotlin": 231559, "Python": 132573, "Scala": 50468, "Java": 34742, "CMake": 2332, "C": 315}
package dcp.day264 // day264.kt // By <NAME>, 2019. import kotlin.math.pow // Generate k-ary deBruijn sequences covering words of length n. // We don't bother using an alphabet: this can just be mapped back and forth if wanted, and we switched k for n. fun deBruijn(k: Int, n: Int): List<Int> { // Generate all the Lyndon words via Duval's 1988 Algorithm. // A Lyndon word is a nonempty string that is strictly smaller in lexicographic order than all its rotations. // A k-ary Lyndon word of length n > 0 is an n-character string over an alphabet of size k. // Here we generate all k-ary Lyndon words of length < n in lexicographic order, from the algorithm in Wikipedia. val lyndon: Sequence<List<Int>> = sequence { val word = mutableListOf(-1) while (word.isNotEmpty()) { // We set up to start with the lexicographically smallest word. // 3. Replace the final remaining symbol of word by its successor in the sorted ordering of the alphabet. word[word.size - 1] += 1 // Output yield(word.toList()) // 1. Repeat the symbols from word to form a new word of length exactly n, where the ith symbol of the new // word it the same as the symbol at position i mod len(word) of word. val m = word.size while (word.size < n) word.add(word[word.size - m]) // 2. As long as the final symbol of word is the last symbol in the sorted ordering of the alphabet, remove it. while (word.isNotEmpty() && word.last() == k - 1) word.removeAt(word.size - 1) } } // A de Bruijn sequence can be generated by concatenating all the Lyndon k-ary words of length at most n // whose length divides n listed in lexicographic order. return lyndon.filter { n % it.size == 0 }.flatten().toList() } // The length of a k-ary de Bruijn sequence with words of length n. fun deBruinLength(k: Int, n: Int): Int = (k.toDouble().pow(n)).toInt() fun covered(k: Int, n: Int, lst: List<Int>): Boolean { // Convert each word into a set, and then into an Int to mark it as covered. // We double the elements so we don't have to cycle. val noncyclingList = (lst + lst) val sz = lst.size return (0 until sz). map { i -> (0 until n).map { noncyclingList[i+it] * k.toDouble().pow(it).toInt() }.sum() }. toSet().size == deBruinLength(k, n) }
0
C++
1
0
5981e97106376186241f0fad81ee0e3a9b0270b5
2,481
daily-coding-problem
MIT License
kotlinLeetCode/src/main/kotlin/leetcode/editor/cn/[56]合并区间.kt
maoqitian
175,940,000
false
{"Kotlin": 354268, "Java": 297740, "C++": 634}
import java.lang.Integer.compare import java.util.* //以数组 intervals 表示若干个区间的集合,其中单个区间为 intervals[i] = [starti, endi] 。请你合并所有重叠的区间,并返 //回一个不重叠的区间数组,该数组需恰好覆盖输入中的所有区间。 // // // // 示例 1: // // //输入:intervals = [[1,3],[2,6],[8,10],[15,18]] //输出:[[1,6],[8,10],[15,18]] //解释:区间 [1,3] 和 [2,6] 重叠, 将它们合并为 [1,6]. // // // 示例 2: // // //输入:intervals = [[1,4],[4,5]] //输出:[[1,5]] //解释:区间 [1,4] 和 [4,5] 可被视为重叠区间。 // // // // 提示: // // // 1 <= intervals.length <= 104 // intervals[i].length == 2 // 0 <= starti <= endi <= 104 // // Related Topics 数组 排序 // 👍 1002 👎 0 //leetcode submit region begin(Prohibit modification and deletion) class Solution { fun merge(intervals: Array<IntArray>): Array<IntArray> { //排序 时间复杂度 O(nlogn) Arrays.sort(intervals) { a: IntArray, b: IntArray -> a[0] - b[0] } //使用链表了来保存每个子集值 var mergeLink = LinkedList<IntArray>() for (interval in intervals){ //返回结果链表为空 //或者链表的大区间小于当前区间的小区间 //当前数组没有重合 if(mergeLink.isEmpty() || mergeLink.last[1] < interval[0]){ mergeLink.add(interval) }else{ //区间有重复 合并区间值 mergeLink.last[1] = Math.max(mergeLink.last[1],interval[1]) } } return mergeLink.toTypedArray() } } //leetcode submit region end(Prohibit modification and deletion)
0
Kotlin
0
1
8a85996352a88bb9a8a6a2712dce3eac2e1c3463
1,756
MyLeetCode
Apache License 2.0
src/Day12.kt
szymon-kaczorowski
572,839,642
false
{"Kotlin": 45324}
fun main() { data class Node( val letter: Char, var visited: Boolean = false, var shortest: Int = Int.MAX_VALUE, ) fun canMove(current: Char, next: Char): Boolean { if (current == 'S' && next == 'a') return true if (current == 'z' && next == 'E') return true if (next != 'E' && next - current <= 1) return true return false } fun part1(input: List<String>): Int { val graph = input.map { it.toCharArray().map { Node(it) }.toMutableList() }.toMutableList() var start: Pair<Int, Int> = -10 to -10 var end: Pair<Int, Int> = -10 to -10 graph.forEachIndexed { row, nodes -> nodes.forEachIndexed() { column, node -> if (node.letter == 'S') { start = row to column } if (node.letter == 'E') { end = row to column } } } val queue = mutableListOf<Pair<Int, Int>>() graph[start.first][start.second].shortest = 0 queue.add(start) while (queue.isNotEmpty()) { val (row, column) = queue.removeFirst() val current = graph[row][column] if (!current.visited) { current.visited = true if (row - 1 in graph.indices) { val potentialNext = graph[row - 1][column] if (!potentialNext.visited) { val letter = potentialNext.letter if (canMove(current.letter, letter)) { potentialNext.shortest = minOf(potentialNext.shortest, current.shortest + 1) queue.add((row - 1) to column) } } } if (row + 1 in graph.indices) { val potentialNext = graph[row + 1][column] if (!potentialNext.visited) { val letter = potentialNext.letter if (canMove(current.letter, letter)) { potentialNext.shortest = minOf(potentialNext.shortest, current.shortest + 1) queue.add((row + 1) to column) } } } if (column + 1 in graph[row].indices) { val potentialNext = graph[row][column + 1] if (!potentialNext.visited) { val letter = potentialNext.letter if (canMove(current.letter, letter)) { potentialNext.shortest = minOf(potentialNext.shortest, current.shortest + 1) queue.add((row) to column + 1) } } } if (column - 1 in graph[row].indices) { val potentialNext = graph[row][column - 1] if (!potentialNext.visited) { val letter = potentialNext.letter if (canMove(current.letter, letter)) { potentialNext.shortest = minOf(potentialNext.shortest, current.shortest + 1) queue.add((row) to column - 1) } } } } } return graph[end.first][end.second].shortest.also { println(it) } } fun part2(input: List<String>): Int { val graph = input.map { it.toCharArray().map { Node(it) }.toMutableList() }.toMutableList() var starts = mutableListOf<Pair<Int, Int>>() var end: Pair<Int, Int> = -10 to -10 graph.forEachIndexed { row, nodes -> nodes.forEachIndexed() { column, node -> if (node.letter == 'a') { starts.add(row to column) } if (node.letter == 'E') { end = row to column } } } val queue = mutableListOf<Pair<Int, Int>>() for (start in starts) { graph[start.first][start.second].shortest = 0 queue.add(start) } while (queue.isNotEmpty()) { val (row, column) = queue.removeFirst() val current = graph[row][column] if (!current.visited) { current.visited = true if (row - 1 in graph.indices) { val potentialNext = graph[row - 1][column] if (!potentialNext.visited) { val letter = potentialNext.letter if (canMove(current.letter, letter)) { potentialNext.shortest = minOf(potentialNext.shortest, current.shortest + 1) queue.add((row - 1) to column) } } } if (row + 1 in graph.indices) { val potentialNext = graph[row + 1][column] if (!potentialNext.visited) { val letter = potentialNext.letter if (canMove(current.letter, letter)) { potentialNext.shortest = minOf(potentialNext.shortest, current.shortest + 1) queue.add((row + 1) to column) } } } if (column + 1 in graph[row].indices) { val potentialNext = graph[row][column + 1] if (!potentialNext.visited) { val letter = potentialNext.letter if (canMove(current.letter, letter)) { potentialNext.shortest = minOf(potentialNext.shortest, current.shortest + 1) queue.add((row) to column + 1) } } } if (column - 1 in graph[row].indices) { val potentialNext = graph[row][column - 1] if (!potentialNext.visited) { val letter = potentialNext.letter if (canMove(current.letter, letter)) { potentialNext.shortest = minOf(potentialNext.shortest, current.shortest + 1) queue.add((row) to column - 1) } } } } } return graph[end.first][end.second].shortest.also { println(it) } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day12_test") check(part1(testInput) == 31) val input = readInput("Day12") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
1d7ab334f38a9e260c72725d3f583228acb6aa0e
6,881
advent-2022
Apache License 2.0
src/Day05.kt
mddanishansari
576,622,315
false
{"Kotlin": 11861}
import java.util.* fun main() { data class Move(val amount: Int, val from: Int, val to: Int) data class Input(val stacks: Map<Int, Stack<Char>>, val moves: List<Move>) fun MutableMap<Int, Stack<Char>>.insertCrate(stackNumber: Int, crate: Char) { if (crate == ' ') return if (this[stackNumber] != null) { this[stackNumber]?.push(crate) return } this[stackNumber] = Stack<Char>().apply { push(crate) } } fun List<String>.parseInput(): Input { val moves = mutableListOf<Move>() val stacks = mutableMapOf<Int, Stack<Char>>() val tempStack = mutableListOf<List<Char>>() forEach { // Read "move X from Y to Z" if (it.startsWith("move")) { val split = it.split(" ") moves.add(Move(amount = split[1].toInt(), from = split[3].toInt(), to = split[5].toInt())) } else if (it.contains('[')) { tempStack.add(it.toCharArray() // Ignore space, [ and ], reads only crate IDs i.e. A, B, C etc .filterIndexed { index, _ -> (index - 1) % 4 == 0 }) } } tempStack.reversed().forEach { chars -> chars.forEachIndexed { crateIndex, crate -> stacks.insertCrate(crateIndex + 1, crate) } } return Input(stacks = stacks, moves = moves) } fun Map<Int, Stack<Char>>.answer(): String { return buildString { entries.forEach { append(it.value.peek()) } } } fun part1(inputLines: List<String>): String { val input = inputLines.parseInput() input.moves.forEach { move -> (1..move.amount).forEach { _ -> input.stacks[move.from]?.pop()?.let { movingCrate -> input.stacks[move.to]?.push(movingCrate) } } } return input.stacks.answer() } fun part2(inputLines: List<String>): String { val input = inputLines.parseInput() input.moves.forEach { move -> val removedCrates = mutableListOf<Char>() (1..move.amount).forEach { _ -> input.stacks[move.from]?.pop()?.let { movingCrate -> removedCrates.add(0, movingCrate) } } removedCrates.forEach { input.stacks[move.to]?.push(it) } } return input.stacks.answer() } // 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") part1(input).println() part2(input).println() }
0
Kotlin
0
0
e032e14b57f5e6c2321e2b02b2e09d256a27b2e2
2,831
advent-of-code-2022
Apache License 2.0
src/day7/newday.kt
mrm1st3r
573,163,888
false
{"Kotlin": 12713}
package day7 import Puzzle sealed class FilesystemEntry(val name: String) { abstract fun getSize(): Int } class File(name: String, private val size: Int) : FilesystemEntry(name) { override fun getSize(): Int = size } class Directory(name: String) : FilesystemEntry(name) { private val elements: MutableMap<String, FilesystemEntry> = mutableMapOf() override fun getSize(): Int = elements .filter { it.key != ".." } .values .sumOf(FilesystemEntry::getSize) fun subDir(name: String): Directory { val find = elements[name] if (find is Directory) { return find } throw RuntimeException("$name is not a directory") } fun addChild(child: FilesystemEntry) { elements[child.name] = child } fun addParent(parent: Directory) { elements[".."] = parent } fun subDirs(): List<Directory> { return elements .filterKeys { it != ".." } .values .filterIsInstance<Directory>() } } fun sumSizes(dir: Directory): Int { var sum = 0 if (dir.getSize() <= 100_000) { sum += dir.getSize() } sum += dir.subDirs() .map(::sumSizes) .sum() return sum } fun flatDirs(dir: Directory): List<Directory> { val mutableList = dir.subDirs() .flatMap { flatDirs(it) } .toMutableList() mutableList.add(dir) return mutableList } private fun readFileSystem(input: List<String>): Directory { val root = Directory("/") var pwd = root input.forEach { when { it.startsWith("$ cd /") -> { // ignore first line } it.startsWith("$ cd") -> { pwd = pwd.subDir(it.substring(5)) } it.startsWith("$ ls") -> { // ignore } it.startsWith("dir") -> { val newDir = Directory(it.substring(4)) newDir.addParent(pwd) pwd.addChild(newDir) } else -> { // file entry val properties = it.split(" ") val file = File(properties[1], properties[0].toInt()) pwd.addChild(file) } } } return root } fun part1(input: List<String>): Int { val root = readFileSystem(input) return sumSizes(root) } fun part2(input: List<String>): Int { val root = readFileSystem(input) val totalSpace = 70_000_000 val requiredSpace = 30_000_000 val usedSpace = root.getSize() val spaceToFree = requiredSpace - (totalSpace - usedSpace) return flatDirs(root) .filter { it.getSize() >= spaceToFree } .minOf { it.getSize() } } fun main() { Puzzle( "day7", ::part1, 95437, ::part2, 24933642 ).test() }
0
Kotlin
0
0
d8eb5bb8a4ba4223331766530099cc35f6b34e5a
2,870
advent-of-code-22
Apache License 2.0
puzzles/src/main/kotlin/com/kotlinground/puzzles/arrays/maxnumberofksumpairs/maxNumberOfKSumPairs.kt
BrianLusina
113,182,832
false
{"Kotlin": 483489, "Shell": 7283, "Python": 1725}
package com.kotlinground.puzzles.arrays.maxnumberofksumpairs /** * Finds the maximum number of operations that are required to find the 2 numbers that sum up to k. * * First the list is sorted in place(this is the assumption used, that it is allowed to sort the input list in place.). * Once the list is sorted, the 2 pointers can be placed at both ends * * Uses 2 pointers to find 2 elements that sum up to K. First sorting is done. This allows us to move either left or * right pointer along the list based off the sum of the 2 elements. The left pointer is at the beginning of the list * while the right pointer is at the end of the list. * * If the sum of these 2 elements is equal to k, we move the left pointer to the right and the right pointer to the left * If they meet, then we can exit the loop as we have found all the possible combinations of 2 elements that can sum * up to k. * * If the current sum of the 2 elements are less than k, then we move the left pointer to the right, this is because * increasing the left pointer gives us a higher chance to find another element that we can sum with the right pointer * to find k. The reverse is true, if the sum is greater than k, then we move the right pointer as reducing this number * allows us to find an element that we can add to the left pointer to find k. * * Complexity: * Time: O(nlogn), this is because we have to first sort the input list * Space: O(1), no extra space is used in this operation as the list is sorted in place. If sorting in place is not * allowed, then this will become O(n) where n is the size of the elements in the list as the algorithm will have to * allocate extra memory to another collection that can be sorted. */ fun maxOperations(nums: IntArray, k: Int): Int { if (nums.size <= 1) { return 0 } nums.sort() var left = 0 var right = nums.lastIndex var operations = 0 while (left < right) { val currentSum = nums[left] + nums[right] if (currentSum == k) { operations++ left++ right-- } else if (currentSum < k) { left++ } else { right-- } } return operations }
1
Kotlin
1
0
5e3e45b84176ea2d9eb36f4f625de89d8685e000
2,230
KotlinGround
MIT License
kotlin/src/2022/Day25_2022.kt
regob
575,917,627
false
{"Kotlin": 50757, "Python": 46520, "Shell": 430}
fun main() { val lines = readInput(25).trim().lines() val digitToSnafu = mapOf(-2 to '=', -1 to '-', 0 to '0', 1 to '1', 2 to '2') val snafuToDigit = digitToSnafu.entries.associate {it.value to it.key} // solution 1: sum the numbers by coordinates, then normalize the answer val N = lines.maxOf {it.length} // max number length val digits = MutableList(N) {0} lines.forEach { it.reversed().forEachIndexed {i, ch -> digits[i] += snafuToDigit[ch]!!} } // normalize each digit to be in the valid [-2, 2] range var i = 0 while (i < digits.size) { // if digit > 2, carry is positive; if digit < -2 carry is negative val carry = when { digits[i] < -2 -> - (2 - digits[i]) / 5 digits[i] in -2..2 -> 0 else -> (digits[i] + 2) / 5 } if (carry != 0) { digits[i] -= carry * 5 if (digits.size == i + 1) digits.add(carry) else digits[i+1] += carry } i += 1 } println(digits.reversed().map {digitToSnafu[it]}.joinToString("")) // solution 2: convert the numbers to long, then convert their sum back into SNAFU // this is easier, but with enough numbers even longs could overflow ... fun toLong(snafu: String): Long { var (total, pow) = 0L to 1L for (i in snafu.indices.reversed()) { total += snafuToDigit[snafu[i]]!! * pow pow *= 5 } return total } val remToDigit = listOf(0, 1, 2, -2, -1) // map remainders of [0,4] to [-2,2] so that if we subtract the latter we get a num divisible by 5 fun toSnafu(num: Long): String { val snafu = mutableListOf<Char>() var x = num while (x > 0) { val digit = remToDigit[(x % 5).toInt()] snafu.add(digitToSnafu[digit]!!) x = (x - digit) / 5 } return snafu.reversed().joinToString("") } val total = lines.map(::toLong).sum() println(toSnafu(total)) }
0
Kotlin
0
0
cf49abe24c1242e23e96719cc71ed471e77b3154
2,024
adventofcode
Apache License 2.0
src/year2022/day25/Day25.kt
lukaslebo
573,423,392
false
{"Kotlin": 222221}
package year2022.day25 import check import readInput import kotlin.math.abs import kotlin.math.pow fun main() { // test if implementation meets criteria from the description, like: val testInput = readInput("2022", "Day25_test") check(part1(testInput), "2=-1=0") val input = readInput("2022", "Day25") println(part1(input)) } private fun part1(input: List<String>): String { return input.sumOf { it.toDecimal() }.toSnafu() } private fun String.toDecimal(): Long { val snafu = this var num = 0L for (i in snafu.indices) { val c = snafu[i] num += c.times() * 5.0.pow(snafu.lastIndex - i).toLong() } return num } private fun Char.times() = when (this) { '0' -> 0 '1' -> 1 '2' -> 2 '-' -> -1 '=' -> -2 else -> error("Factor not available for $this") } private fun Long.toSnafu(): String { var exp = 0 var pow = 5.0.pow(exp++).toLong() var maxNumWithRemainingExp = 2 * pow while (this > pow) { pow = 5.0.pow(exp++).toLong() maxNumWithRemainingExp += 2 * pow } pow = 5.0.pow(exp).toLong() maxNumWithRemainingExp += 2 * pow var total = 0L var snafu = "" while (exp >= 0) { pow = 5.0.pow(exp--).toLong() maxNumWithRemainingExp -= 2 * pow val diff = abs(total - this) var times = diff / pow val minRequiredNumInRemainingExp = if (diff > pow) diff - pow else diff if (exp > 0 && times < 2 && minRequiredNumInRemainingExp > maxNumWithRemainingExp) { times++ } if (total > this) { total -= times * pow snafu += when (times) { 0L -> "0" 1L -> "-" 2L -> "=" else -> error("!") } } else { total += times * pow snafu += when (times) { 0L -> "0" 1L -> "1" 2L -> "2" else -> error("!") } } } return snafu.trimStart { it == '0' } }
0
Kotlin
0
1
f3cc3e935bfb49b6e121713dd558e11824b9465b
2,064
AdventOfCode
Apache License 2.0
src/Day21.kt
jstapels
572,982,488
false
{"Kotlin": 74335}
abstract class MonkeyFun { abstract val name: String abstract fun getValue(): Long open fun solveValue(ans: Long) = if (name == "humn") ans else getValue() fun isHuman(): Boolean { if (name == "humn") return true if (this is NumberMonkey) return false val nm = this as MathMonkey return nm.leftMonkey!!.isHuman() || nm.rightMonkey!!.isHuman() } } data class NumberMonkey(override val name: String, var num: Long): MonkeyFun() { override fun getValue() = num } data class MathMonkey(override val name: String, val left: String, val right: String, val op: String): MonkeyFun() { var leftMonkey: MonkeyFun? = null var rightMonkey: MonkeyFun? = null private val leftNum get() = leftMonkey?.getValue() ?: throw IllegalStateException("no $left") private val rightNum get() = rightMonkey?.getValue() ?: throw IllegalStateException("no $right") override fun getValue(): Long { if (name == "human") println("!!!!! Asking human !!!!! <--") return when (op) { "/" -> leftNum / rightNum "*" -> leftNum * rightNum "-" -> leftNum - rightNum else -> leftNum + rightNum } } override fun solveValue(ans: Long): Long { val human = if (leftMonkey!!.isHuman()) leftMonkey!! else rightMonkey!! val monkey = if (leftMonkey == human) rightMonkey!! else leftMonkey!! val left = (human == leftMonkey) val num = monkey.getValue() return when (op) { "/" -> human.solveValue(if (left) num * ans else num / ans) "*" -> human.solveValue(ans / num) "-" -> human.solveValue(if (left) num + ans else num - ans) else -> human.solveValue(ans - num) } } } fun main() { val day = 21 val numMonkey = """(\w+): (\d+)""".toRegex() val mathMonkey = """(\w+): (\w+) (\S) (\w+)""".toRegex() fun parseMonkey(line: String): MonkeyFun = numMonkey.matchEntire(line)?.destructured?.let { (name, num) -> NumberMonkey(name, num.toLong()) } ?: mathMonkey.matchEntire(line)?.destructured?.let { (name, lm, op, rm) -> MathMonkey(name, lm, rm, op) } ?: throw IllegalArgumentException("No match for $line") fun parseInput(input: List<String>) = input.map { parseMonkey(it) } .associateBy { it.name } fun mapMonkeys(monkeys: Map<String, MonkeyFun>) { monkeys.values .onEach { if (it is MathMonkey) { it.leftMonkey = monkeys[it.left]!! it.rightMonkey = monkeys[it.right]!! } } } fun part1(input: List<String>): Long { val data = parseInput(input) mapMonkeys(data) return data["root"]?.getValue()!! } fun part2(input: List<String>): Long { val data = parseInput(input) mapMonkeys(data) val root = data["root"]!! as MathMonkey val human = if (root.leftMonkey!!.isHuman()) root.leftMonkey!! else root.rightMonkey!! val monkey = if (root.leftMonkey == human) root.rightMonkey!! else root.leftMonkey!! val ans = monkey.getValue() return human.solveValue(ans) } // test if implementation meets criteria from the description, like: val testInput = readInput("Day${day.pad(2)}_test") checkTest(152) { part1(testInput) } checkTest(301) { part2(testInput) } val input = readInput("Day${day.pad(2)}") solution { part1(input) } solution { part2(input) } }
0
Kotlin
0
0
0d71521039231c996e2c4e2d410960d34270e876
3,602
aoc22
Apache License 2.0
src/Day09.kt
OskarWalczak
573,349,185
false
{"Kotlin": 22486}
class Position(var x: Int, var y: Int) class Knot(val name: String, val parent: Knot?){ val position = Position(0,0) fun followParent(){ if(parent == null) return if(parent.position.x !in this.position.x-1..this.position.x+1 || parent.position.y !in this.position.y-1..this.position.y+1){ if(parent.position.x > this.position.x){ this.position.x++ } else if( parent.position.x < this.position.x){ this.position.x-- } if(parent.position.y > this.position.y){ this.position.y++ } else if( parent.position.y < this.position.y){ this.position.y-- } } } } fun createRope(length: Int): List<Knot> { val rope: MutableList<Knot> = ArrayList() rope.add(Knot("H", null)) for(i in 1 until length){ val newKnot = Knot(i.toString(), rope[i-1]) rope.add(newKnot) } return rope } fun tailVisitsForRopeLength(length: Int, instructions: List<String>): Int{ val rope = createRope(length) val head = rope[0] val tail = rope.last() val tailHistory: MutableSet<Pair<Int, Int>> = HashSet() instructions.forEach { line -> val dir: Char = line.split(' ').first()[0] val dist: Int = line.split(' ').last().toInt() for(i in 1..dist){ when(dir){ 'R' -> head.position.x++ 'L' -> head.position.x-- 'U' -> head.position.y++ 'D' -> head.position.y-- } rope.forEach { knot -> knot.followParent() } tailHistory.add(Pair(tail.position.x, tail.position.y)) } } return tailHistory.size } fun main() { fun part1(input: List<String>): Int { return tailVisitsForRopeLength(2, input) } fun part2(input: List<String>): Int { return tailVisitsForRopeLength(10, input) } // test if implementation meets criteria from the description, like: val testInput = readInput("Day09_test") check(part1(testInput) == 13) val input = readInput("Day09") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
d34138860184b616771159984eb741dc37461705
2,277
AoC2022
Apache License 2.0
kotlin/src/com/daily/algothrim/leetcode/hard/MinDistance.kt
idisfkj
291,855,545
false
null
package com.daily.algothrim.leetcode.hard /** * 72. 编辑距离 * * 给你两个单词 word1 和 word2,请你计算出将 word1 转换成 word2 所使用的最少操作数 。 * 你可以对一个单词进行如下三种操作: * * 插入一个字符 * 删除一个字符 * 替换一个字符 */ class MinDistance { companion object { @JvmStatic fun main(args: Array<String>) { println(MinDistance().minDistance("horse", "ros")) println(MinDistance().minDistance("intention", "execution")) println(MinDistance().minDistance("", "execution")) println(MinDistance().minDistance("pneumonoultramicroscopicsilicovolcanoconiosis", "ultramicroscopically")) } } // word1 = "horse", word2 = "ros" // 3 // horse -> rorse (将 'h' 替换为 'r') // rorse -> rose (删除 'r') // rose -> ros (删除 'e') // 1. 不相等 dp[n][m] = math.min(dp[n][m - 1], dp[n - 1][m], dp[n - 1][m - 1]) + 1 插入、删除、替换 // 2. 相等 dp[n][m] = math.min(math.min(dp[i][j - 1], dp[i - 1][j]) + 1, dp[i - 1][j - 1]) fun minDistance(word1: String, word2: String): Int { val n = word1.length val m = word2.length if ( n * m == 0) return n + m val dp = Array(n + 1) { IntArray(m + 1) } for (i in 0 .. n) { dp[i][0] = i } for (j in 0 .. m) { dp[0][j] = j } for (i in 1 .. n) { for (j in 1 .. m) { if (word1[i - 1] == word2[j - 1]) { dp[i][j] = Math.min(Math.min(dp[i][j - 1], dp[i - 1][j]) + 1, dp[i - 1][j - 1]) } else { dp[i][j] = Math.min(Math.min(dp[i][j - 1], dp[i - 1][j]), dp[i - 1][j - 1]) + 1 } } } return dp[n][m] } }
0
Kotlin
9
59
9de2b21d3bcd41cd03f0f7dd19136db93824a0fa
1,873
daily_algorithm
Apache License 2.0
src/main/kotlin/biz/koziolek/adventofcode/year2022/day07/day7.kt
pkoziol
434,913,366
false
{"Kotlin": 715025, "Shell": 1892}
package biz.koziolek.adventofcode.year2022.day07 import biz.koziolek.adventofcode.findInput fun main() { val inputFile = findInput(object {}) val rootDir = parseTerminalOutput(inputFile.bufferedReader().readLines()) println(printTree(rootDir)) println("Total size of directories with a total size of at most 100000: ${sumDirectoriesSize(rootDir, maxSize = 100_000)}") val dirToDelete = chooseDirectoryToDelete( rootDir, fileSystemSize = 70000000, minRequiredSpace = 30000000, ) println("Need to delete ${dirToDelete.name} to free up ${dirToDelete.size}") } sealed class FileOrDir { abstract val name: String abstract val size: Int } data class File( override val name: String, override val size: Int, ) : FileOrDir() data class Dir( override val name: String, val children: List<FileOrDir> = emptyList(), ) : FileOrDir() { override val size: Int get() = children.sumOf { it.size } fun find(path: String): FileOrDir? { val parts = path.split('/', limit = 2) val (head, tail) = if (parts.size == 2) { parts[0] to parts[1] } else { parts[0] to "" } val child = children.find { it.name == head } return when { tail.isBlank() -> child child is Dir -> child.find(tail) else -> null } } fun walk(): Sequence<FileOrDir> = sequence { yield(this@Dir) children.sortedBy { it.name } .forEach { child -> when (child) { is File -> yield(child) is Dir -> yieldAll(child.walk()) } } } fun add(child: FileOrDir): Dir = copy(children = children + child) fun remove(childName: String): Dir = copy(children = children.filter { it.name != childName }) } fun printTree(fileOrDir: FileOrDir, level: Int = 0): String = buildString { append(" ".repeat(level)) append("- ${fileOrDir.name}") when (fileOrDir) { is File -> append(" (file, size=${fileOrDir.size})") is Dir -> { append(" (dir)") fileOrDir.children.sortedBy { it.name }.forEachIndexed { index, child -> append("\n") append(printTree(child, level = level + 1)) } } } } fun parseTerminalOutput(lines: Iterable<String>): Dir { fun updateCurrentDir(dirs: List<Dir>, newFile: FileOrDir): List<Dir> { val currentDir = dirs.last() val updatedDir = currentDir.add(newFile) return dirs.dropLast(1) + updatedDir } fun goUp(dirs: List<Dir>): List<Dir> { return if (dirs.size >= 2) { val (parentDir, currentDir) = dirs.takeLast(2) val updatedParent = parentDir.remove(currentDir.name).add(currentDir) dirs.dropLast(2) + updatedParent } else { dirs } } fun goRoot(dirs: List<Dir>): List<Dir> { var tmpDirs = dirs while (tmpDirs.size >= 2) { tmpDirs = goUp(tmpDirs) } return tmpDirs } return lines .fold(listOf<Dir>(Dir("/"))) { dirs, line -> when { line == "$ cd /" -> goRoot(dirs) line == "$ cd .." -> goUp(dirs) line.startsWith("$ cd ") -> { val (_, _, name) = line.split(' ', limit = 3) val currentDir = dirs.last() when (val childDir = currentDir.find(name)) { null -> throw IllegalStateException("'$name' not found") is File -> throw IllegalStateException("'$name' is a file") is Dir -> dirs + childDir } } line == "$ ls" -> dirs line.startsWith("dir ") -> { val (_, name) = line.split(' ', limit = 2) val newDir = Dir(name) updateCurrentDir(dirs, newDir) } else -> { val (size, name) = line.split(' ', limit = 2) val newFile = File(name, size.toInt()) updateCurrentDir(dirs, newFile) } } } .let { dirs -> goRoot(dirs).single() } } fun sumDirectoriesSize(fileOrDir: FileOrDir, maxSize: Int) = when (fileOrDir) { is File -> 0 is Dir -> fileOrDir .walk() .filter { it is Dir && it.size <= maxSize } .sumOf { it.size } } fun chooseDirectoryToDelete(dir: Dir, fileSystemSize: Int, minRequiredSpace: Int): Dir { val minSize = minRequiredSpace - (fileSystemSize - dir.size) return dir.walk() .filter { it is Dir } .map { it as Dir } .filter { it.size >= minSize } .sortedBy { it.size } .first() }
0
Kotlin
0
0
1b1c6971bf45b89fd76bbcc503444d0d86617e95
5,054
advent-of-code
MIT License
src/main/kotlin/dev/tasso/adventofcode/_2022/day08/Day08.kt
AndrewTasso
433,656,563
false
{"Kotlin": 75030}
package dev.tasso.adventofcode._2022.day08 import dev.tasso.adventofcode.Solution class Day08 : Solution<Int> { override fun part1(input: List<String>): Int = input.mapIndexed { yCoord, currRow -> currRow.mapIndexed{ xCoord, currHeight -> val coords = Pair(yCoord, xCoord) listOf( (input northOf coords).all { it < currHeight }, (input eastOf coords).all { it < currHeight }, (input southOf coords).all { it < currHeight }, (input westOf coords).all { it < currHeight }, ).any{ it } }.count { it } }.sum() override fun part2(input: List<String>): Int = input.mapIndexed { yCoord, currRow -> currRow.mapIndexed{ xCoord, currHeight -> val coords = Pair(yCoord, xCoord) listOf( (input northOf coords).run{ this.indexOfFirst { it >= currHeight }.takeIf{ it > -1 }?.let { it + 1 } ?: this.length}, (input eastOf coords).run{ this.indexOfFirst { it >= currHeight }.takeIf{ it > -1 }?.let { it + 1 } ?: this.length}, (input southOf coords).run{ this.indexOfFirst { it >= currHeight }.takeIf{ it > -1 }?.let { it + 1 } ?: this.length}, (input westOf coords).run{ this.indexOfFirst { it >= currHeight }.takeIf{ it > -1 }?.let { it + 1 } ?: this.length} ).reduce(Int::times) }.max() }.max() /** * Gets the heights of all trees in a straight line North of the provided coordinates */ private infix fun List<String>.northOf(coords: Pair<Int,Int>) : String = String(CharArray(coords.first){ this[coords.first - it - 1][coords.second] }) /** * Gets the heights of all trees in a straight line East of the provided coordinates */ private infix fun List<String>.eastOf(coords: Pair<Int,Int>) : String = this[coords.first].substring((coords.second + 1) until this.first().length) /** * Gets the heights of all trees in a straight line South of the provided coordinates */ private infix fun List<String>.southOf(coords: Pair<Int,Int>) : String = String(CharArray(this.size - coords.first - 1){ this[it + coords.first + 1][coords.second] }) /** * Gets the heights of all trees in a straight line West of the provided coordinates */ private infix fun List<String>.westOf(coords: Pair<Int,Int>) : String = this[coords.first].substring(0 until coords.second).reversed() }
0
Kotlin
0
0
daee918ba3df94dc2a3d6dd55a69366363b4d46c
2,618
advent-of-code
MIT License
src/days/Day04.kt
nicole-terc
574,130,441
false
{"Kotlin": 29131}
package days import readInput fun IntRange.contains(range: IntRange): Boolean { return this.contains(range.first) && this.contains(range.last) } fun IntRange.overlap(range: IntRange): Boolean { return this.contains(range.first) || this.contains(range.last) } fun main() { fun part1(input: List<String>) = input .map { line -> line.split(",").map { range -> range.substringBefore("-").toInt()..range.substringAfter("-").toInt() } } .filter { pairs -> pairs[0].contains(pairs[1]) || pairs[1].contains(pairs[0]) } .size fun part2(input: List<String>) = input .map { line -> line.split(",").map { range -> range.substringBefore("-").toInt()..range.substringAfter("-").toInt() } } .filter { pairs -> pairs[0].overlap(pairs[1]) || pairs[1].overlap(pairs[0]) } .size // test if implementation meets criteria from the description, like: val testInput = readInput("Day04_test") check(part1(testInput) == 2) check(part2(testInput) == 4) val input = readInput("Day04") println("PART 1: " + part1(input)) println("PART 2: " + part2(input)) }
0
Kotlin
0
2
9b0eb9b20e308e5fbfcb2eb7878ba21b45e7e815
1,171
AdventOfCode2022
Apache License 2.0
src/main/kotlin/y2023/day11/Day11.kt
TimWestmark
571,510,211
false
{"Kotlin": 97942, "Shell": 1067}
package y2023.day11 import AoCGenerics import Coord import distance fun main() { AoCGenerics.printAndMeasureResults( part1 = { part1() }, part2 = { part2() } ) } private fun calculateGalaxyDistanceSum(expansionFactor: Int): Long { val galaxies = AoCGenerics.getInputLines("/y2023/day11/input.txt").flatMapIndexed { y, row -> row.mapIndexedNotNull { x, c -> if (c == '#') Coord(x, y) else null } } val galaxyXRanges = IntRange(galaxies.minOf {it.x}, galaxies.maxOf{it.x}) val galaxyYRanges = IntRange(galaxies.minOf { it.y}, galaxies.maxOf { it.y }) val spaceX = galaxyXRanges - galaxies.map{it.x}.toSet() val spaceY = galaxyYRanges - galaxies.map{it.y}.toSet() val expandedUniverseGalaxyCoords = galaxies.map { galaxy -> val addSpaceX = spaceX.count { it < galaxy.x } * expansionFactor val addSpaceY = spaceY.count { it < galaxy.y } * expansionFactor Coord(galaxy.x + addSpaceX, galaxy.y + addSpaceY) } val galaxyPairs = expandedUniverseGalaxyCoords.mapIndexed { index, galaxy -> expandedUniverseGalaxyCoords.slice(index + 1 until expandedUniverseGalaxyCoords.size).map { Pair(galaxy, it)} }.flatten() return galaxyPairs.sumOf { it.first.distance(it.second) } } fun part1() = calculateGalaxyDistanceSum(1) fun part2() = calculateGalaxyDistanceSum(1000000-1)
0
Kotlin
0
0
23b3edf887e31bef5eed3f00c1826261b9a4bd30
1,396
AdventOfCode
MIT License
src/main/java/challenges/educative_grokking_coding_interview/merge_intervals/_3/Intersection.kt
ShabanKamell
342,007,920
false
null
package challenges.educative_grokking_coding_interview.merge_intervals._3 import challenges.educative_grokking_coding_interview.merge_intervals.Interval import java.util.* object Intersection { private fun display(l1: List<Interval>): String { var resultStr = "[" for (i in 0 until l1.size - 1) { resultStr += "[" + l1[i].start.toString() + ", " + l1[i].end .toString() + "], " } resultStr += "[" + l1[l1.size - 1].start.toString() + ", " + l1[l1.size - 1].end .toString() + "]" resultStr += "]" return resultStr } private fun intervalsIntersection( intervalLista: List<Interval>, intervalListb: List<Interval> ): List<Interval> { val intersections: MutableList<Interval> = ArrayList<Interval>() // to store all intersecting intervals // index "i" to iterate over the length of list a and index "j" // to iterate over the length of list b var i = 0 var j = 0 // while loop will break whenever either of the lists ends while (i < intervalLista.size && j < intervalListb.size) { // Let's check if intervalLista[i] intervalListb[j] // 1. start - the potential startpoint of the intersection // 2. end - the potential endpoint of the intersection val start: Int = Math.max(intervalLista[i].start, intervalListb[j].start) val end: Int = Math.min(intervalLista[i].end, intervalListb[j].end) if (start <= end) // if this is an actual intersection intersections.add(Interval(start, end)) // add it to the list // Move forward in the list whose interval ends earlier if (intervalLista[i].end < intervalListb[j].end) i += 1 else j += 1 } return intersections } @JvmStatic fun main(args: Array<String>) { val inputIntervalLista: List<List<Interval>> = listOf( listOf(Interval(1, 2)), listOf(Interval(1, 4), Interval(5, 6), Interval(9, 15)), listOf(Interval(3, 6), Interval(8, 16), Interval(17, 25)), listOf( Interval(4, 7), Interval(9, 16), Interval(17, 28), Interval(39, 50), Interval(55, 66), Interval(70, 89) ), listOf(Interval(1, 3), Interval(5, 6), Interval(7, 8), Interval(12, 15)) ) val inputIntervalListb: List<List<Interval>> = listOf( listOf(Interval(1, 2)), listOf(Interval(2, 4), Interval(5, 7), Interval(9, 15)), listOf(Interval(2, 3), Interval(10, 15), Interval(18, 23)), listOf( Interval(3, 6), Interval(7, 8), Interval(9, 10), Interval(14, 19), Interval(23, 33), Interval(35, 40), Interval(45, 59), Interval(60, 64), Interval(68, 76) ), listOf(Interval(2, 4), Interval(7, 10)) ) for (i in inputIntervalLista.indices) { println( "${i + 1}.\t Interval List A: " + display(inputIntervalLista[i])) println("\t Interval List B: " + display(inputIntervalListb[i])) println( "\t Intersecting intervals in 'A' and 'B' are: " + display( intervalsIntersection( inputIntervalLista[i], inputIntervalListb[i] ) ) ) println(String(CharArray(100)).replace('\u0000', '-')) } } }
0
Kotlin
0
0
ee06bebe0d3a7cd411d9ec7b7e317b48fe8c6d70
3,533
CodingChallenges
Apache License 2.0
app/src/main/java/com/betulnecanli/kotlindatastructuresalgorithms/CodingPatterns/LongestCommonSubstring.kt
betulnecanli
568,477,911
false
{"Kotlin": 167849}
/* The "Longest Common Substring" coding pattern is often used to solve problems where you need to find the longest common substring between two given strings. */ //1. Maximum Sum Increasing Subsequence fun maxSumIncreasingSubsequence(nums: IntArray): Int { val n = nums.size // Create an array to store the maximum sum increasing subsequence ending at each index val dp = IntArray(n) // Initialize each element with its own value for (i in 0 until n) { dp[i] = nums[i] } // Populate the array using the Longest Common Substring approach for (i in 1 until n) { for (j in 0 until i) { if (nums[i] > nums[j] && dp[i] < dp[j] + nums[i]) { dp[i] = dp[j] + nums[i] } } } // Find the maximum sum in the dp array return dp.maxOrNull() ?: 0 } fun main() { // Example usage val nums = intArrayOf(4, 6, 1, 3, 8, 4, 6) val result = maxSumIncreasingSubsequence(nums) println("Maximum Sum Increasing Subsequence: $result") } //2. Edit Distance fun minEditDistance(word1: String, word2: String): Int { val m = word1.length val n = word2.length // Create a 2D array to store the minimum edit distance between prefixes of the two words val dp = Array(m + 1) { IntArray(n + 1) } // Initialize the first row and column with values 0 to m and 0 to n respectively for (i in 0..m) { for (j in 0..n) { if (i == 0) { dp[i][j] = j } else if (j == 0) { dp[i][j] = i } else if (word1[i - 1] == word2[j - 1]) { dp[i][j] = dp[i - 1][j - 1] } else { dp[i][j] = 1 + minOf(dp[i - 1][j], dp[i][j - 1], dp[i - 1][j - 1]) } } } return dp[m][n] } fun main() { // Example usage val word1 = "horse" val word2 = "ros" val result = minEditDistance(word1, word2) println("Minimum Edit Distance: $result") } /* Maximum Sum Increasing Subsequence: The maxSumIncreasingSubsequence function calculates the maximum sum increasing subsequence for a given array of integers using a 1D array to store intermediate results. Edit Distance: The minEditDistance function calculates the minimum edit distance (the number of operations needed to convert one string into another) using a 2D array to store intermediate results. */
2
Kotlin
2
40
70a4a311f0c57928a32d7b4d795f98db3bdbeb02
2,409
Kotlin-Data-Structures-Algorithms
Apache License 2.0
src/main/kotlin/com/jacobhyphenated/advent2023/day5/Day5.kt
jacobhyphenated
725,928,124
false
{"Kotlin": 121644}
package com.jacobhyphenated.advent2023.day5 import com.jacobhyphenated.advent2023.Day /** * Day 5: If You Give A Seed A Fertilizer * * The puzzle input is an almanac that describes the relationship between different gardening components * Seeds map to soil map to fertilizer etc until the end destination is location. * * Each source to destination conversion has a list of maps that look like this: * 50 98 2 * 98 is the source, 2 is the range, and 50 is the destination. * From the above 98 maps to 50 and 99 maps to 51 - the range of 2 extends the source destination map for 2 numbers */ class Day5: Day<Pair<List<Long>, List<SourceDestinationMap>>> { override fun getInput(): Pair<List<Long>, List<SourceDestinationMap>> { return parseInput(readInputFile("5")) } /** * Part 1: Given the starting seed numbers, traverse the list of destination maps to convert the seed to location. * Return the minimum location value * * because the "almanac" maps are in order, we can use the result of the previous mapping as the input to the next */ override fun part1(input: Pair<List<Long>, List<SourceDestinationMap>>): Long { val (seeds, almanac) = input return seeds.minOf { seedNumber -> almanac.fold(seedNumber) { source, destinationMap -> destinationMap[source]} } } /** * Part 2: The seed input actually represents pairs of seed and range * so "79 14 55 13" is actually 79-92, 55-67 * * The puzzle input ranges are too large for a brute force approach. Instead, we need to track the * source ranges as groups, in this case, as Pairs of (sourceStart, range). */ override fun part2(input: Pair<List<Long>, List<SourceDestinationMap>>): Long { val (seedsRangeList, almanac) = input val sourcePairs = seedsRangeList.windowed(2, 2).map { (seed, range) -> Pair(seed, range) } return almanac.fold(sourcePairs) { pairs, destinationMap -> pairs.flatMap { (source, range) -> destinationMap.getRanges(source, range) } }.minOf { (location, _) -> location } } fun parseInput(input: String): Pair<List<Long>, List<SourceDestinationMap>> { val steps = input.split("\n\n") val seeds = steps[0].split(":")[1].trim().split(" ").map { it.toLong() } val almanacMappings = steps.subList(1, steps.size) .map { step -> val stepLines = step.lines() val (source, destination) = stepLines[0].split(" ")[0].split("-to-") val rangeLines = stepLines.subList(1, stepLines.size) .map { line -> line.split(" ").map { it.toLong() } } SourceDestinationMap(source, destination, rangeLines) } return Pair(seeds, almanacMappings) } } /** * Data helper class that does the source destination conversions. * The source and destination names are not actually used because the puzzle is in order * * each range map represents a throuple of (destination, source, range) from the puzzle input * a source-to-destination map can have any number or range maps */ data class SourceDestinationMap(val sourceName: String, val destinationName: String, private val rangeMaps: List<List<Long>>) { /** * The operator fun overrides get such that we can do y = destinationMap\[source] * * Take a single source value and return the resulting destination. * If the source value is not included in a range map, return the source value */ operator fun get(source: Long): Long { return rangeMaps.firstOrNull { (_, sourceStart, range) -> source >= sourceStart && source <sourceStart + range }?.let { (destinationStart, sourceStart) -> source - sourceStart + destinationStart } ?: source } /** * To map entire ranges, we consider the range of the [rangeMaps] and the range of the ([s1], [sourceRange]) pair. * These two ranges can intersect in 4 possible ways (or not intersect at all). * In cases where there are ports of the source range that do not intersect with the map, * split that off and create a new Pair() to represent that unmapped range (and try to map it if possible). * * To visualize how the ranges can intersect * ``` * |***********\........| \ e1 < e2 && e1 > s2 s1 < s2 * |***********\...........\**| e2 < e1 && e2 > s1 s1 < s2 * \ |...........\**| e2 < e1 && e2 < s1 * \ |...........| \ e1 < e2 && e1 > s2 * s2 s1 e1 e2 * ``` * * The source range (s1, e1) is between the | characters * The map range (s2, e2) is between the \ characters * "." - represent spaces with overlap * "*" - represent additional unmapped range from the source range * * @param s1 the start of the source range we are mapping * @param sourceRange the range that describes the length from [s1] * * @return a list of Pair ranges as this single range may be broken up into several smaller ranges */ fun getRanges(s1: Long, sourceRange: Long): List<Pair<Long,Long>> { val e1 = s1 + sourceRange - 1 for ((destinationStart, s2, range) in rangeMaps) { val e2 = s2 + range - 1 if ((e1 <= e2) && (e1 >= s2)) { return if (s1 >= s2) { val offset = s1 - s2 listOf(Pair(destinationStart + offset, sourceRange)) } else { val offset = s2 - s1 getRanges(s1, offset) + Pair(destinationStart, sourceRange - offset) } } else if ((e2 <= e1) && (e2 >= s1)) { val endExcess = getRanges(e2 + 1 , e1 - e2 ) return if (s1 < s2) { val beginningExcess = getRanges(s1, s2 - s1) endExcess + beginningExcess + Pair(destinationStart, range) } else { val offset = s1 - s2 endExcess + Pair(destinationStart + offset, e2 - s1) } } } return listOf(Pair(s1, sourceRange)) } } fun main(@Suppress("UNUSED_PARAMETER") args: Array<String>) { Day5().run() }
0
Kotlin
0
0
90d8a95bf35cae5a88e8daf2cfc062a104fe08c1
6,022
advent2023
The Unlicense
src/main/kotlin/days/Day8.kt
MisterJack49
729,926,959
false
{"Kotlin": 31964}
package days class Day8(alternate: Boolean = false) : Day(8, alternate) { override fun partOne() = inputList.let { val path = it.first().map { if (it == 'L') Direction.L else Direction.R } val network = it.drop(2).parseNetwork() for ((loc, step) in stepper("AAA", path, network)) { if (loc == "ZZZ") return@let step } -1 } override fun partTwo() = inputList.let { input -> val path = input.first().map { if (it == 'L') Direction.L else Direction.R } val network = input.drop(2).parseNetwork() network.map.keys.filter { it.last() == 'A' }.map { for ((loc, step) in stepper(it, path, network)) { if (loc.last() == 'Z') { return@map step.toLong() } } -1L }.fold(1) { acc: Long, i: Long -> lcm(acc, i) } } private fun stepper(start: String, path: List<Direction>, network: Network): Sequence<Pair<String, Int>> = sequence { var i = 0 var loc = start while (true) { val (left, right) = network[loc]!! val dir = path[i++ % path.size] loc = if (dir == Direction.L) left else right yield(Pair(loc, i)) } } enum class Direction { L, R } data class Network(val map: Map<String, Pair<String, String>>) { operator fun get(location: String): Pair<String, String>? = map[location] } private fun gcd(a: Long, b: Long): Long = if (b == 0L) a else gcd(b, a % b) private fun lcm(a: Long, b: Long): Long = if (a == 0L || b == 0L) 0L else (a * b) / gcd(a, b) private val networkRegex = Regex("(?<key>\\w{3}) = \\((?<left>\\w{3}), (?<right>\\w{3})\\)") private fun List<String>.parseNetwork() = Network(associate { val result = networkRegex.find(it)!!.groups result["key"]!!.value to Pair(result["left"]!!.value, result["right"]!!.value) }) }
0
Kotlin
0
0
807a6b2d3ec487232c58c7e5904138fc4f45f808
2,118
AoC-2023
Creative Commons Zero v1.0 Universal
src/Day21.kt
greg-burgoon
573,074,283
false
{"Kotlin": 120556}
fun main() { data class Node(val name: String, var value: String? = null, var dependencies: MutableList<String> = mutableListOf<String>(), var operation: String = "") fun createNodeMap(input: String): MutableMap<String, Node> { var nodeMap = mutableMapOf<String, Node>() input.split("\n").forEach { var nameValue = it.split(": ") var node = Node(nameValue[0]) if (nameValue[1].toLongOrNull() != null) { node.value = nameValue[1] } else { var deps = nameValue[1].split(" ") node.dependencies.add(deps[0]) node.dependencies.add(deps[2]) node.operation = deps[1] } nodeMap.put(node.name, node) } return nodeMap } fun resolveDependencies(rootNode: Node, nodeMap: MutableMap<String, Node>) { var history = ArrayDeque<Node>() history.add(rootNode) while (!history.isEmpty()) { var currentNode = history.last() var deps = currentNode.dependencies.map { nodeMap.get(it)!! }.toList() if (deps.isNotEmpty() && deps.filter { it.value == null }.isEmpty()) { if (deps.filter { it.value?.toLongOrNull() == null }.isNotEmpty()) { currentNode.value = "(" + deps[0].value + currentNode.operation + deps[1].value + ")" } else { currentNode.value = currentNode.operation.let { when (it) { "+" -> { one: Long, two: Long -> one + two } "-" -> { one: Long, two: Long -> one - two } "*" -> { one: Long, two: Long -> one * two } else -> { one: Long, two: Long -> one / two } } }(deps[0].value?.toLong()!!, deps[1].value?.toLong()!!).toString() } } var value = currentNode.value if (value != null) { history.removeLast() } else { history.add(deps[0]) history.add(deps[1]) } } } fun part1(input: String): Long { var nodeMap = createNodeMap(input) var rootNode = nodeMap["root"]!! resolveDependencies(rootNode, nodeMap) return rootNode.value?.toLong()!! } fun solveForHuman(rootNode: Node, nodeMap: MutableMap<String, Node>): Long { var history = ArrayDeque<Node>() history.add(rootNode) // while (!history.isEmpty()) { // var currentNode = history.last() // // } return 0L } fun part2(input: String): Long { var nodeMap = createNodeMap(input) var rootNode = nodeMap["root"]!! rootNode.operation = "=" var humanNode = nodeMap["humn"]!! humanNode.value = "humn" resolveDependencies(rootNode, nodeMap) return solveForHuman(rootNode, nodeMap) } // test if implementation meets criteria from the description, like: val testInput = readInput("Day21_test") val output = part1(testInput) check(output== 152L) val input = readInput("Day21") println(part1(input)) println(part2(input)) }
0
Kotlin
0
1
74f10b93d3bad72fa0fc276b503bfa9f01ac0e35
3,633
aoc-kotlin
Apache License 2.0
src/Day12.kt
achugr
573,234,224
false
null
import java.util.* data class GridCell(val row: Int, val col: Int, val height: Int) data class PathNode(val cell: GridCell, var length: Int) : Comparable<PathNode> { override fun compareTo(other: PathNode): Int { return length.compareTo(other.length) } } class D12Grid(private val grid: List<List<Int>>, private val start: GridCell, private val finish: GridCell) { fun findShortestPath1Length(): Int { return findShortestPathLength { _: PathNode -> 1 } } fun findShortestPath2Length(): Int { return findShortestPathLength { to: PathNode -> if (to.cell.height == 0) 0 else 1 } } private fun findShortestPathLength(moveLengthFunction: (to: PathNode) -> Int): Int { val queue = PriorityQueue<PathNode>() val visited = mutableSetOf<GridCell>() var currentNode: PathNode = PathNode(start, 0) while (currentNode.cell != finish) { getNextPathNodes(currentNode) .filter { nextNode -> nextNode.cell.height <= currentNode.cell.height + 1 } .filter { nextNode -> visited.add(nextNode.cell) } .map { nextNode -> nextNode.copy(length = currentNode.length + moveLengthFunction.invoke(nextNode)) }.forEach { nextNode -> queue.add(nextNode) } currentNode = queue.poll() } return currentNode.length } private fun getNextPathNodes(pathNode: PathNode): List<PathNode> { return Direction.values() .mapNotNull { direction -> val row = pathNode.cell.row + direction.row val col = pathNode.cell.col + direction.col if (row in grid.indices && col in grid[0].indices) { PathNode(GridCell(row, col, grid[row][col]), Int.MAX_VALUE) } else { null } } } companion object GridParser { fun parseInput(input: List<String>): D12Grid { lateinit var start: GridCell lateinit var finish: GridCell val data = input.mapIndexed { row, line -> line.toCharArray().mapIndexed { col, c -> when (c) { 'S' -> { start = GridCell(row, col, 0) 0 } 'E' -> { val finishHeight = 'z'.code - 'a'.code finish = GridCell(row, col, finishHeight) finishHeight } else -> c.code - 'a'.code } }.toList() } return D12Grid(data, start, finish) } } } fun main() { fun part1(input: List<String>): Int { return D12Grid.parseInput(input).findShortestPath1Length() } fun part2(input: List<String>): Int { return D12Grid.parseInput(input).findShortestPath2Length() } // test if implementation meets criteria from the description, like: println(part1(readInput("Day12"))) println(part2(readInput("Day12"))) }
0
Kotlin
0
0
d91bda244d7025488bff9fc51ca2653eb6a467ee
3,222
advent-of-code-kotlin-2022
Apache License 2.0
src/main/kotlin/com/headlessideas/adventofcode/december7/Balancer.kt
Nandi
113,094,752
false
null
package com.headlessideas.adventofcode.december7 import com.headlessideas.adventofcode.utils.readFile fun findBottom(programs: List<Program>): Program { val children = programs.flatMap { it.children } return programs.filter { it.children.isNotEmpty() && !children.contains(it) }[0] } fun findUnbalance(bottom: Program): Int { val unbalanced = bottom.children.firstOrNull { !it.isBalanced() } if (unbalanced == null) { val weightMap = bottom.children.groupBy { it.programWeight() } val unbalance = weightMap.filter { it.value.size == 1 }.toList().first().first val balance = weightMap.filter { it.value.size != 1 }.toList().first().first return weightMap[unbalance]!![0].balancedWeight(balance - unbalance) } return findUnbalance(unbalanced) } fun main(args: Array<String>) { val input = readFile("7.dec.txt").map { val parts = it.split(" -> ") parts[0].split(" ")[0] to it }.toMap() val programs = mutableListOf<Program>() for (p in input) { if (programs.all { it.name != p.key }) { programs.add(Program.create(p.value, input)) } } val bottom = findBottom(programs) println("Part 1: ${bottom.name}") println("Part 2: ${findUnbalance(bottom)}") } data class Program(val name: String, private val weight: Int, val children: List<Program>) { fun programWeight(): Int { return children.map { it.programWeight() }.sum() + weight } fun isBalanced() = children.map { it.programWeight() }.distinct().size == 1 fun balancedWeight(diff: Int) = weight + diff companion object { fun create(input: String, programStrings: Map<String, String>): Program { val family = input.split(" -> ") val parent = family[0].split(" ") val weight = parent[1].drop(1).dropLast(1) val children = if (family.size == 2) { family[1].split(", ").map { Program.create(programStrings[it]!!, programStrings) } } else { listOf() } return Program(parent[0], weight.toInt(), children) } } override fun equals(other: Any?): Boolean { if (other !is Program) return false if (other.name == name) return true return false } override fun hashCode(): Int { return name.hashCode() } }
0
Kotlin
0
0
2d8f72b785cf53ff374e9322a84c001e525b9ee6
2,403
adventofcode-2017
MIT License
src/Day04.kt
Vincentvibe3
573,202,573
false
{"Kotlin": 8454}
fun main() { fun part1(input: List<String>): Int { var fullyContained = 0 for (line in input) { val pair = line.split(",").map { rangeString -> rangeString.split("-").map { it.toInt() } } if (pair[0][0]<=pair[1][0]&&pair[0][1]>=pair[1][1]){ fullyContained++ } else if (pair[1][0]<=pair[0][0]&&pair[1][1]>=pair[0][1]){ fullyContained++ } } return fullyContained } fun part2(input: List<String>): Int { var overlap = 0 for (line in input) { val pair = line.split(",").map { rangeString -> rangeString.split("-").map { it.toInt() } } val overlapSections = (pair[0][0]..pair[0][1]).toSet().intersect(pair[1][0]..pair[1][1]) if (overlapSections.isNotEmpty()){ overlap++ } } return overlap } // test if implementation meets criteria from the description, like: val testInput = readInput("Day04_test") check(part1(testInput) == 2) check(part2(testInput) == 4) val input = readInput("Day04") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
246c8c43a416023343b3ef518ae3e21dd826ee81
1,313
advent-of-code-2022
Apache License 2.0
src/main/kotlin/com/mobiento/aoc/Day04.kt
markburk
572,970,459
false
{"Kotlin": 22252}
package com.mobiento.aoc fun Pair<Int, Int>.toSequence(): Set<Int> { val result = arrayListOf<Int>() for (x in first .. second) { result.add(x) } return result.toSet() } class Day04 { companion object { val regex = "(\\d+)-(\\d+),(\\d+)-(\\d+)".toRegex() } fun part1(input: List<String>): Int { return input.sumOf { line -> regex.matchEntire(line)?.groups?.let { matchGroups -> val firstPair = Pair(extractIntVal(matchGroups, 1), extractIntVal(matchGroups, 2)) val secondPair = Pair(extractIntVal(matchGroups, 3), extractIntVal(matchGroups, 4)) calculatePairForPartOne(firstPair, secondPair) } ?: 0 } } private fun extractIntVal(matchGroups: MatchGroupCollection, index: Int): Int { val group = matchGroups[index] val value = group?.value return value?.toInt() ?: 0 } private fun calculatePairForPartOne(first: Pair<Int, Int>, second: Pair<Int, Int>): Int { return if (isEncompassing(first, second)) 1 else 0 } fun isEncompassing(firstPair: Pair<Int, Int>, secondPair: Pair<Int, Int>): Boolean { return (firstPair.first >= secondPair.first && firstPair.second <= secondPair.second) || (secondPair.first >= firstPair.first && secondPair.second <= firstPair.second) } fun part2(input: List<String>): Int { return input.sumOf { line -> regex.matchEntire(line)?.groups?.let { matchGroups -> val firstPair = Pair(extractIntVal(matchGroups, 1), extractIntVal(matchGroups, 2)) val secondPair = Pair(extractIntVal(matchGroups, 3), extractIntVal(matchGroups, 4)) calculatePairForPartTwo(firstPair, secondPair) } ?: 0 } } fun isOverlapping(first: Pair<Int, Int>, second: Pair<Int, Int>): Boolean { return first.toSequence().intersect(second.toSequence()).isNotEmpty() } fun calculatePairForPartTwo(first: Pair<Int, Int>, second: Pair<Int, Int>): Int { return if (isOverlapping(first, second)) 1 else 0 } }
0
Kotlin
0
0
d28656b4d54c506a01252caf6b493e4f7f97e896
2,150
potential-lamp
Apache License 2.0
src/main/kotlin/days/Extensions.kt
andilau
429,206,599
false
{"Kotlin": 113274}
package days import java.util.Collections.indexOfSubList fun String.toLongNumbers(): LongArray = split(",").map(String::toLong).toLongArray() fun lcm(x: Long, y: Long, vararg ints: Long): Long = ints.fold(x * y / gcd(x, y)) { acc, z -> lcm(acc, z) } fun gcd(a: Long, b: Long): Long { if (b == 0L) return a return gcd(b, a % b) } fun <T> Collection<Iterable<T>>.flattenByIndex(): Sequence<T> = sequence { var index = 0 while (true) { var found = false this@flattenByIndex.forEach { iterable -> iterable.elementAtOrNull(index)?.let { found = true; yield(it) } } if (!found) break index++ } } private const val LOWER_LIMIT = 3 fun <T> List<T>.findThreeContainedListsOrNull(): Triple<List<T>, List<T>, List<T>>? { require(size >= LOWER_LIMIT) { "Cant compress list" } if (size <= LOWER_LIMIT) return Triple(listOf(this[0]), listOf(this[1]), listOf(this[2])) return (2..size / LOWER_LIMIT) .flatMap { i -> (2..size / LOWER_LIMIT - i).map { j -> Pair(i, j) } } .mapNotNull { (i, j) -> val first = take(j) val second = drop(j).dropLast(i) val third = takeLast(i) val substituted = second.subtractAllSubLists(first).subtractAllSubLists(third) (1..size / 2).asSequence() .filter { substituted.size % it == 0 } .firstOrNull { size -> substituted .windowed(size, size) .zipWithNext() .all { it.first == it.second } } ?.let { Triple(first, substituted.take(it), third) } } .minByOrNull { it.toList().sumOf { it.size } } } fun <T> List<T>.subtractAllSubLists(pattern: List<T>): List<T> { val list = this.toMutableList() if (pattern.isEmpty()) return list while (true) { val indexOfSubList = indexOfSubList(list, pattern) if (indexOfSubList == -1) break repeat(pattern.size) { list.removeAt(indexOfSubList) } } return list } fun <T> List<T>.sequenceOfLists(lists: List<List<T>>) = sequence { val list = this@sequenceOfLists.toMutableList() while (list.isNotEmpty()) { lists .filter { indexOfSubList(list, it) == 0 } .forEach { repeat(it.size) { list.removeAt(0) } yield(it) } } }
2
Kotlin
0
0
f51493490f9a0f5650d46bd6083a50d701ed1eb1
2,448
advent-of-code-2019
Creative Commons Zero v1.0 Universal
src/Day23.kt
RusticFlare
574,508,778
false
{"Kotlin": 78496}
private data class Pos(val row: Int, val col: Int) { val n get() = copy(row = row - 1) val ne get() = copy(row = row - 1, col = col + 1) val e get() = copy(col = col + 1) val se get() = copy(row = row + 1, col = col + 1) val s get() = copy(row = row + 1) val sw get() = copy(row = row + 1, col = col - 1) val w get() = copy(col = col - 1) val nw get() = copy(row = row - 1, col = col - 1) } private interface CardinalDirection { val next: CardinalDirection fun moveTo(pos: Pos, positions: Set<Pos>): Pos? object North : CardinalDirection { override val next = South override fun moveTo(pos: Pos, positions: Set<Pos>) = pos.n .takeUnless { pos.n in positions } .takeUnless { pos.ne in positions } .takeUnless { pos.nw in positions } } object South : CardinalDirection { override val next = West override fun moveTo(pos: Pos, positions: Set<Pos>) = pos.s .takeUnless { pos.s in positions } .takeUnless { pos.se in positions } .takeUnless { pos.sw in positions } } object West : CardinalDirection { override val next = East override fun moveTo(pos: Pos, positions: Set<Pos>) = pos.w .takeUnless { pos.w in positions } .takeUnless { pos.nw in positions } .takeUnless { pos.sw in positions } } object East : CardinalDirection { override val next = North override fun moveTo(pos: Pos, positions: Set<Pos>) = pos.e .takeUnless { pos.e in positions } .takeUnless { pos.ne in positions } .takeUnless { pos.se in positions } } } private fun Set<Pos>.next(cardinalDirection: CardinalDirection): Set<Pos> { val directions = generateSequence(cardinalDirection) { it.next }.take(4).toList() return groupBy { pos -> pos.takeUnless { it.n in this || it.ne in this || it.e in this || it.se in this || it.s in this || it.sw in this || it.w in this || it.nw in this } ?: directions.firstNotNullOfOrNull { it.moveTo(pos, positions = this) } ?: pos } .flatMap { (destination, starts) -> when { starts.size > 1 -> starts else -> listOf(destination) } }.toSet() } private fun Set<Pos>.print(index: Int) { val rows = -2..9 val cols = -3..10 println("== End of Round ${index + 1} ==") rows.forEach { row -> println(cols.joinToString(separator = "") { if (Pos(row, it) in this) "#" else "." }) } println() } fun main() { fun part1(input: List<String>): Int { var positions = input.flatMapIndexed { row, s -> s.withIndex().filter { (_, char) -> char == '#' }.map { (col) -> Pos(row, col) } }.toSet() generateSequence(CardinalDirection.North as CardinalDirection) { it.next } .take(10) .forEach { cardinalDirection -> positions = positions.next(cardinalDirection) // .also { it.print(index) } } return ((positions.maxOf { it.row } - positions.minOf { it.row } + 1) * (positions.maxOf { it.col } - positions.minOf { it.col } + 1)) - positions.size } fun part2(input: List<String>): Int { var positions = input.flatMapIndexed { row, s -> s.withIndex().filter { (_, char) -> char == '#' }.map { (col) -> Pos(row, col) } }.toSet() return generateSequence(CardinalDirection.North as CardinalDirection) { it.next } .takeWhile { cardinalDirection -> val next = positions.next(cardinalDirection) (next != positions).also { if (it) positions = next } } .count() + 1 } // test if implementation meets criteria from the description, like: val testInput = readLines("Day23_test") check(part1(testInput) == 110) check(part2(testInput) == 20) val input = readLines("Day23") with(part1(input)) { check(this == 4254) println(this) } with(part2(input)) { check(this == 992) println(this) } }
0
Kotlin
0
1
10df3955c4008261737f02a041fdd357756aa37f
4,324
advent-of-code-kotlin-2022
Apache License 2.0
src/Day04.kt
andrikeev
574,393,673
false
{"Kotlin": 70541, "Python": 18310, "HTML": 5558}
fun main() { fun contains(first: String, second: String): Boolean { val (aStart, aEnd) = first.split("-").map(String::toInt) val (bStart, bEnd) = second.split("-").map(String::toInt) return aStart <= bStart && aEnd >= bEnd || bStart <= aStart && bEnd >= aEnd } fun intersect(first: String, second: String): Boolean { val (aStart, aEnd) = first.split("-").map(String::toInt) val (bStart, bEnd) = second.split("-").map(String::toInt) return aStart in bStart..bEnd || bStart in aStart..aEnd } fun part1(input: List<String>): Int { return input.count { line -> val (first, second) = line.split(",") contains(first, second) } } fun part2(input: List<String>): Int { return input.count { line -> val (first, second) = line.split(",") intersect(first, 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)) }
0
Kotlin
0
1
1aedc6c61407a28e0abcad86e2fdfe0b41add139
1,197
aoc-2022
Apache License 2.0
src/main/kotlin/aoc23/Day15.kt
tom-power
573,330,992
false
{"Kotlin": 254717, "Shell": 1026}
package aoc23 import common.Year23 import aoc23.Day15Domain.LensLibrary import aoc23.Day15Parser.toLensLibrary object Day15 : Year23 { fun List<String>.part1(): Int = toLensLibrary() .sumOfSteps() fun List<String>.part2(): Int = toLensLibrary() .apply { updateBoxes() } .totalFocusingPower() } object Day15Domain { data class LensLibrary( private val steps: List<String> ) { fun sumOfSteps(): Int = steps.sumOf { it.hash() } private val boxes = MutableList<MutableList<Lens>>(256) { mutableListOf() } fun totalFocusingPower(): Int = boxes.focusingPower() fun updateBoxes() { steps.forEach { step -> val label = step.filter { it.isLetter() } val index = label.hash() val box = boxes[index] when { step.contains("-") -> { boxes[index] = box .filterNot { lens -> lens.label == label } .toMutableList() } step.contains("=") -> { val newLens = Lens( label = label, focalLength = step.filter { it.isDigit() }.toInt() ) val indexOfLens = box.indexOfFirst { it.label == newLens.label }.takeIf { it != -1 } boxes[index] = box.apply { indexOfLens ?.let { this[indexOfLens] = newLens } ?: this.add(newLens) } } } } } } private fun String.hash(): Int = this .map { it.code } .fold(0) { acc, i -> (acc + i) * 17 % 256 } private fun List<MutableList<Lens>>.focusingPower(): Int = this.mapIndexed { index, box -> box.mapIndexed { slot, lens -> (index + 1) * (slot + 1) * lens.focalLength }.sum() }.sum() data class Lens( val label: String, val focalLength: Int ) } object Day15Parser { fun List<String>.toLensLibrary(): LensLibrary = LensLibrary( steps = this.first().split(",") ) }
0
Kotlin
0
0
baccc7ff572540fc7d5551eaa59d6a1466a08f56
2,535
aoc
Apache License 2.0
src/main/kotlin/com/github/pjozsef/WeightedRandom.kt
pjozsef
238,381,562
false
null
package com.github.pjozsef import java.util.Random class WeightedCoin(val trueProbability: Double, val random: Random = Random()) { init { require(trueProbability in 0.0..1.0) { "trueProbability must be between 0.0 and 1.0, but was: $trueProbability" } } fun flip(): Boolean { return random.nextDouble() <= trueProbability } } class WeightedDie<T>(probabilities: Map<T, Number>, val random: Random = Random()) { constructor(values: List<T>, probabilities: List<Number>, random: Random = Random()) : this(values.zip(probabilities), random) constructor(probabilities: List<Pair<T, Number>>, random: Random = Random()) : this(probabilities.toMap(), random) private val n = probabilities.size private val alias = IntArray(n) private val prob = DoubleArray(n) private val values: List<T> init { val sumOfProbabilities = probabilities.values.map { it.toDouble() }.sum() val probList = probabilities.mapValues { it.value.toDouble() / sumOfProbabilities }.toList() require(probList.map { it.second }.none { it < 0.0 }) { "Probabilities must not be negative" } values = probList.unzip().first val small = mutableListOf<Int>() val large = mutableListOf<Int>() val scaledProbs = probList.zip(0 until n) { (_, percent), index -> index to percent }.map { it.first to it.second * n }.onEach { (i, value) -> if (value < 1.0) small.add(i) else large.add(i) }.map { it.second }.toTypedArray() while (small.isNotEmpty() && large.isNotEmpty()) { val l = small.removeAt(0) val g = large.removeAt(0) prob[l] = scaledProbs[l] alias[l] = g val pgtemp = scaledProbs[g] + scaledProbs[l] - 1 scaledProbs[g] = pgtemp if (pgtemp < 1) small.add(g) else large.add(g) } while (large.isNotEmpty()) { val g = large.removeAt(0) prob[g] = 1.0 } while (small.isNotEmpty()) { val l = small.removeAt(0) prob[l] = 1.0 } } fun roll(): T = random.nextInt(n).let { i -> if (flipCoin(prob[i], random)) values[i] else values[alias[i]] } } fun flipCoin(trueProbability: Double, random: Random = Random()): Boolean { return WeightedCoin(trueProbability, random).flip() } fun intWeightedDice(probabilities: List<Double>, random: Random = Random()) = WeightedDie(probabilities.indices.toList().zip(probabilities).toMap(), random)
0
Kotlin
0
0
7337618c99095b103f858f4313e7e347a19e36f6
2,621
WeightedRandom
MIT License
src/Day04.kt
orirabi
574,124,632
false
{"Kotlin": 14153}
fun main() { fun parseSingleAssignment(str: String): Pair<Int, Int> { val assignment = str.split("-") check(assignment.size == 2) return assignment.first().toInt() to assignment.last().toInt() } fun parseToPairs(str: String): Pair<Pair<Int, Int>, Pair<Int, Int>> { val assignments = str.split(",") check(assignments.size == 2) val assignment1 = assignments.first() val assignment2 = assignments.last() return parseSingleAssignment(assignment1) to parseSingleAssignment(assignment2) } fun Pair<Int, Int>.fullyContains(that: Pair<Int, Int>): Boolean { return this.first <= that.first && this.second >= that.second } fun getContainingCount(pairs: List<String>): Int { return pairs.asSequence() .map { parseToPairs(it) } .filter { it.first.fullyContains(it.second) || it.second.fullyContains(it.first) } .count() } fun Pair<Int, Int>.has(i: Int): Boolean { return this.first <= i && this.second >= i } fun Pair<Int, Int>.anyOverlap(that: Pair<Int, Int>): Boolean { return this.has(that.first) || this.has(that.second) } fun getOverlappingCount(pairs: List<String>): Int { return pairs.asSequence() .map { parseToPairs(it) } .filter { it.first.anyOverlap(it.second) || it.second.anyOverlap(it.first) } .count() } val allAssignments = readInput("Day04") println(getContainingCount(allAssignments)) println(getOverlappingCount(allAssignments)) }
0
Kotlin
0
0
41cb10eac3234ae77ed7f3c7a1f39c2f9d8c777a
1,594
AoC-2022
Apache License 2.0
src/Day09.kt
karloti
573,006,513
false
{"Kotlin": 25606}
/* import kotlin.math.absoluteValue import kotlin.math.sign data class Point(val x: Int, val y: Int) { operator fun plus(other: Point): Point = Point(x + other.x, y + other.y) infix fun moveTo(d: Point): Point = takeIf { (x - d.x).absoluteValue <= 1 && (y - d.y).absoluteValue <= 1 } ?: Point(x + (d.x - x).sign, y + (d.y - y).sign) } fun String.toPoints() = split(' ') .let { (direction, distance) -> List(distance.toInt()) { when (direction[0]) { 'U' -> Point(0, 1) 'D' -> Point(0, -1) 'L' -> Point(-1, 0) 'R' -> Point(1, 0) else -> throw IllegalArgumentException() } } } fun List<String>.solution(size: Int): Int { val rope = MutableList(size) { Point(0, 0) } val tale: MutableSet<Point> = mutableSetOf() forEach { val headStepByStep: List<Point> = it.toPoints().runningFold(rope[0], Point::plus).drop(1) headStepByStep.onEach { head: Point -> rope[0] = head rope.indices.zipWithNext { i1, i2 -> rope[i2] = rope[i2].moveTo(rope[i1]) } tale += rope.last() } } return tale.size } fun main() { val input: List<String> = readInput("Day09") check(input.solution(2).also(::println) == 5779) check(input.solution(10).also(::println) == 2331) }*/
0
Kotlin
1
2
39ac1df5542d9cb07a2f2d3448066e6e8896fdc1
1,382
advent-of-code-2022-kotlin
Apache License 2.0
src/Day02.kt
RobvanderMost-TomTom
572,005,233
false
{"Kotlin": 47682}
enum class Hand(val score: Int) { ROCK(1), PAPER(2), SCISSOR(3); } enum class Result(val score: Int) { LOSE(0) { override fun playFor(other: Hand): Hand = when (other) { Hand.ROCK -> Hand.SCISSOR Hand.PAPER -> Hand.ROCK Hand.SCISSOR -> Hand.PAPER } }, DRAW(3) { override fun playFor(other: Hand): Hand = other }, WIN(6) { override fun playFor(other: Hand): Hand = when (other) { Hand.ROCK -> Hand.PAPER Hand.PAPER -> Hand.SCISSOR Hand.SCISSOR -> Hand.ROCK } }; abstract fun playFor(other: Hand): Hand } fun main() { fun Char.toHand() = when (this) { 'A', 'X' -> Hand.ROCK 'B', 'Y' -> Hand.PAPER 'C', 'Z' -> Hand.SCISSOR else -> throw RuntimeException("Invalid value") } fun Char.toResult() = when (this) { 'X' -> Result.LOSE 'Y' -> Result.DRAW 'Z' -> Result.WIN else -> throw RuntimeException("Invalid value") } fun Hand.beats(other: Hand) = ((this == Hand.PAPER && other == Hand.ROCK) || (this == Hand.SCISSOR && other == Hand.PAPER) || (this == Hand.ROCK && other == Hand.SCISSOR)) fun Hand.scoreTo(other: Hand) = if (this.beats(other)) { println("$this beats $other -> ${6 + score}") 6 + score } else if (this == other) { println("$this draw to $other -> ${3 + score}") 3 + score } else { println("$this loses from $other -> $score") score } fun part1(input: List<String>): Int { return input.sumOf { it[2].toHand().scoreTo(it[0].toHand()) } } fun part2(input: List<String>): Int { return input.map { it[0].toHand() to it[2].toResult() } .map { it.second.playFor(it.first) to it.second } .sumOf { it.first.score + it.second.score } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day02_test") check(part1(testInput) == 15) val input = readInput("Day02") println(part1(input)) println(part2(input)) }
5
Kotlin
0
0
b7143bceddae5744d24590e2fe330f4e4ba6d81c
2,307
advent-of-code-2022
Apache License 2.0
advent-of-code-2023/src/main/kotlin/eu/janvdb/aoc2023/day11/day11.kt
janvdbergh
318,992,922
false
{"Java": 1000798, "Kotlin": 284065, "Shell": 452, "C": 335}
package eu.janvdb.aoc2023.day11 import eu.janvdb.aocutil.kotlin.point2d.Point2DLong import eu.janvdb.aocutil.kotlin.readLines //private const val FILENAME = "input11-test.txt" private const val FILENAME = "input11.txt" fun main() { runWithDrift(1) runWithDrift(999_999) } private fun runWithDrift(drift: Int) { val galaxies = parseGalaxies(drift) val sum = combinations(galaxies).sumOf { it.first.manhattanDistanceTo(it.second) } println(sum) } private fun parseGalaxies(drift: Int): List<Point2DLong> { val unshiftedPoints = parseInput() return shiftPoints(unshiftedPoints, drift) } private fun parseInput() = readLines(2023, FILENAME).flatMapIndexed { y, line -> line.mapIndexed { x, c -> if (c == '#') Point2DLong(x, y) else null } }.filterNotNull().sorted() private fun shiftPoints(unshiftedPoints: List<Point2DLong>, drift: Int): List<Point2DLong> { val minY = unshiftedPoints.minOf { it.y } val maxY = unshiftedPoints.maxOf { it.y } val jefke = (minY..maxY).reversed() .filter { y -> unshiftedPoints.none { it.y == y } } val shiftedByRows = jefke .fold(unshiftedPoints) { points, y -> points.map { if (it.y > y) Point2DLong(it.x, it.y + drift) else it } } val minX = unshiftedPoints.minOf { it.x } val maxX = unshiftedPoints.maxOf { it.x } val joske = (minX..maxX).reversed() .filter { x -> unshiftedPoints.none { it.x == x } } val shiftedBxCols = joske .fold(shiftedByRows) { points, x -> points.map { if (it.x > x) Point2DLong(it.x + drift, it.y) else it } } return shiftedBxCols } private fun combinations(galaxies: List<Point2DLong>): Sequence<Pair<Point2DLong, Point2DLong>> { return (0..<galaxies.size).asSequence().flatMap { i -> (i + 1..<galaxies.size).asSequence().map { j -> galaxies[i] to galaxies[j] } } }
0
Java
0
0
78ce266dbc41d1821342edca484768167f261752
1,766
advent-of-code
Apache License 2.0
src/Day18.kt
Kvest
573,621,595
false
{"Kotlin": 87988}
import kotlin.math.max fun main() { val testInput = readInput("Day18_test") check(part1(testInput) == 64) check(part2(testInput) == 58) val input = readInput("Day18") println(part1(input)) println(part2(input)) } private fun part1(input: List<String>): Int { val cubes = input.to3DMatrix() return solve(input, cubes) } private fun part2(input: List<String>): Int { val cubes = input.to3DMatrix() val water = fillWithWater(cubes) return solve(input, water) } private fun solve(input: List<String>, emptyCubes: Boolean3DMatrix): Int { return input.sumOf { var cnt = 0 val (xStr,yStr,zStr) = it.split(",") val x = xStr.toInt() val y = yStr.toInt() val z = zStr.toInt() if (emptyCubes.isEmpty(x + 1, y, z)) cnt++ if (emptyCubes.isEmpty(x - 1, y, z)) cnt++ if (emptyCubes.isEmpty(x, y + 1, z)) cnt++ if (emptyCubes.isEmpty(x, y - 1, z)) cnt++ if (emptyCubes.isEmpty(x, y, z + 1)) cnt++ if (emptyCubes.isEmpty(x, y, z - 1)) cnt++ cnt } } private fun List<String>.to3DMatrix(): Boolean3DMatrix { var xMax = 0 var yMax = 0 var zMax = 0 this.forEach { val (x,y,z) = it.split(",") xMax = max(xMax, x.toInt()) yMax = max(yMax, y.toInt()) zMax = max(zMax, z.toInt()) } val result = Array(xMax + 1) { Array(yMax + 1) { BooleanArray(zMax + 1) } } this.forEach { val (x, y, z) = it.split(",") result[x.toInt()][y.toInt()][z.toInt()] = true } return result } private fun fillWithWater(cubes: Boolean3DMatrix): Boolean3DMatrix { val result = Array(cubes.size) { Array(cubes[0].size) { BooleanArray(cubes[0][0].size) { true } } } val xLastIndex = cubes.lastIndex val yLastIndex = cubes[0].lastIndex val zLastIndex = cubes[0][0].lastIndex for (x in cubes.indices) { for (y in cubes[0].indices) { fill(cubes, result, x, y, 0) fill(cubes, result, x, y, zLastIndex) } } for (x in cubes.indices) { for (z in cubes[0][0].indices) { fill(cubes, result, x, 0, z) fill(cubes, result, x, yLastIndex, z) } } for (y in cubes[0].indices) { for (z in cubes[0][0].indices) { fill(cubes, result, 0, y, z) fill(cubes, result, xLastIndex, y, z) } } return result } private fun fill(cubes: Boolean3DMatrix, water: Boolean3DMatrix, x: Int, y: Int, z: Int) { if (!water.isXYZInside(x, y, z) || cubes[x][y][z] || !water[x][y][z]) { return } water[x][y][z] = false fill(cubes, water, x + 1, y, z) fill(cubes, water, x - 1, y, z) fill(cubes, water, x, y + 1, z) fill(cubes, water, x, y - 1, z) fill(cubes, water, x, y, z + 1) fill(cubes, water, x, y, z - 1) } private fun Boolean3DMatrix.isEmpty(x: Int, y: Int, z: Int): Boolean { return if (this.isXYZInside(x, y, z)) { !this[x][y][z] } else { true } } private fun Boolean3DMatrix.isXYZInside(x: Int, y: Int, z: Int): Boolean { return (x in this.indices && y in this[x].indices && z in this[x][y].indices) }
0
Kotlin
0
0
6409e65c452edd9dd20145766d1e0ea6f07b569a
3,277
AOC2022
Apache License 2.0
src/commonMain/kotlin/ai/hypergraph/kaliningraph/repair/ContextualEdits.kt
breandan
245,074,037
false
{"Kotlin": 1482924, "Haskell": 744, "OCaml": 200}
package ai.hypergraph.kaliningraph.repair import ai.hypergraph.kaliningraph.parsing.* import kotlin.random.Random enum class EditType { INS, DEL, SUB } data class ContextEdit(val type: EditType, val context: Context, val newMid: String) { override fun toString(): String = context.run { "$type, (( " + when (type) { EditType.INS -> "$left [${newMid}] $right" EditType.DEL -> "$left ~${mid}~ $right" EditType.SUB -> "$left [${mid} -> ${newMid}] $right" } + " // " + when (type) { EditType.INS -> "$left [${newMid}] $right" EditType.DEL -> "$left ~${mid}~ $right" EditType.SUB -> "$left [${mid} -> ${newMid}] $right" } + " ))" } } data class CEAProb(val cea: ContextEdit, val idx: Int, val frequency: Int) { override fun equals(other: Any?): Boolean = when (other) { is CEAProb -> cea == other.cea && idx == other.idx else -> false } override fun hashCode(): Int = 31 * cea.hashCode() + idx override fun toString(): String = "[[ $cea, $idx, $frequency ]]" } data class Context(val left: String, val mid: String, val right: String) { override fun equals(other: Any?) = when (other) { is Context -> left == other.left && mid == other.mid && right == other.right else -> false } override fun hashCode(): Int { var result = left.hashCode() result = 31 * result + mid.hashCode() result = 31 * result + right.hashCode() return result } } data class CEADist(val allProbs: Map<ContextEdit, Int>) { val P_delSub = allProbs.filter { it.key.type != EditType.INS } val P_insert = allProbs.filter { it.key.type == EditType.INS } val P_delSubOnCtx = P_delSub.keys.groupBy { it.context } val P_insertOnCtx = P_insert.keys.groupBy { it.context } val subLeft: Map<String, Set<String>> = allProbs.keys.filter { it.type == EditType.SUB } .groupBy { it.context.left }.mapValues { it.value.map { it.newMid }.toSet() } val insLeft: Map<String, Set<String>> = allProbs.keys.filter { it.type == EditType.INS } .groupBy { it.context.left }.mapValues { it.value.map { it.newMid }.toSet() } val topThreshold = 50 val topIns = allProbs.entries .filter { it.key.type == EditType.INS }.map { it.key.newMid to it.value } .groupBy { it.first }.mapValues { it.value.sumOf { it.second } } .entries.sortedBy { -it.value }.take(topThreshold).map { it.key }.toSet() val topSub = allProbs.entries .filter { it.key.type == EditType.SUB }.map { it.key.newMid to it.value } .groupBy { it.first }.mapValues { it.value.sumOf { it.second } } .entries.sortedBy { -it.value }.take(topThreshold).map { it.key }.toSet() // val insLeftRight: Map<Pair<String, String>, Set<String>> = allProbs.entries // .filter { it.key.type == EditType.INS }.filter { 10 < it.value }.map { it.key } // .groupBy { it.context.left to it.context.right }.mapValues { it.value.map { it.newMid }.toSet() } } fun CFG.contextualRepair(broken: List<String>): Sequence<List<String>> { val initREAs: List<CEAProb> = contextCSV.relevantEditActions(broken) // Bonuses for previously sampled edits that produced a valid repair val bonusProbs = mutableMapOf<ContextEdit, Int>() // println("Total relevant edit actions: ${initREAs.size}\n${initREAs.take(5).joinToString("\n")}\n...") val samplerTimeout = 10000L var (total, uniqueValid) = 0 to 0 return generateSequence { broken }.map { try { it.sampleEditTrajectoryV0(contextCSV, initREAs, bonusProbs) } catch (e: Exception) { println(broken.joinToString(" ")); e.printStackTrace(); listOf<String>() to listOf() } }.mapNotNull { (finalSeq, edits ) -> if (finalSeq in language) { edits.forEach { bonusProbs[it.cea] = (bonusProbs[it.cea] ?: 0) + 1 } uniqueValid++ finalSeq } else null }.distinct() } fun List<String>.sampleEditTrajectoryV0( ceaDist: CEADist, initREAs: List<CEAProb>, // Bonuses for previously sampled edits that produced a valid repair bonusProbs: Map<ContextEdit, Int>? = null, lengthCDF: List<Double> = listOf(0.5, 0.8, 1.0) ): Pair<List<String>, List<CEAProb>> { // First sample the length of the edit trajectory from the length distribution val rand = Random.nextDouble() val length = lengthCDF.indexOfFirst { rand < it } + 1 if (initREAs.isEmpty()) return this to listOf() val ceaProbs = mutableListOf<CEAProb>() // Now sample an edit trajectory of that length from the edit distribution var listPrime = initREAs.normalizeAndSampleV0(bonusProbs) .also { ceaProbs.add(it) } .let { applyEditAction(it.cea, it.idx + 1) } for (i in 1..length) { val relevantEditActions = ceaDist.relevantEditActions(listPrime) if (relevantEditActions.isEmpty()) { // println("$i-th iteration, no relevant edit actions for: ${listPrime.joinToString(" ") { it.toPyRuleName() }}") return listPrime to ceaProbs } val sampledEdit = relevantEditActions.normalizeAndSampleV0(bonusProbs) .also { ceaProbs.add(it) } listPrime = listPrime.applyEditAction(sampledEdit.cea, sampledEdit.idx + 1) } return listPrime to ceaProbs } // Faster than the above fun List<CEAProb>.normalizeAndSampleV0(bonusProbs: Map<ContextEdit, Int>?): CEAProb { val cdf: List<Int> = (if (bonusProbs == null) map { it.frequency } else map { it.frequency + bonusProbs.getOrElse(it.cea) { 0 } * 100 }) .let { freqs -> val cdf = mutableListOf<Int>() var sum = 0 for (i in freqs.indices) { sum += freqs[i] cdf.add(sum) } cdf } val sample: Int = Random.nextInt(cdf.last()) return this[cdf.binarySearch(sample).let { if (it < 0) -it - 1 else it }.coerceIn(indices)] } fun CEADist.relevantEditActions(snippet: List<String>): List<CEAProb> { val relevantEditActions = mutableListOf<CEAProb>() for (i in 0 until snippet.size - 2) { val ctx = Context(snippet[i], snippet[i + 1], snippet[i + 2]) P_insertOnCtx[Context(ctx.left, "", ctx.mid)]?.forEach { relevantEditActions.add(CEAProb(it, i, P_insert[it]!!)) } if (i == snippet.size - 3) P_insertOnCtx[Context(ctx.mid, "", ctx.right)]?.forEach { relevantEditActions.add(CEAProb(it, i, P_insert[it]!!)) } P_delSubOnCtx[ctx]?.forEach { relevantEditActions.add(CEAProb(it, i, P_delSub[it]!!)) } } return relevantEditActions } fun List<String>.applyEditAction(cea: ContextEdit, idx: Int): List<String> = when (cea.type) { // 6409ms, 20% EditType.INS -> subList(0, idx) + cea.newMid + subList(idx + 1, size) // 17937ms, 55% EditType.DEL -> subList(0, idx) + subList(idx + 1, size) // 2607ms, 8% EditType.SUB -> subList(0, idx) + cea.newMid + subList(idx + 1, size) // 5552ms, 17% }//.also { println("Start:$this\n${cea.type}/${cea.context}/${cea.newMid}/${idx}\nAfter:$it") }
0
Kotlin
8
100
c755dc4858ed2c202c71e12b083ab0518d113714
6,874
galoisenne
Apache License 2.0
src/day08/Day08.kt
marcBrochu
573,884,748
false
{"Kotlin": 12896}
package day08 import readInput import java.lang.Integer.max fun main() { fun part1(input: List<String>): Int { val height = input.size val width = input.first().length val grid = input.map { it.map { it.digitToInt() } } var numVisible = 0 for (h in 0 until height) { for (w in 0 until width) { val curr = grid[h][w] if (w == 0 || h == 0 || w == width - 1 || h == height - 1) { numVisible++ } else { val columnValues = grid.map { it[w] } val leftVisible = grid[h].take(w).all { it < curr } val rightVisible = grid[h].drop(w + 1).all { it < curr } val topVisible = columnValues.take(h).all { it < curr } val bottomVisible = columnValues.drop(h + 1).all { it < curr } if (leftVisible || rightVisible || topVisible || bottomVisible) { numVisible++ } } } } return numVisible } fun part2(input: List<String>): Int { val height = input.size val width = input.first().length val grid = input.map { it.map { it.digitToInt() } } var maxScenicScore = 0 for (h in 0 until height) { for (w in 0 until width) { if (w == 0 || h == 0 || w == width - 1 || h == height - 1) { continue } val curr = grid[h][w] val columnValues = grid.map { it[w] } var leftScenicScore = grid[h].take(w).reversed().takeWhile { it < curr }.count() var rightScenicScore = grid[h].drop(w + 1).takeWhile { it < curr }.count() var topScenicScore = columnValues.take(h).reversed().takeWhile { it < curr }.count() var bottomScenicScore = columnValues.drop(h + 1).takeWhile { it < curr }.count() if (leftScenicScore == 0 || leftScenicScore < grid[h].take(w).size) { leftScenicScore++ } if (rightScenicScore == 0 || rightScenicScore < grid[h].drop(w + 1).size) { rightScenicScore++ } if (topScenicScore == 0 || topScenicScore < columnValues.take(h).size) { topScenicScore++ } if (bottomScenicScore == 0 || bottomScenicScore < columnValues.drop(h + 1).size) { bottomScenicScore++ } val currentScenicScore = leftScenicScore * rightScenicScore * topScenicScore * bottomScenicScore maxScenicScore = max(currentScenicScore, maxScenicScore) } } return maxScenicScore } val input = readInput("day08/Day08") println(part1(input)) println(part2(input)) }
0
Kotlin
0
2
8d4796227dace8b012622c071a25385a9c7909d2
2,936
advent-of-code-kotlin
Apache License 2.0
src/Day11.kt
SergeiMikhailovskii
573,781,461
false
{"Kotlin": 32574}
fun main() { val input = readInput("Day11_test") val monkeys = mutableListOf<Monkey>() val divideOnList = mutableListOf<Int>() input.filter { it.isNotEmpty() }.chunked(6).forEach { val items = it[1].substringAfterLast("Starting items: ").split(", ").map(String::toInt) val operation = it[2].substringAfterLast("Operation: new = ").split(" ") val divisibleBy = it[3].substringAfterLast("Test: divisible by ").toInt() val ifTrueTo = it[4].substringAfterLast("If true: throw to monkey ").toInt() val ifFalseTo = it[5].substringAfterLast("If false: throw to monkey ").toInt() monkeys.add( Monkey( items = items.map(Monkey::Item).toMutableList(), ifTrueTo = ifTrueTo, ifFalseTo = ifFalseTo, operation = Monkey.Operation( action = operation[1], value = operation[2].toIntOrNull() ) ) ) divideOnList.add(divisibleBy) } monkeys.forEach { it.items.forEach { item -> val list = mutableListOf<Int>() divideOnList.forEach { divider -> list.add(item.value % divider) } item.divisionResult.addAll(list) } } for (i in 0 until 10_000) { monkeys.forEachIndexed { monkeyIndex, monkey -> monkey.intersections += monkey.items.size val iterator = monkey.items.iterator() while (iterator.hasNext()) { val it = iterator.next() if (monkey.operation.action == "*") { it.divisionResult = it.divisionResult.map { div -> div * (monkey.operation.value ?: div) }.toMutableList() } else { it.divisionResult = it.divisionResult.map { div -> div + (monkey.operation.value ?: div) }.toMutableList() } for (ind in 0 until it.divisionResult.size) { it.divisionResult[ind] %= divideOnList[ind] } if (it.divisionResult[monkeyIndex] == 0) { monkeys[monkey.ifTrueTo].items.add(it) } else { monkeys[monkey.ifFalseTo].items.add(it) } iterator.remove() } } } val result = monkeys.map { it.intersections.toLong() }.sortedDescending().take(2).reduce { acc, i -> acc * i } println(result) } class Monkey( val items: MutableList<Item>, val ifTrueTo: Int, val ifFalseTo: Int, val operation: Operation, var intersections: Int = 0, ) { class Item( val value: Int, var divisionResult: MutableList<Int> = mutableListOf() ) class Operation( val action: String, val value: Int? ) }
0
Kotlin
0
0
c7e16d65242d3be6d7e2c7eaf84f90f3f87c3f2d
2,946
advent-of-code-kotlin
Apache License 2.0
src/day7/Day7.kt
bartoszm
572,719,007
false
{"Kotlin": 39186}
package day7 import readInput import java.util.* fun main() { val testInput = readInput("day07/test") val input = readInput("day07/input") println(solve1(testInput)) println(solve1(input)) println(solve2(testInput)) println(solve2(input)) } fun dirSizes(lines: List<String>) : Sequence<Int> { val s = Stack<Pair<String, MutableList<Int>>>() fun compute(): Int { val (_, elems) = s.pop() val result = elems.sum() if(s.isNotEmpty()) { s.peek().second.add(result) } return result } fun handleData(l: String) { val result = """^(\w+)""".toRegex() val (f) = result.find(l)!!.destructured if(f != "dir") s.peek().second.add(f.toInt()) } fun withResult(l: String): Boolean { val cmd = l.drop(2).split("""\s+""".toRegex()) if(cmd[0] == "cd") { if(".." == cmd[1]) { return true } else { s.push(cmd[1] to mutableListOf()) } } return false } return sequence { for(l in lines) { if(l.startsWith("$")) { if(withResult(l)) { yield(compute()) } } else { handleData(l) } } while(s.isNotEmpty()) { yield(compute()) } } } fun solve1(lines: List<String>): Int { return dirSizes(lines).filter { it <= 100000 }.sum() } fun solve2(lines: List<String>): Int { val r = dirSizes(lines).toList() val free = 70000000 - r.max() val needed = 30000000 return dirSizes(lines) .filter { free + it >= needed }.min() }
0
Kotlin
0
0
f1ac6838de23beb71a5636976d6c157a5be344ac
1,675
aoc-2022
Apache License 2.0
src/day5/Day05.kt
HGilman
572,891,570
false
{"Kotlin": 109639, "C++": 5375, "Python": 400}
package day5 import readTextGroups import java.util.* fun main() { val (testStacksInput, testProcedureInput) = readTextGroups("day5/Day05_test") check(Day.part1(getStacks(testStacksInput), getProcedure(testProcedureInput)) == "CMZ") val (stackInput, procedureInput)= readTextGroups("day5/Day05") println(Day.part1(getStacks(stackInput), getProcedure(procedureInput))) println(Day.part2(getStacks(stackInput), getProcedure(procedureInput))) } fun getStacks(firstPartInput: String): List<Stack<Char>> { val firstPartData: List<String> = firstPartInput.split("\n") val stackAmount = firstPartData .last() .last { it.isDigit() } .digitToInt() val stacks = List<Stack<Char>>(stackAmount) { Stack() } // don't take last string val stackData = firstPartData.dropLast(1) // go from bottom to top stackData .reversed() .forEach { line -> for (i in 0 until stackAmount) { val symbolIndex = (1 + i * 4) if (symbolIndex < line.length) { val symbol = line[symbolIndex] if (!symbol.isWhitespace()) { stacks[i].push(symbol) } } } } return stacks } fun getProcedure(secondPartInput: String): List<Triple<Int, Int, Int>> { return secondPartInput .split("\n") .map { val parts = it.split(' ') Triple(parts[1].toInt(), parts[3].toInt() - 1, parts[5].toInt() - 1) } } object Day { private fun getResult(stacks: List<Stack<Char>>): String { return stacks.map { s -> s.peek() }.fold("") { acc, c -> acc + c } } fun part1(stacks: List<Stack<Char>>, procedure: List<Triple<Int, Int, Int>>): String { procedure.forEach { p -> val (amount, from, to) = p val fromStack = stacks[from] val toStack = stacks[to] repeat(amount) { if (fromStack.isNotEmpty()) { toStack.push(fromStack.pop()) } } } return getResult(stacks) } fun part2(stacks: List<Stack<Char>>, procedure: List<Triple<Int, Int, Int>>): String { procedure.forEach { p -> val (amount, from, to) = p val fromStack = stacks[from] val toStack = stacks[to] val popArray = mutableListOf<Char>() repeat(amount) { if (fromStack.isNotEmpty()) { popArray.add(fromStack.pop()) } } popArray.reversed().forEach { pop -> toStack.push(pop) } } return getResult(stacks) } }
0
Kotlin
0
1
d05a53f84cb74bbb6136f9baf3711af16004ed12
2,829
advent-of-code-2022
Apache License 2.0
02/02.kt
Steve2608
433,779,296
false
{"Python": 34592, "Julia": 13999, "Kotlin": 11412, "Shell": 349, "Cython": 211}
import java.io.File import kotlin.math.abs private data class Direction(val direction: String, val length: Int) { fun toVec2(): Vec2 = when (direction) { "forward" -> Vec2(length, 0) "down" -> Vec2(0, length) "up" -> Vec2(0, -length) else -> throw IllegalArgumentException(direction) } fun toVec3(): Vec3 = when (direction) { "forward" -> Vec3(length, 0, 0) "down" -> Vec3(0, 0, length) "up" -> Vec3(0, 0, -length) else -> throw IllegalArgumentException(direction) } } private data class Vec2(val x: Int, val y: Int) { operator fun plus(other: Vec2) = Vec2(x + other.x, y + other.y) } private data class Vec3(val x: Int, val y: Int, val aim: Int) { operator fun plus(other: Vec3) = Vec3(x + other.x, y + other.x * aim, aim + other.aim) } private fun part1(directions: Array<Direction>): Int { val pos = directions.map { it.toVec2() }.reduce { acc, vec2 -> acc + vec2 } return abs(pos.x) * abs(pos.y) } private fun part2(directions: Array<Direction>): Int { val pos = directions.map { it.toVec3() }.reduce { acc, vec3 -> acc + vec3 } return abs(pos.x) * abs(pos.y) } fun main() { fun File.readData() = this.readLines().map { val split = it.split(" ") return@map Direction(direction = split[0], length = split[1].toInt()) }.toTypedArray() val example: Array<Direction> = File("example.txt").readData() assert(150 == part1(example)) { "Expected 15 * 10 = 150" } assert(900 == part2(example)) { "Expected 15 * 60 = 900" } val data: Array<Direction> = File("input.txt").readData() println(part1(data)) println(part2(data)) }
0
Python
0
1
2dcad5ecdce5e166eb053593d40b40d3e8e3f9b6
1,567
AoC-2021
MIT License
src/2022/Day23.kt
ttypic
572,859,357
false
{"Kotlin": 94821}
package `2022` import readInput fun main() { fun processRound(elfPositions: Set<Point>, directions: List<Direction>): Set<Point> { val currentToNext: MutableMap<Point, Point> = mutableMapOf() val proposeToCurrent: MutableMap<Point, Point> = mutableMapOf() elfPositions.forEach { point -> val noNeedToMove = directions.all { direction -> point.directionPoints(direction).all { !elfPositions.contains(it) } } val direction = directions.firstOrNull { direction -> point.directionPoints(direction).all { !elfPositions.contains(it) } } if (direction == null || noNeedToMove) { proposeToCurrent[point] = point currentToNext[point] = point } else if (proposeToCurrent.contains(point.toDirection(direction))) { val collision = proposeToCurrent[point.toDirection(direction)]!! currentToNext[point] = point currentToNext[collision] = collision } else { currentToNext[point] = point.toDirection(direction) proposeToCurrent[point.toDirection(direction)] = point } } return currentToNext.values.toSet() } fun part1(input: List<String>): Int { var elfPositions = input.flatMapIndexed { y, line -> line.mapIndexedNotNull { x, char -> if (char == '#') Point(x, y) else null } }.toSet() val directions = Direction.values().toMutableList() repeat(10) { elfPositions = processRound(elfPositions, directions) directions.shift() } val maxX = elfPositions.maxOf { it.x } val maxY = elfPositions.maxOf { it.y } val minX = elfPositions.minOf { it.x } val minY = elfPositions.minOf { it.y } return (maxX - minX + 1) * (maxY - minY + 1) - elfPositions.size } fun part2(input: List<String>): Int { var elfPositions = input.flatMapIndexed { y, line -> line.mapIndexedNotNull { x, char -> if (char == '#') Point(x, y) else null } }.toSet() val directions = Direction.values().toMutableList() var rounds = 0 do { rounds++ val prevPositions = elfPositions elfPositions = processRound(elfPositions, directions) directions.shift() } while (prevPositions != elfPositions) return rounds } // test if implementation meets criteria from the description, like: val testInput = readInput("Day23_test") println(part1(testInput)) println(part2(testInput)) check(part1(testInput) == 110) check(part2(testInput) == 20) val input = readInput("Day23") println(part1(input)) println(part2(input)) } enum class Direction { north, south, west, east } fun Point.directionPoints(direction: Direction): List<Point> { return when(direction) { Direction.north -> listOf(Point(x - 1, y - 1), Point(x, y - 1), Point(x + 1, y - 1)) Direction.south -> listOf(Point(x - 1, y + 1), Point(x, y + 1), Point(x + 1, y + 1)) Direction.west -> listOf(Point(x - 1, y - 1), Point(x - 1, y), Point(x - 1, y + 1)) Direction.east -> listOf(Point(x + 1, y - 1), Point(x + 1, y), Point(x + 1, y + 1)) } } fun Point.toDirection(direction: Direction): Point { return when(direction) { Direction.north -> Point(x, y - 1) Direction.south -> Point(x, y + 1) Direction.west -> Point(x - 1, y) Direction.east -> Point(x + 1, y) } } fun MutableList<Direction>.shift() { val first = removeFirst() add(first) } fun Set<Point>.print() { val maxX = maxOf { it.x } val maxY = maxOf { it.y } val minX = minOf { it.x } val minY = minOf { it.y } println((minY..maxY).joinToString(separator = "\n") { y -> (minX..maxX).joinToString(separator = "") { x -> if (contains(Point(x, y))) "#" else "." } }) }
0
Kotlin
0
0
b3e718d122e04a7322ed160b4c02029c33fbad78
3,963
aoc-2022-in-kotlin
Apache License 2.0
src/Day04.kt
jwklomp
572,195,432
false
{"Kotlin": 65103}
fun main() { fun isFullOverlap(a: List<String>, b: List<String>): Boolean = (a.first().toInt() <= b.first().toInt() && a.last().toInt() >= b.last().toInt()) || (b.first() .toInt() <= a.first().toInt() && b.last().toInt() >= a.last().toInt()) fun isPartialOverlap(a: List<String>, b: List<String>): Boolean = (a.first().toInt()..a.last().toInt()).intersect(b.first().toInt()..b.last().toInt()).isNotEmpty() fun part1(input: List<String>): Int = input .map { it.split(",") } .map { i -> i.map { it.split("-") } } .count { isFullOverlap(it.first(), it.last()) } fun part2(input: List<String>): Int = input .map { it.split(",") } .map { i -> i.map { it.split("-") } } .count { isPartialOverlap(it.first(), it.last()) } val testInput = readInput("Day04_test") println(part1(testInput)) println(part2(testInput)) val input = readInput("Day04") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
1b1121cfc57bbb73ac84a2f58927ab59bf158888
1,045
aoc-2022-in-kotlin
Apache License 2.0
src/Day02.kt
halirutan
575,809,118
false
{"Kotlin": 24802}
fun main() { val rules = mapOf( Pair("A", "X") to 1 + 3, Pair("A", "Y") to 2 + 6, Pair("A", "Z") to 3 + 0, Pair("B", "X") to 1 + 0, Pair("B", "Y") to 2 + 3, Pair("B", "Z") to 3 + 6, Pair("C", "X") to 1 + 6, Pair("C", "Y") to 2 + 0, Pair("C", "Z") to 3 + 3, ) fun part1(input: List<String>): Int { return input.sumOf { val split = it.split(" ") rules[Pair(split[0], split[1])] ?: throw Error("That should not happen") } } val translate = mapOf( "A" to "X", "B" to "Y", "C" to "Z" ) fun fillAnswer(pair: List<String>): Pair<String, String> { val move = pair[0] return when (pair[1]) { "X" -> when (move) { "A" -> Pair(move, "Z") "B" -> Pair(move, "X") "C" -> Pair(move, "Y") else -> throw Error("That should not happen") } "Y" -> Pair(move, translate[move]!!) "Z" -> when (move) { "A" -> Pair(move, "Y") "B" -> Pair(move, "Z") "C" -> Pair(move, "X") else -> throw Error("That also should not happen") } else -> throw Error("Man.. it just keeps coming, right?") } } fun part2(input: List<String>): Int { return input.sumOf { val split = it.split(" ") rules[fillAnswer(split)]?: throw Error("<NAME>") } } val testInput = readInput("Day02_test") val realInput = readInput("Day02") println("Part 1 test input: ${part1(testInput)}") println("Part 1 real input: ${part1(realInput)}") println("Part 2 test input: ${part2(testInput)}") println("Part 2 real input: ${part2(realInput)}") }
0
Kotlin
0
0
09de80723028f5f113e86351a5461c2634173168
1,852
AoC2022
Apache License 2.0
src/main/kotlin/com/oocode/CamelMap.kt
ivanmoore
725,978,325
false
{"Kotlin": 42155}
package com.oocode fun directionsFrom(input: String): CamelMap { val lines = input.split("\n") val instructions = lines[0] .map { if (it == 'L') Choice.Left else Choice.Right } val nodes = lines.drop(2).map { nodeFrom(it) } return CamelMap(instructions, nodes) } enum class Choice { Left, Right } data class CamelMap( private val instructions: List<Choice>, private val nodes: List<Node> ) { private val nodesByName = nodes.associateBy { it.name } fun numberOfSteps(): Long { val startNodes = nodes.filter { it.name.endsWith("A") } val numberOfStepsForEveryStartingNode = startNodes.map { numberOfSteps(it) } return findLCMOfListOfNumbers(numberOfStepsForEveryStartingNode) } private fun numberOfSteps(startNode: Node): Long { var currentNode = startNode var result = 0L while (true) { instructions.forEach { instruction -> if (currentNode.name.endsWith("Z")) return result result++ currentNode = nodesByName[currentNode.follow(instruction)]!! } } } } fun nodeFrom(line: String): Node = line .replace("(", "") .replace(")", "") .split("=") .let { val name = it[0].trim() val children = it[1].split(",") return Node(name, Children(children[0].trim(), children[1].trim())) } data class Children(val left: String, val right: String) data class Node(val name: String, val children: Children) { fun follow(instruction: Choice) = if(instruction==Choice.Left) children.left else children.right } // Copied from https://www.baeldung.com/kotlin/lcm (and then replaced Int with Long) // because I'm not interested in this part of the solution. // I would expect this to be a thing you could find in a library fun findLCM(a: Long, b: Long): Long { val larger = if (a > b) a else b val maxLcm = a * b var lcm = larger while (lcm <= maxLcm) { if (lcm % a == 0L && lcm % b == 0L) { return lcm } lcm += larger } return maxLcm } fun findLCMOfListOfNumbers(numbers: List<Long>): Long { var result = numbers[0] for (i in 1 until numbers.size) { result = findLCM(result, numbers[i]) } return result }
0
Kotlin
0
0
36ab66daf1241a607682e7f7a736411d7faa6277
2,330
advent-of-code-2023
MIT License
src/main/aoc2021/Day21.kt
nibarius
154,152,607
false
{"Kotlin": 963896}
package aoc2021 class Day21(input: List<String>) { private val p1start = input.first().last().digitToInt() private val p2start = input.last().last().digitToInt() class Player(var pos: Int, var score: Int) { // Move the player and return true if the player won fun move(howMuch: Int): Boolean { pos = ((pos + howMuch - 1) % 10) + 1 score += pos return score >= 1000 } } class Die { var rolls: Int = 0 private var value = 1 fun roll(): Int { val result = when (value) { 100 -> 103 99 -> 200 else -> 3 * value + 3 // x + (x + 1) + (x + 2) = 3x + 3 } rolls += 3 value = (rolls % 100) + 1 return result } } private fun playDeterministic(): Int { val p1 = Player(p1start, 0) val p2 = Player(p2start, 0) val die = Die() while(!p1.move(die.roll()) && !p2.move(die.roll())) Unit // Play until one player wins return minOf(p1.score, p2.score) * die.rolls } // Map of possible sum of three dice to number of different die combinations that result in that sum private val dieRolls = listOf(3 to 1, 4 to 3, 5 to 6, 6 to 7, 7 to 6, 8 to 3, 9 to 1) // count how many ways a player can throw the die and win. Returns a map of number of turns to win // to the total amount of dice rolls that results in a victory on that amount of turns. private fun countWaysToFinish( pos: Int, score: Int, turns: Int, totalDieRolls: Long, result: MutableMap<Int, Long> ): MutableMap<Int, Long> { if (score >= 21) { result[turns] = result.getOrDefault(turns, 0) + totalDieRolls return result } dieRolls.forEach { (rolled, count) -> val nextPos = ((pos + rolled - 1) % 10) + 1 countWaysToFinish(nextPos, score + nextPos, turns + 1, count * totalDieRolls, result) } return result } // Counts the number of ways a player can throw the die and not finish within the given amount of turns private fun countWaysToNotFinish(pos: Int, score: Int, turnsLeft: Int): Long { return when { score >= 21 -> 0 // This branch reached the finish, don't count it turnsLeft == 0 -> 1 // This branch ran out of turns, count it else -> dieRolls.sumOf { (rolled, dieCombinationCount) -> val nextPos = ((pos + rolled - 1) % 10) + 1 dieCombinationCount * countWaysToNotFinish(nextPos, score + nextPos, turnsLeft - 1) } } } // Actually only counts in how many ways p1 can win, but with my input and with the example input p1 wins most private fun playDirac(): Long { return countWaysToFinish(p1start, 0, 0, 1, mutableMapOf()) .toList() .sumOf { (p1Turns, totalP1Rolls) -> // For p1 to win in p1Turns, p2 must not finish in p1Turns - 1 totalP1Rolls * countWaysToNotFinish(p2start, 0, p1Turns - 1) } } fun solvePart1(): Int { return playDeterministic() } fun solvePart2(): Long { return playDirac() } }
0
Kotlin
0
6
f2ca41fba7f7ccf4e37a7a9f2283b74e67db9f22
3,308
aoc
MIT License
src/Day02.kt
lmoustak
573,003,221
false
{"Kotlin": 25890}
enum class Roshambo(val points: Int) { ROCK(1), PAPER(2), SCISSORS(3) } val winningMap = mapOf( Roshambo.ROCK to Roshambo.PAPER, Roshambo.PAPER to Roshambo.SCISSORS, Roshambo.SCISSORS to Roshambo.ROCK ) fun main() { fun part1(input: List<String>): Int { val roshamboMap = mapOf( "A" to Roshambo.ROCK, "B" to Roshambo.PAPER, "C" to Roshambo.SCISSORS, "X" to Roshambo.ROCK, "Y" to Roshambo.PAPER, "Z" to Roshambo.SCISSORS ) var score = 0 input.forEach { val picks = it.split(' ') val opponentPick = roshamboMap[picks[0]]!! val playerPick = roshamboMap[picks[1]]!! score += playerPick.points + if (opponentPick == playerPick) { 3 } else if (playerPick == winningMap[opponentPick]) { 6 } else { 0 } } return score } fun part2(input: List<String>): Int { val roshamboMap = mapOf( "A" to Roshambo.ROCK, "B" to Roshambo.PAPER, "C" to Roshambo.SCISSORS ) var score = 0 input.forEach { val picks = it.split(' ') val opponentPick = roshamboMap[picks[0]]!! val playerPick = when (picks[1]) { "Y" -> opponentPick "Z" -> winningMap[opponentPick] "X" -> winningMap.filterValues { pick -> pick == opponentPick }.keys.first() else -> throw IllegalArgumentException() } score += playerPick!!.points + if (opponentPick == playerPick) { 3 } else if (playerPick == winningMap[opponentPick]) { 6 } else { 0 } } return score } val input = readInput("Day02") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
bd259af405b557ab7e6c27e55d3c419c54d9d867
1,983
aoc-2022-kotlin
Apache License 2.0
src/main/kotlin/aoc19/Day3.kt
tahlers
225,198,917
false
null
package aoc19 import kotlin.math.abs object Day3 { enum class Direction { UP, DOWN, LEFT, RIGHT } data class Step(val direction: Direction, val distance: Int) { fun positions(startPos: Pos): List<Pos> { return when (direction) { Direction.UP -> ((startPos.y + 1)..(startPos.y + distance)).map { Pos(startPos.x, it) } Direction.DOWN -> ((startPos.y - 1) downTo (startPos.y - distance)).map { Pos(startPos.x, it) } Direction.RIGHT -> ((startPos.x + 1)..(startPos.x + distance)).map { Pos(it, startPos.y) } Direction.LEFT -> ((startPos.x - 1) downTo (startPos.x - distance)).map { Pos(it, startPos.y) } } } } data class Pos(val x: Int, val y: Int) { fun distance(other: Pos): Int { return abs(x - other.x) + abs(y - other.y) } } fun parseSteps(stepsString: String): List<Step> { return stepsString.split(',').map { s -> val dir = s[0] val distance = s.substring(1).toInt() when (dir) { 'R' -> Step(Direction.RIGHT, distance) 'L' -> Step(Direction.LEFT, distance) 'U' -> Step(Direction.UP, distance) 'D' -> Step(Direction.DOWN, distance) else -> throw IllegalArgumentException("Unparsable step $s") } } } fun distance(wire1: String, wire2: String): Int { val wire1Steps = parseSteps(wire1) val wire2Steps = parseSteps(wire2) val wire1Positions = wire1Steps.fold(listOf(Pos(0, 0))) { init, step -> init + step.positions(init.last()) }.drop(1) val wire2Positions = wire2Steps.fold(listOf(Pos(0, 0))) { init, step -> init + step.positions(init.last()) }.drop(1) val intersections = wire1Positions.intersect(wire2Positions) val distances = intersections.map { it.distance(Pos(0, 0)) } return distances.min() ?: 0 } fun wireLength(wire1: String, wire2: String): Int { val wire1Steps = parseSteps(wire1) val wire2Steps = parseSteps(wire2) val wire1Positions = wire1Steps.fold(listOf(Pos(0, 0))) { init, step -> init + step.positions(init.last()) }.drop(1) val wire2Positions = wire2Steps.fold(listOf(Pos(0, 0))) { init, step -> init + step.positions(init.last()) }.drop(1) val intersections = wire1Positions.intersect(wire2Positions) val wire1PositionsIndexed = wire1Positions.withIndex().filter { it.value in intersections } val wire2PositionsIndexed = wire2Positions.withIndex().filter { it.value in intersections } val wire1Map = wire1PositionsIndexed.groupBy({ it.value }) { it.index + 1 } val wire2Map = wire2PositionsIndexed.groupBy({ it.value }) { it.index + 1 } return intersections.map { (wire1Map[it]?.min() ?: 0) + (wire2Map[it]?.min() ?: 0) }.min() ?: 0 } }
0
Kotlin
0
0
dae62345fca42dd9d62faadf78784d230b080c6f
3,023
advent-of-code-19
MIT License
2021/08-kt/main.kt
20Koen02
433,861,042
false
{"Rust": 84471, "TypeScript": 52261, "Python": 18461, "JavaScript": 2098, "Go": 1516, "Nim": 1501, "Kotlin": 1499, "Java": 1201, "C++": 853}
import java.io.File import kotlin.collections.listOf typealias Entry = List<List<String>> val DIGS = listOf("abcdeg", "ab", "acdfg", "abcdf", "abef", "bcdef", "bcdefg", "abd", "abcdefg", "abcdef") fun readLines(): List<Entry> { return File("in.txt").bufferedReader().readLines().map { l -> l.split(" | ").map { it.split(" ") } } } fun String.permute(result: String = ""): List<String> = if (isEmpty()) listOf(result) else flatMapIndexed { i, c -> removeRange(i, i + 1).permute(result + c) } fun partOne(entry: Entry): Int { return entry[1].filter { x -> listOf(2, 3, 4, 7).contains(x.length) }.count() } fun getValidDigit(perm: String, dig: String): Int { // Check if the digit is valid var decoded = dig.map { perm[it - 'a'] }.sorted().joinToString("") return DIGS.indexOf(decoded) } fun tryPerm(perm: String, entry: Entry): Boolean { // Check if all signal patterns are valid digits var invalid = entry[0].map { getValidDigit(perm, it) }.any { it == -1 } return !invalid } fun partTwo(entry: Entry): Int { // Find correct permutation val perm = "abcdefg".permute().find { tryPerm(it, entry) } // Concat each digit return entry[1].map { getValidDigit(perm!!, it) }.joinToString(separator = "").toInt() } fun main() { println("Running...\n") val lines = readLines() val partOne = lines.map { partOne(it) }.sum() println("Day 8 part one: $partOne") val partTwo = lines.map { partTwo(it) }.sum() println("Day 8 part two: $partTwo") }
0
Rust
1
2
e260249e488b24f0fcf7b5df16cc65f126dd7425
1,499
AdventOfCode
MIT License
src/Day02.kt
wooodenleg
572,658,318
false
{"Kotlin": 30668}
import MatchResult.* enum class HandSign( val opponentValue: String, val myValue: String, ) { Rock("A", "X"), Paper("B", "Y"), Scissors("C", "Z"); val score = ordinal + 1 val weakness: HandSign get() = when (this) { Rock -> Paper Paper -> Scissors Scissors -> Rock } companion object { private val values = buildMap { for (sign in values()) { put(sign.opponentValue, sign) put(sign.myValue, sign) } } fun parse(value: String): HandSign = values[value] ?: error("Unknown value $value") } } enum class MatchResult(val score: Int, val value: String) { Victory(6, "Z"), Draw(3, "Y"), Lost(0, "X"); companion object { private val values = buildMap { for (result in values()) { put(result.value, result) } } fun parse(value: String): MatchResult = values[value] ?: error("Unknown value $value") } } infix fun HandSign.versus(opponentSign: HandSign): Int { val result = when (opponentSign) { this -> Draw weakness -> Lost else -> Victory } return result.score + this.score } fun main() { fun part1(input: List<String>): Int { var score = 0 for (line in input) { val (opponentValue, myValue) = line.split(" ") score += HandSign.parse(myValue) versus HandSign.parse(opponentValue) } return score } fun part2(input: List<String>): Int { var score = 0 for (line in input) { val (opponentValue, resultValue) = line.split(" ") val result = MatchResult.parse(resultValue) val opponentSign = HandSign.parse(opponentValue) val mySign = when (result) { Victory -> opponentSign.weakness Draw -> opponentSign Lost -> opponentSign.weakness.weakness // get weakness of opponents weakness to complete the circle } score += mySign versus opponentSign } return score } // test if implementation meets criteria from the description, like: val testInput = readInputLines("Day02_test") check(part1(testInput) == 15) check(part2(testInput) == 12) val input = readInputLines("Day02") println(part1(input)) println(part2(input)) }
0
Kotlin
0
1
ff1f3198f42d1880e067e97f884c66c515c8eb87
2,458
advent-of-code-2022
Apache License 2.0
src/year_2022/day_12/Day12.kt
scottschmitz
572,656,097
false
{"Kotlin": 240069}
package year_2022.day_12 import readInput import util.toAlphabetPosition data class Position( val row: Int, val column: Int ) data class Heatmap ( val startingPosition: Position, val endingPosition: Position, val locations: List<List<Int>> ) object Day12 { /** * @return */ fun solutionOne(text: List<String>): Int { val startingElevation = 'a'.toAlphabetPosition() val endingElevation = 'z'.toAlphabetPosition() val heatmap = parseText( text = text, startingElevation = startingElevation, endingElevation = endingElevation ) val path = findPath(heatmap, heatmap.startingPosition, heatmap.endingPosition)!! return path.size - 1 } /** * @return */ fun solutionTwo(text: List<String>): Int { val startingElevation = 'a'.toAlphabetPosition() val endingElevation = 'z'.toAlphabetPosition() val heatmap = parseText( text = text, startingElevation = startingElevation, endingElevation = endingElevation ) val lowestLocations = mutableListOf<Position>() heatmap.locations.forEachIndexed { rowIndex, row -> row.forEachIndexed { colIndex, height -> if (height == 1) { lowestLocations.add(Position(rowIndex, colIndex)) } } } return lowestLocations .mapNotNull { position -> findPath(heatmap, position, heatmap.endingPosition)?.size } .minByOrNull { it }!! - 1 } private fun parseText( text: List<String>, startingElevation: Int, endingElevation: Int ): Heatmap { var startingPosition = Position(0, 0) var endingPosition = Position(0,0) val locations = text.mapIndexed() { row, line -> line.mapIndexed { column, letter -> when (letter) { 'S' -> { startingPosition = Position(row, column) startingElevation } 'E' -> { endingPosition = Position(row, column) endingElevation } else -> letter.toAlphabetPosition() } } } return Heatmap( startingPosition = startingPosition, endingPosition = endingPosition, locations = locations ) } private fun findPath(heatmap: Heatmap, startingPosition: Position, endingPosition: Position): List<Position>? { val shortestDistance = mutableMapOf<Position, List<Position>>() val toEvaluateDistance = mutableListOf<Pair<List<Position>, Position>>() // path to positionToEvaluate val startingElevation = heatmap.locations[startingPosition.row][startingPosition.column] shortestDistance[startingPosition] = listOf(startingPosition) val potentialSteps = potentialSteps(startingPosition, heatmap.locations) potentialSteps.forEach { position -> toEvaluateDistance.add(listOf(startingPosition) to position) } while (toEvaluateDistance.isNotEmpty()) { val (path, position) = toEvaluateDistance.removeFirst() val fullPath = path + position when (val previousShortest = shortestDistance[position]) { null -> { shortestDistance[position] = fullPath potentialSteps(position, heatmap.locations).forEach { potentialNextStep -> toEvaluateDistance.add(fullPath to potentialNextStep) } } else -> { if (fullPath.size < previousShortest.size) { shortestDistance[position] = fullPath potentialSteps(position, heatmap.locations).forEach { potentialNextStep -> toEvaluateDistance.add(fullPath to potentialNextStep) } } } } } return shortestDistance[endingPosition] } private fun potentialSteps(position: Position, locations: List<List<Int>>): List<Position> { val elevation = locations[position.row][position.column] val possibleOtherPositions = mutableListOf<Position>() // up if (position.row > 0 && locations[position.row - 1][position.column] <= elevation + 1) { possibleOtherPositions.add(Position(position.row - 1, position.column)) } // down if (position.row < locations.size - 1 && locations[position.row + 1][position.column] <= elevation + 1) { possibleOtherPositions.add(Position(position.row + 1, position.column)) } // left if (position.column > 0 && locations[position.row][position.column - 1] <= elevation + 1) { possibleOtherPositions.add(Position(position.row, position.column - 1)) } // right if (position.column < locations.first().size - 1 && locations[position.row][position.column + 1] <= elevation + 1) { possibleOtherPositions.add(Position(position.row, position.column + 1)) } return possibleOtherPositions } } fun main() { val inputText = readInput("year_2022/day_12/Day12.txt") val solutionOne = Day12.solutionOne(inputText) println("Solution 1: $solutionOne") val solutionTwo = Day12.solutionTwo(inputText) println("Solution 2: $solutionTwo") }
0
Kotlin
0
0
70efc56e68771aa98eea6920eb35c8c17d0fc7ac
5,691
advent_of_code
Apache License 2.0
AOC-2023/src/main/kotlin/Day03.kt
sagar-viradiya
117,343,471
false
{"Kotlin": 72737}
import utils.splitAtNewLines import kotlin.math.pow enum class Move(val direction: Pair<Int, Int>) { LEFT(Pair(0, -1)), RIGHT(Pair(0, 1)), UP(Pair(-1, 0)), DOWN(Pair(1, 0)), TOP_LEFT(Pair(-1, -1)), TOP_RIGHT(Pair(-1, 1)), BOTTOM_LEFT(Pair(1, -1)), BOTTOM_RIGHT(Pair(1, 1)) } object Day03 { fun part01(input: String): Int { val enginSchematic = input.splitAtNewLines().map { it.toCharArray() } var partSum = 0 for (i in enginSchematic.indices) { var j = 0 while (j < enginSchematic[i].size) { if (enginSchematic[i][j].isDigit() && isPartNumber(enginSchematic, Pair(i, j))) { var digit = enginSchematic[i][j].digitToInt() var leftMostIndex = j var rightMostIndex = j while (leftMostIndex - 1 >= 0 && enginSchematic[i][leftMostIndex - 1].isDigit()) { digit += (10.0.pow(j - --leftMostIndex)).toInt() * enginSchematic[i][leftMostIndex].digitToInt() } while (rightMostIndex + 1 < enginSchematic[i].size && enginSchematic[i][rightMostIndex + 1].isDigit()) { digit = (digit * 10) + enginSchematic[i][++rightMostIndex].digitToInt() } j = rightMostIndex + 1 partSum += digit } else { j++ } } } return partSum } fun part02(input: String): Long { val enginSchematic = input.splitAtNewLines().map { it.toCharArray() } var gearRatio = 0L var i = 0 while (i < enginSchematic.size) { var j = 0 while (j < enginSchematic[i].size) { if (enginSchematic[i][j] == '*') { val parts = getPartsAdjacentToGear(enginSchematic, Pair(i, j)) if (parts.first != -1 && parts.second != -1) { gearRatio += parts.first * parts.second } } j++ } i++ } return gearRatio } private fun getPartsAdjacentToGear(enginSchematic: List<CharArray>, gearCoordinates: Pair<Int, Int>): Pair<Int, Int> { var firstPart = -1 var secondPart = -1 val defaultParts = Pair(-1, -1) val visitedDirection = hashSetOf<Move>() Move.entries.forEach { move -> if (!visitedDirection.contains(move)) { visitedDirection.add(move) val moveX = gearCoordinates.second + move.direction.second val moveY = gearCoordinates.first + move.direction.first if (moveX in 0..<enginSchematic[gearCoordinates.first].size && moveY in enginSchematic.indices && enginSchematic[moveY][moveX].isDigit() ) { if (firstPart != -1 && secondPart != -1) return defaultParts var leftmostIndex = moveX var rightmostIndex = moveX var digit = enginSchematic[moveY][moveX].digitToInt() while (leftmostIndex - 1 >= 0 && enginSchematic[moveY][leftmostIndex - 1].isDigit()) { digit += (10.0.pow(moveX - (--leftmostIndex))).toInt() * enginSchematic[moveY][leftmostIndex].digitToInt() if (move == Move.UP) { visitedDirection.add(Move.TOP_LEFT) } else if (move == Move.DOWN) { visitedDirection.add(Move.BOTTOM_LEFT) } } while (rightmostIndex + 1 < enginSchematic[moveY].size && enginSchematic[moveY][rightmostIndex + 1].isDigit()) { digit = (digit * 10) + enginSchematic[moveY][++rightmostIndex].digitToInt() if (move == Move.UP) { visitedDirection.add(Move.TOP_RIGHT) } else if (move == Move.DOWN) { visitedDirection.add(Move.BOTTOM_RIGHT) } } if (firstPart == -1) { firstPart = digit } else if (secondPart == -1) { secondPart = digit } } } } return Pair(firstPart, secondPart) } private fun isPartNumber(enginSchematic: List<CharArray>, coordinates: Pair<Int, Int>): Boolean { Move.entries.forEach { move -> val moveX = coordinates.second + move.direction.second val moveY = coordinates.first + move.direction.first if (moveX in 0..<enginSchematic[coordinates.first].size && moveY in enginSchematic.indices && (enginSchematic[moveY][moveX] != '.' && !enginSchematic[moveY][moveX].isDigit()) ) { return true } } return false } }
0
Kotlin
0
0
7f88418f4eb5bb59a69333595dffa19bee270064
5,124
advent-of-code
MIT License
src/Day03.kt
jaldhar
573,188,501
false
{"Kotlin": 14191}
class Score { companion object { private val scores = mutableMapOf<Char, Int>() init { var v = 1; for (k in (('a' .. 'z') + ('A' .. 'Z'))) { scores[k] = v++ } } fun get(v: Char): Int { return scores[v] ?: 0 } } } fun main() { fun part1(input: List<String>): Int { var total = 0 for (line in input) { val length = line.length / 2 var contents = line.toCharArray() val rucksacks = listOf(contents.take(length), contents.takeLast(length)) total += rucksacks[0].intersect(rucksacks[1]).map({ Score.get(it) }).sumOf { it } } return total; } fun part2(input: List<String>): Int { var total = 0 input.chunked(3) { group -> val rucksacks = group.map({ it.toCharArray().toList() }) total += rucksacks[0].intersect(rucksacks[1]).intersect(rucksacks[2]) .map({ Score.get(it) }).sumOf { it } } return total } // test if implementation meets criteria from the description, like: val testInput = readInput("Day03_test") check(part1(testInput) == 157) check(part2(testInput) == 70) val input = readInput("Day03") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
b193df75071022cfb5e7172cc044dd6cff0f6fdf
1,361
aoc2022-kotlin
Apache License 2.0
kotlin/src/main/kotlin/AoC_Day19.kt
sviams
115,921,582
false
null
object AoC_Day19 { fun parseMap(lines: List<String>) : List<List<Char>> = lines.map { line -> line.toCharArray().toList() } data class Direction(val x: Int, val y: Int, val token: Char) data class State(val x: Int, val y: Int, val dir: Direction, val seen: List<Char>, val count: Int) val validChars = ('A'..'Z').toList() val validTokens = listOf('|', '-') fun findNewDirection(state: State, map: List<List<Char>>) : Direction { val newToken = if (state.dir.token == '|') '-' else '|' val goodStuff = validChars + newToken return when (state.dir.token) { '|' -> if (goodStuff.contains(map[state.y][state.x - 1])) Direction(-1, 0, newToken) else Direction(1, 0, newToken) else -> if (goodStuff.contains(map[state.y - 1][state.x])) Direction(0, -1, newToken) else Direction(0, 1, newToken) } } fun goToEnd(startIndex: Int, map: List<List<Char>>) = generateSequence(State(startIndex,0, Direction(0,1, '|'), emptyList(), 0)) { val current = map[it.y][it.x] when (current) { '+' -> { val newDirection = findNewDirection(it, map) State(it.x + newDirection.x, it.y + newDirection.y, newDirection, it.seen, it.count + 1) } ' ' -> State(0,0,Direction(0,0, '!'), it.seen, it.count) else -> if (validTokens.contains(current)) State(it.x + it.dir.x, it.y + it.dir.y, it.dir, it.seen, it.count + 1) else State(it.x + it.dir.x, it.y + it.dir.y, it.dir, it.seen + current, it.count + 1) } }.takeWhile { it.dir.token != '!' }.last() fun solve(input: List<String>) : State { val map = parseMap(input) return goToEnd(map[0].indexOf('|'), map) } fun solvePt1(input: List<String>) : String = solve(input).seen.joinToString("") fun solvePt2(input: List<String>) : Int = solve(input).count }
0
Kotlin
0
0
19a665bb469279b1e7138032a183937993021e36
1,904
aoc17
MIT License
kotlin/src/katas/kotlin/leetcode/compare_strings/CompareStrings.kt
dkandalov
2,517,870
false
{"Roff": 9263219, "JavaScript": 1513061, "Kotlin": 836347, "Scala": 475843, "Java": 475579, "Groovy": 414833, "Haskell": 148306, "HTML": 112989, "Ruby": 87169, "Python": 35433, "Rust": 32693, "C": 31069, "Clojure": 23648, "Lua": 19599, "C#": 12576, "q": 11524, "Scheme": 10734, "CSS": 8639, "R": 7235, "Racket": 6875, "C++": 5059, "Swift": 4500, "Elixir": 2877, "SuperCollider": 2822, "CMake": 1967, "Idris": 1741, "CoffeeScript": 1510, "Factor": 1428, "Makefile": 1379, "Gherkin": 221}
package katas.kotlin.leetcode.compare_strings import datsok.shouldEqual import org.junit.Test /** * https://leetcode.com/discuss/interview-question/352458/Google-or-OA-Fall-Internship-2019-or-Compare-Strings */ class CompareStringsTests { @Test fun `count smaller strings examples`() { countSmallerStrings("abcd,aabc,bd", "aaa,aa") shouldEqual listOf(3, 2) countSmallerStrings("abcd,abcd,aabc,bd", "aaa,aa") shouldEqual listOf(4, 3) countSmallerStrings("abcd,abcd,abcd,aabc,bd", "aaa,aa") shouldEqual listOf(5, 4) countSmallerStrings("abcd,abcd,abcd,aabc,aabc,bd", "aaa,aa") shouldEqual listOf(6, 5) } @Test fun `string comparison examples`() { "".frequencyCompareTo("") shouldEqual 0 "".frequencyCompareTo("a") shouldEqual -1 "a".frequencyCompareTo("") shouldEqual 1 "aaa".frequencyCompareTo("aaa") shouldEqual 0 "abcd".frequencyCompareTo("aaa") shouldEqual -1 "aaa".frequencyCompareTo("abcd") shouldEqual 1 "a".frequencyCompareTo("bb") shouldEqual -1 "bb".frequencyCompareTo("a") shouldEqual 1 "aabc".frequencyCompareTo("aa") shouldEqual 0 } } private fun countSmallerStrings(a: String, b: String): List<Int> { val aFrequencies = a.split(",").map { it.minCharFrequency() }.sorted() val bFrequencies = b.split(",").map { it.minCharFrequency() } return bFrequencies.map { bFreq -> var index = aFrequencies.binarySearch(bFreq) index = if (index < 0) -(index + 1) else index while (index + 1 < aFrequencies.size && aFrequencies[index] == aFrequencies[index + 1]) index++ index } } private fun String.frequencyCompareTo(that: String): Int = this.minCharFrequency().compareTo(that.minCharFrequency()) private fun String.minCharFrequency(): Int { val min = minOrNull() return count { it == min } }
7
Roff
3
5
0f169804fae2984b1a78fc25da2d7157a8c7a7be
1,885
katas
The Unlicense
src/Day04.kt
psabata
573,777,105
false
{"Kotlin": 19953}
fun main() { fun part1(input: List<Entry>): Int { return input.count { it.range1.contains(it.range2) || it.range2.contains(it.range1) } } fun part2(input: List<Entry>): Int { return input.count { it.range1.overlaps(it.range2) || it.range2.overlaps(it.range1) } } val testInput = InputHelper("Day04_test.txt").readLines { parse(it) } check(part1(testInput) == 2) check(part2(testInput) == 4) val input = InputHelper("Day04.txt").readLines { parse(it) } println("Part 1: ${part1(input)}") println("Part 2: ${part2(input)}") } private fun parse(it: String): Entry { val result = Regex("^(\\d+)-(\\d+),(\\d+)-(\\d+)\$").matchEntire(it)!!.groupValues return Entry( IntRange(result[1].toInt(), result[2].toInt()), IntRange(result[3].toInt(), result[4].toInt()), ) } data class Entry( val range1: IntRange, val range2: IntRange, ) fun IntRange.contains(other: IntRange): Boolean { return contains(other.first) && contains(other.last) } fun IntRange.overlaps(other: IntRange): Boolean { return contains(other.first) || contains(other.last) }
0
Kotlin
0
0
c0d2c21c5feb4ba2aeda4f421cb7b34ba3d97936
1,189
advent-of-code-2022
Apache License 2.0
year2021/src/main/kotlin/net/olegg/aoc/year2021/day4/Day4.kt
0legg
110,665,187
false
{"Kotlin": 511989}
package net.olegg.aoc.year2021.day4 import net.olegg.aoc.someday.SomeDay import net.olegg.aoc.utils.parseInts import net.olegg.aoc.year2021.DayOf2021 /** * See [Year 2021, Day 4](https://adventofcode.com/2021/day/4) */ object Day4 : DayOf2021(4) { override fun first(): Any? { val values = lines .first() .parseInts(",") val boards = data .split("\n\n") .drop(1) .map { it.replace("\\s+".toRegex(), " ").parseInts(" ").map { value -> value to false } } values.fold(boards) { acc, value -> val newAcc = acc.map { it.map { (curr, seen) -> if (curr == value) curr to true else curr to seen } } newAcc.forEach { board -> for (x in 0..<5) { if ((0..<5).all { y -> board[5 * y + x].second }) { return score(board, value) } } for (y in 0..<5) { if ((0..<5).all { x -> board[5 * y + x].second }) { return score(board, value) } } } newAcc } return 0 } override fun second(): Any? { val values = lines .first() .parseInts(",") val boards = data .split("\n\n") .drop(1) .map { it.replace("\\s+".toRegex(), " ").parseInts(" ").map { value -> value to false } } values.fold(boards) { acc, value -> val newAcc = acc.map { it.map { (curr, seen) -> if (curr == value) curr to true else curr to seen } } val filteredAcc = newAcc.filter { board -> for (x in 0..<5) { if ((0..<5).all { y -> board[5 * y + x].second }) { return@filter false } } for (y in 0..<5) { if ((0..<5).all { x -> board[5 * y + x].second }) { return@filter false } } return@filter true } if (filteredAcc.isEmpty()) { return score(newAcc.first(), value) } filteredAcc } return 0 } private fun score( board: List<Pair<Int, Boolean>>, value: Int ) = board.filter { !it.second }.sumOf { it.first } * value } fun main() = SomeDay.mainify(Day4)
0
Kotlin
1
7
e4a356079eb3a7f616f4c710fe1dfe781fc78b1a
2,127
adventofcode
MIT License
src/main/kotlin/days/aoc2015/Day17.kt
bjdupuis
435,570,912
false
{"Kotlin": 537037}
package days.aoc2015 import days.Day class Day17: Day(2015, 17) { override fun partOne(): Any { return calculatePartOne(150) } override fun partTwo(): Any { return calculatePartTwo(150) } fun calculatePartTwo(target: Int): Int { val containers = inputList.map { it.toInt() }.sorted() return createSolutions(target, containers, null, mutableListOf()).let { solutions -> solutions.map { it.size }.let { solutionSizes -> val minContainerCount = solutionSizes.minOrNull()!! solutionSizes.filter { it == minContainerCount } }.count() } } fun calculatePartOne(target: Int): Int { val containers = inputList.map { it.toInt() }.sorted() return countSolutionsForRemainingContainers(target, containers) } fun createSolutions(remainingEggnog: Int, remainingContainers: List<Int>, potentialSolution: List<Int>?, currentSolutions: List<List<Int>>): List<List<Int>> { val solution = potentialSolution ?: mutableListOf() return if (remainingContainers.size == 1) { if (remainingEggnog == remainingContainers[0]) currentSolutions.plusElement(solution.plus(remainingEggnog) ) else currentSolutions } else { val largest = remainingContainers.last() val additionalSolutions = createSolutions(remainingEggnog, remainingContainers.dropLast(1), solution, currentSolutions) when { remainingEggnog == largest -> { return currentSolutions.plus(additionalSolutions).plusElement(solution.plus(largest)) } remainingEggnog < largest -> { return currentSolutions.plus(additionalSolutions) } else -> { return currentSolutions.plus(createSolutions(remainingEggnog - largest, remainingContainers.dropLast(1), solution.plus(largest), currentSolutions)).plus(additionalSolutions) } } } } fun countSolutionsForRemainingContainers(remainingEggnog: Int, remainingContainers: List<Int>): Int { return if (remainingContainers.size == 1) { if (remainingEggnog == remainingContainers[0]) 1 else 0 } else { val largest = remainingContainers.last() val otherSolutions = countSolutionsForRemainingContainers(remainingEggnog, remainingContainers.dropLast(1)) when { remainingEggnog == largest -> { 1 + otherSolutions } remainingEggnog < largest -> { otherSolutions } else -> { otherSolutions + countSolutionsForRemainingContainers(remainingEggnog - largest, remainingContainers.dropLast(1)) } } } } }
0
Kotlin
0
1
c692fb71811055c79d53f9b510fe58a6153a1397
2,916
Advent-Of-Code
Creative Commons Zero v1.0 Universal
src/main/kotlin/com/lucaszeta/adventofcode2020/day16/day16.kt
LucasZeta
317,600,635
false
null
package com.lucaszeta.adventofcode2020.day16 import com.lucaszeta.adventofcode2020.ext.getResourceAsText fun main() { val input = getResourceAsText("/day16/ticket-notes.txt") val ticketFields = extractTicketFields(input) val nearbyTickets = extractNearbyTickets(input) val invalidValues = findInvalidFields(nearbyTickets, ticketFields) println("Ticket scanning error rate: ${invalidValues.reduce(Int::plus)}") val myTicket = extractYourTicket(input) val validTickets = filterValidTickets(nearbyTickets, ticketFields) val fieldsIndex = identifyFieldIndex(validTickets, ticketFields) val result = fieldsIndex .filterKeys { it.startsWith("departure") } .map { myTicket[it.value].toLong() } .reduce(Long::times) println("Product of departure fields: $result") } fun extractYourTicket(input: String): List<Int> { val lines = input.split("\n") val index = lines.indexOf("your ticket:") return lines[index + 1].split(",").map { it.toInt() } } fun extractNearbyTickets(input: String): List<List<Int>> { val lines = input.split("\n") val index = lines.indexOf("nearby tickets:") val nearbyTickets = mutableListOf<List<Int>>() for (i in (index + 1) until lines.size) { if (lines[i].isNotEmpty()) { nearbyTickets.add(lines[i].split(",").map { it.toInt() }) } } return nearbyTickets.toList() } fun extractTicketFields(input: String): Map<String, List<IntRange>> { val ticketFieldResult = "([a-z ]*): (\\d+)-(\\d+) or (\\d+)-(\\d+)" .toRegex() .findAll(input) val ticketFields = mutableMapOf<String, List<IntRange>>() ticketFieldResult.forEach { val name = it.groupValues[1] val firstRange = it.groupValues[2].toInt()..it.groupValues[3].toInt() val secondRange = it.groupValues[4].toInt()..it.groupValues[5].toInt() ticketFields[name] = listOf(firstRange, secondRange) } return ticketFields.toMap() }
0
Kotlin
0
1
9c19513814da34e623f2bec63024af8324388025
2,002
advent-of-code-2020
MIT License