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/Day20.kt
andrikeev
574,393,673
false
{"Kotlin": 70541, "Python": 18310, "HTML": 5558}
import java.util.LinkedList fun main() { fun part1(input: List<String>): Long { val nodes = input.map(String::toLong).mapIndexed(::Node) return InfiniteList(nodes).apply { mix() }.result() } fun part2(input: List<String>): Long { val nodes = input.map(String::toLong).map { it * 811589153 }.mapIndexed(::Node) return InfiniteList(nodes).apply { repeat(10) { mix() } }.result() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day20_test") check(part1(testInput).also { println("part1 test: $it") } == 3L) check(part2(testInput).also { println("part2 test: $it") } == 1623178306L) val input = readInput("Day20") println(part1(input)) println(part2(input)) } private data class Node(val id: Int, val value: Long) private class InfiniteList(private val nodes: List<Node>) { private val list = LinkedList<Node>().apply { addAll(nodes) } private fun realIndex(index: Long): Int { return ((list.lastIndex + (index % list.lastIndex)) % list.lastIndex).toInt() } private fun <T> LinkedList<T>.moveItem(from: Int, to: Int) { if (to != from) { add(to, removeAt(from)) } } fun mix() { nodes.forEach { node -> with(list) { val from = indexOf(node) val value = node.value val to = realIndex(from + value) moveItem(from, to) } } } fun result(): Long { val indexOfZero = list.indexOfFirst { it.value == 0L } return listOf(1000, 2000, 3000).sumOf { list[(indexOfZero + it) % list.size].value } } }
0
Kotlin
0
1
1aedc6c61407a28e0abcad86e2fdfe0b41add139
1,709
aoc-2022
Apache License 2.0
leetcode-75-kotlin/src/main/kotlin/EqualRowAndColumnPairs.kt
Codextor
751,507,040
false
{"Kotlin": 49566}
/** * Given a 0-indexed n x n integer matrix grid, * return the number of pairs (ri, cj) such that row ri and column cj are equal. * * A row and column pair is considered equal if they contain the same elements in the same order (i.e., an equal array). * * * * Example 1: * * * Input: grid = [[3,2,1],[1,7,6],[2,7,7]] * Output: 1 * Explanation: There is 1 equal row and column pair: * - (Row 2, Column 1): [2,7,7] * Example 2: * * * Input: grid = [[3,1,2,2],[1,4,4,5],[2,4,2,2],[2,4,2,2]] * Output: 3 * Explanation: There are 3 equal row and column pairs: * - (Row 0, Column 0): [3,1,2,2] * - (Row 2, Column 2): [2,4,2,2] * - (Row 3, Column 2): [2,4,2,2] * * * Constraints: * * n == grid.length == grid[i].length * 1 <= n <= 200 * 1 <= grid[i][j] <= 10^5 * @see <a href="https://leetcode.com/problems/equal-row-and-column-pairs/">LeetCode</a> */ fun equalPairs(grid: Array<IntArray>): Int { val rowMap = mutableMapOf<List<Int>, Int>() val columnMap = mutableMapOf<List<Int>, Int>() for (rowNumber in grid.indices) { val rowList = mutableListOf<Int>() for (columnNumber in grid[rowNumber].indices) { rowList.add(grid[rowNumber][columnNumber]) } rowMap[rowList] = 1 + rowMap.getOrDefault(rowList, 0) } for (columnNumber in grid[0].indices) { val columnList = mutableListOf<Int>() for (rowNumber in grid.indices) { columnList.add(grid[rowNumber][columnNumber]) } columnMap[columnList] = 1 + columnMap.getOrDefault(columnList, 0) } var result = 0 rowMap.forEach { row, rowFrequency -> result += rowFrequency * columnMap.getOrDefault(row, 0) } return result }
0
Kotlin
0
0
0511a831aeee96e1bed3b18550be87a9110c36cb
1,723
leetcode-75
Apache License 2.0
2022/src/day03/day03.kt
Bridouille
433,940,923
false
{"Kotlin": 171124, "Go": 37047}
package day03 import GREEN import RESET import printTimeMillis import readInput fun Char.score() = when (this) { in 'a'..'z' -> this - 'a' + 1 in 'A'..'Z' -> this - 'A' + 27 else -> throw IllegalStateException("Not a letter") } fun part1(input: List<String>) = input.fold(0) { acc, line -> val secondHalf = line.takeLast(line.length / 2).groupingBy { it }.eachCount() val commonLetter = line.take(line.length / 2).groupingBy { it }.eachCount().filterKeys { secondHalf.keys.contains(it) } acc + commonLetter.entries.first().key.score() } fun part2(input: List<String>) = input.windowed(3, 3).map { lists -> val result = lists[0].groupingBy { it }.eachCount().filterKeys { lists[1].groupingBy { it }.eachCount().contains(it) && lists[2].groupingBy { it }.eachCount().contains(it) } result.entries.first().key.score() }.sum() fun main() { val testInput = readInput("day03_example.txt") printTimeMillis { print("part1 example = $GREEN" + part1(testInput) + RESET) } printTimeMillis { print("part2 example = $GREEN" + part2(testInput) + RESET) } val input = readInput("day03.txt") printTimeMillis { print("part1 input = $GREEN" + part1(input) + RESET) } printTimeMillis { print("part2 input = $GREEN" + part2(input) + RESET) } }
0
Kotlin
0
2
8ccdcce24cecca6e1d90c500423607d411c9fee2
1,310
advent-of-code
Apache License 2.0
src/day14/Code.kt
fcolasuonno
225,219,560
false
null
package day14 import isDebug import java.io.File fun main() { val name = if (isDebug()) "test.txt" else "input.txt" System.err.println(name) val dir = ::main::class.java.`package`.name val input = File("src/$dir/$name").readLines() val (parsed, ranks) = parse(input) println("Part 1 = ${part1(parsed, ranks)}") println("Part 2 = ${part2(parsed, ranks)}") } data class Required(val amount: Long, val source: String) { operator fun times(requiredAmount: Long) = this.copy(amount = amount * requiredAmount) } data class Production(val amount: Int, val chems: List<Required>) { fun expand(input: List<Required>) = chems.map { it * ((amount + input.first().amount - 1) / amount) } + input.drop(1) } fun parse(input: List<String>) = input.map { val (source, product) = it.split(" => ") val (prodAmount, prodName) = product.split(" ") prodName to Production(prodAmount.toInt(), source.split(", ").map { val (srcAmount, srcName) = it.split(" ") Required(srcAmount.toLong(), srcName) }) }.requireNoNulls().toMap().let { it to mutableMapOf("ORE" to 0).apply { val inputCopy = it.toMutableMap() while (inputCopy.isNotEmpty()) { val (key, value) = inputCopy.entries.first { it.value.chems.all { it.source in this } } inputCopy.remove(key) this[key] = value.chems.map { getValue(it.source) }.max()!! + 1 } } } fun part1(input: Map<String, Production>, ranks: MutableMap<String, Int>, requiredAmount: Long = 1L) = generateSequence(listOf(Required(requiredAmount, "FUEL"))) { it.takeUnless { it.size == 1 && it.single().source == "ORE" } ?.sortedByDescending { ranks[it.source] }?.let { input.getValue(it.first().source).expand(it).groupBy { it.source } .values.map { Required(it.map { it.amount }.sum(), it.first().source) } } }.last().single().amount fun part2(input: Map<String, Production>, ranks: MutableMap<String, Int>): Any? { var min = 0L var max = 1000000000000L while (min <= max) { val middle = (min + max) / 2L part1(input, ranks, middle).let { if (it < 1000000000000L) { min = middle + 1 } else max = middle - 1 } } return min - 1 }
0
Kotlin
0
0
d1a5bfbbc85716d0a331792b59cdd75389cf379f
2,358
AOC2019
MIT License
src/main/kotlin/com/github/davio/aoc/y2023/Day4.kt
Davio
317,510,947
false
{"Kotlin": 405939}
package com.github.davio.aoc.y2023 import com.github.davio.aoc.general.Day import com.github.davio.aoc.general.getInputAsList /** * See [Advent of Code 2023 Day 4](https://adventofcode.com/2023/day/4#part2]) */ object Day4 : Day() { private val cards = getInputAsList() .map { Card.parse(it) } override fun part1(): Int = cards.sumOf { it.getScore() } override fun part2(): Int { val totalCopies = cards.associateWith { 1 }.toMutableMap() return totalCopies.entries.sumOf { (card, total) -> card.getIdsOfCopies().forEach { id -> val copy = Card(id) totalCopies[copy] = totalCopies.getValue(copy) + total } total } } private data class Card( val id: Int ) { var winningNumbers: Set<Int> = emptySet() var myNumbers: Set<Int> = emptySet() fun getScore(): Int = if (getMatches() == 0) 0 else 1 shl (getMatches() - 1) fun getMatches(): Int = myNumbers.intersect(winningNumbers).size fun getIdsOfCopies(): List<Int> = MutableList(getMatches()) { offset -> id + offset + 1 } companion object { private const val CARD_PATTERN = """Card\s+(\d+): (.+) \| (.+)""" private val cardRegex = Regex(CARD_PATTERN) fun parse(line: String): Card { val (idStr, winningNumbersPart, myNumbersPart) = cardRegex.matchEntire(line)!!.destructured fun splitNumbers(part: String): Set<Int> = part.trim().split(Regex("\\s+")).map { it.toInt() }.toSet() return Card(idStr.toInt()) .also { it.winningNumbers = splitNumbers(winningNumbersPart) it.myNumbers = splitNumbers(myNumbersPart) } } } } }
1
Kotlin
0
0
4fafd2b0a88f2f54aa478570301ed55f9649d8f3
1,888
advent-of-code
MIT License
src/main/kotlin/com/leonra/adventofcode/advent2023/day08/Day8.kt
LeonRa
726,688,446
false
{"Kotlin": 30456}
package com.leonra.adventofcode.advent2023.day08 import com.leonra.adventofcode.shared.readResource /** https://adventofcode.com/2023/day/8 */ private object Day8 { data class Node(val left: String, val right: String) enum class Direction { LEFT, RIGHT } fun partOne(): Int { val directions = mutableListOf<Direction>() val nodes = mutableMapOf<String, Node>() readResource("/2023/day08/part1.txt") { line -> if (line.isEmpty()) { return@readResource } if (directions.isEmpty()) { line.forEach { if (it == 'L') { directions.add(Direction.LEFT) } else { directions.add(Direction.RIGHT) } } } else { val node = NODES.find(line) if (node != null) { val id = requireNotNull(node.groups[1]).value val left = requireNotNull(node.groups[2]).value val right = requireNotNull(node.groups[3]).value nodes[id] = Node(left, right) } } } var steps = 0 var next = "AAA" while (next != "ZZZ") { val direction = directions[steps % directions.size] next = when(direction) { Direction.LEFT -> requireNotNull(nodes[next]).left Direction.RIGHT -> requireNotNull(nodes[next]).right } steps++ } return steps } fun partTwo(): Long { fun stepsToEnd(directions: List<Direction>, nodes: Map<String, Node>, start: String): Long { var steps = 0L var next = start while (!next.endsWith('Z')) { val direction = directions[(steps % directions.size).toInt()] next = when(direction) { Direction.LEFT -> requireNotNull(nodes[next]).left Direction.RIGHT -> requireNotNull(nodes[next]).right } steps++ } return steps } fun leastCommonMultiple(a: Long, b: Long): Long { var ma = a var mb = b var remainder: Long while (mb != 0L) { remainder = ma % mb ma = mb mb = remainder } return a * b / ma } val directions = mutableListOf<Direction>() val nodes = mutableMapOf<String, Node>() val starts = mutableListOf<String>() readResource("/2023/day08/part1.txt") { line -> if (line.isEmpty()) { return@readResource } if (directions.isEmpty()) { line.forEach { if (it == 'L') { directions.add(Direction.LEFT) } else { directions.add(Direction.RIGHT) } } } else { val node = NODES.find(line) if (node != null) { val id = requireNotNull(node.groups[1]).value if (id.endsWith('A')) { starts.add(id) } val left = requireNotNull(node.groups[2]).value val right = requireNotNull(node.groups[3]).value nodes[id] = Node(left, right) } } } return starts.map { stepsToEnd(directions, nodes, start = it) } .reduce { acc, steps -> leastCommonMultiple(acc, steps) } } private val NODES = Regex("([A-Z0-9]+) = \\(([A-Z0-9]+), ([A-Z0-9]+)\\)") } private fun main() { println("Part 1 steps: ${Day8.partOne()}") println("Part 2 steps: ${Day8.partTwo()}") }
0
Kotlin
0
0
46bdb5d54abf834b244ba9657d0d4c81a2d92487
3,951
AdventOfCode
Apache License 2.0
src/Day02.kt
ranveeraggarwal
573,754,764
false
{"Kotlin": 12574}
// Ugh. fun main() { fun convert(move: String): Int { return when (move) { "X" -> 0 "Y" -> 1 "Z" -> 2 "A" -> 0 "B" -> 1 else -> 2 } } fun part1(input: List<String>): Int { fun getScore(opp: Int, you: Int): Int { return when (opp) { 0 -> when (you) { 1 -> 6 2 -> 0 else -> 3 } 1 -> when (you) { 2 -> 6 0 -> 0 else -> 3 } 2 -> when (you) { 0 -> 6 1 -> 0 else -> 3 } else -> 3 } + you + 1 } return input.fold(0) { sum, line -> sum + getScore(convert(line.split(" ")[0]), convert(line.split(" ")[1])) } } fun part2(input: List<String>): Int { fun getScore(opp: Int, you: Int): Int { return when (opp) { 0 -> when (you) { 1 -> 0 2 -> 1 else -> 2 } 1 -> when (you) { 1 -> 1 2 -> 2 else -> 0 } 2 -> when (you) { 1 -> 2 2 -> 0 else -> 1 } else -> 3 } + 1 + you * 3 } return input.fold(0) { sum, line -> sum + getScore(convert(line.split(" ")[0]), convert(line.split(" ")[1])) } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day02_test") println(part1(testInput)) println(part2(testInput)) val input = readInput("Day02") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
c8df23daf979404f3891cdc44f7899725b041863
1,935
advent-of-code-2022-kotlin
Apache License 2.0
advent-of-code/src/main/kotlin/com/akikanellis/adventofcode/year2022/Day05.kt
akikanellis
600,872,090
false
{"Kotlin": 142932, "Just": 977}
package com.akikanellis.adventofcode.year2022 object Day05 { fun cratesOnTheTopOfEachStack( input: String, craneMovesMultipleCratesAtOnce: Boolean ): String { val stacks = stacks(input) val moves = moves(input) val stacksAfterMoves = stacksAfterMoves( stacks, moves, craneMovesMultipleCratesAtOnce ) return stacksAfterMoves .toSortedMap() .map { (_, crates) -> crates.last() } .joinToString("") } private fun stacks(input: String): Stacks = input .substringBefore("\n\n") .lines() .reversed() .drop(1) .flatMap { it.chunked(4) .map { crate -> crate.trim() } .withIndex() .filter { (_, crate) -> crate.isNotBlank() } .map { (index, crate) -> IndexedValue(index + 1, crate[1]) } }.groupBy( { (index, _) -> index }, { (_, crates) -> crates } ) private fun moves(input: String) = input .substringAfter("\n\n") .lines() .filter { it.isNotBlank() } .map { it.split(" ") } .map { Move(it[1].toInt(), it[3].toInt(), it[5].toInt()) } private fun stacksAfterMoves( stacks: Stacks, moves: List<Move>, craneMovesMultipleCratesAtOnce: Boolean ) = moves .fold(stacks) { latestStacks, (numberOfCrates, sourceStackId, targetStackId) -> val sourceStackCrates = latestStacks[sourceStackId]!! val targetStackCrates = latestStacks[targetStackId]!! val movedCrates = sourceStackCrates .takeLast(numberOfCrates) .let { if (craneMovesMultipleCratesAtOnce) it else it.reversed() } val updatedSourceStackCrates = sourceStackCrates.dropLast(numberOfCrates) val updatedTargetStackCrates = targetStackCrates + movedCrates return@fold latestStacks + Pair(sourceStackId, updatedSourceStackCrates) + Pair(targetStackId, updatedTargetStackCrates) } } private typealias Move = Triple<Int, Int, Int> private typealias Stacks = Map<Int, List<Char>>
8
Kotlin
0
0
036cbcb79d4dac96df2e478938de862a20549dce
2,251
advent-of-code
MIT License
src/main/kotlin/men/zhangfei/leetcode/medium/Problem0139.kt
fitzf
257,562,586
false
{"Kotlin": 9251}
package men.zhangfei.leetcode.medium import java.util.LinkedList import java.util.Queue /** * 139. 单词拆分 * https://leetcode-cn.com/problems/word-break/ */ class Problem0139 { companion object { /** * 动态规划 * 字符串 s 可以被拆分成子字符串 s1 和 s2 * 如果这些子字符串都可以独立地被拆分成符合要求的子字符串,那么整个字符串 s 也可以满足 * e.g. s = "catsanddog", wordDict = ["cats", "dog", "sand", "and", "cat"] * s1 = "catsand", s2 = "dog" * s1-1 = "cats", s1-2 = "and" * s1-1, s1-2 满足, 所以 s1 也满足, s1, s2 都满足,所以 s 也满足 */ fun dp(s: String, wordDict: List<String>): Boolean { val len = s.length val dp = BooleanArray(len + 1) // 空字符串总是字典的一部分, 剩余为 false dp[0] = true for (r in 1..len) { // 通过下标 l 将字符串 s[0, r) 拆分成 s1, s2 for (l in 0 until r) { // 检查 s1 s[0, j) 是否满足条件 检查 s2 s[j, r) 是否满足条件,如果满足,说明 s[0, r) 满足 dp[r] = true if (dp[l] && wordDict.contains(s.substring(l, r))) { dp[r] = true break } } } return dp[len] } /** * 宽度优先搜索 */ fun bfs(s: String, wordDict: List<String>): Boolean { val len = s.length val queue: Queue<Int> = LinkedList() val visited = IntArray(len) queue.add(0) var start: Int while (!queue.isEmpty()) { start = queue.remove() if (0 == visited[start]) { for (end in (start + 1)..len) { if (wordDict.contains(s.substring(start, end))) { queue.add(end) if (end == len) { return true } } } visited[start] = 1 } } return false } } }
1
Kotlin
0
0
a2ea7df7c1e4857808ab054d253dea567049658a
2,323
leetcode
Apache License 2.0
kotlin/src/2022/Day21_2022.kt
regob
575,917,627
false
{"Kotlin": 50757, "Python": 46520, "Shell": 430}
fun main() { val ops = mapOf<Char, (Long, Long) -> Long>( '/' to {x, y -> x / y}, '*' to {x, y -> x * y}, '-' to {x, y -> x - y}, '+' to {x, y -> x + y} ) abstract class Node { abstract fun value(): Long? } data class Value(val x: Long?) :Node() { override fun value() = x } data class Op(val l: Node, val r: Node, val op: Char) :Node() { override fun value(): Long? { val (lv, rv) = l.value() to r.value() return if (lv == null || rv == null) null else ops[op]!!(lv, rv) } } val r = "(\\w+): (\\d+|(\\w+) (.) (\\w+))".toRegex() val monkeys = readInput(21).trim().lines() .associate { val g = r.matchEntire(it)!!.groupValues if (g.subList(3, 6).all {s -> s.isBlank()}) g[1] to listOf(g[2]) else g[1] to g.subList(3, 6) } val nodes = mutableMapOf<String, Node>() fun parse(key: String): Node { val l = monkeys[key]!! if (l.size == 1) return Value(l[0].toLong()) if (l[0] !in nodes) nodes[l[0]] = parse(l[0]) if (l[2] !in nodes) nodes[l[2]] = parse(l[2]) return Op(nodes[l[0]]!!, nodes[l[2]]!!, l[1].first()) } monkeys.keys.forEach { if (it !in nodes) nodes[it] = parse(it) } // part1 println(nodes["root"]!!.value()) // part2 nodes.clear() nodes["humn"] = Value(null) monkeys.keys.forEach { if (it !in nodes) nodes[it] = parse(it) } val root = nodes["root"]!! as Op // go down the tree where the value is null until we reach node 'humn', also store the value neeeded in the current node fun findValue(node: Node, curr: Long): Long { if (node === nodes["humn"]) return curr val n = node as Op val (lv, rv) = n.l.value() to n.r.value() return when (n.op) { '/' -> if (lv == null) findValue(n.l, curr * rv!!) else findValue(n.r, curr / lv) '*' -> if (lv == null) findValue(n.l, curr / rv!!) else findValue(n.r, curr / lv) '-' -> if (lv == null) findValue(n.l, curr + rv!!) else findValue(n.r, lv - curr) '+' -> if (lv == null) findValue(n.l, curr - rv!!) else findValue(n.r, curr - lv) else -> throw IllegalStateException() } } val target = (root.l.value()) ?: root.r.value() val node = if (root.l.value() == null) root.l else root.r println(findValue(node, target!!)) }
0
Kotlin
0
0
cf49abe24c1242e23e96719cc71ed471e77b3154
2,472
adventofcode
Apache License 2.0
src/day02/Day02Answer1.kt
IThinkIGottaGo
572,833,474
false
{"Kotlin": 72162}
package day02 import readInput /** * Answers from [Advent of Code 2022 Day 2 | Kotlin](https://youtu.be/Fn0SY2yGDSA) */ fun main() { operator fun String.component1() = this[0] operator fun String.component2() = this[1] operator fun String.component3() = this[2] fun part1(input: List<String>): Int { // X Y Z // 0 1 2 // 1 2 3 fun shapeScore(shape: Char) = (shape - 'X' + 1) fun resultScore(theirShape: Char, myShape: Char): Int { return when (theirShape to myShape) { 'B' to 'X', 'C' to 'Y', 'A' to 'Z' -> 0 'A' to 'X', 'B' to 'Y', 'C' to 'Z' -> 3 'C' to 'X', 'A' to 'Y', 'B' to 'Z' -> 6 else -> error("Check your inputs") } } return input.sumOf { round -> val (theirShape, _, myShape) = round shapeScore(myShape) + resultScore(theirShape, myShape) } } fun part2(input: List<String>): Int { fun shapeScore(theirShape: Char, desiredResult: Char): Int { return when (theirShape to desiredResult) { 'A' to 'Y', 'B' to 'X', 'C' to 'Z' -> 1 // Rock 'B' to 'Y', 'C' to 'X', 'A' to 'Z' -> 2 // Paper 'C' to 'Y', 'A' to 'X', 'B' to 'Z' -> 3 // Scissors else -> error("Check your inputs") } } // X Y Z // 0 1 2 // 0 3 6 fun resultScore(result: Char) = (result - 'X') * 3 return input.sumOf { round -> val (theirShape, _, result) = round shapeScore(theirShape, result) + resultScore(result) } } val testInput = readInput("day02_test") check(part1(testInput) == 15) check(part2(testInput) == 12) val input = readInput("day02") println(part1(input)) // 12586 println(part2(input)) // 13193 }
0
Kotlin
0
0
967812138a7ee110a63e1950cae9a799166a6ba8
1,912
advent-of-code-2022
Apache License 2.0
Retos/Reto #19 - ANÁLISIS DE TEXTO [Media]/kotlin/mjordanaam.kt
mouredev
581,049,695
false
{"Python": 3866914, "JavaScript": 1514237, "Java": 1272062, "C#": 770734, "Kotlin": 533094, "TypeScript": 457043, "Rust": 356917, "PHP": 281430, "Go": 243918, "Jupyter Notebook": 221090, "Swift": 216751, "C": 210761, "C++": 164758, "Dart": 159755, "Ruby": 70259, "Perl": 52923, "VBScript": 49663, "HTML": 45912, "Raku": 44139, "Scala": 30892, "Shell": 27625, "R": 19771, "Lua": 16625, "COBOL": 15467, "PowerShell": 14611, "Common Lisp": 12715, "F#": 12710, "Pascal": 12673, "Haskell": 11051, "Assembly": 10368, "Elixir": 9033, "Visual Basic .NET": 7350, "Groovy": 7331, "PLpgSQL": 6742, "Clojure": 6227, "TSQL": 5744, "Zig": 5594, "Objective-C": 5413, "Apex": 4662, "ActionScript": 3778, "Batchfile": 3608, "OCaml": 3407, "Ada": 3349, "ABAP": 2631, "Erlang": 2460, "BASIC": 2340, "D": 2243, "Awk": 2203, "CoffeeScript": 2199, "Vim Script": 2158, "Brainfuck": 1550, "Prolog": 1342, "Crystal": 783, "Fortran": 778, "Solidity": 560, "Standard ML": 525, "Scheme": 457, "Vala": 454, "Limbo": 356, "xBase": 346, "Jasmin": 285, "Eiffel": 256, "GDScript": 252, "Witcher Script": 228, "Julia": 224, "MATLAB": 193, "Forth": 177, "Mercury": 175, "Befunge": 173, "Ballerina": 160, "Smalltalk": 130, "Modula-2": 129, "Rebol": 127, "NewLisp": 124, "Haxe": 112, "HolyC": 110, "GLSL": 106, "CWeb": 105, "AL": 102, "Fantom": 97, "Alloy": 93, "Cool": 93, "AppleScript": 85, "Ceylon": 81, "Idris": 80, "Dylan": 70, "Agda": 69, "Pony": 69, "Pawn": 65, "Elm": 61, "Red": 61, "Grace": 59, "Mathematica": 58, "Lasso": 57, "Genie": 42, "LOLCODE": 40, "Nim": 38, "V": 38, "Chapel": 34, "Ioke": 32, "Racket": 28, "LiveScript": 25, "Self": 24, "Hy": 22, "Arc": 21, "Nit": 21, "Boo": 19, "Tcl": 17, "Turing": 17}
/* * Crea un programa que analice texto y obtenga: * - Número total de palabras. * - Longitud media de las palabras. * - Número de oraciones del texto (cada vez que aparecen un punto). * - Encuentre la palabra más larga. * * Todo esto utilizando un único bucle. */ fun analyzeText(text: String) { var sentences: Int = 0 var words = arrayOf<String>() var aux: String = "" var nwords: Int = 0 var length: Int = 0 var longest = hashMapOf<Int, Array<String>>(0 to arrayOf<String>()) for (letter in text) { val regex1 = Regex("[.?!]+") val regex2 = Regex("[¿|:()/@%$,]+") if (regex1.matches(letter.toString())) { sentences++ words += aux length += aux.length nwords++ if (aux.length > longest.keys.first()) { longest = hashMapOf(aux.length to arrayOf<String>(aux)) } else if (aux.length == longest.keys.first()) { longest[aux.length] = longest.getOrDefault(aux.length, emptyArray()) + aux } aux = "" }else if (letter == ' ') { if (aux != "") { words += aux length += aux.length nwords++ if (aux.length > longest.keys.first()) { longest = hashMapOf(aux.length to arrayOf(aux)) } else if (aux.length == longest.keys.first()) { longest[aux.length] = longest.getOrDefault(aux.length, emptyArray()) + aux } aux = "" } }else if (regex2.matches(letter.toString())){ }else { aux += letter } } var average = length/nwords println("> Total Words = $nwords") println("> Average length = $average") println("> Number of sentences = $sentences") println("> Longest word/words (${longest.keys.first()} letters) = ${longest.get(longest.keys.first()).contentToString()}") println() } fun main() { var text: String = "Hello. World!" analyzeText(text) text = "Crea un programa que analice texto y obtenga:." + "Número total de palabras." + "Longitud media de las palabras." + "Número de oraciones del texto (cada vez que aparecen un punto)." + "Encuentre la palabra más larga." + "Todo esto utilizando un único bucle." analyzeText(text) text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis condimentum mauris non enim mollis dictum. In " + "feugiat ut justo in vulputate. Aliquam erat volutpat. Vivamus porttitor commodo felis, sed gravida eros " + "fermentum non. Mauris sagittis id neque sit amet ullamcorper. Sed eu pretium ex, ut ornare quam. Maecenas " + "consectetur elit a nisi maximus, et vehicula lorem finibus. Duis sapien justo, placerat in vestibulum a, " + "vestibulum non lacus. Sed egestas, nisi." analyzeText(text) }
4
Python
2,929
4,661
adcec568ef7944fae3dcbb40c79dbfb8ef1f633c
3,089
retos-programacion-2023
Apache License 2.0
src/Day09.kt
Kietyo
573,293,671
false
{"Kotlin": 147083}
import kotlin.math.absoluteValue import kotlin.math.min import kotlin.math.pow import kotlin.math.sign import kotlin.math.sqrt fun main() { data class Point(var x: Int, var y: Int) class Game( numPoints: Int ) { val sqrt2 = sqrt(2.0) val tolerance = 0.0001 val knots: List<Point> = MutableList(numPoints) { Point(0, 0) } fun dst(p1: Point, p2: Point): Double { val dst = sqrt( (p1.x - p2.x.toDouble()).pow(2) + (p1.y - p2.y.toDouble()).pow(2) ) if (dst in (sqrt2 - tolerance)..(sqrt2 + tolerance)) { return 1.0 } return dst } fun moveHead(dir: String) { when (dir) { "R" -> knots[0].x += 1 "L" -> knots[0].x -= 1 "U" -> knots[0].y += 1 "D" -> knots[0].y -= 1 } knots.windowed(2).forEach { val head = it[0] val tail = it[1] val dst = dst(head, tail) if (dst > 1.0) { val xDst = head.x - tail.x val yDst = head.y - tail.y tail.x += min(xDst.absoluteValue, 1) * xDst.sign tail.y += min(yDst.absoluteValue, 1) * yDst.sign } } } } fun part1(input: List<String>): Unit { val game = Game(2) val tailPositions = mutableSetOf<Point>() input.forEach { val (dir, steps) = it.split(" ") val stepsAsInt = steps.toInt() repeat(stepsAsInt) { game.moveHead(dir) tailPositions.add(game.knots.last().copy()) } } println(tailPositions.size) } fun part2(input: List<String>): Unit { val game = Game(10) val tailPositions = mutableSetOf<Point>() input.forEach { val (dir, steps) = it.split(" ") val stepsAsInt = steps.toInt() repeat(stepsAsInt) { game.moveHead(dir) tailPositions.add(game.knots.last().copy()) } } println(tailPositions.size) } val dayString = "day9" // test if implementation meets criteria from the description, like: val testInput = readInput("${dayString}_test") // part1(testInput) // part2(testInput) val input = readInput("${dayString}_input") part1(input) // part2(input) }
0
Kotlin
0
0
dd5deef8fa48011aeb3834efec9a0a1826328f2e
2,579
advent-of-code-2022-kietyo
Apache License 2.0
2021/src/main/kotlin/Day21.kt
eduellery
433,983,584
false
{"Kotlin": 97092}
class Day21(val input: List<String>) { private val positionPlayerOne: Int = input[0].removePrefix("Player 1 starting position: ").toInt() private val positionPlayerTwo: Int = input[1].removePrefix("Player 2 starting position: ").toInt() private fun HashMap<Game, Long>.addCount(game: Game, count: Long) { this[game] = if (this.containsKey(game)) this[game]!! + count else count } private fun simulateRoll(game: Game): List<Game> { val games = listOf(game.deepCopy(), game.deepCopy(), game.deepCopy()) return games.forEachIndexed { index, thisGame -> thisGame.roll(index + 1) }.let { games } } fun solve1(): Long { val game = Game(Player.of(1, positionPlayerOne), Player.of(2, positionPlayerTwo)) var (lastRoll, rollCount) = listOf(0, 0) while (game.getWinner(1000) == null) { game.roll((if (lastRoll < 100) ++lastRoll else 1.also { lastRoll = 1 }).also { rollCount++ }) .roll((if (lastRoll < 100) ++lastRoll else 1.also { lastRoll = 1 }).also { rollCount++ }) .roll((if (lastRoll < 100) ++lastRoll else 1.also { lastRoll = 1 }).also { rollCount++ }) } return game.getLoser().score.toLong() * game.totalRollCount } fun solve2(): Long { var states = hashMapOf<Game, Long>() val startGame = Game(Player.of(1, positionPlayerOne, 0), Player.of(2, positionPlayerTwo, 0)) states[startGame] = 1 while (states.any { it.key.getWinner(21) == null }) { val newStates: HashMap<Game, Long> = hashMapOf() states.forEach { (game, count) -> if (game.getWinner(21) != null) { newStates.addCount(game, count) } else { val newGames = simulateRoll(game) newGames.forEach { newGame -> newStates.addCount(newGame, count) } } } states = newStates } return states.map { entry -> Pair(entry.key.getWinner(21)!!.name, entry.value) } .groupBy { it.first } .mapValues { it.value.sumOf { list -> list.second } } .maxOf { it.value } } private data class Player(var name: Int, var position: Int, var score: Int) { fun move(roll: Int) { position += roll while (position > 10) { position -= 10 } } fun increaseScore() { score += position } companion object { fun of(name: Int, position: Int, score: Int = 0): Player = Player(name, position, score) } } private data class Game(var playerOne: Player, var playerTwo: Player) { var rollCount = 0 var totalRollCount = 0 private var rollingPlayer: Player = playerOne fun getWinner(winningScore: Int): Player? { if (playerOne.score >= winningScore) return this.playerOne if (playerTwo.score >= winningScore) return this.playerTwo return null } fun getLoser(): Player = if (playerOne.score < playerTwo.score) playerOne else playerTwo fun deepCopy(): Game { val result = Game(playerOne.copy(), playerTwo.copy()) result.rollingPlayer = if (rollingPlayer == playerOne) result.playerOne else result.playerTwo result.rollCount = rollCount result.totalRollCount = totalRollCount return result } fun roll(roll: Int): Game = advance(rollingPlayer, roll).let { this } private fun advance(player: Player, roll: Int) { player.move(roll) rollCount++ totalRollCount++ if (rollCount == 3) { rollingPlayer.increaseScore() rollingPlayer = if (rollingPlayer == playerOne) playerTwo else playerOne rollCount = 0 } } } }
0
Kotlin
0
1
3e279dd04bbcaa9fd4b3c226d39700ef70b031fc
3,992
adventofcode-2021-2025
MIT License
src/main/kotlin/aoc2023/day5/day5Solver.kt
Advent-of-Code-Netcompany-Unions
726,531,711
false
{"Kotlin": 94973}
package aoc2023.day5 import lib.* suspend fun main() { setupChallenge().solveChallenge() } fun setupChallenge(): Challenge<Pair<List<Long>, Map<MapTypes, List<Pair<LongRange, Long>>>>> { return setup { day(5) year(2023) //input("example.txt") parser { val groups = it.getStringsGroupedByEmptyLine() val seeds = groups[0][0].replace("seeds: ", "").asListOfLongs() val mapMap = mutableMapOf<MapTypes, List<Pair<LongRange, Long>>>() groups.drop(1).forEach { val currentMap = createMap(it.drop(1)) when (it[0]) { "seed-to-soil map:" -> { mapMap[MapTypes.Seed] = currentMap } "soil-to-fertilizer map:" -> { mapMap[MapTypes.Soil] = currentMap } "fertilizer-to-water map:" -> { mapMap[MapTypes.Fertilizer] = currentMap } "water-to-light map:" -> { mapMap[MapTypes.Water] = currentMap } "light-to-temperature map:" -> { mapMap[MapTypes.Light] = currentMap } "temperature-to-humidity map:" -> { mapMap[MapTypes.Temperature] = currentMap } "humidity-to-location map:" -> { mapMap[MapTypes.Humidity] = currentMap } } } seeds to mapMap } partOne { val seeds = it.first val maps = it.second var closest = Long.MAX_VALUE seeds.forEach { var type = MapTypes.Seed var currentValue = it while (mapOrder.containsKey(type)) { val currentMap = maps[type]!! val match = currentMap.firstOrNull { it.first.first <= currentValue && it.first.last >= currentValue } if (match != null) { currentValue = match.second + (currentValue - match.first.first) } type = mapOrder[type]!! } closest = minOf(currentValue, closest) } closest.toString() } partTwo { val seedRanges = it.first.windowed(2, 2).map { it[0] until it[0] + it[1] } val maps = it.second var closest = Long.MAX_VALUE seedRanges.forEach { var type: MapTypes? = MapTypes.Seed var currentValues = listOf(it) do { val currentMap = maps[type]!! currentValues = currentValues.mapValuesTo2(currentMap) type = mapOrder.getOrDefault(type, null) } while (type != MapTypes.Location) closest = minOf(currentValues.minOf { it.first }, closest) } closest.toString() } } } enum class MapTypes { Seed, Soil, Fertilizer, Water, Light, Temperature, Humidity, Location } val mapOrder = mapOf( Pair(MapTypes.Seed, MapTypes.Soil), Pair(MapTypes.Soil, MapTypes.Fertilizer), Pair(MapTypes.Fertilizer, MapTypes.Water), Pair(MapTypes.Water, MapTypes.Light), Pair(MapTypes.Light, MapTypes.Temperature), Pair(MapTypes.Temperature, MapTypes.Humidity), Pair(MapTypes.Humidity, MapTypes.Location) ) fun createMap(lines: List<String>): List<Pair<LongRange, Long>> { val res = mutableListOf<Pair<LongRange, Long>>() lines.map { it.asListOfLongs() } .forEach { res.add(it[1] until it[1] + it[2] to it[0]) } return res.sortedBy { it.first.first } } fun List<LongRange>.mapValuesTo2(destination: List<Pair<LongRange, Long>>): List<LongRange> { val res = mutableListOf<LongRange>() val sourceIterator = this.listIterator() val destIterator = destination.iterator() var currentDest = destIterator.next() while (sourceIterator.hasNext()) { var sourceRange = sourceIterator.next() while(!sourceRange.isEmpty()) { while (currentDest.first.last < sourceRange.first && destIterator.hasNext()) { currentDest = destIterator.next() } val destRange = currentDest.first if(destRange.last < sourceRange.first && !destIterator.hasNext()) { res.add(sourceRange) while (sourceIterator.hasNext()) { res.add(sourceIterator.next()) } break } if (sourceRange.first < destRange.first) { val last = minOf(sourceRange.last, destRange.first) res.add(sourceRange.first..last) if (last == sourceRange.last) { break } } val intersection = sourceRange.intersect(destRange) val offset = intersection.first - destRange.first res.add((currentDest.second + offset)until(intersection.size() + currentDest.second + offset)) sourceRange = sourceRange.startAt(intersection.last + 1) } } return res.sortedBy { it.first } } fun List<LongRange>.mapValuesTo(destination: List<Pair<LongRange, Long>>): MutableList<LongRange> { val res = mutableListOf<LongRange>() this.forEach { range -> var remaining = range while (true) { val match = destination.firstOrNull { it.first.intersects(remaining) } if (match == null) { res.add(remaining) break } val matchedRange = match.first.intersect(remaining) val destStart = match.second + (remaining.first - match.first.first) res.add(destStart until (destStart + matchedRange.count())) if (matchedRange.first > remaining.first) { res.add(remaining.first until matchedRange.first) } if (matchedRange.last < remaining.last) { remaining = (matchedRange.last + 1)..remaining.last } else { break } } } return res }
0
Kotlin
0
0
a77584ee012d5b1b0d28501ae42d7b10d28bf070
6,404
AoC-2023-DDJ
MIT License
src/main/kotlin/days/Day5.kt
hughjdavey
433,597,582
false
{"Kotlin": 53042}
package days import util.Utils import kotlin.math.max import kotlin.math.min class Day5 : Day(5) { private val vents = inputList.flatMap { it.split(" -> ") }.flatMap { it.split(",") } .map { it.toInt() }.chunked(4).map { Vent(Utils.Coord(it[0], it[1]), Utils.Coord(it[2], it[3])) } override fun partOne(): Any { return atLeastTwoOverlaps(vents.filterNot(Vent::isDiagonal)) } override fun partTwo(): Any { return atLeastTwoOverlaps(vents) } private fun atLeastTwoOverlaps(vents: List<Vent>): Int { return vents.flatMap(Vent::getPoints).fold(mutableMapOf<Utils.Coord, Int>()) { diagram, coord -> diagram.compute(coord) { k, v -> if (v == null) 1 else v + 1 } diagram }.count { it.value >= 2 } } data class Vent(val start: Utils.Coord, val end: Utils.Coord) { private fun isVertical() = start.x == end.x private fun isHorizontal() = start.y == end.y fun isDiagonal() = !isVertical() && !isHorizontal() fun getPoints(): List<Utils.Coord> { val (minX, minY, maxX, maxY) = listOf(min(start.x, end.x), min(start.y, end.y), max(start.x, end.x), max(start.y, end.y)) val points = (minX..maxX).flatMap { xx -> (minY..maxY).map { yy -> Utils.Coord(xx, yy) } } return if (!isDiagonal()) points else { val sets = points.chunked(maxX - (minX - 1)) val index = sets.first().indexOfFirst { it == start || it == end } (if (index == 0) sets else sets.reversed()).mapIndexed { idx, coords -> coords[idx] } } } } }
0
Kotlin
0
0
a3c2fe866f6b1811782d774a4317457f0882f5ef
1,642
aoc-2021
Creative Commons Zero v1.0 Universal
src/main/kotlin/Day03.kt
robert-iits
573,124,643
false
{"Kotlin": 21047}
import java.lang.IllegalArgumentException class Day03 { private fun splitRucksackInHalf(rucksack: String): Pair<String, String> { return Pair(rucksack.take(rucksack.length/2), rucksack.takeLast(rucksack.length/2)) } fun getPriority(item: Char): Int { return if (item.code >= 'a'.code) { item.code - 'a'.code + 1 } else { item.code - 'A'.code + 27 } } fun findCommonItem(rucksack: String): Char { splitRucksackInHalf(rucksack).let { (firstHalf, secondHalf) -> firstHalf.onEach {char -> if (secondHalf.contains(char)) return char } } throw IllegalArgumentException() } fun part1(listOfRucksacks: List<String>): Int { return listOfRucksacks.sumOf { rucksack -> getPriority(findCommonItem(rucksack)) } } fun part2(listOfRucksacks: List<String>): Int { val rucksacks = listOfRucksacks.toMutableList() var sumOfPriority = 0 while(rucksacks.isNotEmpty()) { rucksacks.take(3).let { sumOfPriority += getPriority(getCommonChar(it)) rucksacks.removeAll(it) } } return sumOfPriority } private fun getCommonChar(it: List<String>): Char { it.first().forEach { char -> if (it[1].contains(char) && it.last().contains(char)) return char } throw IllegalArgumentException() } } fun main () { println("part 1:") println(Day03().part1(readInput("Day03"))) println("part 2:") println(Day03().part2(readInput("Day03"))) }
0
Kotlin
0
0
223017895e483a762d8aa2cdde6d597ab9256b2d
1,650
aoc2022
Apache License 2.0
src/day11/Day11.kt
daniilsjb
726,047,752
false
{"Kotlin": 66638, "Python": 1161}
package day11 import java.io.File import kotlin.math.max import kotlin.math.min fun main() { val data = parse("src/day11/Day11.txt") println("🎄 Day 11 🎄") println() println("[Part 1]") println("Answer: ${part1(data)}") println() println("[Part 2]") println("Answer: ${part2(data)}") } private fun parse(path: String): List<List<Char>> = File(path) .readLines() .map(String::toList) private fun solve(data: List<List<Char>>, scale: Long): Long { val emptyRows = data.indices .filter { row -> data[row].all { it == '.' } } val emptyCols = data[0].indices .filter { col -> data.all { it[col] == '.' } } val galaxies = mutableListOf<Pair<Int, Int>>() for ((y, row) in data.withIndex()) { for ((x, col) in row.withIndex()) { if (col == '#') { galaxies.add(x to y) } } } var accumulator = 0L for (a in 0..galaxies.lastIndex) { for (b in (a + 1)..galaxies.lastIndex) { val (ax, ay) = galaxies[a] val (bx, by) = galaxies[b] val x0 = min(ax, bx) val x1 = max(ax, bx) val y0 = min(ay, by) val y1 = max(ay, by) val nx = emptyCols.count { it in x0..x1 } val ny = emptyRows.count { it in y0..y1 } accumulator += (x1 - x0) + nx * (scale - 1) accumulator += (y1 - y0) + ny * (scale - 1) } } return accumulator } private fun part1(data: List<List<Char>>): Long = solve(data, scale = 2L) private fun part2(data: List<List<Char>>): Long = solve(data, scale = 1_000_000L)
0
Kotlin
0
0
46a837603e739b8646a1f2e7966543e552eb0e20
1,753
advent-of-code-2023
MIT License
src/day18/Day18.kt
dkoval
572,138,985
false
{"Kotlin": 86889}
package day18 import readInput import java.util.* import kotlin.math.abs private const val DAY_ID = "18" private data class Rock( val x: Int, val y: Int, val z: Int ) private data class Delta( val dx: Int, val dy: Int, val dz: Int ) private data class Range( var min: Int = Int.MAX_VALUE, var max: Int = Int.MIN_VALUE ) { operator fun contains(value: Int): Boolean = value in min..max fun onNext(value: Int) { min = minOf(min, value) max = maxOf(max, value) } } fun main() { fun parseInput(input: List<String>): List<Rock> = input.map { line -> val (x, y, z) = line.split(",").map { it.toInt() } Rock(x, y, z) } fun part1(input: List<String>): Int { val rocks = parseInput(input) val n = rocks.size var common = 0 for (i in 0 until n - 1) { for (j in i + 1 until n) { val (x1, y1, z1) = rocks[i] val (x2, y2, z2) = rocks[j] if ((abs(x1 - x2) == 1 && y1 == y2 && z1 == z2) || (abs(y1 - y2) == 1 && x1 == x2 && z1 == z2) || (abs(z1 - z2) == 1 && x1 == x2 && y1 == y2)) { common++ } } } return 6 * n - 2 * common } fun part2(input: List<String>): Int { val rocks = parseInput(input).toSet() val rangeX = Range() val rangeY = Range() val rangeZ = Range() for (rock in rocks) { rangeX.onNext(rock.x) rangeY.onNext(rock.y) rangeZ.onNext(rock.z) } val deltas = listOf( Delta(-1, 0, 0), Delta(1, 0, 0), // Ox Delta(0, -1, 0), Delta(0, 1, 0), // Oy Delta(0, 0, -1), Delta(0, 0, 1)) // Oz fun isTrapped(source: Rock): Boolean { // ~ bfs val q: Queue<Rock> = ArrayDeque() val seen: MutableSet<Rock> = mutableSetOf() q.offer(source) seen += source while (!q.isEmpty()) { val curr = q.poll() // must be an "empty" position if (curr in rocks) { continue } // reached beyond rocks? if (curr.x !in rangeX || curr.y !in rangeY || curr.z !in rangeZ) { return false } for ((dx, dy, dz) in deltas) { val next = Rock(curr.x + dx, curr.y + dy, curr.z + dz) if (next !in seen) { q.offer(next) seen += next } } } return true } var ans = 0 for ((x, y, z) in rocks) { for ((dx, dy, dz) in deltas) { val next = Rock(x + dx, y + dy, z + dz) if (!isTrapped(next)) { ans++ } } } return ans } // test if implementation meets criteria from the description, like: val testInput = readInput("day${DAY_ID}/Day${DAY_ID}_test") check(part1(testInput) == 64) check(part2(testInput) == 58) val input = readInput("day${DAY_ID}/Day${DAY_ID}") println(part1(input)) // answer = 3454 println(part2(input)) // answer = 2014 }
0
Kotlin
1
0
791dd54a4e23f937d5fc16d46d85577d91b1507a
3,403
aoc-2022-in-kotlin
Apache License 2.0
src/test/kotlin/days/y2022/Day12Test.kt
jewell-lgtm
569,792,185
false
{"Kotlin": 161272, "Jupyter Notebook": 103410, "TypeScript": 78635, "JavaScript": 123}
package days.y2022 import days.Day import org.hamcrest.MatcherAssert.assertThat import org.hamcrest.core.Is.`is` import org.junit.jupiter.api.Test class Day12 : Day(2022, 12) { override fun partOne(input: String): Any { val (map, startPos, endPos) = parseInput(input) return findPath(map, startPos, endPos) } override fun partTwo(input: String): Any { val (map, _, endPos) = parseInput(input) val startPositions = map.scanAll { it == 'S'.code || it == 'a'.code } var best = Int.MAX_VALUE for (startPos in startPositions) { val path = findPath(map, startPos, endPos) if (path < best) { best = path } } return best } fun parseInput(input: String): Triple<List<List<Int>>, Pair<Int, Int>, Pair<Int, Int>> { val lines = input.trim().lines() val map = lines.map { line -> line.trim().map { it.code } } val startPos = map.scanFor { it == 'S'.code } val endPos = map.scanFor { it == 'E'.code } return Triple(map, startPos, endPos) } fun <T> List<List<T>>.scanFor(test: (T) -> Boolean) = scanAll(test).first() fun <T> List<List<T>>.scanAll(test: (T) -> Boolean): List<Pair<Int, Int>> { val result = mutableListOf<Pair<Int, Int>>() for (i in indices) { for (j in this[i].indices) { if (test(this[i][j])) { result.add(i to j) } } } return result } private fun findPath(map: List<List<Int>>, startPos: Pair<Int, Int>, endPos: Pair<Int,Int>): Int { val pathLengthTo = mutableMapOf(startPos to 0) val nodesToVisit = mutableSetOf(startPos) var currPos: Pair<Int, Int> while (nodesToVisit.isNotEmpty()) { currPos = nodesToVisit.minByOrNull { candidate -> pathLengthTo[candidate]?.let { it + 1 } ?: Int.MAX_VALUE }!! if (currPos == endPos) { return pathLengthTo[currPos]!! } nodesToVisit.remove(currPos) currPos.neighbors(map).forEach { val travelToNeighbor = pathLengthTo[currPos]!! + 1 if (travelToNeighbor <= (pathLengthTo[it] ?: Int.MAX_VALUE)) { pathLengthTo[it] = travelToNeighbor nodesToVisit.add(it) } } } return Int.MAX_VALUE } private fun Pair<Int, Int>.neighbors(map: List<List<Int>>): List<Pair<Int, Int>> { return listOf( Pair(first - 1, second), Pair(first + 1, second), Pair(first, second - 1), Pair(first, second + 1) ) .filter { it.first in map.indices && it.second in map[it.first].indices } .filter { neighbor -> val value = map[this.first][this.second].takeUnless { it == 'S'.code } ?: 'a'.code val otherValue = map[neighbor.first][neighbor.second].takeUnless { it == 'E'.code } ?: 'z'.code otherValue <= value + 1 } } } class Day12Test { val exampleInput = """ Sabqponm abcryxxl accszExk acctuvwj abdefghi """.trimIndent() @Test fun testExampleOne() { assertThat(Day12().partOne(exampleInput), `is`(31)) } @Test fun testPartOne() { assertThat(Day12().partOne(), `is`(440)) } @Test fun testExampleTwo() { assertThat( Day12().partTwo(exampleInput), `is`(29) ) } @Test fun testPartTwo() { assertThat(Day12().partTwo(), `is`(439)) } }
0
Kotlin
0
0
b274e43441b4ddb163c509ed14944902c2b011ab
3,738
AdventOfCode
Creative Commons Zero v1.0 Universal
2021/src/main/kotlin/day11_func.kt
madisp
434,510,913
false
{"Kotlin": 388138}
import utils.IntGrid import utils.Solution import utils.Vec2i import utils.withCounts fun main() { Day11Func.run() } object Day11Func : Solution<IntGrid>() { override val name = "day11" override val parser = IntGrid.singleDigits private tailrec fun flash(alreadyFlashed: Set<Vec2i>, grid: IntGrid): IntGrid { val flashPts = grid.coords.filter { it !in alreadyFlashed && grid[it] == 0 }.toSet() val flashSurrounding = flashPts.flatMap { it.surrounding } .filter { it !in flashPts && it !in alreadyFlashed } .withCounts() val flashedGrid = grid.map { coord, value -> (value + (flashSurrounding[coord] ?: 0)).coerceAtMost(10) % 10 } if (flashedGrid.coords.none { flashedGrid[it] == 0 && it !in alreadyFlashed && it !in flashPts }) { return flashedGrid } return flash(alreadyFlashed + flashPts, flashedGrid) } /** * Generates a sequence of Grid, Int pairs with the Int representing * how many flashes there were that day */ fun evolve(input: IntGrid): Sequence<IntGrid> { return generateSequence(input) { flash(emptySet(), it.map { _, v -> (v + 1) % 10 }) } } override fun part1(input: IntGrid): Int { return evolve(input) .take(101) .map { grid -> grid.values.count { it == 0 } } .sum() } override fun part2(input: IntGrid): Int { return evolve(input) .takeWhile { grid -> grid.values.any { it != 0 } } .count() } }
0
Kotlin
0
1
3f106415eeded3abd0fb60bed64fb77b4ab87d76
1,460
aoc_kotlin
MIT License
src/main/kotlin/com/hj/leetcode/kotlin/problem1074/Solution.kt
hj-core
534,054,064
false
{"Kotlin": 619841}
package com.hj.leetcode.kotlin.problem1074 /** * LeetCode page: [1074. Number of Submatrices That Sum to Target](https://leetcode.com/problems/number-of-submatrices-that-sum-to-target/); */ class Solution { /* Complexity: * Time O(M^2 * N) and Space O(MN) where M and N are the number of rows and * columns of matrix; */ fun numSubmatrixSumTarget(matrix: Array<IntArray>, target: Int): Int { var result = 0 val prefixSum = matrix.prefixSum() for (top in matrix.indices) { for (bottom in top..<matrix.size) { // Like condensing the rows between top and bottom into a single row val countRightSum = hashMapOf<Int, Int>().apply { this[0] = 1 } for (right in matrix[top].indices) { val rightSum = (prefixSum[bottom][right] - (prefixSum.getOrNull(top - 1)?.get(right) ?: 0)) val complement = rightSum - target if (complement in countRightSum) { result += checkNotNull(countRightSum[complement]) } countRightSum[rightSum] = 1 + (countRightSum[rightSum] ?: 0) } } } return result } private fun Array<IntArray>.prefixSum(): Array<IntArray> { val result = Array(size) { IntArray(this[it].size) } result[0][0] = this[0][0] for (column in 1..<this[0].size) { result[0][column] = this[0][column] + result[0][column - 1] } for (row in 1..<this.size) { result[row][0] = this[row][0] + result[row - 1][0] } for (row in 1..<this.size) { for (column in 1..<this[row].size) { result[row][column] = (this[row][column] + result[row - 1][column] + result[row][column - 1] - result[row - 1][column - 1]) } } return result } }
1
Kotlin
0
1
14c033f2bf43d1c4148633a222c133d76986029c
2,031
hj-leetcode-kotlin
Apache License 2.0
src/main/Day09.kt
ssiegler
572,678,606
false
{"Kotlin": 76434}
package day09 import geometry.* import utils.readInput data class Rope(val knots: List<Position>) { fun move(direction: Direction) = Rope( knots.subList(1, knots.size).scan(knots[0].move(direction)) { lead, tail -> tail.follow(lead) } ) private fun Position.follow(head: Position): Position = when (head.x - x to head.y - y) { -1 to -1, -1 to 0, -1 to 1, 0 to -1, 0 to 0, 0 to 1, 1 to -1, 1 to 0, 1 to 1 -> this 2 to 0 -> x + 1 to y -2 to 0 -> x - 1 to y 0 to 2 -> x to y + 1 0 to -2 -> x to y - 1 2 to 1 -> x + 1 to y + 1 2 to -1 -> x + 1 to y - 1 -2 to 1 -> x - 1 to y + 1 -2 to -1 -> x - 1 to y - 1 1 to 2 -> x + 1 to y + 1 1 to -2 -> x + 1 to y - 1 -1 to 2 -> x - 1 to y + 1 -1 to -2 -> x - 1 to y - 1 2 to 2 -> x + 1 to y + 1 2 to -2 -> x + 1 to y - 1 -2 to -2 -> x - 1 to y - 1 -2 to 2 -> x - 1 to y + 1 else -> error("Broken link: $this to $head") } } fun String.readMoves() = when (get(0)) { 'R' -> Direction.Right 'D' -> Direction.Down 'L' -> Direction.Left 'U' -> Direction.Up else -> error("Unknown direction ${get(0)}") } to substring(2).toInt() fun part1(filename: String): Int = readMoves(filename).simulate(2).map { it.knots.last() }.toSet().size fun part2(filename: String): Int = readMoves(filename).simulate(10).map { it.knots.last() }.toSet().size internal fun readMoves(filename: String): List<Direction> = readInput(filename).map(String::readMoves).flatMap { (direction, count) -> generateSequence { direction }.take(count) } internal fun List<Direction>.simulate(knots: Int): List<Rope> = scan(Rope((1..knots).map { 0 to 0 })) { rope, direction -> rope.move(direction) } private const val filename = "Day09" fun main() { println(part1(filename)) println(part2(filename)) }
0
Kotlin
0
0
9133485ca742ec16ee4c7f7f2a78410e66f51d80
2,181
aoc-2022
Apache License 2.0
src/main/kotlin/g1801_1900/s1889_minimum_space_wasted_from_packaging/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g1801_1900.s1889_minimum_space_wasted_from_packaging // #Hard #Array #Sorting #Binary_Search #Prefix_Sum // #2023_06_22_Time_910_ms_(100.00%)_Space_67.5_MB_(100.00%) class Solution { fun minWastedSpace(packages: IntArray, boxes: Array<IntArray>): Int { val numPackages = packages.size packages.sort() val preSum = LongArray(numPackages) preSum[0] = packages[0].toLong() for (i in 1 until packages.size) { preSum[i] = packages[i] + preSum[i - 1] } var ans = Long.MAX_VALUE for (box in boxes) { box.sort() // Box of required size not present if (packages[numPackages - 1] > box[box.size - 1]) { continue } // Find the total space wasted var totalWastedSpace: Long = 0 var prev = -1 for (j in box) { if (prev == packages.size - 1) { break } if (j < packages[0] || j < packages[prev + 1]) { continue } // Find up to which package the current box can fit val upper = findUpperBound(packages, j) if (upper == -1) { continue } // The current box will be able to handle the packages from // prev + 1 to the upper index val totalSpace = (upper.toLong() - prev.toLong()) * j val packageSum = preSum[upper] - if (prev >= 0) preSum[prev] else 0 val spaceWastedCurr = totalSpace - packageSum totalWastedSpace += spaceWastedCurr prev = upper } ans = Math.min(ans, totalWastedSpace) } return if (ans == Long.MAX_VALUE) -1 else (ans % MOD).toInt() } private fun findUpperBound(packages: IntArray, key: Int): Int { var l = 0 var h = packages.size while (l < h) { val m = l + (h - l) / 2 if (packages[m] <= key) { l = m + 1 } else { h = m } } return h - 1 } companion object { private const val MOD = 1000000007 } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
2,290
LeetCode-in-Kotlin
MIT License
src/Day02.kt
ech0matrix
572,692,409
false
{"Kotlin": 116274}
import Play.* import Outcome.* fun main() { fun part1(input: List<String>): Int { val scores = input.map { Game(it[0].toPlay(), it[2].toPlay()) }.map { it.score() } //scores.forEach{println(it)} return scores.sum() } fun part2(input: List<String>): Int { val scores = input.map { val opponent = it[0].toPlay() val outcome = it[2].toOutcome() Game(opponent, outcome.toPlay(opponent)) }.map { it.score() } return scores.sum() } val testInput = readInput("Day02_test") check(part1(testInput) == 15) val input = readInput("Day02") println(part1(input)) println(part2(input)) } fun Char.toPlay(): Play { return when(this) { 'A', 'X' -> ROCK 'B', 'Y' -> PAPER 'C', 'Z' -> SCISSORS else -> throw IllegalArgumentException("Invalid letter: $this") } } fun Outcome.toPlay(opponent: Play): Play { return when(this) { DRAW -> opponent LOSE -> when(opponent) { ROCK -> SCISSORS PAPER -> ROCK SCISSORS -> PAPER } WIN -> when(opponent) { ROCK -> PAPER PAPER -> SCISSORS SCISSORS -> ROCK } } } fun Char.toOutcome(): Outcome { return when(this) { 'X' -> LOSE 'Y' -> DRAW 'Z' -> WIN else -> throw IllegalArgumentException("Invalid letter: $this") } } enum class Play { ROCK, PAPER, SCISSORS } enum class Outcome { LOSE, DRAW, WIN } data class Game( val opponent: Play, val self: Play ) { fun score(): Int { //println(this) val playScore = when(self) { ROCK -> 1 PAPER -> 2 SCISSORS -> 3 } //println(playScore) val matchScore = when { (self == opponent) -> 3 isWinner() -> 6 else -> 0 } //println(matchScore) //println() return playScore + matchScore } // Denotes if 'self' wins or loses (undefined on tie) private fun isWinner(): Boolean { return when(self) { ROCK -> opponent == SCISSORS PAPER -> opponent == ROCK SCISSORS -> opponent == PAPER } } }
0
Kotlin
0
0
50885e12813002be09fb6186ecdaa3cc83b6a5ea
2,333
aoc2022
Apache License 2.0
2022/src/test/kotlin/Day02.kt
jp7677
318,523,414
false
{"Kotlin": 171284, "C++": 87930, "Rust": 59366, "C#": 1731, "Shell": 354, "CMake": 338}
import io.kotest.core.spec.style.StringSpec import io.kotest.matchers.shouldBe private enum class Outcome { WIN, LOOSE, DRAW; companion object { fun from(input: String) = when (input) { "X" -> LOOSE "Y" -> DRAW "Z" -> WIN else -> throw IllegalArgumentException(input) } } fun score() = when (this) { WIN -> 6 LOOSE -> 0 DRAW -> 3 } } private enum class Shape { ROCK, PAPER, SCISSORS; companion object { fun from(input: String) = when (input) { "A", "X" -> ROCK "B", "Y" -> PAPER "C", "Z" -> SCISSORS else -> throw IllegalArgumentException(input) } } fun score() = when (this) { ROCK -> 1 PAPER -> 2 SCISSORS -> 3 } } private data class Game(val other: Shape, val you: Shape?, val outcome: Outcome?) { fun scoreForSelected() = you?.score() ?: throw IllegalStateException() fun scoreForOutcome() = outcome?.score() ?: throw IllegalStateException() fun calcOutcome() = Game( other, you, when (you) { other.forWin() -> Outcome.WIN other.forLoose() -> Outcome.LOOSE else -> Outcome.DRAW } ) fun decrypt() = Game( other, when (outcome) { Outcome.DRAW -> other Outcome.WIN -> other.forWin() Outcome.LOOSE -> other.forLoose() else -> throw IllegalStateException() }, outcome ) private fun Shape.forLoose() = this.forWin().forWin() private fun Shape.forWin() = when (this) { Shape.ROCK -> Shape.PAPER Shape.PAPER -> Shape.SCISSORS Shape.SCISSORS -> Shape.ROCK } } class Day02 : StringSpec({ "puzzle part 01" { val totalScore = getPuzzleInput("day02-input.txt") .map { it.split(' ') } .map { Game(Shape.from(it.first()), Shape.from(it.last()), null) } .map { it.calcOutcome() } .sumOf { it.scoreForOutcome() + it.scoreForSelected() } totalScore shouldBe 14531 } "puzzle part 02" { val totalScore = getPuzzleInput("day02-input.txt") .map { it.split(' ') } .map { Game(Shape.from(it.first()), null, Outcome.from(it.last())) } .map { it.decrypt() } .sumOf { it.scoreForOutcome() + it.scoreForSelected() } totalScore shouldBe 11258 } })
0
Kotlin
1
2
8bc5e92ce961440e011688319e07ca9a4a86d9c9
2,594
adventofcode
MIT License
src/main/kotlin/final_450/arrays/exam.kt
ch8n
312,467,034
false
null
package final_450.arrays fun main() { val input = "23" val numbers = arrayOf<String>("123", "234", "567") val names = arrayOf<String>("chetan", "pokemon", "sokemon") val result = numbers .zip(names) .sortedBy { it.second } .firstOrNull { it.first.contains(input) } ?: "No Contact" println(result) val input0 = "00-44 48 5555 8361".apply { println(length % 2 == 0) } val input2 = "0 - 22 1985--324".trim().apply { println(length) } // even val result2 = input2.split("") .filter { it.toIntOrNull() != null } .chunked(3) .let { if (it.last().size == 1) { val newFormat = it.takeLast(2) .joinToString("") .split("") .filter { it.toIntOrNull() != null } .chunked(2) return@let it.dropLast(2) + newFormat } it } .joinToString(separator = "-") { it.joinToString(separator = "") } //022-198-53-24 println(result2) val yearOfVacation: Int = 2014 val startMonth: String = "April" val endMonth: String = "May" val dayOfWeek: String = "Wednesday" // answer = 7 val holidays = getDays(startMonth, endMonth, yearOfVacation, dayOfWeek) println(holidays / 7) val target = 3 val nodes1 = listOf(1, 3) val nodes2 = listOf(2, 2) val links = nodes1.zip(nodes2) val sorted = links.map { val (first,second) = it listOf(first,second).sorted() } println(sorted) } fun getDays(startMonth: String, endMonth: String, year: Int, startDay: String): Int { val weekIndex = listOf( "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" ) val monthIndex = listOf( "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December", ) val dayInMonth = mapOf( "January" to 31, "February" to if (isLeapYear(year)) 29 else 28, "March" to 31, "April" to 30, "May" to 31, "June" to 30, "July" to 31, "August" to 31, "September" to 30, "October" to 31, "November" to 30, "December" to 31, ) val indexOfStartMonth = monthIndex.indexOf(startMonth) val indexOfEndMonth = monthIndex.indexOf(endMonth) val result = (indexOfStartMonth..indexOfEndMonth).map { val month = monthIndex.get(it) dayInMonth.get(month) ?: 0 }.sum() val startedOn = weekIndex.indexOf(startDay) return result - startedOn } fun isLeapYear(year: Int): Boolean { return when { year % 4 != 0 -> false year % 400 == 0 -> true else -> year % 100 != 0 } }
3
Kotlin
0
1
e0619ebae131a500cacfacb7523fea5a9e44733d
2,934
Big-Brain-Kotlin
Apache License 2.0
advent-of-code-2022/src/main/kotlin/year_2022/Day08.kt
rudii1410
575,662,325
false
{"Kotlin": 37749}
package year_2022 import util.Runner fun main() { val LEFT = 0 val TOP = 1 val RIGHT = 2 val BOTTOM = 3 /* Part 1 */ fun findTallerTree(tree: List<String>, part: Int, currentTree: Int, v: Int, h: Int, maxV: Int, maxH: Int): Boolean { if (v == 0 || h == 0 || v == maxV - 1 || h == maxH - 1) return false return when (part) { LEFT -> { if (tree[v][h - 1].digitToInt() < currentTree) findTallerTree(tree, part, currentTree, v, h - 1, maxV, maxH) else true } TOP -> { if (tree[v - 1][h].digitToInt() < currentTree) findTallerTree(tree, part, currentTree, v - 1, h, maxV, maxH) else true } RIGHT -> { if (tree[v][h + 1].digitToInt() < currentTree) findTallerTree(tree, part, currentTree, v, h + 1, maxV, maxH) else true } else -> { if (tree[v + 1][h].digitToInt() < currentTree) findTallerTree(tree, part, currentTree, v + 1, h, maxV, maxH) else true } } } fun part1(tree: List<String>): Int { val maxV = tree.size val maxH = tree[0].length return (maxV * maxH) - tree.mapIndexed { v, row -> row.mapIndexed { h, c -> findTallerTree(tree, LEFT, c.digitToInt(), v, h, maxV, maxH) && findTallerTree(tree, TOP, c.digitToInt(), v, h, maxV, maxH) && findTallerTree(tree, RIGHT, c.digitToInt(), v, h, maxV, maxH) && findTallerTree(tree, BOTTOM, c.digitToInt(), v, h, maxV, maxH) }.count { it } }.sum() } Runner.run(::part1, 21) /* Part 2 */ fun traversePart(tree: List<String>, part: Int, currentTree: Int, v: Int, h: Int, maxV: Int, maxH: Int): Int { if (v == 0 || h == 0 || v == maxV - 1 || h == maxH - 1) return 0 return when (part) { LEFT -> { 1 + if (tree[v][h - 1].digitToInt() < currentTree) { traversePart(tree, part, currentTree, v, h - 1, maxV, maxH) } else 0 } TOP -> { 1 + if (tree[v - 1][h].digitToInt() < currentTree) { traversePart(tree, part, currentTree, v - 1, h, maxV, maxH) } else 0 } RIGHT -> { 1 + if (tree[v][h + 1].digitToInt() < currentTree) { traversePart(tree, part, currentTree, v, h + 1, maxV, maxH) } else 0 } else -> { 1 + if (tree[v + 1][h].digitToInt() < currentTree) { traversePart(tree, part, currentTree, v + 1, h, maxV, maxH) } else 0 } } } fun part2(tree: List<String>): Int { val maxV = tree.size val maxH = tree[0].length return tree.mapIndexed { v, row -> row.mapIndexed { h, c -> traversePart(tree, LEFT, c.digitToInt(), v, h, maxV, maxH) * traversePart(tree, TOP, c.digitToInt(), v, h, maxV, maxH) * traversePart(tree, RIGHT, c.digitToInt(), v, h, maxV, maxH) * traversePart(tree, BOTTOM, c.digitToInt(), v, h, maxV, maxH) }.max() }.max() } Runner.run(::part2, 8) }
1
Kotlin
0
0
ab63e6cd53746e68713ddfffd65dd25408d5d488
3,487
advent-of-code
Apache License 2.0
src/day11/Day11.kt
JoeSkedulo
573,328,678
false
{"Kotlin": 69788}
package day11 import Runner import day11.Operator.* fun main() { Day11Runner().solve() } class Day11Runner : Runner<Long>( day = 11, expectedPartOneTestAnswer = 10605, expectedPartTwoTestAnswer = 2713310158 ) { override fun partOne(input: List<String>, test: Boolean): Long { return solve( monkeys = monkeys(input), rounds = 20, worryReduction = 3 ) } override fun partTwo(input: List<String>, test: Boolean): Long { return solve( monkeys = monkeys(input), rounds = 10000, worryReduction = 1 ) } private fun solve(monkeys: List<Monkey>, rounds: Int, worryReduction: Int) : Long { val commonDenominator = monkeys.map { it.test.divisibleBy } .reduce { a, b -> a * b } repeat(rounds) { monkeys.forEach { monkey -> monkey.currentItems.forEach { item -> val operationResult = monkey.operation.calculate(item) / worryReduction val testResult = operationResult % monkey.test.divisibleBy == 0L if (testResult) { monkeys[monkey.test.monkeyIfTrue].currentItems.add(operationResult % commonDenominator) } else { monkeys[monkey.test.monkeyIfFalse].currentItems.add(operationResult % commonDenominator) } } monkey.itemsInspected.addAll(monkey.currentItems) monkey.currentItems.clear() } } return monkeys .map { monkey -> monkey.itemsInspected.count().toLong() } .sortedDescending() .subList(0, 2) .reduce { a, b -> a * b } } private fun monkeys(input: List<String>) : List<Monkey> { return input.windowed(6, 7).map { lines -> monkey(lines) } } private fun monkey(input: List<String>) : Monkey { return Monkey( currentItems = items(input[1]), operation = operation(input[2]), test = test(input[3], input[4], input[5]) ) } private fun items(line: String): MutableList<Long> { return line.replace(" Starting items: ", "") .split(", ") .map { it.toLong() } .toMutableList() } private fun operation(line: String) : Operation { val operator = when (line[23]) { '*' -> Multiply '+' -> Add '-' -> Subtract else -> throw RuntimeException() } val value = line.split(" ").last() .toLongOrNull() ?.let { OperationLong(it) } ?: OperationOld return Operation( operator = operator, value = value ) } private fun test(line: String, trueLine: String, falseLine: String) : Test { return Test( divisibleBy = line.split(" ").last().toLong(), monkeyIfTrue = trueLine.split( " ").last().toInt(), monkeyIfFalse = falseLine.split(" ").last().toInt() ) } private fun Operation.calculate(input: Long) : Long { val value = when (this.value) { is OperationLong -> this.value.v OperationOld -> input } return when (this.operator) { Add -> input + value Subtract -> input - value Multiply -> input * value } } } data class Monkey( val currentItems: MutableList<Long>, val itemsInspected: MutableList<Long> = mutableListOf(), val operation: Operation, val test: Test ) data class Operation( val operator: Operator, val value: OperationValue ) data class Test( val divisibleBy: Long, val monkeyIfTrue: Int, val monkeyIfFalse: Int ) sealed interface OperationValue data class OperationLong( val v: Long ) : OperationValue object OperationOld : OperationValue enum class Operator { Add, Subtract, Multiply }
0
Kotlin
0
0
bd8f4058cef195804c7a057473998bf80b88b781
4,060
advent-of-code
Apache License 2.0
src/com/akshay/adventofcode/Day05.kt
AkshayChordiya
574,736,798
false
{"Kotlin": 3303}
package com.akshay.adventofcode import java.io.File data class Move(val quantity: Int, val source: Int, val target: Int) { companion object { fun of(line: String): Move { return line .split(" ") .filterIndexed { index, _ -> index % 2 == 1 } .map { it.toInt() } .let { Move(it[0], it[1] - 1, it[2] - 1) } } } } /** * Advent of Code 2022 - Day 5 (Supply Stacks) * http://adventofcode.com/2022/day/5 */ class Day05 { fun partOne(stacks: List<ArrayDeque<Char>>, moves: List<Move>): String { moves.forEach { move -> repeat(move.quantity) { stacks[move.target].addFirst(stacks[move.source].removeFirst()) } } return stacks.map { it.first() }.joinToString(separator = "") } fun partTwo(stacks: List<ArrayDeque<Char>>, moves: List<Move>): String { moves.forEach { step -> stacks[step.source] .subList(0, step.quantity) .asReversed() .map { stacks[step.target].addFirst(it) } .map { stacks[step.source].removeFirst() } } return stacks.map { it.first() }.joinToString(separator = "") } fun populateStacks(lines: List<String>, onCharacterFound: (Int, Char) -> Unit) { lines .filter { it.contains("[") } .forEach { line -> line.mapIndexed { index, char -> if (char.isLetter()) { val stackNumber = index / 4 val value = line[index] onCharacterFound(stackNumber, value) } } } } } fun main() { val lines = File("input.txt").readLines() val day05 = Day05() // Calculate number of stacks needed val stacks = List(9) { ArrayDeque<Char>() } // Fill the stacks day05.populateStacks(lines) { stackNumber, value -> stacks[stackNumber].addLast(value) } // Get the moves val moves = lines.filter { it.contains("move") }.map { Move.of(it) } // Perform the moves println(day05.partOne(stacks.map { ArrayDeque(it) }.toList(), moves)) println(day05.partTwo(stacks, moves)) }
0
Kotlin
0
0
ad60a71bd00e260a11b2546f67c4d8c135cb88b6
2,245
advent-of-code-kotlin-2022
Apache License 2.0
src/main/kotlin/days/Day02.kt
Kebaan
573,069,009
false
null
package days import days.Day02.HandShape.* import utils.Day import utils.GameResult import utils.GameResult.* import utils.toPair fun main() { Day02.solve() } object Day02 : Day<Int>(2022, 2) { private fun calculateScoreForRound(round: RockPaperScissorsGame): Int { val outcomeScore = when (round.play()) { Lose -> 0 Draw -> 3 Win -> 6 } return outcomeScore + (round.myChoice.value) } private fun parseHandShape(input: String) = when (input) { "A", "X" -> Rock "B", "Y" -> Paper "C", "Z" -> Scissor else -> error("invalid input") } private fun parseStrategy(input: String) = when (input) { "X" -> Lose "Y" -> Draw "Z" -> Win else -> error("invalid input") } private fun List<String>.toRockPaperScissorRounds(transform: (Pair<String, String>) -> RockPaperScissorsGame): List<RockPaperScissorsGame> { return this.map { transform(it.toPair(" ")) } } override fun part1(input: List<String>): Int { return input.toRockPaperScissorRounds { val opponentChoice = parseHandShape(it.first) val myChoice = parseHandShape(it.second) RockPaperScissorsGame(opponentChoice, myChoice) }.sumOf { calculateScoreForRound(it) } } override fun part2(input: List<String>): Int { return input.toRockPaperScissorRounds { val opponentChoice = parseHandShape(it.first) val gameStrategy = parseStrategy(it.second) val myChoice = opponentChoice.findHand(gameStrategy) RockPaperScissorsGame(opponentChoice, myChoice) }.sumOf { calculateScoreForRound(it) } } override fun doSolve() { part1(input).let { check(it == 11666) println(it) } part2(input).let { check(it == 12767) println(it) } } data class RockPaperScissorsGame(val opponentChoice: HandShape, val myChoice: HandShape) { fun play(): GameResult { return myChoice.playAgainst(opponentChoice) } } sealed interface HandShape { val value: Int fun winningAgainst(): HandShape fun losingAgainst(): HandShape fun playAgainst(opponentChoice: HandShape): GameResult { return when (opponentChoice) { winningAgainst() -> Win losingAgainst() -> Lose else -> Draw } } fun findHand(gameStrategy: GameResult) = when (gameStrategy) { Draw -> this Lose -> this.winningAgainst() Win -> this.losingAgainst() } object Rock : HandShape { override val value = 1 override fun winningAgainst() = Scissor override fun losingAgainst() = Paper } object Paper : HandShape { override val value = 2 override fun winningAgainst() = Rock override fun losingAgainst() = Scissor } object Scissor : HandShape { override val value = 3 override fun winningAgainst() = Paper override fun losingAgainst() = Rock } } override val testInput = """ A Y B X C Z""".trimIndent().lines() }
0
Kotlin
0
0
ef8bba36fedbcc93698f3335fbb5a69074b40da2
3,383
Advent-of-Code-2022
Apache License 2.0
src/main/kotlin/day11/SolutionPart2.kt
TestaDiRapa
573,066,811
false
{"Kotlin": 50405}
package day11 import java.io.File import java.lang.Exception class IntModule( initial: Int = 0, oldModuleMap: Map<Int, Int>? = null ) { private val moduleMap = oldModuleMap ?: listOf(2,3,5,7,11,13,17,19,23).fold(emptyMap()) { acc, it -> acc + (it to initial%it)} operator fun plus(increment: Int): IntModule = moduleMap.keys.fold(emptyMap<Int, Int>()) { acc, it -> acc + (it to (moduleMap[it]!! + increment)%it) }.let { IntModule(oldModuleMap = it) } operator fun times(increment: Int): IntModule = moduleMap.keys.fold(emptyMap<Int, Int>()) { acc, it -> acc + (it to (moduleMap[it]!! * increment)%it) }.let { IntModule(oldModuleMap = it) } fun squared(): IntModule = moduleMap.keys.fold(emptyMap<Int, Int>()) { acc, it -> acc + (it to (moduleMap[it]!! * moduleMap[it]!!)%it) }.let { IntModule(oldModuleMap = it) } fun isDivisibleBy(other: Int): Boolean = moduleMap[other] == 0 } data class MonkeyModule( val id: Int, val items: List<IntModule>, val operation: (IntModule) -> IntModule, val nextMonkey: (IntModule) -> Int, val monkeyActivity: Long = 0 ) { fun doATurn(monkeys: List<MonkeyModule>, verbose: Boolean = false): List<MonkeyModule> { if (items.isEmpty()) return monkeys val updatedMonkeys = items.fold(monkeys) { acc, item -> if (verbose) println("Monkey $id inspects an item with a worry level of $item.") val newLevel = operation(item) if (verbose) println("\tWorry level is now $newLevel.") val receiverMonkeyId = nextMonkey(newLevel) if (verbose) println("\tItem with worry level $newLevel is thrown to monkey $receiverMonkeyId.") val receiverMonkey = acc.first { it.id == receiverMonkeyId } acc.filter { it.id != receiverMonkeyId } + receiverMonkey.copy( items = receiverMonkey.items + newLevel ) } return updatedMonkeys.filter { it.id != id } + this.copy(items = emptyList(), monkeyActivity = monkeyActivity + items.size) } } fun parseNextMonkeyWithModule(input: String): (IntModule) -> Int { val divisor = Regex("Test: divisible by ([0-9]+)").find(input)!!.groupValues[1].toInt() val ifTrue = Regex("If true: throw to monkey ([0-9]+)").find(input)!!.groupValues[1].toInt() val ifFalse = Regex("If false: throw to monkey ([0-9]+)").find(input)!!.groupValues[1].toInt() return { it -> if (it.isDivisibleBy(divisor)) ifTrue else ifFalse} } fun parseOperationWithModule(rawOperation: String): (IntModule) -> IntModule { Regex("new = ([0-9a-z]+) ([*+-]) ([0-9a-z]+)") .find(rawOperation)!! .groupValues .let { groups -> val first = groups[1] val op = groups[2] val second = groups[3] return if(first == "old" && second == "old") { when(op) { "+" -> { it -> it * 2 } "*" -> { it -> it.squared() } else -> throw Exception("Operation not supported") } } else { when(op) { "+" -> { it -> it + second.toInt() } "*" -> { it -> it * second.toInt() } else -> throw Exception("Operation not supported") } } } } fun parseInputFileWithModule() = File("src/main/kotlin/day11/input.txt") .readText() .split(Regex("\r?\n\r?\n")) .fold(emptyList<MonkeyModule>()) { acc, rawMonkey -> val monkeyId = Regex("Monkey ([0-9]+)").find(rawMonkey)!!.groupValues[1].toInt() val items = Regex("[0-9]+").findAll( Regex("Starting items: ([0-9]+,? ?)+").find(rawMonkey)!!.value ).toList().map { IntModule(it.value.toInt()) } val operation = parseOperationWithModule( Regex("Operation: new = [a-z0-9]+ [*+-] [a-z0-9]+").find(rawMonkey)!!.value ) val nextMonkey = parseNextMonkeyWithModule(rawMonkey) acc + MonkeyModule( monkeyId, items, operation, nextMonkey ) } fun findMonkeyBusinessAfterNthRound(rounds: Int): Long { val monkeys = parseInputFileWithModule() val ids = (monkeys.indices) val finalMonkeys = (0 until rounds).fold(monkeys) { m, _ -> ids.fold(m) { acc, id -> val monkey = acc.first { it.id == id } monkey.doATurn(acc) } } val monkeyActivity = finalMonkeys.map { it.monkeyActivity }.sortedDescending() return monkeyActivity[0] * monkeyActivity[1] } fun main() { println("The level of monkey business after 10000 rounds is ${findMonkeyBusinessAfterNthRound(10000)}") }
0
Kotlin
0
0
b5b7ebff71cf55fcc26192628738862b6918c879
4,942
advent-of-code-2022
MIT License
src/main/kotlin/g1701_1800/s1786_number_of_restricted_paths_from_first_to_last_node/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g1701_1800.s1786_number_of_restricted_paths_from_first_to_last_node // #Medium #Dynamic_Programming #Heap_Priority_Queue #Graph #Topological_Sort #Shortest_Path // #2023_06_18_Time_977_ms_(100.00%)_Space_75.1_MB_(100.00%) import java.util.PriorityQueue class Solution { private class Pair(var v: Int, var cwt: Int) : Comparable<Pair> { override fun compareTo(other: Pair): Int { return cwt - other.cwt } } private class Edge(var v: Int, var wt: Int) private lateinit var dtl: IntArray private lateinit var dp: IntArray fun countRestrictedPaths(n: Int, edges: Array<IntArray>): Int { val graph = buildGraph(n, edges) val pq = PriorityQueue<Pair>() val vis = BooleanArray(n + 1) dtl = IntArray(n + 1) pq.add(Pair(n, 0)) while (pq.isNotEmpty()) { val rem = pq.remove() if (vis[rem.v]) { continue } dtl[rem.v] = rem.cwt vis[rem.v] = true for (edge in graph[rem.v]) { if (!vis[edge.v]) { pq.add(Pair(edge.v, rem.cwt + edge.wt)) } } } dp = IntArray(n + 1) return dfs(graph, 1, BooleanArray(n + 1), n) } private fun dfs(graph: List<MutableList<Edge>>, vtx: Int, vis: BooleanArray, n: Int): Int { if (vtx == n) { return 1 } var ans: Long = 0 vis[vtx] = true for (edge in graph[vtx]) { if (!vis[edge.v] && dtl[edge.v] < dtl[vtx]) { val x = dfs(graph, edge.v, vis, n) ans = (ans + x) % M } else if (dtl[edge.v] < dtl[vtx] && vis[edge.v]) { ans = (ans + dp[edge.v]) % M } } dp[vtx] = ans.toInt() return ans.toInt() } private fun buildGraph(n: Int, edges: Array<IntArray>): List<MutableList<Edge>> { val graph: MutableList<MutableList<Edge>> = ArrayList() for (i in 0..n) { graph.add(ArrayList()) } for (edge in edges) { val u = edge[0] val v = edge[1] val wt = edge[2] graph[u].add(Edge(v, wt)) graph[v].add(Edge(u, wt)) } return graph } companion object { private const val M = 1000000007 } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
2,392
LeetCode-in-Kotlin
MIT License
src/day03/Day03.kt
TheJosean
573,113,380
false
{"Kotlin": 20611}
package day03 import readInput fun main() { fun getCharValue(char: Char) = if (char.isLowerCase()) char - 'a' + 1 else char - 'A' + 27 fun part1(input: List<String>) = input.sumOf { val set = HashSet<Char>() it.forEachIndexed { index, c -> if (index < it.length / 2) { set.add(c) } if (index >= it.length / 2 && set.contains(c)) { return@sumOf getCharValue(c) } } return@sumOf 0 } fun part2(input: List<String>) = input.chunked(3) .sumOf { strings -> val map = HashMap<Char, Int>() strings.forEachIndexed { index, s -> s.forEach { if (map.containsKey(it)) { if (index - 1 == map[it]) { map[it] = index } } else { map[it] = 0 -index } } } val char = map.entries.first { it.value + 1 == strings.size }.key return@sumOf getCharValue(char) } // test if implementation meets criteria from the description, like: val testInput = readInput("/day03/Day03_test") check(part1(testInput) == 157) check(part2(testInput) == 70) val input = readInput("/day03/Day03") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
798d5e9b1ce446ba3bac86f70b7888335e1a242b
1,562
advent-of-code
Apache License 2.0
TwoSum.kt
ncschroeder
604,822,497
false
{"Kotlin": 19399}
/* https://leetcode.com/problems/two-sum/ Given an array of integers `nums` and an integer `target`, return indices of the two numbers such that they add up to `target`. You may assume that each input would have exactly one solution, and you may not use the same element twice. You can return the answer in any order. Follow-up: Can you come up with an algorithm that is less than O(n^2) time complexity? Yes */ /* Simple O(n^2) solution I actually got this same challenge in an interview, though there were a couple minor differences. I had to print the pairs instead of returning an int array and there was a possibility of there being multiple solutions. I used the JavaScript equivalent of this solution for that. */ fun twoSum1(nums: IntArray, target: Int): IntArray { for (i in 0 until nums.lastIndex) { val intToFind = target - nums[i] for (j in i + 1..nums.lastIndex) { if (nums[j] == intToFind) { return intArrayOf(i, j) } } } throw Exception("No answer found") } // O(n) solution fun twoSum2(nums: IntArray, target: Int): IntArray { // If the target is even, then it's possible that there are 2 elements in nums that are the same that // add up to the target if (target % 2 == 0) { val halfOfTarget: Int = target / 2 val halfOfTargetIndices: List<Int> = nums.indices.filter { nums[it] == halfOfTarget } if (halfOfTargetIndices.size == 2) { return halfOfTargetIndices.toIntArray() } } /* Unless the elements that sum to the target are the same, there can't be duplicates of elements that are part of the solution because if there were, then there would be more than 1 valid solution. Make a Map where the keys are the elements and the values are the indices of those elements. If there are duplicates, I believe the associate function will map those elements to the last index they were found at, but those elements don't matter. */ val elementsAndIndices: Map<Int, Int> = nums.withIndex().associate { (index, element) -> element to index } for ((index1, element) in nums.withIndex()) { val intToFind = target - element val index2: Int? = elementsAndIndices[intToFind] // If the target is even and target / 2 is an element, then intToFind will be the same as that element // so index2 will be equal to index1 if (index2 != null && element != intToFind) { return intArrayOf(index1, index2) } } throw Exception("No answer found") }
0
Kotlin
0
0
c77d0c8bb0595e61960193fc9b0c7a31952e8e48
2,624
Coding-Challenges
MIT License
src/main/kotlin/day13/Day13.kt
dustinconrad
572,737,903
false
{"Kotlin": 100547}
package day13 import byEmptyLines import readResourceAsBufferedReader fun main() { println("part 1: ${part1(readResourceAsBufferedReader("13_1.txt").readLines())}") println("part 2: ${part2(readResourceAsBufferedReader("13_1.txt").readLines())}") } fun part1(input: List<String>): Int { val pairs = input.byEmptyLines() .map { val (l,r) = it.split("\n") PacketPair(parsePacket(l), parsePacket(r)) } val inOrder = pairs.mapIndexed { index, packetPair -> index + 1 to packetPair.inOrder() } .filter { it.second } return inOrder.sumOf { it.first } } fun part2(input: List<String>): Int { val packets = input.byEmptyLines() .flatMap { val (l,r) = it.split("\n") listOf(parsePacket(l), parsePacket(r)) }.toMutableList() val p1 = PacketList(listOf(PacketInt(2))) val p2 = PacketList(listOf(PacketInt(6))) packets.add(p1) packets.add(p2) packets.sort() val i1 = packets.indexOf(p1) val i2 = packets.indexOf(p2) return (i1 + 1) * (i2 + 1) } sealed class PacketData: Comparable<PacketData> { } object PacketListStart: PacketData() { override fun compareTo(other: PacketData): Int { TODO("Not yet implemented") } } data class PacketList(val data: List<PacketData>): PacketData() { override fun compareTo(other: PacketData): Int { val result = when (other){ is PacketInt -> this.compareTo(PacketList(listOf(other))) is PacketList -> { for (i in 0 until minOf(data.size, other.data.size)) { val l = data[i] val r = other.data[i] val c = l.compareTo(r) if (c != 0) { //println("$this ? $other -> $c") return c } } data.size.compareTo(other.data.size) } else -> throw IllegalArgumentException() } //println("$this ? $other -> $result") return result } } data class PacketInt(val data: Int): PacketData() { override fun compareTo(other: PacketData): Int { val result = when (other) { is PacketInt -> data.compareTo(other.data) is PacketList -> PacketList(listOf(this)).compareTo(other) else -> throw IllegalArgumentException() } //println("$this ? $other -> $result") return result } } fun parsePacket(line: String): PacketList { val stack = ArrayDeque<PacketData>() val chars = StringBuilder() fun processChars() { if (chars.isNotEmpty()) { val n = chars.toString().toInt() chars.clear() stack.add(PacketInt(n)) } } line.forEach { when(it) { '[' -> { stack.add(PacketListStart) processChars() } ']' -> { processChars() val parts = mutableListOf<PacketData>() while (stack.last() != PacketListStart) { parts.add(stack.removeLast()) } stack.removeLast() stack.add(PacketList(parts.asReversed().toList())) } ',' -> processChars() else -> { chars.append(it) } } } return stack.first() as PacketList } data class PacketPair(val left: PacketList, val right: PacketList) { fun inOrder(): Boolean { val result = left <= right // println("$left <= $right: $result") // println() return result } }
0
Kotlin
0
0
1dae6d2790d7605ac3643356b207b36a34ad38be
3,677
aoc-2022
Apache License 2.0
kotlin/src/main/kotlin/year2023/Day15.kt
adrisalas
725,641,735
false
{"Kotlin": 130217, "Python": 1548}
package year2023 fun main() { val input = readInput2("Day15") Day15.part1(input).println() Day15.part2(input).println() } object Day15 { fun part1(input: String): Int { return input .split(",") .sumOf { it.customHash() } } fun part2(input: String): Int { val sequence = input.split(",") val boxes = List(256) { mutableMapOf<String, Int>() } sequence.forEach { line -> val (value, length) = line.split("=", "-") if (line.contains("-")) { boxes[value.customHash()] -= value } else { boxes[value.customHash()][value] = length.toInt() } } return boxes .mapIndexed { boxNumber, box -> val boxPlusOne = (boxNumber + 1) val slotPlusOnePerLength = box.values .mapIndexed { slotNumber, length -> (slotNumber + 1) * length } .sum() boxPlusOne * slotPlusOnePerLength } .sum() } private fun String.customHash(): Int { return this.fold(0) { hash, c -> ((hash + c.code) * 17) % 256 } } }
0
Kotlin
0
2
6733e3a270781ad0d0c383f7996be9f027c56c0e
1,226
advent-of-code
MIT License
src/main/kotlin/day8/Day8.kt
stoerti
726,442,865
false
{"Kotlin": 19680}
package io.github.stoerti.aoc.day8 import io.github.stoerti.aoc.IOUtils import io.github.stoerti.aoc.MathUtils import kotlin.math.ceil import kotlin.math.floor import kotlin.math.sqrt fun main(args: Array<String>) { val lines = IOUtils.readInput("day_8_input") val directions = lines[0] val mapLines = lines.subList(2, lines.size) val map = mapLines.associate { it.substring(0, 3) to Paths(it.substring(7, 10), it.substring(12, 15)) } println("Result1: ${part1(directions, map)}") println("Result2: ${part2(directions, map)}") } fun part1(directions: String, map: Map<String, Paths>) : Long { var currentNode = "AAA" var steps = 0L while (currentNode != "ZZZ") { directions.toCharArray().forEach { if (map[currentNode] == null) println("Node $currentNode does not exist") currentNode = map[currentNode]!!.let { path -> if (it == 'L') path.left else path.right } steps++ } } return steps } fun part2(directions: String, map: Map<String, Paths>) : Long { val allANodes = map.filterKeys { it.endsWith('A') } val allCurrentNodes = allANodes.keys.associateWith { it }.toMutableMap() val allNodeSteps = allANodes.keys.associateWith { 0L }.toMutableMap() allCurrentNodes.keys.forEach { node -> var steps = 0L var currentNode = node while (!currentNode.endsWith('Z')) { directions.toCharArray().forEach { direction -> currentNode = map[currentNode]!!.let { path -> if (direction == 'L') path.left else path.right } steps++ } } allNodeSteps[node] = steps } return MathUtils.getLeastCommonMultiple(allNodeSteps.values) } data class Paths(val left: String, val right: String)
0
Kotlin
0
0
05668206293c4c51138bfa61ac64073de174e1b0
1,683
advent-of-code
Apache License 2.0
src/main/kotlin/com/ginsberg/advent2016/Day04.kt
tginsberg
74,924,040
false
null
/* * Copyright (c) 2016 by <NAME> */ package com.ginsberg.advent2016 import kotlin.comparisons.compareBy /** * Advent of Code - Day 4: December 4, 2016 * * From http://adventofcode.com/2016/day/4 * */ class Day04(rawInput: String) { val rooms = rawInput.split("\n").map(::Room) /** * What is the sum of the sector IDs of the real rooms? */ fun solvePart1(): Int = rooms .filter { it.isValid() } .map { it.accessCode } .sum() /** * What is the sector ID of the room where North Pole objects are stored? */ fun solvePart2(find: String = "northpole object storage"): Int = rooms .filter { it.isValid() } .filter { it.decrypted == find } .first() .accessCode class Room(raw: String) { val name: String = raw.substringBeforeLast('-') val accessCode: Int = raw.substringAfterLast('-').substringBefore('[').toInt() val checksum: String = raw.substringAfter('[').substringBefore(']') val decrypted: String by lazy { decryptName() } // Group by frequency, convert to pairs, sort by count desc, letter asc, join first 5. fun isValid(): Boolean { return name .replace("-", "") .groupBy { it } .mapValues { it.value.size } .toList() .sortedWith(compareBy({ 0 - it.second }, { it.first })) .take(5) .map { it.first } .joinToString(separator = "") == this.checksum } private fun decryptName(): String = name.map { if (it == '-') ' ' else shiftChar(it) }.joinToString(separator = "") private fun shiftChar(c: Char): Char = ((((c - 'a') + this.accessCode) % 26) + 'a'.toInt()).toChar() } }
0
Kotlin
0
3
a486b60e1c0f76242b95dd37b51dfa1d50e6b321
1,885
advent-2016-kotlin
MIT License
leetcode/kotlin/course-schedule-ii.kt
PaiZuZe
629,690,446
false
null
class Solution { fun findOrder(numCourses: Int, prerequisites: Array<IntArray>): IntArray { val toFrom = prerequisitesToToFrom(prerequisites, numCourses) val formatedPrerequisites = formatPrerequisites(prerequisites, numCourses) val path = dfs(toFrom, formatedPrerequisites) return if (path.size == numCourses) { path } else { intArrayOf() } } private fun dfs(toFrom: Array<IntArray>, prerequisites: Array<IntArray>): IntArray { val n = toFrom.size val visited = BooleanArray(n) { false } val frontier = ArrayDeque<Int>() val path = mutableListOf<Int>() prerequisites.forEachIndexed { i, it -> if (it.size == 0) { frontier.add(i) } } while (frontier.isNotEmpty()) { val course = frontier.removeLast() if (visited[course]) { continue } visited[course] = true path.add(course) val validNeighboors = getValidNeighboors(course, toFrom, prerequisites, visited) validNeighboors.forEach { neighboor -> frontier.add(neighboor) } } return path.toIntArray() } private fun getValidNeighboors(course: Int, toFrom: Array<IntArray>, prerequisites: Array<IntArray>, visited: BooleanArray): List<Int> { return toFrom[course] .filter { !visited[it] && prerequisites[it].filter{ preq -> !visited[preq] }.size == 0 } } private fun prerequisitesToToFrom(prerequisites: Array<IntArray>, n: Int): Array<IntArray> { val toFrom = Array<MutableList<Int>>(n) { mutableListOf<Int>() } for (prerequisit in prerequisites) { toFrom[prerequisit[1]].add(prerequisit[0]) } return Array(n) { toFrom[it].toIntArray() } } private fun formatPrerequisites(prerequisites: Array<IntArray>, n: Int): Array<IntArray> { val toFrom = Array<MutableList<Int>>(n) { mutableListOf<Int>() } for (prerequisit in prerequisites) { toFrom[prerequisit[0]].add(prerequisit[1]) } return Array(n) { toFrom[it].toIntArray() } } } fun main() { val sol = Solution() val preqs = arrayOf<IntArray>( intArrayOf(1, 0), intArrayOf(2, 0), intArrayOf(3, 1), intArrayOf(3, 2) ) println(sol.findOrder(4, preqs).joinToString(" ")) }
0
Kotlin
0
0
175a5cd88959a34bcb4703d8dfe4d895e37463f0
2,521
interprep
MIT License
kotlin/2020/qualification-round/indicium/src/main/kotlin/Solution.kt
ShreckYe
345,946,821
false
null
fun main() { val T = readLine()!!.toInt() repeat(T) { t -> val (N, K) = readLine()!!.splitToSequence(' ').map(String::toInt).toList() val answerMatrix = latinMatrices(N).find { it.trace() == K } println("Case #${t + 1}: ${if (answerMatrix == null) "IMPOSSIBLE" else "POSSIBLE\n${answerMatrix}"}") } } class SquareMatrix private constructor(val n: Int, val content: IntArray) { companion object { fun zeroMatrix(n: Int) = SquareMatrix(n, IntArray(n * n)) } operator fun get(i: Int, j: Int): Int = content[n * i + j] fun copyWithChange(i: Int, j: Int, value: Int) = SquareMatrix(n, content.copyOf().apply { this[n * i + j] = value }) override fun toString(): String { val indices = 0 until n return indices.asSequence().map { i -> val ni = n * i indices.map { j -> content[ni + j] }.joinToString(" ") }.joinToString("\n") } } data class MatrixIndex(val i: Int, val j: Int) fun latinMatrices(n: Int): Sequence<SquareMatrix> = latinMatricesFrom(n, SquareMatrix.zeroMatrix(n), 0, 0, (1..n).toList()) fun latinMatricesFrom( n: Int, squareMatrix: SquareMatrix, fromI: Int, fromJ: Int, remainingRowChoices: List<Int> ): Sequence<SquareMatrix> = if (fromI == n) sequenceOf(squareMatrix) else if (fromJ == n) latinMatricesFrom(n, squareMatrix, fromI + 1, 0, (1..n).toList()) else remainingRowChoices.asSequence() .filterNot { value -> (0 until fromI).any { squareMatrix[it, fromJ] == value } } .flatMap { value -> latinMatricesFrom( n, squareMatrix.copyWithChange(fromI, fromJ, value), fromI, fromJ + 1, remainingRowChoices.filter { it != value } ) } fun SquareMatrix.trace() = (0 until n).map { this[it, it] }.sum()
0
Kotlin
1
1
743540a46ec157a6f2ddb4de806a69e5126f10ad
1,843
google-code-jam
MIT License
src/main/kotlin/day04.kt
tobiasae
434,034,540
false
{"Kotlin": 72901}
class Day04 : Solvable("04") { override fun solveA(input: List<String>): String { val (drawnNumbers, boards) = readInput(input) for (i in drawnNumbers) { boards.forEach { val result = it.drawNumber(i) if (result >= 0) { return (result * i).toString() } } } return "nobody wins" } override fun solveB(input: List<String>): String { val (drawnNumbers, boards) = readInput(input) var index = 0 var remainingBoards = boards while (remainingBoards.size > 1) { remainingBoards = remainingBoards.filter { it.drawNumber(drawnNumbers[index]) < 0 } index++ } val lastBoard = remainingBoards.first() for (i in index until drawnNumbers.size) { val result = lastBoard.drawNumber(drawnNumbers[i]) if (result >= 0) { return (result * drawnNumbers[i]).toString() } } return "the last one does not win" } private fun readInput(input: List<String>): Pair<List<Int>, List<Board>> { val drawnNumbers = input.first().split(",").map { it.toInt() } val boards = mutableListOf<Board>() for (b in 2 until input.size step 6) { boards.add(Board(input.subList(b, b + 5))) } return Pair(drawnNumbers, boards) } } class Board { val board: Array<IntArray> val rowCount: IntArray val columnCount: IntArray constructor(lines: List<String>) { board = lines .map { it.trim().split("\\s+".toRegex()).map { it.toInt() }.toIntArray() } .toTypedArray() rowCount = board.map { 0 }.toIntArray() columnCount = board.first().map { 0 }.toIntArray() } fun drawNumber(n: Int): Int { for (i in board.indices) { for (j in board[i].indices) { if (board[i][j] == n) { board[i][j] = -1 rowCount[i]++ columnCount[j]++ } } } return getSolution() } fun getSolution(): Int { if (rowCount.contains(board.size) || columnCount.contains(board.first().size)) { return board.map { it.filter { it > 0 }.sum() }.sum() } return -1 } }
0
Kotlin
0
0
16233aa7c4820db072f35e7b08213d0bd3a5be69
2,435
AdventOfCode
Creative Commons Zero v1.0 Universal
kotlin/src/main/kotlin/AoC_Day24.kt
sviams
115,921,582
false
null
object AoC_Day24 { data class Link(val a: Int, val b: Int) { fun matches(output: Int) : Boolean = a == output || b == output fun opposite(input: Int) : Int = if (a == input) b else a } fun parseInput(input: List<String>) : List<Link> = input.map { line -> val split = line.split("/") Link(split[0].toInt(), split[1].toInt()) } fun findStrongestBridge(output: Int, links: List<Link>, sum: Int) : Int { val matches = links.filter { it.matches(output) } return matches.map { m -> val nextOutput = m.opposite(output) findStrongestBridge(nextOutput,links.minus(m), sum + nextOutput) + output }.max() ?: sum } fun solvePt1(input: List<String>) : Int = findStrongestBridge(0, parseInput(input), 0) fun findLongestBridges(output: Int, links: List<Link>, combo: Pair<Int, Int>) : Pair<Int, Int> { val matches = links.filter { it.matches(output) } val allLongest = matches.map { m -> val nextOutput = m.opposite(output) findLongestBridges(nextOutput,links.minus(m), Pair(combo.first + nextOutput + output, combo.second + 1)) } val maxLength = allLongest.maxBy { it.second }?.second return allLongest.filter { it.second == maxLength }.maxBy { it.first } ?: combo } fun solvePt2(input: List<String>) : Int = findLongestBridges(0, parseInput(input), Pair(0,0)).first }
0
Kotlin
0
0
19a665bb469279b1e7138032a183937993021e36
1,467
aoc17
MIT License
facebook/y2019/round1/c.kt
mikhail-dvorkin
93,438,157
false
{"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408}
package facebook.y2019.round1 private fun solve(): Int { val (n, hei) = readInts() data class Ladder(val id: Int, val x: Int, val yFrom: Int, val yTo: Int) val ladders = List(n) { val (x, yFrom, yTo) = readInts(); Ladder(it, x, yFrom, yTo) } val e = Array(n + 2) { IntArray(n + 2) } val ys = ladders.flatMap { listOf(it.yFrom, it.yTo) }.toSet().sorted() for ((y, yNext) in ys.zipWithNext()) { val idsOrdered = ladders.filter { (it.yFrom <= y) && (y < it.yTo) }.sortedBy { it.x }.map { it.id } for ((i, j) in idsOrdered.zipWithNext()) { e[i][j] += yNext - y e[j][i] += yNext - y } } val inf = n * hei ladders.forEach { if (it.yFrom == 0) { e[n][it.id] = inf } if (it.yTo == hei) { e[it.id][n + 1] = inf } } return edmonsKarp(e, n, n + 1).takeIf { it < inf } ?: -1 } fun edmonsKarp(c: Array<IntArray>, s: Int, t: Int): Int { val n = c.size val f = Array(n) { IntArray(n) } val queue = IntArray(n) val prev = IntArray(n) var res = 0 while (true) { queue[0] = s var low = 0 var high = 1 prev.fill(-1) prev[s] = s while (low < high && prev[t] == -1) { val v = queue[low] low++ for (u in 0 until n) { if (prev[u] != -1 || f[v][u] == c[v][u]) { continue } prev[u] = v queue[high] = u high++ } } if (prev[t] == -1) { break } var flow = Int.MAX_VALUE var u = t while (u != s) { flow = minOf(flow, c[prev[u]][u] - f[prev[u]][u]) u = prev[u] } u = t while (u != s) { f[prev[u]][u] += flow f[u][prev[u]] -= flow u = prev[u] } res += flow } return res } fun main() = repeat(readInt()) { println("Case #${it + 1}: ${solve()}") } private val isOnlineJudge = System.getProperty("ONLINE_JUDGE") == "true" @Suppress("unused") private val stdStreams = (false to false).apply { if (!isOnlineJudge) { if (!first) System.setIn(java.io.File("input.txt").inputStream()) if (!second) System.setOut(java.io.PrintStream("output.txt")) }} private fun readLn() = readLine()!! private fun readInt() = readLn().toInt() private fun readStrings() = readLn().split(" ") private fun readInts() = readStrings().map { it.toInt() }
0
Java
1
9
30953122834fcaee817fe21fb108a374946f8c7c
2,125
competitions
The Unlicense
src/Day03.kt
fdorssers
575,986,737
false
null
fun main() { fun part1(input: List<String>): Int = input .asSequence() .map { it.chunked(it.length / 2) } .map { Pair(it[0].toSet(), it[1].toSet()) } .map { it.first.intersect(it.second) } .map { it.first() } .sumOf { if (it.isUpperCase()) it.code - 38 else it.code - 96 } fun part2(input: List<String>): Int = input .asSequence() .chunked(3) .map { it.map { rs -> rs.toSet() } } .map { it[0].intersect(it[1]).intersect(it[2]) } .map { it.first() } .sumOf { if (it.isUpperCase()) it.code - 38 else it.code - 96 } val testInput = readInputLines("Day03_test") val input = readInputLines("Day03") check(part1(testInput) == 157) println(part1(input)) check(part2(testInput) == 70) println(part2(input)) }
0
Kotlin
0
0
bdd1300b8fd6a1b8bce38aa6851e68d05193c636
833
advent-of-code-kotlin
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/MinScore.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 java.util.LinkedList import java.util.Queue import kotlin.math.min /** * 2492. Minimum Score of a Path Between Two Cities * @see <a href="https://leetcode.com/problems/minimum-score-of-a-path-between-two-cities/">Source</a> */ fun interface MinScore { operator fun invoke(n: Int, roads: Array<IntArray>): Int } class MinScoreBFS : MinScore { override operator fun invoke(n: Int, roads: Array<IntArray>): Int { var ans = Int.MAX_VALUE val gr: MutableList<MutableList<Pair<Int, Int>>> = ArrayList() for (i in 0 until n + 1) { gr.add(ArrayList()) } for (edge in roads) { gr[edge[0]].add(Pair(edge[1], edge[2])) // u-> {v, dis} gr[edge[1]].add(Pair(edge[0], edge[2])) // v-> {u, dis} } val vis = IntArray(n + 1) { 0 } val q: Queue<Int> = LinkedList() q.add(1) vis[1] = 1 while (q.isNotEmpty()) { val node: Int = q.poll() for (pair in gr[node]) { val v: Int = pair.first val dis: Int = pair.second ans = min(ans, dis) if (vis[v] == 0) { vis[v] = 1 q.add(v) } } } return ans } } class MinScoreDFS : MinScore { private var ans = Int.MAX_VALUE override operator fun invoke(n: Int, roads: Array<IntArray>): Int { val adj: MutableList<MutableList<IntArray>> = ArrayList() for (i in 0..n) adj.add(ArrayList()) for (k in roads) { adj[k[0]].add(intArrayOf(k[1], k[2])) adj[k[1]].add(intArrayOf(k[0], k[2])) } val vis = BooleanArray(n + 1) dfs(adj, 1, vis) return ans } private fun dfs(g: List<List<IntArray>>, node: Int, vis: BooleanArray) { vis[node] = true for (k in g[node]) { ans = min(ans, k[1]) if (!vis[k[0]]) { dfs(g, k[0], vis) } } } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
2,676
kotlab
Apache License 2.0
src/main/kotlin/days/Day11.kt
hughjdavey
572,954,098
false
{"Kotlin": 61752}
package days import xyz.hughjd.aocutils.Collections.split class Day11 : Day(11) { override fun partOne(): Any { return play(getMonkeys(), 20).map { it.inspections } .sortedDescending().take(2) .let { it[0] * it[1] } } override fun partTwo(): Any { return play(getMonkeys(), 10000, false).map { it.inspections } .sortedDescending().take(2) .let { it[0].toLong() * it[1] } } fun getMonkeys(): List<Monkey> { return inputList.split("").mapIndexed { index, it -> val (op, n) = Regex("old ([+|*]) (\\d+|old)").find(it[2].trim().replace("Operation: ", ""))!!.destructured val test = it[3].split(" ").last().toLong() val onTrue = it[4].split(" ").last().toInt() val onFalse = it[5].split(" ").last().toInt() Monkey(index, ArrayDeque(getItems(it[1])), op to n, test, onTrue, onFalse) } } fun play(monkeys: List<Monkey>, rounds: Int, reliefOn: Boolean = true): List<Monkey> { (0 until rounds).forEach { round(monkeys, reliefOn) } return monkeys } fun round(monkeys: List<Monkey>, reliefOn: Boolean = true): List<Monkey> { monkeys.forEach { monkey -> turn(monkey, monkeys, reliefOn) } return monkeys } private fun turn(monkey: Monkey, monkeys: List<Monkey>, reliefOn: Boolean) { for (i in monkey.items.indices) { var worryLevel = monkey.items.removeFirst() worryLevel = monkey.operation(worryLevel) if (reliefOn) { worryLevel /= 3 } else { worryLevel %= monkeys.map { it.divisor }.fold(1L) { acc, elem -> acc * elem } } val nextMonkeyIndex = monkey.test(worryLevel) val nextMonkey = monkeys.find { it.index == nextMonkeyIndex }!! nextMonkey.items.addLast(worryLevel) } } private fun getItems(str: String): List<Long> { return Regex("\\d+").findAll(str.trim().replace("Starting items: ", "")) .map { it.value.toLong() }.toList() } data class Monkey(val index: Int, val items: ArrayDeque<Long>, val operation: Pair<String, String>, val divisor: Long, val onTrue: Int, val onFalse: Int) { var inspections = 0 fun operation(old: Long): Long { inspections++ val (op, n) = operation val num = if (n == "old") old else n.toLong() return if (op == "+") old + num else old * num } fun test(item: Long): Int { return if (item % divisor == 0L) onTrue else onFalse } } }
0
Kotlin
0
2
65014f2872e5eb84a15df8e80284e43795e4c700
2,674
aoc-2022
Creative Commons Zero v1.0 Universal
src/Day14.kt
jimmymorales
572,156,554
false
{"Kotlin": 33914}
fun main() { fun List<String>.parseCave(): MutableSet<Pair<Int, Int>> = map { line -> line.split(" -> ") .map { path -> path.split(",").let { (x, y) -> x.toInt() to y.toInt() } } .zipWithNext { (x1, y1), (x2, y2) -> if (y1 == y2) { val range = if (x1 < x2) x1..x2 else x2..x1 range.map { it to y1 } } else { val range = if (y1 < y2) y1..y2 else y2..y1 range.map { x1 to it } } } .flatten() }.flatten().toMutableSet() fun MutableSet<Pair<Int, Int>>.sandEmulation( caveLowerLimit: Int, onRest: MutableSet<Pair<Int, Int>>.(Pair<Int, Int>, () -> Unit) -> SandLoop, onEndReached: MutableSet<Pair<Int, Int>>.(Pair<Int, Int>, () -> Unit) -> SandLoop, ): Int { var sand = 0 timeUnit@ while (true) { var sandX = 500 var sandY = 0 while (sandY < caveLowerLimit) { if (sandX to sandY + 1 !in this) { sandY++ } else if (sandX - 1 to sandY + 1 !in this) { sandY++ sandX-- } else if (sandX + 1 to sandY + 1 !in this) { sandY++ sandX++ } else { // rest when (onRest(sandX to sandY) { sand++ }) { SandLoop.Finish -> break@timeUnit SandLoop.NextSand -> continue@timeUnit SandLoop.EndSand -> break SandLoop.None -> Unit } } } when (onEndReached(sandX to sandY) { sand++ }) { SandLoop.Finish -> break SandLoop.EndSand, SandLoop.NextSand, SandLoop.None -> Unit } } return sand } fun part1(input: List<String>): Int { val cave = input.parseCave() val caveLowerLimit = cave.maxOf(Pair<Int, Int>::second) return cave.sandEmulation( caveLowerLimit, onRest = { (x, y), operator -> operator() this.add(x to y) SandLoop.NextSand }, onEndReached = { _, _ -> SandLoop.Finish }, ) } fun part2(input: List<String>): Int { val cave = input.parseCave() val caveLowerLimit = cave.maxOf(Pair<Int, Int>::second) + 1 return cave.sandEmulation( caveLowerLimit, onRest = { (x, y), operator -> if (x == 500 && y == 0) { operator() SandLoop.Finish } else { SandLoop.EndSand } }, onEndReached = { (x, y), operator -> operator() this.add(x to y) SandLoop.None }, ) } // test if implementation meets criteria from the description, like: val testInput = readInput("Day14_test") check(part1(testInput) == 24) val input = readInput("Day14") println(part1(input)) // part 2 check(part2(testInput) == 93) println(part2(input)) } private enum class SandLoop { Finish, NextSand, EndSand, None }
0
Kotlin
0
0
fb72806e163055c2a562702d10a19028cab43188
3,408
advent-of-code-2022
Apache License 2.0
src/main/kotlin/com/leonra/adventofcode/advent2023/day07/Day7.kt
LeonRa
726,688,446
false
{"Kotlin": 30456}
package com.leonra.adventofcode.advent2023.day07 import com.leonra.adventofcode.shared.readResource /** https://adventofcode.com/2023/day/7 */ private object Day7 { data class Game(val hand: String, val bid: Int) fun partOne(): Int { class CardComparator: Comparator<Char> { val valueMap = mapOf( 'A' to 13, 'K' to 12, 'Q' to 11, 'J' to 10, 'T' to 9, '9' to 8, '8' to 7, '7' to 6, '6' to 5, '5' to 4, '4' to 3, '3' to 2, '2' to 1, ) override fun compare(card1: Char, card2: Char): Int = checkNotNull(valueMap[card1]).compareTo(checkNotNull(valueMap[card2])) } class HandComparator: Comparator<String> { val cardComparator = CardComparator() override fun compare(hand1: String, hand2: String): Int { val hand1Type = hand1.type val hand2Type = hand2.type if (hand1Type == hand2Type) { for (index in hand1.indices) { val cardCompare = cardComparator.compare(hand1[index], hand2[index]) if (cardCompare == 0) { continue } return cardCompare } return 0 } return hand1Type - hand2Type } val String.type: Int get() { val cards = mutableMapOf<Char, Int>() for (card in this) { cards[card] = (cards[card] ?: 0) + 1 } val duplicates = cards.maxOf { it.value } val uniques = cards.size return when { duplicates == 5 -> FIVE_OF_A_KIND duplicates == 4 -> FOUR_OF_A_KIND duplicates == 3 && uniques == 2 -> FULL_HOUSE duplicates == 3 && uniques == 3 -> THREE_OF_A_KIND duplicates == 2 && uniques == 3 -> TWO_PAIR duplicates == 2 && uniques == 4 -> ONE_PAIR else -> HIGH_CARD } } } val games = mutableListOf<Game>() readResource("/2023/day07/part1.txt") { line -> val split = line.split(" ") games.add(Game(hand = split[0], bid = split[1].toInt())) } val handComparator = HandComparator() games.sortWith { game1, game2 -> handComparator.compare(game1.hand, game2.hand) } var winnings = 0 games.forEachIndexed { index, game -> winnings += (index + 1) * game.bid } return winnings } fun partTwo(): Int { class CardComparator: Comparator<Char> { val valueMap = mapOf( 'A' to 13, 'K' to 12, 'Q' to 11, 'T' to 10, '9' to 9, '8' to 8, '7' to 7, '6' to 6, '5' to 5, '4' to 4, '3' to 3, '2' to 2, 'J' to 1, ) override fun compare(card1: Char, card2: Char): Int = checkNotNull(valueMap[card1]).compareTo(checkNotNull(valueMap[card2])) } class HandComparator: Comparator<String> { val cardComparator = CardComparator() override fun compare(hand1: String, hand2: String): Int { val hand1Type = hand1.strongestType val hand2Type = hand2.strongestType if (hand1Type == hand2Type) { for (index in hand1.indices) { val cardCompare = cardComparator.compare(hand1[index], hand2[index]) if (cardCompare == 0) { continue } return cardCompare } return 0 } return hand1Type - hand2Type } private val String.strongestType: Int get() { val cards = mutableMapOf<Char, Int>() for (card in this) { cards[card] = (cards[card] ?: 0) + 1 } val jacks = cards.remove('J') ?: 0 val duplicates = cards.maxOfOrNull { it.value } ?: 0 val uniques = cards.size return when { duplicates + jacks == 5 -> FIVE_OF_A_KIND duplicates + jacks == 4 -> FOUR_OF_A_KIND duplicates == 3 && uniques == 2 && jacks == 0 -> FULL_HOUSE duplicates == 2 && uniques == 2 && jacks == 1 -> FULL_HOUSE duplicates == 3 && uniques == 3 && jacks == 0 -> THREE_OF_A_KIND duplicates == 2 && uniques == 3 && jacks == 1 -> THREE_OF_A_KIND duplicates == 1 && uniques == 3 && jacks == 2 -> THREE_OF_A_KIND duplicates == 2 && uniques == 3 && jacks == 0 -> TWO_PAIR duplicates == 2 && uniques == 4 && jacks == 0 -> ONE_PAIR duplicates == 1 && uniques == 4 && jacks == 1 -> ONE_PAIR else -> HIGH_CARD } } } val games = mutableListOf<Game>() readResource("/2023/day07/part1.txt") { line -> val split = line.split(" ") games.add(Game(hand = split[0], bid = split[1].toInt())) } val handComparator = HandComparator() games.sortWith { game1, game2 -> handComparator.compare(game1.hand, game2.hand) } var winnings = 0 games.forEachIndexed { index, game -> winnings += (index + 1) * game.bid } return winnings } private const val FIVE_OF_A_KIND = 6 private const val FOUR_OF_A_KIND = 5 private const val FULL_HOUSE = 4 private const val THREE_OF_A_KIND = 3 private const val TWO_PAIR = 2 private const val ONE_PAIR = 1 private const val HIGH_CARD = 0 } private fun main() { println("Part 1 winnings: ${Day7.partOne()}") println("Part 2 winnings: ${Day7.partTwo()}") }
0
Kotlin
0
0
46bdb5d54abf834b244ba9657d0d4c81a2d92487
6,627
AdventOfCode
Apache License 2.0
src/main/aoc2015/Day13.kt
nibarius
154,152,607
false
{"Kotlin": 963896}
package aoc2015 import com.marcinmoskala.math.permutations class Day13(input: List<String>) { private val parsedInput = parseInput(input) private val persons = parsedInput.map { it.key.first }.distinct().toSet() private fun parseInput(input: List<String>): Map<Pair<String, String>, Int> { return input.associate { val parts = it.split(" ") val who = parts.first() val other = parts.last().dropLast(1) val gain = if (parts[2] == "gain") 1 else -1 val amount = gain * parts[3].toInt() Pair(who, other) to amount } } private fun totalHappiness(order: List<String>): Int { var sum = 0 for (i in order.indices) { val prev = order[(i - 1 + order.size) % order.size] val self = order[i] val next = order[(i + 1) % order.size] sum += parsedInput.getOrDefault(Pair(self, prev), 0) + parsedInput.getOrDefault(Pair(self, next), 0) } return sum } private fun happinessOfBestSeatingOrder(persons: Set<String>): Int { return persons.permutations() // all permutations contains a lot of duplicate seating orders since // the seating is cyclic and it doesn't matter where at the table you sit. // Remove a bunch of duplicates (but far from all) by only looking at the // ones where one given person is is first. .filter { it.first() == persons.first() } .maxOf { totalHappiness(it) } // A much better approach would be to implement Sawada's algorithm for generating // all unique necklaces (seating orders). But since this solution runs in less than // a second for both parts, this is good enough. // https://byorgey.wordpress.com/2010/03/12/math-combinatorics-multiset-and-sawadas-algorithm/ } fun solvePart1(): Int { return happinessOfBestSeatingOrder(persons) } fun solvePart2(): Int { val withMe = persons.toMutableSet().apply { add("me") } return happinessOfBestSeatingOrder(withMe) } }
0
Kotlin
0
6
f2ca41fba7f7ccf4e37a7a9f2283b74e67db9f22
2,182
aoc
MIT License
src/main/kotlin/twentytwentytwo/Day12.kt
JanGroot
317,476,637
false
{"Kotlin": 80906}
package twentytwentytwo import twentytwentytwo.Structures.Point2d typealias Land = Point2d fun main() { val input = {}.javaClass.getResource("input-12.txt")!!.readText().linesFiltered { it.isNotEmpty() }; val day = Day12(input) println(day.part1()) println(day.part2()) // } class Day12(private val input: List<String>) { private val land = input.mapIndexed { y, row -> row.mapIndexed { x, s -> Point2d(x, y, s) } }.flatten() fun part1(): Int { val start = land.filter { it.value == 'S' }.map{ Point2d(it.x, it.y, 'a')}.first() return land.bfs(start) } fun part2() = land.filter { it.value == 'a' }.minOfOrNull { land.bfs(it) } fun List<Land>.bfs(start: Point2d): Int { val queue = Structures.ArrayListQueue<Pair<Point2d, Int>>() queue.enqueue(Pair(start, 1)) val visited = hashSetOf<Point2d>() visited.add(start) while (!queue.isEmpty) { val (node, index) = queue.dequeue()!! fun search(point: Point2d) = land.firstOrNull { it.x == point.x && it.y == point.y } node.neighbors().mapNotNull { search(it) }.forEach { neighbour -> val nv = if (neighbour.value == 'E') 'z' else neighbour.value if (node.value == 'S' || (nv <= node.value + 1) && visited.add(neighbour)) { if (neighbour.value == 'E') return index queue.enqueue(Pair(neighbour, index + 1)) } } } return Int.MAX_VALUE } }
0
Kotlin
0
0
04a9531285e22cc81e6478dc89708bcf6407910b
1,560
aoc202xkotlin
The Unlicense
src/Day07.kt
mborromeo
571,999,097
false
{"Kotlin": 10600}
fun main() { class File(val size: Int) class Directory(val name: String) { private val directories: MutableList<Directory> = mutableListOf() private val files: MutableList<File> = mutableListOf() fun size(): Int = files.sumOf { it.size } + directories.sumOf { it.size() } fun addDirectory(directoryName: String, path: List<String>) = getDirectoryAtPath(path).addDirectory(Directory(directoryName)) fun addFile(file: File, path: List<String>) = getDirectoryAtPath(path).addFile(file) fun directoriesFlattened(): Set<Directory> = setOf(this) + directories + directories.flatMap { it.directoriesFlattened() } private fun addDirectory(directory: Directory) = directories.add(directory) private fun addFile(file: File) = files.add(file) private fun getDirectoryAtPath(path: List<String>) = path.fold(this) { acc, str -> acc.directories.first { it.name == str } } } fun fileSystem(input: List<String>): Directory { val fs = Directory("/") val cp: MutableList<String> = mutableListOf() input.drop(1).map { when { it.any { c -> c.isDigit() } -> { fs.addFile(File(it.split(" ").first().toInt()), cp) } it.contains("dir") -> { fs.addDirectory(it.substring(4), cp) } it.contains("cd") && it.contains("..") -> { cp.removeLast() } it.contains("cd") && !it.contains("..") -> { cp.add(it.substring(5)) } else -> {} } } return fs } fun part1(input: List<String>): Int = fileSystem(input).directoriesFlattened().map { it.size() }.filter { it <= 100000 }.sum() fun part2(input: List<String>): Int { val toBeRemoved = fileSystem(input).directoriesFlattened().map{ it.size() }.max() - 40000000 return fileSystem(input).directoriesFlattened().map { it.size() }.filter { it >= toBeRemoved }.minBy { it } } val input = readInput("Day07_input") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
d01860ecaff005aaf8e1e4ba3777a325a84c557c
2,088
advent-of-code-kotlin-2022
Apache License 2.0
src/main/kotlin/year2022/day19/Problem.kt
Ddxcv98
573,823,241
false
{"Kotlin": 154634}
package year2022.day19 import IProblem import java.util.regex.Pattern import kotlin.math.max import kotlin.math.min class Problem : IProblem { private val blueprints = mutableListOf<Array<IntArray>>() init { val pattern = Pattern.compile("\\d+") javaClass .getResourceAsStream("/2022/19.txt")!! .bufferedReader() .forEachLine { line -> val matches = pattern .matcher(line) .results() .map { it.group().toInt() } .toList() blueprints.add( arrayOf( intArrayOf(matches[1], 0, 0, 0), intArrayOf(matches[2], 0, 0, 0), intArrayOf(matches[3], matches[4], 0, 0), intArrayOf(matches[5], 0, matches[6], 0) ) ) } } private fun geodes(best: Int, blueprint: Array<IntArray>, robots: IntArray, money: IntArray, time: Int): Int { if (time == 0) { return max(best, money[GEODE]) } if (money[GEODE] + time * robots[GEODE] + time * (time - 1) / 2 <= best) { return best } var n = max(best, money[GEODE] + time * robots[GEODE]) for (i in 0 until SIZE) { val cost = blueprint[i] if ((0 until SIZE).any { cost[it] != 0 && robots[it] == 0 }) { continue } val mins = (0 until SIZE).maxOf { if (money[it] >= cost[it]) { 1 } else { (cost[it] - money[it] + 2 * robots[it] - 1) / robots[it] } } if (time < mins) { continue } val updatedRobots = robots.copyOf() val updatedMoney = IntArray(SIZE) { money[it] + mins * robots[it] - cost[it] } updatedRobots[i]++ n = geodes(n, blueprint, updatedRobots, updatedMoney, time - mins) } return n } override fun part1(): Int { val robots = intArrayOf(1, 0, 0, 0) val money = intArrayOf(0, 0, 0, 0) return blueprints .indices .sumOf { (it + 1) * geodes(0, blueprints[it], robots, money, 24) } } override fun part2(): Int { val robots = intArrayOf(1, 0, 0, 0) val money = intArrayOf(0, 0, 0, 0) return (0 until min(3, blueprints.size)) .fold(1) { acc, i -> acc * geodes(0, blueprints[i], robots, money, 32) } } }
0
Kotlin
0
0
455bc8a69527c6c2f20362945b73bdee496ace41
2,630
advent-of-code
The Unlicense
src/main/kotlin/mat/ShortestPath.kt
yx-z
106,589,674
false
null
package mat import util.* import java.lang.Math.abs import java.util.* import kotlin.collections.HashMap import kotlin.collections.HashSet // given a grid G[1..n, 1..n], where G[i, j] = 1 represents an obstacle and 0 // o/w, and a starting point s = (u, v), and finally an ending point t = (p, q) // find the shortest path from s to t, i.e. w/ min # of cells in the path // you may assume that inputs are valid and such path exists // A* search algorithm // for more shortest path algorithms used in a graph with traditional G = (V, E) // representation, please see src/graph/core/ShortestPath*.kt) fun OneArray<OneArray<Int>>.aStar(start: Tuple2<Int, Int>, goal: Tuple2<Int, Int>): List<Tuple2<Int, Int>> { val path = ArrayList<Tuple2<Int, Int>>() val f = HashMap<Tuple2<Int, Int>, Int>() val g = HashMap<Tuple2<Int, Int>, Int>() val parent = HashMap<Tuple2<Int, Int>, Tuple2<Int, Int>?>() val closed = HashSet<Tuple2<Int, Int>>() indices.forEach { i -> indices.forEach { j -> f[i tu j] = INF g[i tu j] = INF parent[i tu j] = null } } g[start] = 0 f[start] = g[start]!! + heuristic(start, goal) val open = PriorityQueue<Tuple2<Int, Int>>(Comparator { c1, c2 -> f[c1]!! - f[c2]!! }) open.add(start) trav@ while (open.isNotEmpty()) { val curr = open.remove() val (i, j) = curr if (curr == goal) { break@trav } closed.add(curr) val neighbors = HashSet<Tuple2<Int, Int>>() // finding neighbors in all eight directions (-1..1).forEach { deltaX -> (-1..1).forEach { deltaY -> if (deltaX != 0 || deltaY != 0) { // ensuring != curr val neighbor = i + deltaX tu j + deltaY if (isValid(neighbor)) { neighbors.add(neighbor) } } } } neighbor@ for (neighbor in neighbors) { if (closed.contains(neighbor)) { continue@neighbor } if (!open.contains(neighbor)) { open.add(neighbor) } // here the idea is basically the same as finding a tense edge and // relax if necessary in dijkstra's algorithm val tmpG = g[curr]!! + dist(curr, neighbor) if (tmpG >= g[neighbor]!!) { continue@neighbor } parent[neighbor] = curr g[neighbor] = tmpG f[neighbor] = g[neighbor]!! + heuristic(neighbor, goal) } } // reconstruct path from parent map var c: Tuple2<Int, Int>? = goal while (c != null) { path.add(0, c) c = parent[c] } return path } private fun OneArray<OneArray<Int>>.isValid(curr: Tuple2<Int, Int>): Boolean { val (i, j) = curr return i in indices && j in indices && this[i, j] == 0 } private fun dist(curr: Tuple2<Int, Int>, neighbor: Tuple2<Int, Int>): Int { val (i, j) = curr val (p, q) = neighbor return abs(i - j) + abs(p - q) // counting the manhattan distance } // heuristic function based on manhattan distance private fun heuristic(curr: Tuple2<Int, Int>, goal: Tuple2<Int, Int>): Int { val (i, j) = curr val (p, q) = goal return (p - i) + (q - j) } fun main(args: Array<String>) { val G = oneArrayOf( oneArrayOf(0, 0, 1, 0), oneArrayOf(0, 0, 1, 0), oneArrayOf(0, 1, 1, 0), oneArrayOf(0, 0, 0, 1)) println(G.aStar(1 tu 1, 1 tu 4)) }
0
Kotlin
0
1
15494d3dba5e5aa825ffa760107d60c297fb5206
3,103
AlgoKt
MIT License
src/main/kotlin/com/ginsberg/advent2023/Day23.kt
tginsberg
723,688,654
false
{"Kotlin": 112398}
/* * Copyright (c) 2023 by <NAME> */ /** * Advent of Code 2023, Day 23 - A Long Walk * Problem Description: http://adventofcode.com/2023/day/23 * Blog Post/Commentary: https://todd.ginsberg.com/post/advent-of-code/2023/day23/ */ package com.ginsberg.advent2023 import kotlin.math.max class Day23(input: List<String>) { private val grid = input.map { it.toCharArray() }.toTypedArray() private val start = Point2D(input.first().indexOfFirst { it == '.' }, 0) private val goal = Point2D(input.last().indexOfFirst { it == '.' }, input.lastIndex) fun solvePart1(): Int = traverse { location -> location.cardinalNeighbors() .filter { grid.isSafe(it) } .filter { newLocation -> grid[newLocation].matchesDirection(newLocation - location) } .map { it to 1 } } fun solvePart2(): Int { val reducedGrid = reduceGrid() return traverse { location -> reducedGrid .getValue(location) .map { it.key to it.value } } } private fun Char.matchesDirection(direction: Point2D): Boolean = when (this) { '^' -> Point2D.NORTH == direction '<' -> Point2D.WEST == direction 'v' -> Point2D.SOUTH == direction '>' -> Point2D.EAST == direction '.' -> true else -> false } private fun traverse(nextLocations: (Point2D) -> List<Pair<Point2D, Int>>): Int { var best = 0 val visited = mutableSetOf<Point2D>() fun traverseWork(location: Point2D, steps: Int):Int { if (location == goal) { best = max(steps, best) return best } visited += location nextLocations(location) .filter { (place, _) -> place !in visited } .forEach { (place, distance) -> traverseWork(place, distance + steps) } visited -= location return best } return traverseWork(start, 0) } private fun reduceGrid(): Map<Point2D, Map<Point2D, Int>> = grid.findDecisionPoints().let { decisionPoints -> decisionPoints.associateWith { point -> reduceGridFromPoint(point, decisionPoints) } } private fun reduceGridFromPoint(from: Point2D, toAnyOther: Set<Point2D>): Map<Point2D, Int> { val queue = ArrayDeque<Pair<Point2D, Int>>().apply { add(from to 0) } val seen = mutableSetOf(from) val answer = mutableMapOf<Point2D, Int>() while (queue.isNotEmpty()) { val (location, distance) = queue.removeFirst() if (location != from && location in toAnyOther) { answer[location] = distance } else { location.cardinalNeighbors() .filter { grid.isSafe(it) } .filter { grid[it] != '#' } .filter { it !in seen } .forEach { seen += it queue.add(it to distance + 1) } } } return answer } private fun Array<CharArray>.findDecisionPoints() = buildSet { add(start) add(goal) this@findDecisionPoints.forEachIndexed { y, row -> row.forEachIndexed { x, c -> if (c != '#') { Point2D(x, y).apply { if (cardinalNeighbors() .filter { grid.isSafe(it) } .filter { grid[it] != '#' }.size > 2 ) { add(this) } } } } } } }
0
Kotlin
0
12
0d5732508025a7e340366594c879b99fe6e7cbf0
3,847
advent-2023-kotlin
Apache License 2.0
src/main/kotlin/week2/TreeHouse.kt
waikontse
572,850,856
false
{"Kotlin": 63258}
package week2 import shared.Puzzle import shared.ReadUtils.Companion.toIntList import shared.ReadUtils.Companion.transpose typealias Pos = Pair<Int, Int> class Trees(val treesMap: List<List<Int>>) { val maxX: Int = treesMap[0].size val maxY: Int = treesMap.size val transposed: List<List<Int>> = treesMap.transpose() } class TreeHouse : Puzzle(8) { override fun solveFirstPart(): Any { val intTreesMap = Trees(puzzleInput.map { it.toIntList() }) val corners = (2 * intTreesMap.maxX + 2 * intTreesMap.maxY - 4) return countVisibleTrees(intTreesMap) + corners } override fun solveSecondPart(): Any { val trees = Trees(puzzleInput.map { it.toIntList() }) return countScenicScore(trees, 1 to 1, listOf()) .max() } private fun countVisibleTrees(trees: Trees): Int { return countVisibleTreeLR(trees, 1 to 1, 0) } private tailrec fun countVisibleTreeLR(trees: Trees, pos: Pos, acc: Int): Int { if (pos.first == 1 && pos.second >= trees.maxY - 1) { return acc } val canSee = if (isTreeVisible(trees, pos)) 1 else 0 return countVisibleTreeLR(trees, pos.inc(trees), acc.plus(canSee)) } private fun Pos.inc(trees: Trees): Pos { return if (this.first >= trees.maxX - 2) { this.copy(first = 1, second = this.second.inc()) } else { this.copy(first = this.first.inc()) } } private fun isTreeVisible(trees: Trees, pos: Pos): Boolean { return canSeeTreeFromLeft(trees, pos) || canSeeTreeFromRight(trees, pos) || canSeeTreeFromTop(trees, pos) || canSeeTreeFromBottom(trees, pos) } private fun canSeeTreeFromLeft(trees: Trees, pos: Pos) = canSeeTree(trees.treesMap[pos.second], pos.first) private fun canSeeTreeFromRight(trees: Trees, pos: Pos) = canSeeTree(trees.treesMap[pos.second].reversed(), trees.maxX - 1 - pos.first) private fun canSeeTreeFromTop(trees: Trees, pos: Pos) = canSeeTree(trees.transposed[pos.first], pos.second) private fun canSeeTreeFromBottom(trees: Trees, pos: Pos) = canSeeTree(trees.transposed[pos.first].reversed(), trees.maxX - 1 - pos.second) private fun canSeeTree(trees: List<Int>, pos: Int): Boolean { if (pos == 0) { return true } // Check if largest number before val target = trees[pos] val before = trees.take(pos) // Check if target is the largest up till that point val isLargest = before.max() < target // Check if unique number before return isLargest && !before.contains(target) } private tailrec fun countScenicScore(trees: Trees, pos: Pos, acc: List<Int>): List<Int> { if (pos.first == 1 && pos.second >= trees.maxY - 1) { return acc } val scenicScore: Int = scenicScore(trees, pos) return countScenicScore(trees, pos.inc(trees), acc.plus(scenicScore)) } private fun scenicScore(trees: Trees, pos: Pos): Int { return countScenicScoreLeft(trees.treesMap[pos.second], pos.first, pos.first.dec(), 0) * countScenicScoreRight(trees.treesMap[pos.second], pos.first, pos.first.inc(), 0) * countScenicScoreTop(trees.transposed[pos.first], pos.second, pos.second.dec(), 0) * countScenicScoreBottom(trees.transposed[pos.first], pos.second, pos.second.inc(), 0) } private fun treeIsSmaller(trees: List<Int>, from: Int, to: Int) = trees[from] <= trees[to] private tailrec fun countScenicScoreLeft(trees: List<Int>, from: Int, to: Int, acc: Int): Int { if (to == -1) { return acc } else if (treeIsSmaller(trees, from, to)) { return acc.inc() } return countScenicScoreLeft(trees, from, to.dec(), acc.inc()) } private tailrec fun countScenicScoreRight(trees: List<Int>, from: Int, to: Int, acc: Int): Int { if (to == trees.size) { return acc } else if (treeIsSmaller(trees, from, to)) { return acc.inc() } return countScenicScoreRight(trees, from, to.inc(), acc.inc()) } private fun countScenicScoreTop(trees: List<Int>, from: Int, to: Int, acc: Int) = countScenicScoreLeft(trees, from, to, acc) private fun countScenicScoreBottom(trees: List<Int>, from: Int, to: Int, acc: Int) = countScenicScoreRight(trees, from, to, acc) }
0
Kotlin
0
0
860792f79b59aedda19fb0360f9ce05a076b61fe
4,545
aoc-2022-in-kotllin
Creative Commons Zero v1.0 Universal
src/chapter3/section2/ex7.kt
w1374720640
265,536,015
false
{"Kotlin": 1373556}
package chapter3.section2 import chapter3.section1.testOrderedST /** * 为二叉查找树添加一个方法avgCompares()来计算一颗给定的树中的一次随机命中查找平均所需要的比较次数 * (即树的各结点路径长度之和除以树的大小再加1) * 实现两种方案:一种使用递归(用时为线性级别,所需空间和树高成正比) * 一种模仿size()在每个结点中添加一个变量(所需空间为线性级别,查询耗时为常数) */ fun <K : Comparable<K>, V : Any> BinarySearchTree<K, V>.avgCompares(): Int { if (isEmpty()) return 0 return compares(root!!) / size() + 1 } fun <K : Comparable<K>, V : Any> BinarySearchTree<K, V>.avgComparesDouble(): Double { if (isEmpty()) return 0.0 return compares(root!!) / size().toDouble() + 1 } private fun <K : Comparable<K>, V : Any> compares(node: BinarySearchTree.Node<K, V>): Int { var leftCompares = 0 if (node.left != null) { leftCompares = compares(node.left!!) } var rightCompares = 0 if (node.right != null) { rightCompares = compares(node.right!!) } return leftCompares + rightCompares + node.count - 1 } class BinarySearchTreeCompares<K : Comparable<K>, V : Any> : BinarySearchTree<K, V>() { class ComparesNode<K : Comparable<K>, V : Any>(key: K, value: V, left: Node<K, V>? = null, right: Node<K, V>? = null, count: Int = 1, var compare: Int = 0) : Node<K, V>(key, value, left, right, count) override fun put(key: K, value: V) { if (root == null) { //将父类默认的Node替换为HeightNode root = ComparesNode(key, value) } else { put(root!!, key, value) } } override fun put(node: Node<K, V>, key: K, value: V) { when { node.key > key -> { if (node.left == null) { node.left = ComparesNode(key, value) } else { put(node.left!!, key, value) } } node.key < key -> { if (node.right == null) { node.right = ComparesNode(key, value) } else { put(node.right!!, key, value) } } else -> node.value = value } node.count = size(node.left) + size(node.right) + 1 if (node is ComparesNode) { calculateCompare(node) } } fun avgCompares(): Int { if (isEmpty()) return 0 return compare(root) / size() + 1 } private fun compare(node: Node<K, V>?): Int { return if (node is ComparesNode) { node.compare } else 0 } private fun calculateCompare(node: ComparesNode<K, V>) { node.compare = compare(node.left) + compare(node.right) + node.count - 1 } override fun deleteMin(node: Node<K, V>): Node<K, V>? { val result = super.deleteMin(node) if (result is ComparesNode) { calculateCompare(result) } return result } override fun deleteMax(node: Node<K, V>): Node<K, V>? { val result = super.deleteMax(node) if (result is ComparesNode) { calculateCompare(result) } return result } override fun delete(node: Node<K, V>, key: K): Node<K, V>? { val result = super.delete(node, key) if (result is ComparesNode) { calculateCompare(result) } return result } } fun main() { testOrderedST(BinarySearchTreeCompares()) val checkArray = arrayOf( arrayOf(2, 1, 3) to 1, arrayOf(1, 2, 3) to 2, arrayOf(5, 2, 7, 1, 3, 4, 6, 8, 9, 10) to 3 ) checkArray.forEach { pair -> val st1 = BinarySearchTree<Int, Int>() val st2 = BinarySearchTreeCompares<Int, Int>() pair.first.forEach { st1.put(it, 0) st2.put(it, 0) } check(st1.avgCompares() == pair.second) check(st2.avgCompares() == pair.second) } println("check succeed.") }
0
Kotlin
1
6
879885b82ef51d58efe578c9391f04bc54c2531d
4,368
Algorithms-4th-Edition-in-Kotlin
MIT License
src/Day08.kt
bananer
434,885,332
false
{"Kotlin": 36979}
fun main() { /* digit abcdefg num num-unique 0 xxx xxx 6 1 x x 2 x 2 x xxx x 5 3 x xx xx 5 4 xxx x 4 x 5 xx x xx 5 6 xx xxxx 6 7 x x x 3 x 8 xxxxxxx 7 x 9 xxxx xx 6 */ fun parseInput(input: List<String>): List<Pair<List<String>, List<String>>> { return input.map { line -> val (signalPatterns, outputValue) = line.split("|").map { it.trim().split(" ") } Pair(signalPatterns, outputValue) } } fun part1(input: List<String>): Int { val uniqueSegmentNumbers = setOf(2, 4, 3, 7) return parseInput(input).sumOf { line -> line.second.count { uniqueSegmentNumbers.contains(it.length) } } } fun part2(input: List<String>): Int { return input.size } // test if implementation meets criteria from the description, like: val testInput = readInput("Day08_test") val testOutput1 = part1(testInput) println("test output1: $testOutput1") check(testOutput1 == 26) val testOutput2 = part2(testInput) println("test output2: $testOutput2") //check(testOutput2 == -1) val input = readInput("Day08") println("output part1: ${part1(input)}") println("output part2: ${part2(input)}") }
0
Kotlin
0
0
98f7d6b3dd9eefebef5fa3179ca331fef5ed975b
1,383
advent-of-code-2021
Apache License 2.0
src/Day04.kt
b0n541
571,797,079
false
{"Kotlin": 17810}
fun main() { infix fun IntRange.fullyContains(other: IntRange): Boolean { for (value in other) { if (value !in this) { return false } } return true } infix fun IntRange.overlaps(other: IntRange): Boolean { for (value in other) { if (value in this) { return true } } return false } fun String.toIntRanges() = this.split(",") .map { numberStrings -> numberStrings .split("-") .map { it.toInt() } } .map { numbers -> numbers[0]..numbers[1] } fun part1(input: List<String>): Int { return input .map { it.toIntRanges() } .count { it[0] fullyContains it[1] || it[1] fullyContains it[0] } } fun part2(input: List<String>): Int { return input .map { it.toIntRanges() } .count { it[0] overlaps it[1] } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day04_test") val input = readInput("Day04") val resultTest1 = part1(testInput) println("Test 1: $resultTest1") check(resultTest1 == 2) val resultPart1 = part1(input) println("Part 1: $resultPart1") check(resultPart1 == 498) val resultTest2 = part2(testInput) println("Test 2: $resultTest2") check(resultTest2 == 4) val resultPart2 = part2(input) println("Part 2: $resultPart2") check(resultPart2 == 859) }
0
Kotlin
0
0
d451f1aee157fd4d47958dab8a0928a45beb10cf
1,563
advent-of-code-2022
Apache License 2.0
src/Day01.kt
Narmo
573,031,777
false
{"Kotlin": 34749}
fun main() { data class Food(val calories: Int) class Elf { private val inventory = mutableListOf<Food>() fun add(food: Food) = inventory.add(food) fun getInventory() = inventory.toList() fun getTotalEnergy() = inventory.sumOf { it.calories } } fun getElves(input: List<String>): List<Elf> { val elves = mutableListOf<Elf>() var currentElf = Elf() input.forEachIndexed { index, s -> if (s.isEmpty()) { if (currentElf.getInventory().isNotEmpty()) { elves.add(currentElf) } currentElf = Elf() } else { currentElf.add(Food(s.toInt())) } if (index == input.size - 1) { elves.add(currentElf) } } return elves.toList() } fun part1(input: List<String>): Int { return getElves(input).maxOf { it.getTotalEnergy() } } fun part2(input: List<String>): Int { val elves = getElves(input).sortedBy { it.getTotalEnergy() }.reversed() return elves.take(3).sumOf { it.getTotalEnergy() } } val testInput = readInput("Day01_test") check(part1(testInput) == 24_000) check(part2(testInput) == 45_000) val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
335641aa0a964692c31b15a0bedeb1cc5b2318e0
1,149
advent-of-code-2022
Apache License 2.0
src/main/kotlin/aoc2019/day22_slam_shuffle/SlamShuffle.kt
barneyb
425,532,798
false
{"Kotlin": 238776, "Shell": 3825, "Java": 567}
package aoc2019.day22_slam_shuffle import java.util.* fun main() { util.solve(3036, ::partOne) util.solve(2019, ::partOneReverse) util.solve(70618172909245, ::partTwoReverse) } internal fun String.words() = this.split(" ") internal fun List<Op>.forward(card: Long) = this.fold(card) { c, op -> op.forward(c) } internal fun List<Op>.reverse(card: Long) = this.asReversed().fold(card) { c, op -> op.reverse(c) } const val DECK_SIZE_ONE: Long = 10007 const val ITERATIONS_ONE: Long = 1 fun partOne(input: String) = partOne(input, DECK_SIZE_ONE, 2019, ITERATIONS_ONE) fun partOne( input: String, deckSize: Long, card: Long, iterations: Long ): Long { var itrsLeft = iterations var c = card val d = object : TreeMap<Long, List<Op>>() { override operator fun get(key: Long): List<Op> { return super.get(key)!! } } d[1] = reduceOps(input.toOps(deckSize)) var prev = 1L val cutoff = iterations / 2 while (prev < cutoff) { val n = prev * 2 d[n] = reduceOps(d[prev] + d[prev]) prev = n } while (itrsLeft > 0) { val (n, ops) = d.lowerEntry(itrsLeft + 1) c = ops.forward(c) itrsLeft -= n } return c } fun partOneReverse(input: String) = input .toOps(DECK_SIZE_ONE) .reverse(3036) const val DECK_SIZE_TWO: Long = 119_315_717_514_047 const val ITERATIONS_TWO: Long = 101_741_582_076_661 fun partTwo(input: String) = partTwo( input, DECK_SIZE_TWO, 2020, ITERATIONS_TWO ) internal fun partTwo( input: String, deckSize: Long, card: Long, iterations: Long ): Long { val ops = input.toOps(deckSize) var c = card for (i in 0 until iterations) { c = ops.reverse(c) } return c } fun partTwoReverse(input: String) = partOne( input, DECK_SIZE_TWO, 2020, DECK_SIZE_TWO - ITERATIONS_TWO - 1 )
0
Kotlin
0
0
a8d52412772750c5e7d2e2e018f3a82354e8b1c3
2,005
aoc-2021
MIT License
src/day22/a/day22a.kt
pghj
577,868,985
false
{"Kotlin": 94937}
package day22.a import readInputLines import shouldBe import util.IntVector import vec import java.util.regex.Pattern import kotlin.math.max fun main() { val input = read() val top = input.map.keys.minOfOrNull { it[1] }!! val left = input.map.keys.filter { it[1] == top }.minOfOrNull { it[0] }!! var p = vec(left, top) var d = vec(1, 0) for (i in input.move) { when (i) { is Int -> { for (k in 1..i) { var c = input.map[p + d] if (c == null) { val q = input.wrapAround(p, d) c = input.map[q] if (c == '#') break p = q } else { if (c == '#') break p += d } input.map[p] = directionIcon(d) } } is Char ->{ input.map[p] = rotationIcon(d, i) when(i) { 'L' -> d = d.rotate(1, 0) 'R' -> d = d.rotate(0, 1) } } } } input.print() val answer = score(p, d) shouldBe(27436, answer) } fun score(p: IntVector, d: IntVector): Long { return when (d) { vec(1,0) -> 0L vec(0,1) -> 1L vec(-1,0) -> 2L vec(0,-1) -> 3L else -> throw RuntimeException() } + 1000 * (p[1]+1) + 4 * (p[0]+1) } class Input( val map: HashMap<IntVector, Char>, val move: ArrayList<Any>, val width: Int, val height: Int ) { fun print() { for (y in 0 until height) { for (x in 0 until width) { val q = vec(x,y) val c = map[q] print(c?:' ') } print('\n') } print('\n') } fun wrapAround(p: IntVector, d: IntVector): IntVector { val r = -d var q = p while (map.containsKey(q + r)) q += r return q } } fun read(): Input { val lines = readInputLines(22) val instr = lines.last() val m = lines.subList(0, lines.size-1).filter { it.isNotBlank() } val map = HashMap<IntVector, Char>() var p = vec(0, 0) var w = 0 var h = 0 m.forEach { row -> var q = p for (c in row) { if (c == '.' || c == '#') map[q] = c q += vec(1,0) w = max(w, q[0]) h = max(h, q[1]) } p += vec(0,1) } val t = instr.split(Pattern.compile("[0-9]+")).filter { it.isNotBlank() }.map { it[0] } val n = instr.split(Pattern.compile("[RL]")).map { it.toInt() } val moves = ArrayList<Any>() for (i in t.indices) { moves.add(n[i]) moves.add(t[i]) } moves.add(n.last()) return Input(map, moves, w+1, h+1) } fun directionIcon(d: IntVector) : Char = if (d[0] == 0) '┃' else '━' fun rotationIcon(d: IntVector, t: Char) : Char { return when (if (t == 'R') d.rotate(1, 0) else d) { vec(1, 0) -> '┛' vec(-1, 0) -> '┏' vec(0, -1) -> '┓' vec(0, 1) -> '┗' else -> '?' } }
0
Kotlin
0
0
4b6911ee7dfc7c731610a0514d664143525b0954
3,186
advent-of-code-2022
Apache License 2.0
src/Day04.kt
JohannesPtaszyk
573,129,811
false
{"Kotlin": 20483}
fun main() { fun part1(input: List<String>): Int = input.map { line -> val ranges = line.split(",").map { rangeString -> val (first, second) = rangeString.split("-") first.toInt()..second.toInt() } val (first, second) = ranges first to second }.count { val (first, second) = it first.intersect(second).size == second.count() || second.intersect(first).size == first.count() } fun part2(input: List<String>): Int = input.map { line -> val ranges = line.split(",").map { rangeString -> val (first, second) = rangeString.split("-") first.toInt()..second.toInt() } val (first, second) = ranges first to second }.count { val (first, second) = it first.intersect(second).isNotEmpty() } val testInput = readInput("Day04_test") val input = readInput("Day04") println("Part1 test: ${part1(testInput)}") check(part1(testInput) == 2) println("Part 1: ${part1(input)}") println("Part2 test: ${part2(testInput)}") check(part2(testInput) == 4) println("Part 2: ${part2(input)}") }
0
Kotlin
0
1
6f6209cacaf93230bfb55df5d91cf92305e8cd26
1,172
advent-of-code-2022
Apache License 2.0
src/Day01.kt
zirman
572,627,598
false
{"Kotlin": 89030}
fun main() { fun splitOn(separator: String, input: List<String>): List<List<String>> { tailrec fun splitOn(acc: List<List<String>>, input: List<String>): List<List<String>> { val index = input.indexOf(separator) return if (index == -1) { acc.plusElement(input) } else { splitOn( acc = acc.plusElement(input.slice(0 until index)), input = input.slice((index + 1) until input.size) ) } } return splitOn(emptyList(), input) } fun part1(input: List<String>): Long { val elfs = splitOn("", input) return elfs.map { elf -> elf.sumOf { it.toLong() } }.max() } fun part2(input: List<String>): Long { val elfs = splitOn("", input) return elfs.map { elf -> elf.sumOf { it.toLong() } }.asSequence().sortedDescending().take(3).sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") check(part1(testInput) == 24000L) check(part2(testInput) == 45000L) val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
1
2ec1c664f6d6c6e3da2641ff5769faa368fafa0f
1,227
aoc2022
Apache License 2.0
src/Day08.kt
spaikmos
573,196,976
false
{"Kotlin": 83036}
fun main() { // Dimension of row val DIM = 99 fun part1(input: List<String>): Int { // Create a 2D array of the same size as the input //var seenTrees = mutableSetOf(Pair(0, 0)) var seenTrees = Array(DIM) {Array(DIM) {0} } for (i in 0..(DIM-1)) { val nums = input[i].map{ it - '0' } // Count trees from the left. var maxHeight = nums[0] seenTrees[i][0] = 1 for (j in 1..(DIM-2)) { if (nums[j] > maxHeight) { maxHeight = nums[j] seenTrees[i][j] = 1 } } // Count trees from the right maxHeight = nums[DIM-1] seenTrees[i][DIM-1] = 1 for (j in (DIM-2) downTo 1) { if (nums[j] > maxHeight) { maxHeight = nums[j] seenTrees[i][j] = 1 } } // Count trees from the top maxHeight = input[0][i] - '0' seenTrees[0][i] = 1 for (j in 1..(DIM-2)) { val height = input[j][i] - '0' if (height > maxHeight) { maxHeight = height seenTrees[j][i] = 1 } } // Count trees from the bottom maxHeight = input[DIM-1][i] - '0' seenTrees[DIM-1][i] = 1 for (j in (DIM-2) downTo 1) { val height = input[j][i] - '0' if (height > maxHeight) { maxHeight = height seenTrees[j][i] = 1 } } } // Count the total number of trees var total = 0 for (i in seenTrees) { total += i.sum() } return total } fun part2(input: List<String>): Int { var max = 0 for (i in 1..97) { for (j in 1..97) { val curHeight = input[i][j] - '0' // count north var score = 1 var numTrees = 1 for (k in j-1 downTo 1) { if ((input[i][k] - '0') < curHeight) { numTrees++ } else { break } } score *= numTrees // count south numTrees = 1 for (k in j+1..DIM-2) { if ((input[i][k] - '0') < curHeight) { numTrees++ } else { break } } score *= numTrees // count east numTrees = 1 for (k in i+1..DIM-2) { if ((input[k][j] - '0') < curHeight) { numTrees++ } else { break } } score *= numTrees // count west numTrees = 1 for (k in i-1 downTo 1) { if ((input[k][j] - '0') < curHeight) { numTrees++ } else { break } } score *= numTrees if (score > max) { max = score } } } return max } val input = readInput("../input/Day08") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
6fee01bbab667f004c86024164c2acbb11566460
3,601
aoc-2022
Apache License 2.0
src/Day04.kt
BHFDev
572,832,641
false
null
fun main() { fun part1(input: List<String>): Int { return input.count { pair -> val elves = pair .split(',') .map {elf -> elf.split('-').map { it.toInt() } } val elf1 = Pair(elves[0][0], elves[0][1]) val elf2 = Pair(elves[1][0], elves[1][1]) (elf1.first >= elf2.first && elf1.second <= elf2.second || elf2.first >= elf1.first && elf2.second <= elf1.second) } } fun part2(input: List<String>): Int { return input.count { pair -> val elves = pair .split(',') .map {elf -> elf.split('-').map { it.toInt() } } val elf1 = Pair(elves[0][0], elves[0][1]) val elf2 = Pair(elves[1][0], elves[1][1]) (elf1.first <= elf2.first && elf1.second >= elf2.first || elf2.first <= elf1.first && elf2.second >= elf1.first) } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day04_test") check(part2(testInput) == 4) val input = readInput("Day04") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
b158069483fa02636804450d9ea2dceab6cf9dd7
1,267
aoc-2022-in-kotlin
Apache License 2.0
aoc21/day_12/main.kt
viktormalik
436,281,279
false
{"Rust": 227300, "Go": 86273, "OCaml": 82410, "Kotlin": 78968, "Makefile": 13967, "Roff": 9981, "Shell": 2796}
import java.io.File fun String.small(): Boolean = all { it.isLowerCase() } fun List<String>.hasDuplicate() = size != distinct().size fun countPaths( neighs: MutableMap<String, Set<String>>, mayVisit: (node: String, path: List<String>) -> Boolean, ): Int { val openPaths = mutableListOf(listOf("start")) var result = 0 while (!openPaths.isEmpty()) { val p = openPaths.first() openPaths.removeFirst() for (n in neighs.get(p.last())!!) { if (n == "end") { result += 1 continue } if (n == "start") continue if (mayVisit(n, p)) openPaths.add(p + listOf(n)) } } return result } fun main() { val neighs = mutableMapOf<String, Set<String>>() for (line in File("input").readLines()) { line.split("-").let { neighs.merge(it[0], setOf(it[1]), Set<String>::union) neighs.merge(it[1], setOf(it[0]), Set<String>::union) } } val first = countPaths(neighs) { n, p -> !(n.small() && p.contains(n)) } println("First: $first") val second = countPaths(neighs) { n, p -> !n.small() || p.count { it == n } == 0 || (p.count { it == n } == 1 && !p.filter { it.small() }.hasDuplicate()) } println("Second: $second") }
0
Rust
1
0
f47ef85393d395710ce113708117fd33082bab30
1,347
advent-of-code
MIT License
kotlin/src/main/kotlin/year2021/Day05.kt
adrisalas
725,641,735
false
{"Kotlin": 130217, "Python": 1548}
package year2021 private data class Point(val x: Int, val y: Int) private data class Line(val pointA: Point, val pointB: Point) private fun part1(input: List<String>): Int { val points: MutableMap<Point, Int> = HashMap() val lines = readLines(input) lines .map { toPointsPart1(it) } .flatten() .forEach { points[it] = points.getOrDefault(it, 0) + 1 } return points.values.count { it > 1 } } private fun readLines(input: List<String>): List<Line> { return input.map { val points = it.split(" -> ") val left = points[0].split(",") val begin = Point( Integer.valueOf(left[0]), Integer.valueOf(left[1]) ) val right = points[1].split(",") val end = Point( Integer.valueOf(right[0]), Integer.valueOf(right[1]) ) Line(begin, end) } } private fun toPointsPart1(line: Line): List<Point> { val (pointA, pointB) = line val points: MutableList<Point> = ArrayList() val begin = if (pointA.x < pointB.x || pointA.y < pointB.y) pointA else pointB val end = if (pointA == begin) pointB else pointA if (begin.x == end.x) { for (i in begin.y..end.y) { points.add(Point(begin.x, i)) } } else if (begin.y == end.y) { for (i in begin.x..end.x) { points.add(Point(i, begin.y)) } } return points } private fun part2(input: List<String>): Int { val points: MutableMap<Point, Int> = HashMap() val lines = readLines(input) lines .map { toPointsPart2(it) } .flatten() .forEach { points[it] = points.getOrDefault(it, 0) + 1 } return points.values.count { it > 1 } } private fun toPointsPart2(line: Line): List<Point> { val (pointA, pointB) = line val points: MutableList<Point> = ArrayList() var begin = if (pointA.x < pointB.x || pointA.y < pointB.y) pointA else pointB var end = if (pointA == begin) pointB else pointA if (begin.x == end.x) { for (i in begin.y..end.y) { points.add(Point(begin.x, i)) } } else if (begin.y == end.y) { for (i in begin.x..end.x) { points.add(Point(i, begin.y)) } } else { begin = if (pointA.x < pointB.x) pointA else pointB end = if (pointA == begin) pointB else pointA if (needsToGoUp(begin, end)) { for (i in 0..(end.x - begin.x)) { points.add(Point(begin.x + i, begin.y - i)) } } else { for (i in 0..(end.x - begin.x)) { points.add(Point(begin.x + i, begin.y + i)) } } } return points } private fun needsToGoUp(begin: Point, end: Point): Boolean { return begin.y > end.y } fun main() { // test if implementation meets criteria from the description, like: val testInput = readInput("Day05_test") check(part1(testInput) == 5) check(part2(testInput) == 12) val input = readInput("Day05") println(part1(input)) println(part2(input)) }
0
Kotlin
0
2
6733e3a270781ad0d0c383f7996be9f027c56c0e
3,091
advent-of-code
MIT License
src/main/kotlin/adventofcode/year2021/Day11DumboOctopus.kt
pfolta
573,956,675
false
{"Kotlin": 199554, "Dockerfile": 227}
package adventofcode.year2021 import adventofcode.Puzzle import adventofcode.PuzzleInput import adventofcode.common.neighbors class Day11DumboOctopus(customInput: PuzzleInput? = null) : Puzzle(customInput) { private val grid by lazy { input.lines().map { it.map { it.toString().toInt() } } } private fun List<List<Int>>.incrementAll() = map { it.map(Int::inc) } private fun List<List<Int>>.increment(points: List<Pair<Int, Int>>) = mapIndexed { y, row -> row.mapIndexed { x, col -> col + points.filter { it.first == x && it.second == y }.size } } private fun List<List<Int>>.flashes() = flatMapIndexed { y, row -> row.mapIndexedNotNull { x, col -> if (col > 9) x to y else null } } private fun List<List<Int>>.reset() = map { row -> row.map { col -> if (col > 9) 0 else col } } private fun List<List<Int>>.simulate(steps: Int) = generateSequence(0 to this) { (previousFlashes, previousGrid) -> val incrementedGrid = previousGrid.incrementAll() val (newFlashes, newGrid, _) = generateSequence( Triple(0, incrementedGrid, emptySet<Pair<Int, Int>>()) ) { (currentFlashes, currentGrid, alreadyFlashed) -> val flashes = currentGrid.flashes().minus(alreadyFlashed) val neighbors = flashes.flatMap { currentGrid.neighbors(it.first, it.second, true) } when (flashes.size) { 0 -> null else -> Triple(currentFlashes + flashes.size, currentGrid.increment(neighbors), alreadyFlashed.plus(flashes)) } } .last() previousFlashes + newFlashes to newGrid.reset() } .take(steps + 1) .last() override fun partOne() = grid.simulate(100).first override fun partTwo() = generateSequence(0 to grid) { (previousStep, previousGrid) -> previousStep + 1 to previousGrid.simulate(1).second } .first { (_, grid) -> grid.flatten().all { it == 0 } } .first }
0
Kotlin
0
0
72492c6a7d0c939b2388e13ffdcbf12b5a1cb838
1,972
AdventOfCode
MIT License
src/advent/of/code/Dijkstra.kt
1nco
725,911,911
false
{"Kotlin": 112713, "Shell": 103}
package advent.of.code import advent.of.code.types.Graph fun dijkstra(graph: Graph<String>, start: String, map: MutableList<MutableList<Int>>): Map<String, String?> { var S: MutableSet<String> = mutableSetOf() // a subset of vertices, for which we know the true distance /* * delta represents the length of the shortest distance paths * from start to v, for v in vertices. * * The values are initialized to infinity, as we'll be getting the key with the min value */ var delta = graph.vertices.map { it to Int.MAX_VALUE }.toMap().toMutableMap() delta[start] = 0 val previous: MutableMap<String, String?> = graph.vertices.map { it to null }.toMap().toMutableMap() while (S != graph.vertices) { // let v be the closest vertex that has not yet been visited val v: String = delta .filter { !S.contains(it.key) } .minBy { it.value }!! .key graph.edges.getValue(v).minus(S).forEach { neighbor -> var last = "D" if (previous[v] != null) { last = getMovementDirection(previous[v]!!, v); } val movement = getMovementDirection(v, neighbor); val checkableNeighbors: MutableMap<String, String> = mutableMapOf(); if ((last == "D" || last == "U")) { if (movement == "R") { val vertex: Pos = Pos(v.split(";")[0].toInt(), v.split(";")[1].toInt()); val neighborVertex: Pos = Pos(neighbor.split(";")[0].toInt(), neighbor.split(";")[1].toInt()); for (i in 0..2) { checkableNeighbors.put( "${vertex.line};${vertex.column + i}", "${neighborVertex.line};${neighborVertex.column + i}" ) } } if (movement == "L") { val vertex: Pos = Pos(v.split(";")[0].toInt(), v.split(";")[1].toInt()); val neighborVertex: Pos = Pos(neighbor.split(";")[0].toInt(), neighbor.split(";")[1].toInt()); for (i in 0..2) { checkableNeighbors.put( "${vertex.line};${vertex.column - i}", "${neighborVertex.line};${neighborVertex.column - i}" ) } } } else if ((last == "R" || last == "L")) { if (movement == "D") { val vertex: Pos = Pos(v.split(";")[0].toInt(), v.split(";")[1].toInt()); val neighborVertex: Pos = Pos(neighbor.split(";")[0].toInt(), neighbor.split(";")[1].toInt()); for (i in 0..2) { checkableNeighbors.put( "${vertex.line + i};${vertex.column}", "${neighborVertex.line + i};${neighborVertex.column}" ) } } if (movement == "U") { val vertex: Pos = Pos(v.split(";")[0].toInt(), v.split(";")[1].toInt()); val neighborVertex: Pos = Pos(neighbor.split(";")[0].toInt(), neighbor.split(";")[1].toInt()); for (i in 0..2) { checkableNeighbors.put( "${vertex.line - i};${vertex.column}", "${neighborVertex.line - i};${neighborVertex.column}" ) } } } checkableNeighbors.forEach { nv -> if (delta.contains(nv.value)) { val newPath = delta.getValue(nv.key) + graph.weights.getValue(Pair(nv.key, nv.value)) if (newPath < delta.getValue(nv.value)) { delta[nv.value] = newPath previous[nv.value] = nv.key } } } // var last = "R" // if (previous[v] != null) { // last = getMovementDirection(previous[v]!!, v); // } // val movement = getMovementDirection(v, neighbor); // // val newPath = delta.getValue(v) + graph.weights.getValue(Pair(v, neighbor)) // if (newPath < delta.getValue(neighbor) && !wasLast3MovesTheSame(previous, v, movement) && notGoingBackwards(last, movement)) { // delta[neighbor] = newPath // previous[neighbor] = v // } } S.add(v) } return previous.toMap() } //private fun <T> getValue(d: MutableMap<T, Int>, prev: MutableMap<T, T?>, v: T): Int { // val previous = prev as MutableMap<String, String>; // val vertex = v.toString() // val delta = d as MutableMap<String, Int> // return if (wasLast3MovesTheSame(previous.toMutableMap(), vertex)) { // Int.MAX_VALUE; // } else { // delta[vertex]!! // } //} private fun notGoingBackwards(last: String, current: String): Boolean { if ((last == "U" && current == "D") || (last == "D" && current == "U") || (last == "R" && current == "L") || (last == "L" && current == "R")) { return false; } else { return true; } } private fun <T> wasLast3MovesTheSame(prev: MutableMap<T, T?>, v: T, curr: String): Boolean { val previous = prev as LinkedHashMap<String, String>; val vertex = v.toString() if (previous[vertex] != null && previous[previous[vertex]] != null) { val last = getMovementDirection(previous[vertex]!!, vertex) val beforeLast = getMovementDirection(previous[previous[vertex]]!!, previous[vertex]!!) if (last == beforeLast && last == curr && beforeLast == curr) { return true } else { return false } } else { return false; } // return if(lastMoves.size > 2) lastMoves.subList(lastMoves.size - 3, lastMoves.size).all { it == move } else false; } private fun getMovementDirection(v: String, neighbor: String): String { val vx = v.split(";")[0].toInt(); val vy = v.split(";")[1].toInt(); val nx = neighbor.split(";")[0].toInt(); val ny = neighbor.split(";")[1].toInt(); if (vx < nx) { return "D"; } if (vx > nx) { return "U" } if (vy < ny) { return "R" } if (vy > ny) { return "L" } return ""; } fun <T> shortestPath(shortestPathTree: Map<T, T?>, start: T, end: T): List<T> { fun pathTo(start: T, end: T): List<T> { if (shortestPathTree[end] == null) return listOf(end) return listOf(pathTo(start, shortestPathTree[end]!!), listOf(end)).flatten() } return pathTo(start, end) } data class Pos(var line: Int, var column: Int);
0
Kotlin
0
0
0dffdeba1ebe0b44d24f94895f16f0f21ac8b7a3
6,836
advent-of-code
Apache License 2.0
src/day04/Day04.kt
wickenico
573,048,677
false
{"Kotlin": 7731}
package day04 import readInput fun main() { println(part1(readInput("day04", "input"))) println(part2(readInput("day04", "input"))) } fun part1(input: List<String>): Int { var result = 0 input.forEach { line -> val ranges = line.split(",") val first = ranges[0].split("-").map { it.toInt() } val second = ranges[1].split("-").map { it.toInt() } if ((first[0] >= second[0] && first[1] <= second[1]) || (second[0] >= first[0] && second[1] <= first[1]) ) { result++ } } return result } fun part2(input: List<String>): Int { var result = 0 input.forEach { line -> val ranges = line.split(",") val first = ranges[0].split("-").map { it.toInt() } val second = ranges[1].split("-").map { it.toInt() } if ((second[0] <= first[1] && second[0] >= first[0]) || (first[0] <= second[1] && first[0] >= second[0])) { result++ } } return result }
0
Kotlin
0
0
00791dc0870048b08092e38338cd707ce0f9706f
999
advent-of-code-kotlin
Apache License 2.0
src/Day13.kt
p357k4
573,068,508
false
{"Kotlin": 59696}
import kotlin.math.min sealed interface Message { data class Number(val value: Int) : Message data class Messages(val messages: MutableList<Message>, val parent: Messages?) : Message } enum class Ordered { YES, NO, MAYBE } fun main() { fun decode(input: String): Message { val parent = Message.Messages(mutableListOf(), null) var current: Message.Messages? = parent var index = 0 while (true) { if (index == input.length) { break } if (input[index] == '[') { val child = Message.Messages(mutableListOf(), current) current?.messages?.add(child) current = child index++ continue; } if (input[index] == ']') { current = current?.parent index++ continue } if (input[index] == ',') { index++ continue } var number = 0 while (input[index].isDigit()) { number = 10 * number + input[index].digitToInt() index++ } current?.messages?.add(Message.Number(number)) } return parent } fun isOrdered(left: Message, right: Message): Ordered { if (left is Message.Number && right is Message.Number) { if (left.value < right.value) { return Ordered.YES } if (left.value > right.value) { return Ordered.NO } return Ordered.MAYBE } if (left is Message.Messages && right is Message.Number) { return isOrdered(left, Message.Messages(mutableListOf(right), null)) } if (left is Message.Number && right is Message.Messages) { return isOrdered(Message.Messages(mutableListOf(left), null), right) } if (left is Message.Messages && right is Message.Messages) { for(i in 0 until left.messages.size.coerceAtMost(right.messages.size)) { val result = isOrdered(left.messages[i], right.messages[i]) if (result != Ordered.MAYBE) { return result } } if (left.messages.size < right.messages.size) { return Ordered.YES } if (left.messages.size > right.messages.size) { return Ordered.NO } return Ordered.MAYBE } throw IllegalStateException("cannot end with MAYBE order") } fun part1(input: String): Int { val result = input .split("\n\n") .mapIndexed() { index, packet -> val (left, right) = packet.lines().map { decode(it) } val result = isOrdered(left, right) if (result == Ordered.YES) { index + 1 } else { 0 } }.sum() return result } fun part2(input: String): Int { val marker2 = decode("[[2]]") val marker6 = decode("[[6]]") val result = (input.lines().filterNot { it.isEmpty() }.map { line -> decode(line) } + marker2 + marker6) .sortedWith { a, b -> if (isOrdered(a, b) == Ordered.NO) { 1 } else { -1 } } val divider2 = result.indexOf(marker2) + 1 val divider6 = result.indexOf(marker6) + 1 return divider2 * divider6 } // test if implementation meets criteria from the description, like: val testInputExample = readText("Day13_example") check(part1(testInputExample) == 13) check(part2(testInputExample) == 140) val testInput = readText("Day13_test") println(part1(testInput)) println(part2(testInput)) }
0
Kotlin
0
0
b9047b77d37de53be4243478749e9ee3af5b0fac
4,072
aoc-2022-in-kotlin
Apache License 2.0
src/main/kotlin/days/Day4.kt
nicopico-dev
726,255,944
false
{"Kotlin": 37616}
package days import kotlin.math.pow class Day4 : Day(4) { private val cards: List<Card> by lazy { inputList.map { parseCard(it) } } override fun partOne(): Any { return cards .map { it.winningNumbersYouHave.size } .sumOf { computePoints(winCount = it) } } override fun partTwo(): Any { return processCards().values.sum() } /** * Compute the number of each card the user as won as the end */ fun processCards(): Map<CardId, Int> { val allCards: List<Card> = cards + cards.flatMap { processCard(it) } return allCards .groupBy { it.id } .mapValues { it.value.size } } /** * Return *all* cards won by [card] */ private fun processCard(card: Card): List<Card> { val wonCards = getWonCards(card) return if (wonCards.isEmpty()) emptyList() // Each won card must be processed as well else wonCards + wonCards.flatMap { processCard(it) } } /** * Return the first round of cards won by [card] */ private fun getWonCards(card: Card): List<Card> { return card.computeWonCopies() .map { cardId -> cards.first { it.id == cardId } } } data class Card( val id: CardId, val winningNumbers: Set<Int>, val numbersYouHave: Set<Int>, ) { val winningNumbersYouHave: Set<Int> = winningNumbers intersect numbersYouHave fun computeWonCopies(): List<CardId> { return if (winningNumbersYouHave.isEmpty()) { emptyList() } else { val winCount = winningNumbersYouHave.size var cardId = id buildList { repeat(winCount) { cardId = cardId.next() add(cardId) } } } } } @JvmInline value class CardId(val id: Int) { fun next() = CardId(id + 1) } companion object { private val cardRegex = Regex("Card\\s+(\\d+): ([\\d\\s]+)\\|([\\d\\s]+)") private val spaceRegex = Regex("\\s+") fun parseCard(data: String): Card { val match = cardRegex.matchEntire(data) require(match != null) { "Invalid format for Card ($data)" } val (id, winningNumbers, numbersYouHave) = match.destructured return Card( id = CardId(id.toInt()), winningNumbers = winningNumbers.extractNumbers(), numbersYouHave = numbersYouHave.extractNumbers(), ) } private fun String.extractNumbers() = this .trim() .split(spaceRegex) .map(String::toInt) .toSet() fun computePoints(winCount: Int): Int { return if (winCount > 0) { 2.0.pow(winCount - 1.0).toInt() } else { 0 } } } }
0
Kotlin
0
0
1a13c8bd3b837c1ce5b13f90f326f0277249d23e
3,091
aoc-2023
Creative Commons Zero v1.0 Universal
problems/2850/kotlin/Solution.kt
misut
678,196,869
false
{"Kotlin": 32683}
class Solution { fun minimumMoves(grid: Array<IntArray>): Int { val queue = mutableListOf(grid to 0) val visited = mutableSetOf(grid.stringify()) while(true) { val (board, moves) = queue.removeFirst() if (board.isCoveredAll()) { return moves } queue.addAll(board.spread().filter { visited.add(it.stringify()) }.map { it to moves + 1 }) } } } fun Array<IntArray>.forEachCells(action: (Int) -> Unit) = this.forEachCellsWithPosition { _, i -> action(i) } fun Array<IntArray>.forEachCellsWithPosition(action: (Pair<Int, Int>, Int) -> Unit) = this.forEachIndexed { col, list -> list.forEachIndexed { row, num -> action(col to row, num) } } fun Array<IntArray>.isCoveredAll(): Boolean { var covered = true this.forEachCells { if (it != 1) { covered = false return@forEachCells } } return covered } fun Array<IntArray>.spread(): List<Array<IntArray>> { val boards = mutableListOf<Array<IntArray>>() val (cols, rows) = size to first().size this.forEachCellsWithPosition { pos, stones -> if (stones > 1) { pos.adjacents().forEach { if (it.first in (0 until cols) && it.second in (0 until rows)) { val board = this.copy() board[pos.first][pos.second] = stones - 1 board[it.first][it.second] += 1 boards.add(board) } } } } return boards } fun Array<IntArray>.copy(): Array<IntArray> { val (cols, rows) = size to first().size return Array(cols) { col -> IntArray(rows) { row -> this[col][row] } } } fun Array<IntArray>.stringify(): String { val buffer = StringBuffer() this.forEachCells { buffer.append(it.digitToChar()) } return buffer.toString() } fun Pair<Int, Int>.adjacents(): List<Pair<Int, Int>> = listOf(first - 1 to second, first + 1 to second, first to second - 1, first to second + 1)
0
Kotlin
0
0
52fac3038dd29cb8eefebbf4df04ccf1dda1e332
2,048
ps-leetcode
MIT License
src/Day14.kt
maciekbartczak
573,160,363
false
{"Kotlin": 41932}
import kotlin.math.max import kotlin.math.min fun main() { fun part1(input: List<String>): Int { val grid = parseInput(input, false) return getGrainsWithinBoundsCount(grid) } fun part2(input: List<String>): Int { val grid = parseInput(input, true) return getGrainsWithinBoundsCount(grid) + 1 } val testInput = readInput("Day14_test") // check(part1(testInput) == 24) check(part2(testInput) == 93) val input = readInput("Day14") // println(part1(input)) println(part2(input)) } private fun parseInput(input: List<String>, addFloor: Boolean): MutableList<MutableList<Char>> { val paths = input.flatMap { val coords = it.split(" -> ") coords.zipWithNext().map { pair -> val pairs = listOf(pair.first.getCoords(), pair.second.getCoords()) .sortedWith(compareBy( { coords -> coords.first }, { coords -> coords.second } )) val first = pairs.first() val second = pairs.last() first.first..second.first to first.second..second.second } } return paths.toGrid(addFloor) } private fun getGrainsWithinBoundsCount(grid: MutableList<MutableList<Char>>): Int { var withinBounds: Boolean var counter = 0 do { withinBounds = grid.simulateSand() if (withinBounds) { counter++ } } while (withinBounds) grid.prettyPrint() return counter } private fun String.getCoords(): Pair<Int, Int> { val split = this.split(",") return split[0].toInt() to split[1].toInt() } private fun List<Pair<IntRange, IntRange>>.toGrid(addWall: Boolean): MutableList<MutableList<Char>> { // this might be a bit hacky, but I think that we can just simulate infinity with a big enough number // due to the paths being limited horizontally with their coordinates val infinity = 1000 val minX = this .map { it.first.first } .filter { it> 0 } .min() val maxX = max(this.maxOf { it.first.last }, infinity) var maxY = this.maxOf { it.second.last } var pairs = this if (addWall) { maxY += 2 pairs = pairs + (-infinity + minX..infinity to maxY..maxY) } val grid = mutableListOf<MutableList<Char>>() val startX = min(-infinity, 0) for (y in 0..maxY) { val row = mutableListOf<Char>() for (x in startX..maxX - minX) { row.add('.') } grid.add(row) } pairs.forEach { for (x in it.first.first..it.first.last) { for (y in it.second.first..it.second.last) { val gridX = x - minX - startX grid[y][gridX] = '#' } } } grid[0][500 - minX - startX] = '+' return grid } private fun List<List<Char>>.prettyPrint() { this.forEach { row -> row.forEach { print(it) } println() } } private fun List<MutableList<Char>>.simulateSand(): Boolean { val sandSourceX = this.first().indexOf('+') var currentSandPosition = sandSourceX to 0 var moving = true while (moving) { moving = false for (sandOffset in sandOffsets) { val newSandPosition = currentSandPosition.offsetBy(sandOffset) if (!this.isWithinBounds(newSandPosition)) { return false } if (this.moveSand(currentSandPosition, newSandPosition, sandSourceX) != currentSandPosition) { currentSandPosition = newSandPosition moving = true break } } } if (this.isSandSource(currentSandPosition)) { return false } return true } private fun List<MutableList<Char>>.moveSand( currentSandPosition: Pair<Int, Int>, nextSandPosition: Pair<Int, Int>, sourceX: Int ): Pair<Int, Int> { if (this[nextSandPosition.second][nextSandPosition.first] != '.') { return currentSandPosition } this[nextSandPosition.second][nextSandPosition.first] = 'o' // do not remove the sand source from grid for drawing purposes if (currentSandPosition.first == sourceX && currentSandPosition.second == 0) { this[currentSandPosition.second][currentSandPosition.first] = '+' } else { this[currentSandPosition.second][currentSandPosition.first] = '.' } return nextSandPosition } private fun List<MutableList<Char>>.isWithinBounds(coords: Pair<Int, Int>): Boolean { return coords.second in this.indices && coords.first in this[0].indices } private fun List<MutableList<Char>>.isSandSource(coords: Pair<Int, Int>): Boolean { return this[coords.second][coords.first] == '+' } val sandOffsets = listOf( 0 to 1, -1 to 1, 1 to 1 )
0
Kotlin
0
0
53c83d9eb49d126e91f3768140476a52ba4cd4f8
4,799
advent-of-code-2022
Apache License 2.0
src/main/kotlin/com/anahoret/aoc2022/day05/main.kt
mikhalchenko-alexander
584,735,440
false
null
package com.anahoret.aoc2022.day05 import java.io.File import kotlin.collections.ArrayDeque private fun <E> ArrayDeque<E>.removeFirst(count: Int): List<E> { val result = mutableListOf<E>() repeat(count) { result.add(removeFirst()) } return result } data class Move(val from: Int, val to: Int, val count: Int) { companion object { private val regex = "move (\\d+) from (\\d+) to (\\d+)".toRegex() fun parse(str: String): Move { val (count, from, to) = regex.find(str)!!.groupValues.drop(1).map(String::toInt) return Move(from, to, count) } } } class Stacks(private val stacks: List<ArrayDeque<String>>) { companion object { fun parse(str: String): Stacks { val stacks = str.lines() .dropLast(1) .map { it.windowed(size = 3, step = 4).map(::extractSymbol) } .let(::toStacks) return Stacks(stacks) } private fun toStacks(rows: List<List<String>>): List<ArrayDeque<String>> { val stacks = List(9) { ArrayDeque<String>() } rows.forEach { row -> row.forEachIndexed { idx, symbol -> if (symbol.isNotBlank()) { stacks[idx].addLast(symbol) } } } return stacks } private fun extractSymbol(crate: String): String { return crate[1].toString() } } fun moveAll9000(moves: List<Move>): Stacks { val newStacks = stacks.map(::ArrayDeque) moves.forEach { move9000(it, newStacks) } return Stacks(newStacks) } fun moveAll9001(moves: List<Move>): Stacks { val newStacks = stacks.map(::ArrayDeque) moves.forEach { move9001(it, newStacks) } return Stacks(newStacks) } fun top(): String { return stacks.joinToString(separator = "") { it.firstOrNull() ?: " " } } private fun move9000(move: Move, stacks: List<ArrayDeque<String>>) { repeat(move.count) { val symbol = stacks[move.from - 1].removeFirst() stacks[move.to - 1].addFirst(symbol) } } private fun move9001(move: Move, stacks: List<ArrayDeque<String>>) { stacks[move.from - 1] .removeFirst(move.count) .reversed() .forEach(stacks[move.to - 1]::addFirst) } } fun main() { val input = File("src/main/kotlin/com/anahoret/aoc2022/day05/input.txt") .readText() .trim() val (stacksInput, moveInput) = input.split("\n\n") val stacks = stacksInput .let(Stacks.Companion::parse) val moves = moveInput .split("\n") .map(Move.Companion::parse) // Part 1 println(stacks.moveAll9000(moves).top()) // Part 2 println(stacks.moveAll9001(moves).top()) }
0
Kotlin
0
0
b8f30b055f8ca9360faf0baf854e4a3f31615081
2,905
advent-of-code-2022
Apache License 2.0
src/year2023/day13/Solution.kt
TheSunshinator
572,121,335
false
{"Kotlin": 144661}
package year2023.day13 import arrow.core.Either import arrow.core.identity import arrow.core.left import arrow.core.nonEmptyListOf import arrow.core.right import utils.ProblemPart import utils.readInputs import utils.runAlgorithm import utils.transpose fun main() { val (realInput, testInputs) = readInputs(2023, 13, transform = ::parse) runAlgorithm( realInput = realInput, testInputs = testInputs, part1 = ProblemPart( expectedResultsForTests = nonEmptyListOf(405), algorithm = getSolution(reflectionError = 0), ), part2 = ProblemPart( expectedResultsForTests = nonEmptyListOf(400), algorithm = getSolution(reflectionError = 1), ), ) } private fun parse(input: List<String>): List<List<String>> { return input.fold(mutableListOf(mutableListOf<String>())) { accumulator, line -> if (line.isEmpty()) accumulator.add(mutableListOf()) else accumulator.last().add(line) accumulator } } private fun getSolution(reflectionError: Int): (List<List<String>>) -> Long = { input -> input.asSequence() .map { findMirror(it, reflectionError = reflectionError) } .sumOf { mirrorLocation -> mirrorLocation?.fold( ifLeft = ::identity, ifRight = { 100 * it }, ) ?: 0 } } private fun findMirror(pattern: List<String>, reflectionError: Int = 0): Either<Long, Long>? { return pattern.findMirror(reflectionError)?.right() ?: pattern.transpose().findMirror(reflectionError)?.left() } private fun List<String>.findMirror(reflectionError: Int): Long? { return (1..lastIndex).asSequence() .filter { potentialMirrorIndex -> val sideA = ((potentialMirrorIndex - 1)downTo 0).joinToString(separator = "") { this[it] } val sideB = (potentialMirrorIndex..lastIndex).joinToString(separator = "") { this[it] } sideA.zip(sideB).count { (a, b) -> a != b } == reflectionError } .singleOrNull() ?.toLong() }
0
Kotlin
0
0
d050e86fa5591447f4dd38816877b475fba512d0
2,087
Advent-of-Code
Apache License 2.0
src/commonMain/kotlin/advent2020/day14/Day14Puzzle.kt
jakubgwozdz
312,526,719
false
null
package advent2020.day14 fun part1(input: String): String { val lines = input.trim().lineSequence() val memory = mutableMapOf<Long, Long>() var andMask = "111111111111111111111111111111111111".toLong(2) var orMask = "000000000000000000000000000000000000".toLong(2) lines.forEach { line -> val mask = mask(line) if (mask != null) { andMask = mask.replace('X', '1').toLong(2) orMask = mask.replace('X', '0').toLong(2) } else { val (addr, value) = memOp(line) ?: error("Invalid line $line") val result = (value and andMask) or orMask memory[addr] = result } } return memory.values.sum().toString() } fun part2(input: String): String { val lines = input.trim().lineSequence() val memory = mutableMapOf<Long, Long>() var masks = emptyList<Pair<Long, Long>>() lines.forEach { line -> val newMask = mask(line) if (newMask != null) { masks = sequence { val queue = mutableListOf(newMask) while (queue.isNotEmpty()) { val mask = queue.removeFirst() val index = mask.indexOf('X') if (index >= 0) { queue.add(mask.replaceRange(index, index + 1, "_")) queue.add(mask.replaceRange(index, index + 1, "1")) } else { val andMask = mask.replace('0', '1').replace('_', '0').toLong(2) val orMask = mask.replace('0', '0').replace('_', '0').toLong(2) yield(andMask to orMask) } } }.toList() } else { val (addr, value) = memOp(line) ?: error("Invalid line $line") masks.map { (andMask, orMask) -> (addr and andMask) or orMask } .forEach { addr1 -> memory[addr1] = value } } } return memory.values.sum().toString() } val maskRegex by lazy { """mask = ([01X]{36})""".toRegex() } private fun mask(line: String) = maskRegex.matchEntire(line) ?.destructured ?.component1() val memOpRegex by lazy { """mem\[(\d+)\] = (\d+)""".toRegex() } private fun memOp(line: String) = memOpRegex.matchEntire(line) ?.destructured ?.let { (a, v) -> a.toLong() to v.toLong() }
0
Kotlin
0
2
e233824109515fc4a667ad03e32de630d936838e
2,371
advent-of-code-2020
MIT License
src/main/kotlin/com/ginsberg/advent2018/Day13.kt
tginsberg
155,878,142
false
null
/* * Copyright (c) 2018 by <NAME> */ /** * Advent of Code 2018, Day 13 - Mine Cart Madness * * Problem Description: http://adventofcode.com/2018/day/13 * Blog Post/Commentary: https://todd.ginsberg.com/post/advent-of-code/2018/day13/ */ package com.ginsberg.advent2018 import java.util.TreeSet typealias Track = Array<CharArray> class Day13(rawInput: List<String>) { private val track: Track = rawInput.map { it.toCharArray() }.toTypedArray() private val carts: Set<Cart> = Cart.findAll(track) fun solvePart1(): Point = collisions().first() fun solvePart2(): Point { collisions().toList() // Consume the entire sequence return carts.first { it.alive }.run { Point(this.x, this.y) } } private fun collisions(): Sequence<Point> = sequence { while (carts.count { it.alive } > 1) { carts.sorted().forEach { cart -> if (cart.alive) { cart.move(track) // If we collided, mark ourselves and the cart we collided with as not alive // yield the crash site. carts.firstOrNull { cart.collidesWith(it) }?.let { otherCart -> cart.alive = false otherCart.alive = false yield(Point(cart.x, cart.y)) } } } } } private data class Cart(var x: Int, var y: Int, var direction: Direction, var turn: Turn = Turn.Left, var alive: Boolean = true) : Comparable<Cart> { companion object { fun findAll(theTrack: Track): Set<Cart> = theTrack.mapIndexed { y, row -> row.mapIndexed { x, spot -> if (spot in setOf('>', '<', '^', 'v')) { Cart(x, y, Direction(spot)) } else null } } .flatten() .filterNotNull() .toCollection(TreeSet()) } fun collidesWith(other: Cart): Boolean = this != other && this.alive && other.alive && x == other.x && y == other.y fun move(track: Track) { // Move in the direction we are facing x += direction.dx y += direction.dy // Handle turning, anything else is movement in the same direction the next time through. when (track[y][x]) { // Interchange rules '+' -> { direction = direction.turn(turn) turn = turn.next } // Turn '\\' -> { direction = when (direction) { Direction.North, Direction.South -> direction.left else -> direction.right } } // Turn '/' -> { direction = when (direction) { Direction.East, Direction.West -> direction.left else -> direction.right } } } } override fun compareTo(other: Cart): Int = when { y < other.y -> -1 y > other.y -> 1 x < other.x -> -1 x > other.x -> 1 else -> 0 } } private sealed class Turn { abstract val next: Turn object Left : Turn() { override val next = Center } object Center : Turn() { override val next = Right } object Right : Turn() { override val next = Left } } private sealed class Direction { companion object { operator fun invoke(id: Char): Direction = when (id) { '^' -> North 'v' -> South '>' -> East '<' -> West else -> throw IllegalArgumentException("No such direction $id") } } abstract val left: Direction abstract val right: Direction abstract val dx: Int abstract val dy: Int fun turn(turn: Turn): Direction = when (turn) { Turn.Left -> this.left Turn.Center -> this Turn.Right -> this.right } object North : Direction() { override val left = West override val right = East override val dx = 0 override val dy = -1 } object South : Direction() { override val left = East override val right = West override val dx = 0 override val dy = 1 } object East : Direction() { override val left = North override val right = South override val dx = 1 override val dy = 0 } object West : Direction() { override val left = South override val right = North override val dx = -1 override val dy = 0 } } }
0
Kotlin
1
18
f33ff59cff3d5895ee8c4de8b9e2f470647af714
5,312
advent-2018-kotlin
MIT License
src/day04/Day04.kt
zypus
573,178,215
false
{"Kotlin": 33417, "Shell": 3190}
package day04 import AoCTask // https://adventofcode.com/2022/day/4 operator fun IntRange.contains(other: IntRange): Boolean { return other.first in this && other.last in this } private fun parseRangePairs(input: List<String>) = input.map { line -> line .split(",", limit = 2) .map { ranges -> val (from, to) = ranges.split("-").map { it.toInt() } from..to } } fun part1(input: List<String>): Int { val countOfFullyContained = parseRangePairs(input).count { ranges -> val (a,b) = ranges a in b || b in a } return countOfFullyContained } fun part2(input: List<String>): Int { val countOfOverlaps = parseRangePairs(input).count { ranges -> val (a,b) = ranges a.first in b || a.last in b || b.first in a || b.last in a } return countOfOverlaps } fun main() = AoCTask("day04").run { // test if implementation meets criteria from the description, like: check(part1(testInput) == 2) check(part2(testInput) == 4) println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
f37ed8e9ff028e736e4c205aef5ddace4dc73bfc
1,092
aoc-2022
Apache License 2.0
src/main/kotlin/com/jacobhyphenated/advent2023/day8/Day8.kt
jacobhyphenated
725,928,124
false
{"Kotlin": 121644}
package com.jacobhyphenated.advent2023.day8 import com.jacobhyphenated.advent2023.Day typealias Direction = Map<String, Pair<String,String>> /** * Day 8: <NAME> * * The puzzle input consists of two parts. The first part is a set of instructions indicating which * direction to take (R = right, L = left). Those instructions repeat forever. * The second part maps a starting position to two possible ending positions (a left and a right) */ class Day8: Day<Pair<String, Direction>> { override fun getInput(): Pair<String, Direction> { return parseInput(readInputFile("8")) } /** * Part1: The starting position is AAA and the ending position is ZZZ * Following the instructions, how many steps does it take to get to the end? */ override fun part1(input: Pair<String, Direction>): Int { val (instructionString, directions) = input val instructionGenerator = InfiniteGenerator(instructionString.toCharArray().toList()) var current = "AAA" while (current != "ZZZ") { current = nextPosition(instructionGenerator, current, directions) } return instructionGenerator.num } /** * Part 2: There are multiple starting points (every position that ends with A) * and multiple ending points (every position that ends with Z) * * Starting at all possible starting locations at the same time, how many steps until * each position has reached and end point at the same time? */ override fun part2(input: Pair<String, Direction>): Long { val (instructionString, directions) = input val currentPositions = directions.keys.filter { it.endsWith("A") }.toMutableList() // find how long it takes to reach the end from each starting position val endIndexes = currentPositions.map { start -> var current = start val instructionGenerator = InfiniteGenerator(instructionString.toCharArray().toList()) while (!current.endsWith("Z")){ current = nextPosition(instructionGenerator, current, directions) } instructionGenerator.num.toLong() } // Note: This only works because for this puzzle, the repeating pattern of the instructions // starts at the same time for each starting location. That does not necessarily have to be true return lcm(endIndexes) } fun parseInput(input: String): Pair<String, Direction> { val (instructions, directionList) = input.split("\n\n") val directionMap = directionList.lines().map { line -> val (key, lrPair) = line.split(" = ") val (left, right) = lrPair.removeSuffix(")").removePrefix("(").split(", ") Pair(key, Pair(left, right)) }.associate { (key, pair) -> key to pair }.toMap() return Pair(instructions, directionMap) } private fun nextPosition(generator: InfiniteGenerator<Char>, current: String, directions: Direction): String { return when(val instruction = generator.next()) { 'L' -> directions.getValue(current).first 'R' -> directions.getValue(current).second else -> throw IllegalArgumentException("Invalid instruction $instruction") } } override fun warmup(input: Pair<String, Direction>) { part1(input) } } class InfiniteGenerator<T>(private val order: List<T>) { var num = 0 fun next(): T { return order[num % order.size].also { num++ } } } fun main(@Suppress("UNUSED_PARAMETER") args: Array<String>) { Day8().run() }
0
Kotlin
0
0
90d8a95bf35cae5a88e8daf2cfc062a104fe08c1
3,398
advent2023
The Unlicense
src/main/kotlin/com/ginsberg/advent2020/Day20.kt
tginsberg
315,060,137
false
null
/* * Copyright (c) 2020 by <NAME> */ /** * Advent of Code 2020, Day 20 - Jurassic Jigsaw * Problem Description: http://adventofcode.com/2020/day/20 * Blog Post/Commentary: https://todd.ginsberg.com/post/advent-of-code/2020/day20/ */ package com.ginsberg.advent2020 import kotlin.math.sqrt class Day20(input: String) { private val tiles: List<Tile> = parseInput(input) private val image: List<List<Tile>> = createImage() fun solvePart1(): Long = image.first().first().id * image.first().last().id * image.last().first().id * image.last().last().id fun solvePart2(): Int { val seaMonsterOffsets = listOf( Point2D(0, 18), Point2D(1, 0), Point2D(1, 5), Point2D(1, 6), Point2D(1, 11), Point2D(1, 12), Point2D(1, 17), Point2D(1, 18), Point2D(1, 19), Point2D(2, 1), Point2D(2, 4), Point2D(2, 7), Point2D(2, 10), Point2D(2, 13), Point2D(2, 16) ) return imageToSingleTile() .orientations() .first { it.maskIfFound(seaMonsterOffsets) } .body .sumBy { row -> row.count { char -> char == '#' } } } private fun imageToSingleTile(): Tile { val rowsPerTile = tiles.first().body.size val body = image.flatMap { row -> (1 until rowsPerTile - 1).map { y -> row.joinToString("") { it.insetRow(y) }.toCharArray() } }.toTypedArray() return Tile(0, body) } private fun createImage(): List<List<Tile>> { val width = sqrt(tiles.count().toFloat()).toInt() var mostRecentTile: Tile = findTopCorner() var mostRecentRowHeader: Tile = mostRecentTile return (0 until width).map { row -> (0 until width).map { col -> when { row == 0 && col == 0 -> mostRecentTile col == 0 -> { mostRecentRowHeader = mostRecentRowHeader.findAndOrientNeighbor(Orientation.South, Orientation.North, tiles) mostRecentTile = mostRecentRowHeader mostRecentRowHeader } else -> { mostRecentTile = mostRecentTile.findAndOrientNeighbor(Orientation.East, Orientation.West, tiles) mostRecentTile } } } } } private fun findTopCorner(): Tile = tiles .first { tile -> tile.sharedSideCount(tiles) == 2 } .orientations() .first { it.isSideShared(Orientation.South, tiles) && it.isSideShared(Orientation.East, tiles) } private enum class Orientation { North, East, South, West } private class Tile(val id: Long, var body: Array<CharArray>) { private val sides: Set<String> = Orientation.values().map { sideFacing(it) }.toSet() private val sidesReversed = sides.map { it.reversed() }.toSet() fun sharedSideCount(tiles: List<Tile>): Int = sides.sumOf { side -> tiles .filterNot { it.id == id } .count { tile -> tile.hasSide(side) } } fun isSideShared(dir: Orientation, tiles: List<Tile>): Boolean = tiles .filterNot { it.id == id } .any { tile -> tile.hasSide(sideFacing(dir)) } fun findAndOrientNeighbor(mySide: Orientation, theirSide: Orientation, tiles: List<Tile>): Tile { val mySideValue = sideFacing(mySide) return tiles .filterNot { it.id == id } .first { it.hasSide(mySideValue) } .also { it.orientToSide(mySideValue, theirSide) } } fun insetRow(row: Int): String = body[row].drop(1).dropLast(1).joinToString("") fun maskIfFound(mask: List<Point2D>): Boolean { var found = false val maxWidth = mask.maxByOrNull { it.y }!!.y val maxHeight = mask.maxByOrNull { it.x }!!.x (0..(body.size - maxHeight)).forEach { x -> (0..(body.size - maxWidth)).forEach { y -> val lookingAt = Point2D(x, y) val actualSpots = mask.map { it + lookingAt } if (actualSpots.all { body[it.x][it.y] == '#' }) { found = true actualSpots.forEach { body[it.x][it.y] = '0' } } } } return found } fun orientations(): Sequence<Tile> = sequence { repeat(2) { repeat(4) { yield(this@Tile.rotateClockwise()) } this@Tile.flip() } } private fun hasSide(side: String): Boolean = side in sides || side in sidesReversed private fun flip(): Tile { body = body.map { it.reversed().toCharArray() }.toTypedArray() return this } private fun rotateClockwise(): Tile { body = body.mapIndexed { x, row -> row.mapIndexed { y, _ -> body[y][x] }.reversed().toCharArray() }.toTypedArray() return this } private fun sideFacing(dir: Orientation): String = when (dir) { Orientation.North -> body.first().joinToString("") Orientation.South -> body.last().joinToString("") Orientation.West -> body.map { row -> row.first() }.joinToString("") Orientation.East -> body.map { row -> row.last() }.joinToString("") } private fun orientToSide(side: String, direction: Orientation) = orientations().first { it.sideFacing(direction) == side } } private fun parseInput(input: String): List<Tile> = input.split("\n\n").map { it.lines() }.map { tileText -> val id = tileText.first().substringAfter(" ").substringBefore(":").toLong() val body = tileText.drop(1).map { it.toCharArray() }.toTypedArray() Tile(id, body) } }
0
Kotlin
2
38
75766e961f3c18c5e392b4c32bc9a935c3e6862b
6,346
advent-2020-kotlin
Apache License 2.0
src/main/kotlin/day15.kt
Gitvert
725,292,325
false
{"Kotlin": 97000}
fun day15 (lines: List<String>) { val initializationSequence = parseInitializationSequence(lines) val sum = initializationSequence.sumOf { calculateHashValue(it) } println("Day 15 part 1: $sum") val lenses = parseLenses(lines) val boxes = mutableListOf<MutableList<Lens>>() for (i in 0..255) { boxes.add(mutableListOf()) } lenses.forEach { lens -> val hash = calculateHashValue(lens.label) if (lens.operation == '-') { removeLens(boxes, hash, lens) } else { addLens(boxes, hash, lens) } } val totalFocusingPower = boxes.mapIndexed { index, box -> calculateFocusingPower(box, index) }.sum() println("Day 15 part 2: $totalFocusingPower") println() } fun calculateFocusingPower(lenses: List<Lens>, boxNumber: Int): Int { return lenses.mapIndexed { index, lens -> (boxNumber + 1) * (index + 1) * lens.focalLength }.sum() } fun addLens( boxes: MutableList<MutableList<Lens>>, hash: Int, lens: Lens) { if (boxes[hash].map { it.label }.contains(lens.label)) { boxes[hash].replaceAll { if (it.label == lens.label) { lens } else { it } } } else { boxes[hash].add(lens) } } fun removeLens( boxes: MutableList<MutableList<Lens>>, hash: Int, lens: Lens) { if (boxes[hash].map { it.label }.contains(lens.label)) { boxes[hash].removeIf { it.label == lens.label } } } fun calculateHashValue(characters: String): Int { var currentValue = 0 characters.forEach { currentValue += it.code currentValue *= 17 currentValue %= 256 } return currentValue } fun parseLenses(lines: List<String>): List<Lens> { return lines[0].split(",").map { if (it.contains("-")) { Lens(it.split("-")[0], '-', 0) } else { Lens(it.split("=")[0], '=', Integer.parseInt(it.split("=")[1])) } } } fun parseInitializationSequence(lines: List<String>): List<String> { return lines[0].split(",") } data class Lens(val label: String, val operation: Char, val focalLength: Int)
0
Kotlin
0
0
f204f09c94528f5cd83ce0149a254c4b0ca3bc91
2,236
advent_of_code_2023
MIT License
src/main/kotlin/adventofcode2022/solution/day_2.kt
dangerground
579,293,233
false
{"Kotlin": 51472}
package adventofcode2022.solution import adventofcode2022.util.readDay import java.lang.RuntimeException private const val DAY_NUM = 2 fun main() { Day2(DAY_NUM.toString()).solve() } class Day2(private val num: String) { private val inputText = readDay(num) fun solve() { println("Day $num Solution") println("* Part 1: ${solution1()}") println("* Part 2: ${solution2()}") } fun solution1(): Long { return inputText.lines().map { val round = it.split(" ") val opponent = Sign.ofFirst(round.first()) val me = Sign.ofSecond(round.last()) return@map opponent.versus(me) + me.points }.sum() } fun solution2(): Long { return inputText.lines().map { val round = it.split(" ") val opponent = Sign.ofFirst(round.first()) val me = when (round.last()) { "X" -> opponent.winsAgainst() "Y" -> opponent "Z" -> opponent.loseAgainst() else -> throw RuntimeException("not happening") } return@map opponent.versus(me) + me.points }.sum() } } enum class Sign(val points: Long) { ROCK(1), PAPER(2), SCISSORS(3); companion object { fun ofFirst(sign: String) = when (sign) { "A" -> ROCK "B" -> PAPER "C" -> SCISSORS else -> throw RuntimeException("not happening") } fun ofSecond(sign: String) = when (sign) { "X" -> ROCK "Y" -> PAPER "Z" -> SCISSORS else -> throw RuntimeException("not happening") } } private fun loses(against: Sign) = this == against.winsAgainst() fun winsAgainst() = when (this) { ROCK -> SCISSORS PAPER -> ROCK SCISSORS -> PAPER } fun loseAgainst() = when (this) { ROCK -> PAPER PAPER -> SCISSORS SCISSORS -> ROCK } fun versus(against: Sign) = if (this == against) { 3 } else if (this.loses(against)) { 6 } else { 0 } }
0
Kotlin
0
0
f1094ba3ead165adaadce6cffd5f3e78d6505724
2,152
adventofcode-2022
MIT License
src/nativeMain/kotlin/com.qiaoyuang.algorithm/round1/Questions7.kt
qiaoyuang
100,944,213
false
{"Kotlin": 338134}
package com.qiaoyuang.algorithm.round1 import com.qiaoyuang.algorithm.round0.BinaryTreeNode fun test7() { fun printlnResults(preOrder: IntArray, inOrder: IntArray) { val tree = rebuildBinaryTree(preOrder, inOrder) val preOrderList = preOrder.toList() val inOrderList = inOrder.toList() val assert = tree.preOrderList() == preOrderList && tree.inOrderList() == inOrderList println("The pre-order is $preOrderList, the in-order is $inOrderList, rebuild binary tree is $assert") } val preOrder0 = intArrayOf(1, 2, 4, 7, 3, 5, 6, 8) val inOrder0 = intArrayOf(4, 7, 2, 1, 5, 3, 8, 6) printlnResults(preOrder0, inOrder0) printlnResults(intArrayOf(1), intArrayOf(1)) val preOrder1 = intArrayOf(1, 2, 3, 4, 5, 6, 7, 8) val inOrder1 = intArrayOf(8, 7, 6, 5, 4, 3, 2, 1) printlnResults(preOrder1, inOrder1) val preOrder2 = intArrayOf(1, 2, 3, 4, 5, 6, 7, 8) val inOrder2 = intArrayOf(1, 2, 3, 4, 5, 6, 7, 8) printlnResults(preOrder2, inOrder2) } /** * Questions 7: Input a Binary Tree's pre-order and in-order results, please rebuild this Binary Tree. */ fun rebuildBinaryTree(preOrder: IntArray, inOrder: IntArray): BinaryTreeNode<Int> { if (preOrder.isEmpty() || inOrder.isEmpty()) throw IllegalArgumentException("The pre-order and in-order cannot be empty IntArray") if (preOrder.size != inOrder.size) throw IllegalArgumentException("The pre-order's length must equals in-order's length") val rootElement = preOrder.first() return BinaryTreeNode(rootElement).apply { val inIndexOfRoot = inOrder.indexOf(rootElement) if (inIndexOfRoot >= 0) { left = rebuildBinaryTree(preOrder, 1, inIndexOfRoot, inOrder, 0, inIndexOfRoot - 1) right = rebuildBinaryTree(preOrder, inIndexOfRoot + 1, preOrder.lastIndex, inOrder, inIndexOfRoot + 1, inOrder.lastIndex) } else throw IllegalArgumentException("The pre-order and in-order not matching") } } private fun rebuildBinaryTree( preOrder: IntArray, preStart: Int, preEnd: Int, inOrder: IntArray, inStart: Int, inEnd: Int, ): BinaryTreeNode<Int>? { if (preEnd >= preOrder.size || inEnd >= inOrder.size || preStart > preEnd || inStart > inEnd || preStart < 0 || inStart < 0) return null val rootElement = preOrder[preStart] return BinaryTreeNode(rootElement).apply { val rootIndexInInOrder = inOrder.indexOf(rootElement) val countOfLeftNodes = rootIndexInInOrder - inStart left = rebuildBinaryTree( preOrder, preStart + 1, preStart + countOfLeftNodes, inOrder, inStart, rootIndexInInOrder - 1, ) right = rebuildBinaryTree( preOrder, preStart + countOfLeftNodes + 1, preEnd, inOrder, rootIndexInInOrder + 1, inEnd, ) } }
0
Kotlin
3
6
66d94b4a8fa307020d515d4d5d54a77c0bab6c4f
2,864
Algorithm
Apache License 2.0
src/Day01.kt
AndreiShilov
572,661,317
false
{"Kotlin": 25181}
fun main() { fun getCalMap(input: List<String>): MutableMap<Int, Int> { val calMap = mutableMapOf<Int, Int>() var counter = 0 var acc = 0 input.forEach { it -> if (it.isBlank()) { calMap[counter] = acc counter++ acc = 0 } else { acc += it.toInt() } } if (acc != 0) calMap[counter] = acc return calMap } fun getCalMap2(input: List<String>): List<Int> { val list = mutableListOf<Int>() var acc = 0 for (line in input) { if (line.isNotBlank()) { acc += line.toInt(); continue } list += acc acc = 0 } if (acc != 0) list += acc return list } fun getCalMap3(input: List<String>): List<Int> { return input.joinToString(",").split(",,").map { it.split(",").sumOf { cal -> cal.toInt() } } } fun part1(input: List<String>): Int { return getCalMap3(input).max() } fun part2(input: List<String>): Int { return getCalMap3(input) .sortedDescending() .subList(0, 3) .sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") check(part1(testInput) == 24000) check(part2(testInput) == 45000) val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
852b38ab236ddf0b40a531f7e0cdb402450ffb9a
1,519
aoc-2022
Apache License 2.0
src/day23/Code.kt
fcolasuonno
572,734,674
false
{"Kotlin": 63451, "Dockerfile": 1340}
package day23 import Coord import day06.main import neighbours import readInput fun main() { val directionCheck = listOf<(Set<Coord>, Coord) -> Coord?>( { s, c -> c.copy(second = c.second - 1) .takeIf { listOf(it, it.copy(first = it.first - 1), it.copy(first = it.first + 1)) .all { it !in s } } }, { s, c -> c.copy(second = c.second + 1) .takeIf { listOf(it, it.copy(first = it.first - 1), it.copy(first = it.first + 1)) .all { it !in s } } }, { s, c -> c.copy(first = c.first - 1) .takeIf { listOf(it, it.copy(second = it.second - 1), it.copy(second = it.second + 1)) .all { it !in s } } }, { s, c -> c.copy(first = c.first + 1) .takeIf { listOf(it, it.copy(second = it.second - 1), it.copy(second = it.second + 1)) .all { it !in s } } } ) fun parse(input: List<String>) = input.flatMapIndexed { y, s -> s.mapIndexedNotNull { x, c -> c.takeIf { it == '#' }?.let { Coord(x, y) } } }.toSet() fun Set<Coord>.toSequence() = generateSequence(this to 0) { (elves, firstConsidered) -> elves.groupBy(keySelector = { elf -> (firstConsidered until (firstConsidered + 4)) .firstNotNullOfOrNull { directionCheck[it % 4](elves, elf) } ?.takeIf { elf.neighbours.any { it in elves } } ?: elf }).flatMap { (newCoord, competingElves) -> if (competingElves.size == 1) listOf(newCoord) else competingElves } .toSet().takeIf { it != elves } ?.let { it to firstConsidered + 1 } } fun part1(input: Set<Coord>) = input.toSequence().drop(10).first().first .let { (it.maxOf(Coord::first) - it.minOf(Coord::first) + 1) * (it.maxOf(Coord::second) - it.minOf(Coord::second) + 1) - it.size } fun part2(input: Set<Coord>) = input.toSequence().count() val input = parse(readInput(::main.javaClass.packageName)) println("Part1=\n" + part1(input)) println("Part2=\n" + part2(input)) }
0
Kotlin
0
0
9cb653bd6a5abb214a9310f7cac3d0a5a478a71a
2,379
AOC2022
Apache License 2.0
src/Day01.kt
hiteshchalise
572,795,242
false
{"Kotlin": 10694}
fun main() { fun part1(input: List<String>): Int { val caloriesList = input.map { if (it.isNotEmpty()) it.toInt() else 0 } val listOfTotalCalories = mutableListOf<Int>() caloriesList.reduce { acc: Int, calories: Int -> if (calories > 0) acc + calories else { listOfTotalCalories.add(acc) 0 } } return listOfTotalCalories.max() } fun part2(input: List<String>): Int { val caloriesList = input.map { if (it.isNotEmpty()) it.toInt() else 0 } val listOfTotalCalories = mutableListOf<Int>() caloriesList.reduce { acc: Int, calories: Int -> if (calories > 0) acc + calories else { listOfTotalCalories.add(acc) 0 } } return listOfTotalCalories.sortedDescending().subList(0, 3).sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") check(part1(testInput) == 24000) val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
e4d66d8d1f686570355b63fce29c0ecae7a3e915
1,156
aoc-2022-kotlin
Apache License 2.0
src/Day19.kt
EdoFanuel
575,561,680
false
{"Kotlin": 80963}
class Day19 { private val pattern = "Blueprint (\\d+): Each ore robot costs (\\d+) ore. Each clay robot costs (\\d+) ore. Each obsidian robot costs (\\d+) ore and (\\d+) clay. Each geode robot costs (\\d+) ore and (\\d+) obsidian." private val maxCapacity = 100 data class Material(val ore: Int, val clay: Int, val obsidian: Int, val geode: Int) { operator fun plus(other: Material): Material = Material( this.ore + other.ore, this.clay + other.clay, this.obsidian + other.obsidian, this.geode + other.geode ) operator fun unaryMinus(): Material = Material(-this.ore, -this.clay, -this.obsidian, -this.geode) operator fun minus(other: Material): Material = this + -other fun gte(other: Material) = this.ore >= other.ore && this.clay >= other.clay && this.obsidian >= other.obsidian && this.geode >= other.geode fun lte(other: Material) = this.ore <= other.ore && this.clay <= other.clay && this.obsidian <= other.obsidian && this.geode <= other.geode } data class Robot(val input: Material, val output: Material) data class State(val available: Material, val production: Material, val time: Int) fun traverse(state: State, blueprint: Map<String, Robot>, cache: MutableMap<State, Int> = mutableMapOf()): Int { if (state.time == 0) return state.available.geode if (state !in cache) { cache[state] = evaluate(blueprint, state).maxOf { afterBuild -> val afterProduce = afterBuild.copy( time = afterBuild.time - 1, available = afterBuild.available + state.production, production = afterBuild.production ) traverse(afterProduce, blueprint, cache) } } return cache[state]!! } private fun evaluate(blueprint: Map<String, Robot>, state: State): List<State> { val current = state.available val prev = state.available - state.production // We consider building a miner only if we couldn't build it in the previous step if (!canBuild(blueprint["geode"]!!, prev) && canBuild(blueprint["geode"]!!, current)) { return listOf(buildRobot(state, blueprint["geode"]!!)) } val postConstructStates = mutableListOf<State>() for (type in listOf("obsidian", "clay", "ore")) { if (!canBuild(blueprint[type]!!, prev) && canBuild(blueprint[type]!!, current)) { postConstructStates += buildRobot(state, blueprint[type]!!) } } postConstructStates += state // do nothing return postConstructStates } private fun canBuild(robot: Robot, material: Material) = material.gte(robot.input) private fun buildRobot(state: State, robot: Robot) = state.copy( time = state.time, available = state.available - robot.input, production = state.production + robot.output ) fun readInput(input: String): Pair<Int, Map<String, Robot>> { val matches = input.match(pattern)!!.groupValues val id = matches[1].toInt() val oreRobot = Robot( Material(matches[2].toInt(), 0, 0, 0), Material(1, 0, 0, 0) ) val clayRobot = Robot( Material(matches[3].toInt(), 0, 0, 0), Material(0, 1, 0, 0) ) val obsidianRobot = Robot( Material(matches[4].toInt(), matches[5].toInt(), 0, 0), Material(0, 0, 1, 0) ) val geodeRobot = Robot( Material(matches[6].toInt(), 0, matches[7].toInt(), 0), Material(0, 0, 0, 1) ) return id to mapOf( "ore" to oreRobot, "clay" to clayRobot, "obsidian" to obsidianRobot, "geode" to geodeRobot ) } } fun main() { val day = Day19() fun part1(input: List<String>): Long { var result = 0L for (line in input) { val (id, robots) = day.readInput(line) val maxGeode = day.traverse( Day19.State( Day19.Material(0, 0, 0, 0), Day19.Material(1, 0, 0, 0), 24 ), robots ) println("$id, $maxGeode") result += id * maxGeode } return result } fun part2(input: List<String>): Long { var result = 1L for (line in if (input.size >= 3) input.subList(0, 3) else input) { val (id, robots) = day.readInput(line) val maxGeode = day.traverse( Day19.State( Day19.Material(0, 0, 0, 0), Day19.Material(1, 0, 0, 0), 32 ), robots ) println("$id, $maxGeode") result *= maxGeode } return result } val test = readInput("Day19_test") println("=== Part 1 (test) ===") println(part1(test)) println("=== Part 2 (test) ===") println(part2(test)) val input = readInput("Day19") println("=== Part 1 (puzzle) ===") println(part1(input)) println("=== Part 2 (puzzle) ===") println(part2(input)) }
0
Kotlin
0
0
46a776181e5c9ade0b5e88aa3c918f29b1659b4c
5,340
Advent-Of-Code-2022
Apache License 2.0
src/main/kotlin/biz/koziolek/adventofcode/year2021/day02/day2.kt
pkoziol
434,913,366
false
{"Kotlin": 715025, "Shell": 1892}
package biz.koziolek.adventofcode.year2021.day02 import biz.koziolek.adventofcode.findInput fun main() { val inputFile = findInput(object {}) val position = calculatePosition(inputFile.bufferedReader().lineSequence()) println("Position: $position") println("Answer 1: ${position.horizontal * position.depth}") val positionWithAim = calculatePositionWithAim(inputFile.bufferedReader().lineSequence()) println("Position with aim: $positionWithAim") println("Answer 2: ${positionWithAim.horizontal * positionWithAim.depth}") } data class Position(val horizontal: Int, val depth: Int) data class PositionAndAim(val position: Position, val aim: Int) data class Command(val direction: String, val value: Int) fun calculatePosition(lines: Sequence<String>): Position = parseCommands(lines) .fold(Position(0, 0)) { acc, command -> when (command.direction) { "forward" -> acc.copy(horizontal = acc.horizontal + command.value) "down" -> acc.copy(depth = acc.depth + command.value) "up" -> acc.copy(depth = acc.depth - command.value) else -> throw IllegalArgumentException("Unknown direction: ${command.direction}") } } fun calculatePositionWithAim(lines: Sequence<String>): Position = parseCommands(lines) .fold(PositionAndAim(Position(0, 0), 0)) { acc, command -> when (command.direction) { "forward" -> acc.copy(position = acc.position.copy( horizontal = acc.position.horizontal + command.value, depth = acc.position.depth + acc.aim * command.value )) "down" -> acc.copy(aim = acc.aim + command.value) "up" -> acc.copy(aim = acc.aim - command.value) else -> throw IllegalArgumentException("Unknown direction: ${command.direction}") } } .position private fun parseCommands(lines: Sequence<String>) = lines .map { it.split(" ", limit = 2) } .filter { it.size == 2 } .map { Command(direction = it[0], value = it[1].toInt()) }
0
Kotlin
0
0
1b1c6971bf45b89fd76bbcc503444d0d86617e95
2,333
advent-of-code
MIT License
src/main/kotlin/dev/bogwalk/batch2/Problem29.kt
bog-walk
381,459,475
false
null
package dev.bogwalk.batch2 import java.math.BigInteger import kotlin.math.pow /** * Problem 29: Distinct Powers * * https://projecteuler.net/problem=29 * * Goal: Count the distinct terms in a sequence generated by a^b when 2 <= a <= N and 2 <= b <= N. * * Constraints: 2 <= N <= 1e5 * * e.g.: N = 4 * terms = {4, 8, 16}, {9, 27, 81}, {16, 64, 256} * count = 8 */ class DistinctPowers { /** * SPEED (WORSE) 10.10s for N = 1e3 */ fun distinctPowersBrute(n: Int): Long { val distinct = mutableSetOf<BigInteger>() for (a in 2..n) { for (b in 2..n) { val power = a.toBigInteger().pow(b) distinct.add(power) } } return distinct.size.toLong() } /** * Solution finds the amount of duplicate terms produced by a^b and subtracts that from the * maximum integer combinations, (n - 1)^2. No need to calculate base 2 exponents larger than * 16 since 2^17 > 1e5 (upper constraint). * * SPEED (BETTER) 8.6e5ns for N = 1e3 */ fun distinctPowers(n: Int): Long { val maxExp = minOf(16, n - 1) val minExponents = IntArray(n * maxExp - 1) for (i in 1..maxExp) { for (j in 2..n) { val index = i * j - 2 if (minExponents[index] == 0) { minExponents[index] = i } } } val bases = IntArray(n - 1) var duplicates = 0L val exponentDuplicates = LongArray(maxExp - 1) for (num in 2..n) { val parent = bases[num - 2] if (parent == 0) { var power: Long = 1L * num * num while (power <= n) { bases[power.toInt() - 2] = num power *= num } } else { var exponent = 0 var reduce = num while (reduce > 1) { reduce /= parent exponent++ } if (exponentDuplicates[exponent - 2] != 0L) { duplicates += exponentDuplicates[exponent - 2] } else { var dupes = 0L for (y in 2..n) { if (minExponents[y * exponent - 2] < exponent) { dupes++ } } exponentDuplicates[exponent - 2] = dupes duplicates += dupes } } } return (1.0 * n - 1).pow(2).toLong() - duplicates } }
0
Kotlin
0
0
62b33367e3d1e15f7ea872d151c3512f8c606ce7
2,652
project-euler-kotlin
MIT License
kotlin/src/main/kotlin/dev/mikeburgess/euler/problems/Problem012.kt
mddburgess
261,028,925
false
null
package dev.mikeburgess.euler.problems import dev.mikeburgess.euler.sequences.PrimeSequence import dev.mikeburgess.euler.sequences.triangleNumbers import kotlin.math.sqrt /** * Problem 12 * * The sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle * number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms would be: * * 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ... * * Let us list the factors of the first seven triangle numbers: * * 1: 1 * 3: 1,3 * 6: 1,2,3,6 * 10: 1,2,5,10 * 15: 1,3,5,15 * 21: 1,3,7,21 * 28: 1,2,4,7,14,28 * * We can see that 28 is the first triangle number to have over five divisors. * * What is the value of the first triangle number to have over five hundred divisors? */ class Problem012 : Problem { private val primes = PrimeSequence() private fun Long.countDivisors(): Int = when (this) { 1L -> 1 2L, 3L -> 2 else -> primes.takeWhile { it <= sqrt(this.toDouble()) } .map { this.countFactors(it) + 1 } .reduce { a, b -> a * b } } private fun Long.countFactors(prime: Long): Int { var count = 0 var temp = this while (temp % prime == 0L) { temp /= prime count++ } return count } override fun solve(): Long = triangleNumbers() .first { it.countDivisors() > 500 } }
0
Kotlin
0
0
86518be1ac8bde25afcaf82ba5984b81589b7bc9
1,453
project-euler
MIT License
src/main/kotlin/com/ginsberg/advent2018/Day23.kt
tginsberg
155,878,142
false
null
/* * Copyright (c) 2018 by <NAME> */ /** * Advent of Code 2018, Day 23 - Experimental Emergency Teleportation * * Problem Description: http://adventofcode.com/2018/day/23 * Blog Post/Commentary: https://todd.ginsberg.com/post/advent-of-code/2018/day23/ */ package com.ginsberg.advent2018 import kotlin.math.abs class Day23(rawInput: List<String>) { private val swarm: List<Nanobot> = rawInput.map { Nanobot.of(it) } fun solvePart1(): Int { val fattestBot = swarm.maxBy { it.radius }!! return swarm.count { fattestBot.inRange(it) } } fun solvePart2(): Int { val neighbors: Map<Nanobot, Set<Nanobot>> = swarm.map { bot -> Pair(bot, swarm.filterNot { it == bot }.filter { bot.withinRangeOfSharedPoint(it) }.toSet()) }.toMap() val clique: Set<Nanobot> = BronKerbosch(neighbors).largestClique() return clique.map { it.location.distanceTo(Point3d.origin) - it.radius }.max()!! } private data class Nanobot(val location: Point3d, val radius: Int) { fun inRange(other: Nanobot): Boolean = location.distanceTo(other.location) <= radius fun withinRangeOfSharedPoint(other: Nanobot): Boolean = location.distanceTo(other.location) <= radius + other.radius companion object { private val digitsRegex = """^pos=<(-?\d+),(-?\d+),(-?\d+)>, r=(\d+)$""".toRegex() fun of(input: String): Nanobot = digitsRegex.find(input)?.let { val (x, y, z, r) = it.destructured Nanobot(Point3d(x.toInt(), y.toInt(), z.toInt()), r.toInt()) } ?: throw IllegalArgumentException("Cannot parse $input") } } private data class Point3d(val x: Int, val y: Int, val z: Int) { fun distanceTo(other: Point3d): Int = abs(x - other.x) + abs(y - other.y) + abs(z - other.z) companion object { val origin = Point3d(0, 0, 0) } } }
0
Kotlin
1
18
f33ff59cff3d5895ee8c4de8b9e2f470647af714
2,012
advent-2018-kotlin
MIT License
2023/src/day03/Day03.kt
scrubskip
160,313,272
false
{"Kotlin": 198319, "Python": 114888, "Dart": 86314}
package day03 import java.io.File fun main() { val input = File("src/day03/Day03.txt").readLines() val schematic = Schematic(input) println(schematic.getPartNumbers().sum()) println(schematic.getGearRatios().sum()) } typealias Coordinate = Pair<Int, Int> data class Rectangle(val top: Int, val left: Int, val bottom: Int, val right: Int, val value: Int) { fun touches(coordinate: Coordinate): Boolean { return coordinate.first in top - 1..bottom + 1 && coordinate.second in left - 1..right + 1 } } val NUMBER_REGEX = Regex("(\\d+)") val SYMBOL_REGEX = Regex("[^\\d\\.]") class Schematic(entries: List<String>) { private val symbolMap: MutableMap<Coordinate, String> = mutableMapOf() private val numberMap: MutableMap<Coordinate, Rectangle> = mutableMapOf() private var maxNumberLength = 0 init { entries.forEachIndexed { rowIndex: Int, row: String -> NUMBER_REGEX.findAll(row).forEach { //println("adding number ${it.value.toInt()}") numberMap[Coordinate(rowIndex, it.range.first)] = Rectangle( rowIndex, it.range.first, rowIndex, it.range.last, it.value.toInt() ) if (it.value.length > maxNumberLength) { maxNumberLength = it.value.length } } SYMBOL_REGEX.findAll(row).forEach { // println("adding symbol ${it.value}") symbolMap[Coordinate(rowIndex, it.range.first)] = it.value } } } fun getPartNumbers(): List<Int> { return numberMap.entries.filter { isTouchingSymbol(it.value.toString(), it.key) }.map { it.value.value } } fun isTouchingSymbol(numberString: String, coordinate: Coordinate): Boolean { for (row in coordinate.first - 1..coordinate.first + 1) { for (col in (coordinate.second - 1..coordinate.second + numberString.length)) { if (symbolMap.containsKey(Coordinate(row, col))) { return true } } } return false } fun getGearRatios(): List<Int> { // First go through the symbol map and find "*" val gearRatios = mutableListOf<Int>() symbolMap.entries.filter { it.value == "*" }.forEach { // Each gear has 2 numbers touching it val foundNumber = mutableListOf<Int>() for (row in it.key.first - 1..it.key.first + 1) { for (col in it.key.second - maxNumberLength - 1..it.key.second + 1) { if (numberMap.containsKey(Coordinate(row, col))) { // Check that the number is touching val rect = numberMap[Coordinate(row, col)] if (rect!!.touches(it.key)) { foundNumber.add(rect.value) } } } } if (foundNumber.size == 2) { gearRatios.add(foundNumber[0] * foundNumber[1]) } } return gearRatios } }
0
Kotlin
0
0
a5b7f69b43ad02b9356d19c15ce478866e6c38a1
3,190
adventofcode
Apache License 2.0
src/main/kotlin/kt/kotlinalgs/app/graph/PathsWithSum.ws.kts
sjaindl
384,471,324
false
null
package kt.kotlinalgs.app.graph import java.util.* /* Achtung: Immer map etc. zurücksetzen!! BC: from root, cur element .. test cases! */ Solution().test() /* 10 15,5 17,7,2 18,8,3,1 alt.. store complete sum in set<Int> 10, 15, 17, 18 .. check at each node if (set.contains(runningSum - k)) -> incr. count sums = Map number to #number count start at root rec pathsWithSum(root: Node<T>, sum: Int, sums: MutableMap<Int, Int>, int runningSum) ctr = 0 sums.addOrIncrease(runningSum + root.value) // start new path or continue path(s) check if value == sum -> ctr++ if (set.contains(node.value - k)) -> ctr += sums[..] (count) return ctr + pathsWithSum(root.left,..) + pathsWithSum(root.right,..) + 1,-1, 8 .. 1,0,8 -> 2 1,-2,8 .. 1,-1,7 -> 1 */ class Solution { fun test() { println("test") val root = Node(10) root.left = Node(5) root.left?.left = Node(3) root.left?.left?.left = Node(3) root.left?.left?.right = Node(-2) root.left?.right = Node(1) root.left?.right?.right = Node(2) root.right = Node(-3) root.right?.right = Node(11) val tree = BinarySearchTree() println(tree.pathsWithSum(root, 3)) println(tree.pathsWithSum(root, 4)) println(tree.pathsWithSum(root, 8)) println(tree.pathsWithSum(root, 10)) } } data class Node( val value: Int, var left: Node? = null, var right: Node? = null ) class BinarySearchTree { fun pathsWithSum(root: Node, sum: Int): Int { val sums: MutableMap<Int, Int> = mutableMapOf() return pathsWithSumRec(root, sum, sums, 0) } private fun pathsWithSumRec( root: Node?, // 3 targetSum: Int, // 8 sums: MutableMap<Int, Int>, // [10:1, 15:1, 18:1] runningSum: Int) : Int { // 15 if (root == null) return 0 /* 1,-1, 8 RS .. 1,0,8 -> 2 1,-2,8 RS .. 1,-1,7 -> 1 */ val newSum = runningSum + root.value val searchedSum = newSum - targetSum var paths = if(newSum == targetSum) 1 else 0 sums[searchedSum]?.let { count -> // covers also case if (root.value == targetSum) /* e.g. with targetSum == 8 at index 2: 1,-2,8 RS .. 1,-1,7 -> 1 rs - ts = 7 - 8 = -1 */ paths += count } addOrIncrease(sums, newSum) paths += pathsWithSumRec(root.left, targetSum, sums, newSum) paths += pathsWithSumRec(root.right, targetSum, sums, newSum) // Achtung: Immer zurücksetzen!! removeOrDecrease(sums, newSum) return paths } private fun addOrIncrease(sums: MutableMap<Int, Int>, value: Int) { val oldCount = sums.getOrDefault(value, 0) sums[value] = oldCount + 1 } private fun removeOrDecrease(sums: MutableMap<Int, Int>, value: Int) { val oldCount = sums.getOrDefault(value, 0) if (oldCount > 1) sums[value] = oldCount - 1 else sums.remove(value) } }
0
Java
0
0
e7ae2fcd1ce8dffabecfedb893cb04ccd9bf8ba0
3,132
KotlinAlgs
MIT License
src/main/kotlin/day19.kt
tobiasae
434,034,540
false
{"Kotlin": 72901}
class Day19 : Solvable("19") { val cache = HashMap<List<String>, Pair<Set<Point>, List<Point>>>() override fun solveA(input: List<String>): String { val result = getPoints(input) cache[input] = result return result.first.size.toString() } override fun solveB(input: List<String>): String { val scannerPositions = cache[input]?.second ?: getPoints(input).second var max = Int.MIN_VALUE for (i in scannerPositions.indices) { for (j in i + 1 until scannerPositions.size) { val diff = scannerPositions[i] - scannerPositions[j] val distance = Math.abs(diff.x) + Math.abs(diff.y) + Math.abs(diff.z) if (distance > max) max = distance } } return max.toString() } private fun getPoints(input: List<String>): Pair<Set<Point>, List<Point>> { val scanners = getScannerViews(input) val first = scanners.first() val otherScanners = scanners.drop(1).toMutableList() val scannerPositions = mutableListOf<Point>() while (otherScanners.isNotEmpty()) { val other = otherScanners.removeAt(0) val (points, scannerPosition) = first.accumulatePoints(other) if (points.size > 0) { first.points.addAll(points) scannerPositions.add(scannerPosition) } else otherScanners.add(other) } return Pair(first.points, scannerPositions) } private fun getScannerViews(input: List<String>): List<Scanner> { return mutableListOf<Scanner>().apply { input.forEach { if (it.startsWith("---")) this.add(Scanner(mutableSetOf())) else if (it.length > 1) { val (x, y, z) = it.split(",").map(String::toInt) this.last().points.add(Point(x, y, z)) } } } } } data class Scanner(val points: MutableSet<Point>) { fun accumulatePoints(other: Scanner): Pair<Set<Point>, Point> { for (r in 0..23) { val rotated = other.getRotation(r) points.forEach { p -> rotated.points.forEach { o -> val diff = p - o val translated = rotated.points.map { it + diff } if (translated.intersect(points).size >= 12) { return Pair(points.union(translated), diff) } } } } return Pair(setOf(), Point(0, 0, 0)) } fun getRotation(r: Int): Scanner = Scanner(points.map { it.getRotation(r) }.toMutableSet()) } data class Point(val x: Int, val y: Int, val z: Int) { fun getRotation(r: Int): Point = when (r) { 0 -> this 1 -> Point(-y, x, z) 2 -> Point(-x, -y, z) 3 -> Point(y, -x, z) 4 -> Point(-z, y, x) 5 -> Point(-y, -z, x) 6 -> Point(z, -y, x) 7 -> Point(y, z, x) 8 -> Point(z, y, -x) 9 -> Point(-y, z, -x) 10 -> Point(-z, -y, -x) 11 -> Point(y, -z, -x) 12 -> Point(-x, y, -z) 13 -> Point(-y, -x, -z) 14 -> Point(x, -y, -z) 15 -> Point(y, x, -z) 16 -> Point(x, -z, y) 17 -> Point(z, x, y) 18 -> Point(-x, z, y) 19 -> Point(-z, -x, y) 20 -> Point(-x, -z, -y) 21 -> Point(z, -x, -y) 22 -> Point(x, z, -y) 23 -> Point(-z, x, -y) else -> throw Exception("Invalid rotation argument $r") } fun getAllRotations(): List<Point> = (0..23).map(this::getRotation) operator fun plus(other: Point): Point = Point(x + other.x, y + other.y, z + other.z) operator fun minus(other: Point): Point = Point(x - other.x, y - other.y, z - other.z) }
0
Kotlin
0
0
16233aa7c4820db072f35e7b08213d0bd3a5be69
4,050
AdventOfCode
Creative Commons Zero v1.0 Universal
src/Day07.kt
astrofyz
572,802,282
false
{"Kotlin": 124466}
fun main() { class Directory( var size: Int = 0, val root: Directory? = null, var listdir: MutableMap<String, Directory>? = null ){ constructor(root: Directory): this(0, root, mutableMapOf<String, Directory>()) constructor(size: Int, root: Directory): this(size, root, null) } fun Directory.addDir(name: String) { this.listdir?.set(name, Directory(this)) } fun Directory.addFile(name: String, size: Int){ this.listdir?.set(name, Directory(size, this)) this.size += size } fun part1(input: List<String>): Int { var currentDir = Directory(listdir = mutableMapOf<String, Directory>()) // init root directory val directoriesSize = mutableListOf<Int>() for (line in input.slice(1 until input.size)){ if (line.startsWith("$ cd") and !line.contains("..")){ currentDir = currentDir.listdir!![line.drop(5)]!! } else if (line.startsWith("dir ")){ currentDir.addDir(line.drop(4)) } else if (line[0].isDigit()){ currentDir.addFile(line.split(" ")[1], line.split(" ")[0].toInt()) } else if (line.startsWith("$ cd ..")){ currentDir.size = currentDir.listdir!!.values.sumOf{it.size} directoriesSize.add(currentDir.size) currentDir = currentDir.root!! } } while (currentDir.root!=null){ currentDir.size = currentDir.listdir!!.values.sumOf{it.size} directoriesSize.add(currentDir.size) currentDir = currentDir.root!! } currentDir.size = currentDir.listdir!!.values.sumOf{it.size} directoriesSize.add(currentDir.size) println("part 1 : ${directoriesSize.filter { it < 100000 }.sum()}") val needToFree: Int = 30000000 - (70000000 - directoriesSize.max()) println("part 2: ${directoriesSize.filter { it > needToFree }.min()}") return 0 } // test if implementation meets criteria from the description, like: val testInput = readInput("Day07_test") part1(testInput) val input = readInput("Day07") part1(input) }
0
Kotlin
0
0
a0bc190b391585ce3bb6fe2ba092fa1f437491a6
2,243
aoc22
Apache License 2.0
grind-75-kotlin/src/main/kotlin/LongestPalindrome.kt
Codextor
484,602,390
false
{"Kotlin": 27206}
/** * Given a string s which consists of lowercase or uppercase letters, * return the length of the longest palindrome that can be built with those letters. * * Letters are case sensitive, for example, "Aa" is not considered a palindrome here. * * * * Example 1: * * Input: s = "abccccdd" * Output: 7 * Explanation: One longest palindrome that can be built is "dccaccd", whose length is 7. * Example 2: * * Input: s = "a" * Output: 1 * Explanation: The longest palindrome that can be built is "a", whose length is 1. * * * Constraints: * * 1 <= s.length <= 2000 * s consists of lowercase and/or uppercase English letters only. * @see <a href="https://leetcode.com/problems/longest-palindrome/">LeetCode</a> */ fun longestPalindrome(s: String): Int { val memoryMap = mutableMapOf<Char, Int>() s.forEach { character -> memoryMap.put(character, 1 + memoryMap.getOrDefault(character, 0)) } var longestPalindromeLength = 0 var middleElementEncountered = false memoryMap.values.forEach { frequency -> if (frequency.rem(2) == 0) { longestPalindromeLength += frequency } else { if (middleElementEncountered == false) { longestPalindromeLength += frequency middleElementEncountered = true } else { longestPalindromeLength += frequency - 1 } } } return longestPalindromeLength }
0
Kotlin
0
0
87aa60c2bf5f6a672de5a9e6800452321172b289
1,454
grind-75
Apache License 2.0
src/main/kotlin/dev/tasso/adventofcode/_2021/day03/Day03.kt
AndrewTasso
433,656,563
false
{"Kotlin": 75030}
package dev.tasso.adventofcode._2021.day03 import dev.tasso.adventofcode.Solution class Day03 : Solution<Int> { override fun part1(input: List<String>): Int { var gammaString = "" var epsilonString = "" for(i in 0 until input[0].length) { val (zeros, ones) = input.map{c -> c[i]}.partition {c -> c == '0' } gammaString += if (zeros.size > ones.size) "0" else "1" epsilonString += if (zeros.size < ones.size) "0" else "1" } val gamma = Integer.parseInt(gammaString, 2) val epsilon = Integer.parseInt(epsilonString, 2) return gamma * epsilon } override fun part2(input: List<String>): Int { var oxygenGeneratorValues = input.toList() var co2ScrubberValues = input.toList() for(i in 0 until oxygenGeneratorValues[0].length) { oxygenGeneratorValues = if (oxygenGeneratorValues.count { s -> s[i] == '1' } >= oxygenGeneratorValues.count { s -> s[i] == '0' }) { oxygenGeneratorValues.filter { s -> s[i] == '1' } } else { oxygenGeneratorValues.filter { s -> s[i] == '0' } } if (oxygenGeneratorValues.size == 1) break } for(i in 0 until co2ScrubberValues[0].length) { co2ScrubberValues = if (co2ScrubberValues.count { s -> s[i] == '0' } <= co2ScrubberValues.count { s -> s[i] == '1' }) { co2ScrubberValues.filter { s -> s[i] == '0' } } else { co2ScrubberValues.filter { s -> s[i] == '1' } } if (co2ScrubberValues.size == 1) break } val oxygenGeneratorRating = Integer.parseInt(oxygenGeneratorValues[0], 2) val co2ScrubberRating = Integer.parseInt(co2ScrubberValues[0], 2) return oxygenGeneratorRating * co2ScrubberRating } }
0
Kotlin
0
0
daee918ba3df94dc2a3d6dd55a69366363b4d46c
1,886
advent-of-code
MIT License
src/main/kotlin/se/brainleech/adventofcode/aoc2015/Aoc2015Day02.kt
fwangel
435,571,075
false
{"Kotlin": 150622}
package se.brainleech.adventofcode.aoc2015 import se.brainleech.adventofcode.compute import se.brainleech.adventofcode.readText import se.brainleech.adventofcode.verify class Aoc2015Day02 { data class Box(val l: Long, val w: Long, val h: Long) { private fun surfaceArea(): Long = 0 .plus(2.times(l).times(w)) .plus(2.times(w).times(h)) .plus(2.times(h).times(l)) private fun smallestArea(): Long = minOf( l.times(w), w.times(h), h.times(l) ) fun wrappingPaperArea(): Long = surfaceArea().plus(smallestArea()) private fun ribbonBowLength() = 1 .times(l) .times(w) .times(h) private fun shortestDistance(): Long { val first = minOf(l, w, h) val second = listOf(l, w, h).sorted().drop(1).first() return 0.plus(first).plus(first).plus(second).plus(second) } fun ribbonLength(): Long { return shortestDistance().plus(ribbonBowLength()) } } private fun String.asBox(): Box { val (l, w, h) = this.split("x").map { it.toLong() } return Box(l, w, h) } fun part1(input: String): Long { return input.split("\n") .sumOf { it.asBox().wrappingPaperArea() } } fun part2(input: String): Long { return input.split("\n") .sumOf { it.asBox().ribbonLength() } } } fun main() { val solver = Aoc2015Day02() val prefix = "aoc2015/aoc2015day02" val testData = readText("$prefix.test.txt") val realData = readText("$prefix.real.txt") verify(101L, solver.part1(testData)) compute({ solver.part1(realData) }, "$prefix.part1 = ") verify(48L, solver.part2(testData)) compute({ solver.part2(realData) }, "$prefix.part2 = ") }
0
Kotlin
0
0
0bba96129354c124aa15e9041f7b5ad68adc662b
1,859
adventofcode
MIT License