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/day24/day.kt
LostMekka
574,697,945
false
{"Kotlin": 92218}
package day24 import util.Direction2NonDiagonal import util.Direction2NonDiagonal.* import util.PathFindingMove import util.PathFindingState import util.Point import util.Rect import util.boundingRect import util.findPath import util.readInput import util.shouldBe fun main() { val testInput = readInput(Input::class, testInput = true).parseInput() testInput.part1() shouldBe 18 testInput.part2() shouldBe 54 val input = readInput(Input::class).parseInput() println("output for part1: ${input.part1()}") println("output for part2: ${input.part2()}") } private class Input( val blizzards: Map<Point, Direction2NonDiagonal>, val bounds: Rect, ) { val start = Point(0, -1) val end = Point(bounds.maxX, bounds.maxY + 1) } private fun <T> List<T>.shrunkBy(border: Int) = subList(border, size - border) private fun List<String>.parseInput(): Input { val obstacles = buildMap { for ((y, line) in this@parseInput.shrunkBy(1).withIndex()) { for ((x, char) in line.trim('#').withIndex()) { when (char) { '>' -> put(Point(x, y), Right) '^' -> put(Point(x, y), Up) '<' -> put(Point(x, y), Left) 'v' -> put(Point(x, y), Down) } } } } val bounds = obstacles.keys.boundingRect() return Input(obstacles, bounds) } private fun Input.create3dSearchSpace(): List<Set<Point>> { val space = List(bounds.size().toInt()) { bounds.toMutableSet().apply { add(start); add(end) } } for ((p, d) in blizzards) { for (t in space.indices) { space[t] -= Point((p.x + t * d.dx).mod(bounds.width), (p.y + t * d.dy).mod(bounds.height)) } } return space } private data class State( val pos: Point, val t: Int, val searchSpace: List<Set<Point>>, val target: Point, ) : PathFindingState<State> { override fun nextMoves() = sequence { val nextT = t + 1 val nextSlice = searchSpace[nextT % searchSpace.size] for (n in pos.neighbours()) if (n in nextSlice) yield(PathFindingMove(1, copy(pos = n, t = nextT))) if (pos in nextSlice) yield(PathFindingMove(1, copy(t = nextT))) } override fun estimatedCostToGo() = pos.manhattanDistanceTo(target).toLong() override fun isGoal() = pos == target override fun equals(other: Any?) = other is State && other.pos == pos && other.t == t override fun hashCode() = 31 * pos.hashCode() + t } private fun Input.part1(): Int { val space = create3dSearchSpace() val path = findPath(State(start, 0, space, end)) ?: error("no path found") return path.nodes.size - 1 } private fun Input.part2(): Int { val space = create3dSearchSpace() val path1 = findPath(State(start, 0, space, end)) ?: error("no path found") val path2 = findPath(path1.nodes.last().state.copy(target = start)) ?: error("no path found") val path3 = findPath(path2.nodes.last().state.copy(target = end)) ?: error("no path found") return path1.nodes.size + path2.nodes.size + path3.nodes.size - 3 }
0
Kotlin
0
0
58d92387825cf6b3d6b7567a9e6578684963b578
3,123
advent-of-code-2022
Apache License 2.0
kotlin/src/com/daily/algothrim/leetcode/RelativeSortArray.kt
idisfkj
291,855,545
false
null
package com.daily.algothrim.leetcode /** * 1122. 数组的相对排序 * * 给你两个数组,arr1 和 arr2, * * arr2 中的元素各不相同 * arr2 中的每个元素都出现在 arr1 中 * 对 arr1 中的元素进行排序,使 arr1 中项的相对顺序和 arr2 中的相对顺序相同。未在 arr2 中出现过的元素需要按照升序放在 arr1 的末尾。 * * 示例: * * 输入:arr1 = [2,3,1,3,2,4,6,7,9,2,19], arr2 = [2,1,4,3,9,6] * 输出:[2,2,2,1,4,3,3,9,6,7,19] * * 提示: * * arr1.length, arr2.length <= 1000 * 0 <= arr1[i], arr2[i] <= 1000 * arr2 中的元素 arr2[i] 各不相同 * arr2 中的每个元素 arr2[i] 都出现在 arr1 中 * * */ class RelativeSortArray { companion object { @JvmStatic fun main(args: Array<String>) { RelativeSortArray().solution(intArrayOf( 2, 3, 1, 3, 2, 4, 6, 7, 9, 2, 19 ), intArrayOf( 2, 1, 4, 3, 9, 6 )).forEach { println(it) } println() RelativeSortArray().solution2(intArrayOf( 2, 3, 1, 3, 2, 4, 6, 7, 9, 2, 19 ), intArrayOf( 2, 1, 4, 3, 9, 6 )).forEach { println(it) } } } // 输入:arr1 = [2,3,1,3,2,4,6,7,9,2,19], arr2 = [2,1,4,3,9,6] // 输出:[2,2,2,1,4,3,3,9,6,7,19] fun solution(arr1: IntArray, arr2: IntArray): IntArray { // 将arr2构建成散列表 val rule = hashMapOf<Int, Int>() arr2.forEachIndexed { index, i -> rule[i] = index } // 快速排序 quickSort(arr1, 0, arr1.size - 1, rule) return arr1 } private fun quickSort(a: IntArray, start: Int, end: Int, rule: Map<Int, Int>) { if (start < end) { val mid = sort(a, start, end, rule) quickSort(a, start, mid - 1, rule) quickSort(a, mid + 1, end, rule) } } private fun sort(a: IntArray, start: Int, end: Int, rule: Map<Int, Int>): Int { val pivot = a[end] val pivotIndex = rule[pivot] var n = start var m = start while (n < end) { val curIndex = rule[a[n]] if (pivotIndex != null && curIndex != null) { if (curIndex < pivotIndex) { if (n != m) { swap(a, n, m) } m++ } } else if (curIndex != null) { if (n != m) { swap(a, n, m) } m++ } else if (pivotIndex == null) { if (a[n] < pivot) { if (n != m) { swap(a, n, m) } m++ } } n++ } swap(a, m, end) return m } private fun swap(a: IntArray, i: Int, j: Int) { val temp = a[i] a[i] = a[j] a[j] = temp } /** * 计数 */ fun solution2(arr1: IntArray, arr2: IntArray): IntArray { val result = IntArray(arr1.size) // 找到最大值 var max = Int.MIN_VALUE arr1.forEach { if (max < it) max = it } // 构建计数容器 val count = IntArray(max + 1) // 开始计数 arr1.forEach { count[it] = count[it] + 1 } // 优先排序arr2中的数据 var j = 0 arr2.forEach { var i = count[it] while (i-- > 0) { result[j++] = it } count[it] = 0 } // 将排序剩余的 count.forEachIndexed { index, i -> var k = i while (k-- > 0) { result[j++] = index } } return result } }
0
Kotlin
9
59
9de2b21d3bcd41cd03f0f7dd19136db93824a0fa
3,981
daily_algorithm
Apache License 2.0
src/main/kotlin/at/mpichler/aoc/solutions/year2022/Day07.kt
mpichler94
656,873,940
false
{"Kotlin": 196457}
package at.mpichler.aoc.solutions.year2022 import at.mpichler.aoc.lib.Day import at.mpichler.aoc.lib.PartSolution open class Part7A : PartSolution() { private lateinit var commands: List<Command> internal lateinit var tree: File override fun parseInput(text: String) { val commands: MutableList<Command> = mutableListOf() for (command in text.trim().split("$ ")) { if (command.isEmpty()) { continue } if (command.startsWith("ls")) { val output = command.split("\n").drop(1).filter { it.isNotEmpty() } commands.add(Ls(output)) } else { commands.add(Cd(command.drop(3).trim())) } } commands.removeFirst() this.commands = commands.toList() } override fun config() { val root = File("/") var currentDir = root for (command in commands) { if (command is Ls) { command.apply(currentDir) } else if (command is Cd) { currentDir = command.apply(currentDir) } } tree = root } override fun compute(): Int { return sumSizes(tree) } private fun sumSizes(dir: File): Int { val dirSize = dir.getTotalSize() var size = 0 if (dirSize < 100_000 && dir.size == 0) { size += dirSize } size += dir.files.sumOf { sumSizes(it) } return size } override fun getExampleInput(): String? { return """ $ cd / $ ls dir a 14848514 b.txt 8504156 c.dat dir d $ cd a $ ls dir e 29116 f 2557 g 62596 h.lst $ cd e $ ls 584 i $ cd .. $ cd .. $ cd d $ ls 4060174 j 8033020 d.log 5626152 d.ext 7214296 k """.trimIndent() } override fun getExampleAnswer(): Int { return 95_437 } sealed class Command data class Cd(val arg: String) : Command() { fun apply(currentDir: File): File { val result = if (arg.endsWith("..")) { currentDir.parent as File } else { currentDir.getFile(arg) } return result } } data class Ls(val output: List<String>) : Command() { fun apply(dir: File) { for (line in output) { if (line.startsWith("dir")) { dir.addFile(File(line.drop(4), parent = dir)) } else { val parts = line.split(" ") dir.addFile(File(parts[1], parts[0].toInt(), dir)) } } } } data class File(val name: String, val size: Int = 0, val parent: File? = null) { val files: MutableList<File> = mutableListOf() fun addFile(file: File) { files.add(file) } fun getFile(name: String): File { return files.first { it.name == name } } fun getTotalSize(): Int { return files.sumOf { it.getTotalSize() } + size } } } class Part7B : Part7A() { override fun compute(): Int { val needed = 30_000_000 - (70_000_000 - tree.getTotalSize()) val (minSize, _) = getMinDir(tree, needed) return minSize } private fun getMinDir(dir: File, needed: Int): Pair<Int, File> { var minSize = dir.getTotalSize() var minDir = dir for (file in dir.files) { if (file.size != 0) { continue } val (childMinSize, childMinDir) = getMinDir(file, needed) if (childMinSize in (needed + 1)..minSize) { minDir = childMinDir minSize = childMinSize } } return Pair(minSize, minDir) } override fun getExampleAnswer(): Int { return 24_933_642 } } fun main() { Day(2022, 7, Part7A(), Part7B()) }
0
Kotlin
0
0
69a0748ed640cf80301d8d93f25fb23cc367819c
4,195
advent-of-code-kotlin
MIT License
src/main/kotlin/aoc07/Solution07.kt
rainer-gepardec
573,386,353
false
{"Kotlin": 13070}
package aoc07 import java.nio.file.Paths import kotlin.math.abs class Node(val parent: Node?, val name: String, val type: String, val size: Int = 0) { val children = mutableListOf<Node>() override fun toString(): String { return "$name ($type)" } } fun main() { val lines = Paths.get("src/main/resources/aoc_07.txt").toFile().useLines { it.toList() } println(solution1(lines)) println(solution2(lines)) } fun solution1(lines: List<String>): Int { return solve(lines).filter { it <= 100000 }.sum() } fun solution2(lines: List<String>): Int { val fileList = solve(lines) val maxSpace = 70000000 val installSpace = 30000000 val usedSpace = fileList.max() val freeSpace = maxSpace - usedSpace val requiredSpace = installSpace - freeSpace return fileList.filter { requiredSpace - it < 0 }.maxBy { requiredSpace - it } } fun solve(lines: List<String>): List<Int> { val shellLines = lines .filterNot { it.contains("$ ls") } .map { it.split(" ") } .map { if (it.size == 2) Pair(it[0], it[1]) else Pair(it[1], it[2]) } val rootNode = Node(null, "/", "dir") var currentNode: Node? = null for (shellLine in shellLines) { if (shellLine.first == "cd") { currentNode = if (shellLine.second == "..") { currentNode?.parent } else { if (currentNode == null) { rootNode } else { currentNode.children.add(Node(currentNode, currentNode.name + "/" + shellLine.second, "dir")) currentNode.children.last() } } } else if (shellLine.first.toIntOrNull() !== null) { currentNode?.children?.add(Node(currentNode, shellLine.second, "file", shellLine.first.toInt())) } } val sizeMap = mutableMapOf<String, Int>() calculate(rootNode, sizeMap) return sizeMap.toList().map { it.second }.sortedDescending() } fun calculate(node: Node, sizeMap: MutableMap<String, Int>): Int { return if (node.type == "dir") { val size = node.children.filter { it.type == "dir" }.sumOf { calculate(it, sizeMap) } + calcFileSize(node) sizeMap[node.name] = size; size } else { calcFileSize(node) } } fun calcFileSize(node: Node): Int { return node.children.filter { it.type == "file" }.sumOf { it.size } }
0
Kotlin
0
0
c920692d23e8c414a996e8c1f5faeee07d0f18f2
2,431
aoc2022
Apache License 2.0
src/main/kotlin/day8/Day8.kt
afTrolle
572,960,379
false
{"Kotlin": 33530}
package day8 import Day import ext.merge import ext.mergeMatrix import ext.transpose fun main() { Day8("Day08").apply { println(part1(parsedInput)) println(part2(parsedInput)) } } fun <E> List<List<E>>.forEachByRow( rowProgression: IntProgression = this.indices, colProgression: IntProgression = this.first().indices, action: (rowIndex: Int, colIndex: Int, item: E) -> Unit ) { for (rowIndex in rowProgression) { for (colIndex in colProgression) { action(rowIndex, colIndex, this[rowIndex][colIndex]) } } } fun <E> List<List<E>>.forEachByCol( colProgression: IntProgression = this.first().indices, rowProgression: IntProgression = this.indices, action: (rowIndex: Int, colIndex: Int, item: E) -> Unit ) { for (colIndex in colProgression) { for (rowIndex in rowProgression) { action(rowIndex, colIndex, this[rowIndex][colIndex]) } } } class Day8(input: String) : Day<List<List<Int>>>(input) { override fun parseInput(): List<List<Int>> = inputByLines.map { it.map { it.digitToInt() } } override fun part1(input: List<List<Int>>): Int { fun List<Int>.updateVisible() = runningFold(-1 to true) { (topHeight, _), height -> if (height > topHeight) { height to true } else { topHeight to false } }.drop(1).map { it.second } fun List<List<Int>>.getAnswerByRows() = map { row -> val leftToRight = row.updateVisible() val rightToLeft = row.reversed().updateVisible().reversed() leftToRight.merge(rightToLeft) { a: Boolean, b: Boolean -> a || b } } val answerByRows = input.getAnswerByRows() val answerByCols = input.transpose().getAnswerByRows().transpose() return answerByRows.mergeMatrix(answerByCols) { a: Boolean, b: Boolean -> a || b }.flatten().count { it } } override fun part2(input: List<List<Int>>): Any { val rowNum = input.size val colNum = input.first().size var top = 0; fun isEdge(row: Int, col: Int) = row == 0 || col == 0 || rowNum - 1 == row || colNum - 1 == col input.forEachByRow { rowIndex: Int, colIndex: Int, item: Int -> if (isEdge(rowIndex, colIndex)) { return@forEachByRow } else { // left-to-right var leftToRight = 0 for (col in colIndex + 1 until input[rowIndex].size) { leftToRight += 1 if (input[rowIndex][col] >= item) break } // right-to-left var rightToLeft = 0 for (col in (0 until colIndex).reversed()) { rightToLeft += 1 if (input[rowIndex][col] >= item) break } // top-to-bottom var topToBottom = 0 for (row in (rowIndex + 1 until input.size)) { topToBottom += 1 if (input[row][colIndex] >= item) break } // bottom-to-top var bottomToTop = 0 for (row in (0 until rowIndex).reversed()) { bottomToTop += 1 if (input[row][colIndex] >= item) break } val score = leftToRight * rightToLeft * topToBottom * bottomToTop top = top.coerceAtLeast(score) } } return top } }
0
Kotlin
0
0
4ddfb8f7427b8037dca78cbf7c6b57e2a9e50545
3,585
aoc-2022
Apache License 2.0
src/main/kotlin/Day09.kt
todynskyi
573,152,718
false
{"Kotlin": 47697}
import kotlin.math.abs fun main() { fun count(moves: List<Move>, length: Int): Int { val visited = mutableSetOf<Point>() var head = Point() val tail = mutableListOf<Point>() (0 until length).forEach { tail.add(Point()) } moves.forEach { move -> (0 until move.distance).forEach { head = head.move(move) var neighbour = head for (j in 0 until length) { tail[j] = tail[j].follow(neighbour) neighbour = tail[j] } visited.add(tail[tail.size - 1]) } } return visited.size } fun part1(input: List<Move>): Int = count(input, 1) fun part2(input: List<Move>): Int = count(input, 9) // test if implementation meets criteria from the description, like: val testInput = readInput("Day09_test") .map { Move(it[0].toString(), it.split(" ").last().toInt()) } check(part1(testInput) == 13) println(part2(testInput)) val input = readInput("Day09") .map { Move(it[0].toString(), it.split(" ").last().toInt()) } println(part1(input)) println(part2(input)) } data class Move(val direction: String, val distance: Int) data class Point(val x: Int = 0, val y: Int = 0) { fun move(move: Move): Point { return when (move.direction) { "U" -> Point(x, y + 1) "D" -> Point(x, y - 1) "L" -> Point(x - 1, y) "R" -> Point(x + 1, y) else -> Point(x + 1, y) } } fun follow(head: Point): Point { val shouldMove = abs(x - head.x) > 1 || abs(y - head.y) > 1 if (!shouldMove) { return this } var x1 = x var y1 = y if (x1 > head.x) { x1-- } else if (x1 < head.x) { x1++ } if (y1 > head.y) { y1-- } else if (y1 < head.y) { y1++ } return Point(x1, y1) } }
0
Kotlin
0
0
5f9d9037544e0ac4d5f900f57458cc4155488f2a
2,056
KotlinAdventOfCode2022
Apache License 2.0
src/Day02.kt
jamie23
573,156,415
false
{"Kotlin": 19195}
import Hand.* import kotlin.IllegalArgumentException fun main() { fun part1(input: List<String>) = input.sumOf { it[2].toHand().value + it[2].toHand().result(it[0].toHand()) } fun part2(input: List<String>) = input.sumOf { it[2].requiredHand(it[0].toHand()).value + it[2].resultToInt() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day02_test") check(part1(testInput) == 15) check(part2(testInput) == 12) val input = readInput("Day02") println(part1(input)) println(part2(input)) } fun Char.resultToInt() = when { this == 'X' -> 0 this == 'Y' -> 3 this == 'Z' -> 6 else -> throw IllegalArgumentException() } fun Char.toHand() = when { this == 'X' || this == 'A' -> R this == 'Y' || this == 'B' -> P this == 'Z' || this == 'C' -> S else -> throw IllegalArgumentException() } fun Char.requiredHand(opposition: Hand) = when { this == 'X' -> opposition.beats this == 'Y' -> opposition this == 'Z' -> opposition.loses else -> throw IllegalArgumentException() } enum class Hand(val value: Int) { R(1), P(2), S(3); fun result(opposition: Hand) = when { this.beats == opposition -> 6 opposition.beats == this -> 0 else -> 3 } val beats: Hand get() = when (this) { R -> S P -> R S -> P } val loses: Hand get() = when (this) { R -> P P -> S S -> R } }
0
Kotlin
0
0
cfd08064654baabea03f8bf31c3133214827289c
1,569
Aoc22
Apache License 2.0
src/main/kotlin/ru/amai/study/hackerrank/practice/interviewPreparationKit/hashmaps/triplets/CountTriplets.kt
slobanov
200,526,003
false
null
package ru.amai.study.hackerrank.practice.interviewPreparationKit.hashmaps.triplets import java.util.* fun countTriplets(array: LongArray, ratio: Long): Long { fun modR(iv: IndexedValue<Long>) = iv.value % ratio == 0L fun divR(iv: IndexedValue<Long>) = IndexedValue(iv.index, iv.value / ratio) fun List<IndexedValue<Long>>.indexes() = map { (index, _) -> index } fun candidates(power: Int) = (0 until power).fold(array.withIndex()) { curArr, _ -> curArr.filter(::modR).map(::divR) }.groupBy { (_, value) -> value } .mapValues { (_, indexedValues) -> indexedValues.indexes() } val (iCandidates, jCandidates, kCandidates) = listOf(0, 1, 2).map(::candidates) val commonBases = kCandidates.keys.filter { v -> (v in iCandidates) && (v in jCandidates) } return commonBases.map { v -> val kvCandidates = kCandidates.getValue(v) val jvCandidates = jCandidates.getValue(v) val ivCandidates = iCandidates.getValue(v) countTriplesForSingleBaseValue(ivCandidates, jvCandidates, kvCandidates) }.sum() } private fun countTriplesForSingleBaseValue( ivCandidates: List<Int>, jvCandidates: List<Int>, kvCandidates: List<Int> ): Long { var i = 0 var j = 0 var k = 0 var iCnt = 0L var jCnt = 0L var kCnt = 0L while ((k < kvCandidates.size) && (i < ivCandidates.size) && (j < jvCandidates.size)) { val ivc = ivCandidates[i] val jvc = jvCandidates[j] val kvc = kvCandidates[k] when { kvc <= jvc -> { kCnt += jCnt k++ } jvc <= ivc -> { jCnt += iCnt j++ } else -> { i++ iCnt += 1L } } } while ((k < kvCandidates.size) && (j < jvCandidates.size)) { val jvc = jvCandidates[j] val kvc = kvCandidates[k] when { kvc <= jvc -> { kCnt += jCnt k++ } else -> { jCnt += iCnt j++ } } } if ((k < kvCandidates.size) && (kvCandidates[k] > jvCandidates.last())) { kCnt += jCnt * (kvCandidates.size - k) } return kCnt } fun main() { val scanner = Scanner(System.`in`) val nr = scanner.nextLine().trim().split(" ") val r = nr[1].toLong() val array = scanner.nextLine().trim().split(" ").map { it.toLong() }.toLongArray() val result = countTriplets(array, r) println(result) }
0
Kotlin
0
0
2cfdf851e1a635b811af82d599681b316b5bde7c
2,623
kotlin-hackerrank
MIT License
y2018/src/main/kotlin/adventofcode/y2018/Day04.kt
Ruud-Wiegers
434,225,587
false
{"Kotlin": 503769}
package adventofcode.y2018 import adventofcode.io.AdventSolution object Day04 : AdventSolution(2018, 4, "Repose Record") { override fun solvePartOne(input: String): Int { val schedule = parseSchedule(input) val sleepiestGuard = schedule.maxByOrNull { g -> g.value.sumOf { it.last - it.first } }!! val sleepiestMinute = (0..59).maxByOrNull { m -> sleepiestGuard.value.count { m in it } }!! return sleepiestGuard.key * sleepiestMinute } override fun solvePartTwo(input: String): Int { val schedule = parseSchedule(input) val (guard, minute) = schedule.keys .flatMap { g -> (0..59).map { m -> g to m } } .maxByOrNull { (g, m) -> schedule[g]!!.count { m in it } }!! return guard * minute } private fun parseSchedule(input: String): Map<Int, List<IntRange>> { val schedule = mutableMapOf<Int, MutableList<IntRange>>() var scheduleOfActiveGuard: MutableList<IntRange>? = null var asleep = 0 input.lineSequence() .sorted() .map { it.substringAfter(':').substringBefore(']').toInt() to it.substringAfter("] ") } .forEach { (minute, message) -> when { '#' in message -> { val guard = message.substringAfter('#').substringBefore(' ').toInt() scheduleOfActiveGuard = schedule.getOrPut(guard) { mutableListOf() } } message == "falls asleep" -> asleep = minute message == "wakes up" -> scheduleOfActiveGuard?.add(asleep until minute) } } return schedule } }
0
Kotlin
0
3
fc35e6d5feeabdc18c86aba428abcf23d880c450
1,762
advent-of-code
MIT License
src/main/kotlin/Problem27.kt
jimmymorales
496,703,114
false
{"Kotlin": 67323}
import kotlin.math.pow /** * Quadratic primes * * Euler discovered the remarkable quadratic formula: n^2 + n + 41 * * It turns out that the formula will produce 40 primes for the consecutive integer values 0 <= n <= 39. However, when * is n = 40, 40^2 + 40 +41 = 40(40+1) + 41 divisible by 41, and certainly when n = 41, 41^2 + 41 + 41 is clearly * divisible by 41. * * The incredible formula n^2 - 79n + 1601 was discovered, which produces 80 primes for the consecutive values * 0 <= n <= 79. The product of the coefficients, −79 and 1601, is −126479. * * Considering quadratics of the form: * * n ^2 + an + b, where |a| < 1000 and |b| <= 1000 * where |n| is the modulus/absolute value of n * e.g. |11| = 11 and |-4| = 4 * * Find the product of the coefficients, a and b, for the quadratic expression that produces the maximum number of * primes for consecutive values of n, starting with n = 0. * * https://projecteuler.net/problem=27 */ fun main() { println(numOfPrimes(a = 1, b = 41)) println(numOfPrimes(a = -79, b = 1601)) println(quadraticPrimes()) } private fun quadraticPrimes(): Int { var numOfPrimes = 0 var abPair = 0 to 0 for (a in -999 until 1_000) { for (b in -1_000..1_000) { val count = numOfPrimes(a, b) if (count > numOfPrimes) { numOfPrimes = count abPair = a to b } } } return abPair.first * abPair.second } private fun numOfPrimes(a: Int, b: Int): Int { var count = -1 var n = -1 do { count++ n++ val res = n.toDouble().pow(2.0) + (a * n) + b } while (isPrime(res.toLong())) return count }
0
Kotlin
0
0
e881cadf85377374e544af0a75cb073c6b496998
1,716
project-euler
MIT License
src/Day11.kt
phoenixli
574,035,552
false
{"Kotlin": 29419}
fun main() { fun part1(input: List<String>): Long { val monkeys = mutableListOf<Monkey>() input.chunked(7).forEach { monkeys.add(Monkey.of(it)) } repeat(20) { monkeys.forEach { it.inspect(monkeys) } } return monkeys.map { monkey -> monkey.numInspection } .sortedDescending() .take(2) .reduce { acc, it -> acc * it } } fun part2(input: List<String>): Long { val monkeys = mutableListOf<Monkey>() input.chunked(7).forEach { monkeys.add(Monkey.of(it)) } val mod = monkeys.map { monkey -> monkey.divisibleBy }.reduce{ acc, it -> acc * it } repeat(10000) { monkeys.forEach { it.newInspection(mod, monkeys) } } return monkeys.map { monkey -> monkey.numInspection } .sortedDescending() .take(2) .reduce { acc, it -> acc * it } } val input = readInput("Day11") println(part1(input)) println(part2(input)) } class Monkey( val id: Int, val items: MutableList<Long>, val operation: (Long) -> Long, val divisibleBy: Long, val trueMonkeyId: Int, val falseMonkeyId: Int ) { var numInspection = 0L fun inspect(monkeys: List<Monkey>) { for (item in items) { numInspection++ val worry = operation(item) / 3 if (worry % divisibleBy == 0L) { monkeys[trueMonkeyId].items.add(worry) } else { monkeys[falseMonkeyId].items.add(worry) } } items.clear() } fun newInspection(mod: Long, monkeys: List<Monkey>) { for (item in items) { numInspection++ val worry = operation(item) % mod if (worry % divisibleBy == 0L) { monkeys[trueMonkeyId].items.add(worry) } else { monkeys[falseMonkeyId].items.add(worry) } } items.clear() } companion object { fun of(input: List<String>): Monkey { val id = input[0].substringAfter(' ').dropLast(1).toInt() val items = mutableListOf<Long>() input[1].replace(" ", "").substringAfter(":").split(',').forEach { items.add(it.toLong()) } val operationIdx = input[2].lastIndexOf(' ') - 1 val operationStr = input[2].substring(operationIdx, operationIdx + 1) val secondOperand = input[2].substringAfterLast(' ') val operation: (Long) -> Long = when { secondOperand == "old" -> ({ it * it }) else -> { val value = secondOperand.toLong() if (operationStr == "+") { ({ it + value }) } else { ({ it * value }) } } } val divisibleBy = input[3].substringAfterLast(' ').toLong() val trueMonkeyId = input[4].substringAfterLast(' ').toInt() val falseMonkeyId = input[5].substringAfterLast(' ').toInt() return Monkey(id, items, operation, divisibleBy, trueMonkeyId, falseMonkeyId) } } }
0
Kotlin
0
0
5f993c7b3c3f518d4ea926a792767a1381349d75
3,346
Advent-of-Code-2022
Apache License 2.0
src/main/kotlin/com/kishor/kotlin/algo/algorithms/SelectionAlgorithms.kt
kishorsutar
276,212,164
false
null
package com.kishor.kotlin.algo.algorithms fun main() { val quickSelect = QuickSelect(arrayOf(2, 4, 7, -1, 0, 9)) println("the kth smallest ${quickSelect.select(3)}") } class QuickSelect(val nums: Array<Int>) { // selection phase // quickSelect// // pivot = // partition // swap fun select(k: Int): Int { return quickSelect(0, nums.size - 1, k - 1) } private fun quickSelect(firstIndex: Int, lastIndex: Int, k: Int): Int { val pivotIndex = partitionSmallest(firstIndex, lastIndex) if (pivotIndex < k) { return quickSelect(pivotIndex + 1, lastIndex, k) } else if (pivotIndex > k) { return quickSelect(firstIndex, pivotIndex - 1, k) } return nums[pivotIndex] } private fun partitionSmallest(firstIndex: Int, lastIndex: Int): Int { var first = firstIndex val pivot = (first..lastIndex).shuffled().first() swap(pivot, lastIndex) for (i in nums.indices) { if (nums[i] < nums[lastIndex]) { swap(first, i) first++ } } swap(first, lastIndex) return first } private fun partitionLargest(firstIndex: Int, lastIndex: Int): Int { var first = firstIndex val pivot = (first..lastIndex).shuffled().first() swap(pivot, lastIndex) for (i in nums.indices - 1) { if (nums[i] > nums[lastIndex]) { swap(first, i) first++ } } swap(first, lastIndex) return first } private fun swap(one: Int, other: Int) { val temp = nums[one] nums[one] = nums[other] nums[other] = temp } }
0
Kotlin
0
0
6672d7738b035202ece6f148fde05867f6d4d94c
1,752
DS_Algo_Kotlin
MIT License
src/main/kotlin/2021/Day9.kt
mstar95
317,305,289
false
null
package `2021` import days.Day class Day9 : Day(9) { override fun partOne(): Any { val board = createBoard(inputList) return lowPoints(board).sumOf { it.second + 1 } } override fun partTwo(): Any { val board = createBoard(inputList) val basins = lowPoints(board).map { findBasin(board, listOf(it)) }.map { it.size }.sortedDescending() // println(basins) return basins[0] * basins[1] * basins[2] } fun findBasin( board: Board, toSee: List<Pair<Point, Int>>, seen: Set<Point> = setOf(), ): Set<Point> { if (toSee.isEmpty()) { return seen; } val f = toSee.first() val n = board.neighbours(f.first).filter { it.second != 9 }.filter { it.first !in seen } .filter { it.second > f.second } return findBasin(board, toSee.drop(1) + n, seen + f.first) } fun lowPoints(board: Board): List<Pair<Point, Int>> { return board.board.filter { point -> val neighbours = board.neighboursValues(point.key) val all = neighbours.all { it > point.value } all }.map { it.key to it.value } } fun createBoard(param: List<String>): Board { val mutableMap = mutableMapOf<Point, Int>() var x = 0 var y = 0 for (line in param) { for (c in line) { val p = Point(x, y) mutableMap.put(p, c.toString().toInt()) x++ } x = 0 y++ } return Board(mutableMap.toMap()) } data class Board(val board: Map<Point, Int> = mapOf()) { val sides = listOf( // 1 to 1, // 1 to -1, 1 to 0, 0 to 1, 0 to -1, // -1 to 1, // -1 to -1, -1 to 0, ) fun neighboursValues(p: Point): List<Int> = sides.map { Point(it.first + p.x, it.second + p.y) }.map { board[it] ?: Int.MAX_VALUE } fun neighbours(p: Point): List<Pair<Point, Int>> = sides.map { Point(it.first + p.x, it.second + p.y) }.mapNotNull { i -> board[i]?.let { i to it } } } data class Point(val x: Int, val y: Int) }
0
Kotlin
0
0
ca0bdd7f3c5aba282a7aa55a4f6cc76078253c81
2,369
aoc-2020
Creative Commons Zero v1.0 Universal
src/Day03.kt
JanTie
573,131,468
false
{"Kotlin": 31854}
import kotlin.streams.toList fun main() { fun parseInput(input: List<String>) = input .filter { it.isNotEmpty() } .map { listOf(it.substring(0, it.length / 2), it.substring(it.length / 2)) } .map { rucksack -> rucksack.map { compartment -> compartment.chars().toList().map { if (it >= 97) it - 97 + 1 else it - 65 + 27 } } } fun part1(input: List<String>): Int { return parseInput(input).sumOf { rucksack -> rucksack[0].first { it in rucksack[1] } } } fun part2(input: List<String>): Int { return parseInput(input).let { list -> list.chunked(3) // list / group / rucksack / compartment / item .map { group -> group.map { rucksack -> rucksack.flatten() } } // list / group / rucksack / item .map { group -> group.flatten().distinct().first { group.all { rucksack -> rucksack.contains(it) } } } }.sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day03_test") val input = readInput("Day03") check(part1(testInput) == 157) println(part1(input)) check(part2(testInput) == 70) println(part2(input)) }
0
Kotlin
0
0
3452e167f7afe291960d41b6fe86d79fd821a545
1,279
advent-of-code-2022
Apache License 2.0
src/algorithmdesignmanualbook/sorting/BucketSort.kt
realpacific
234,499,820
false
null
package algorithmdesignmanualbook.sorting import algorithmdesignmanualbook.print import utils.assertIterableSame /** * Maintains bucket of 0..9 or a-z * The number of iterations requires depends on number of characters in longest element (length wise) * * [Algorithm](https://www.youtube.com/watch?v=JMlYkE8hGJM) */ class BucketSort(arr: IntArray) { // 0..9 bucket private val bucket = LinkedHashMap<Int, MutableList<Int>>() private val result = mutableListOf<Int>() /** * Length of longest element */ private var iterations: Int init { (0..9).forEach { bucket[it] = mutableListOf() } result.addAll(arr.toList()) val largestElement = arr.maxOrNull()!! iterations = largestElement.getNumberOfDigits() } fun run(): List<Int> { // Requires pass equal to digits in longest element (0 until iterations).forEach { pass -> bucketSort(pass) } return result.toList() } private fun bucketSort(pass: Int) { println("Pass $pass") emptyBucket() result.forEach { item -> // start from LSB in case of integer val digit = item.getDigitAt(iterations - 1 - pass) // add it to respective bucket, use digits value to find the bucket bucket[digit]!!.add(item) } result.clear() // pick element from bucket while maintaining the order 0..9 bucket.values.forEach(result::addAll) println("Bucket: $bucket") } private fun emptyBucket() { bucket.values.forEach(MutableList<Int>::clear) } /** * Pad element at the start so that all element's length is same as the longest one */ private fun Int.getDigitAt(pos: Int): Int { return Integer.valueOf(this.toString().padStart(iterations, '0')[pos].toString()) } private fun Int.getNumberOfDigits(): Int { var number = this var count = 0 while (number != 0) { number /= 10 count++ } return count } } fun main() { run { val input = intArrayOf(44, 12, 1, 300, 3, 66, 101, 7, 9) val sort = BucketSort(input) assertIterableSame(input.clone().sorted(), sort.run().print()) } run { val input = intArrayOf(4400, 1102, 701, 3001, 333, 2, 555, 90, 14, 86, 4477, 98, 100) val sort = BucketSort(input) assertIterableSame(input.clone().sorted(), sort.run().print()) } }
4
Kotlin
5
93
22eef528ef1bea9b9831178b64ff2f5b1f61a51f
2,538
algorithms
MIT License
src/Day03.kt
inssein
573,116,957
false
{"Kotlin": 47333}
fun main() { fun findCommon(a: String, b: String): String { val set = a.toSet() return b.filter { set.contains(it) } } fun Char.toPriority() = if (this.isLowerCase()) this - 'a' + 1 else this - 'A' + 27 fun part1(input: List<String>): Int { return input.sumOf { val firstHalf = it.take(it.length / 2) val secondHalf = it.takeLast(it.length / 2) findCommon(firstHalf, secondHalf) .first() .toPriority() } } fun part2(input: List<String>): Int { return input .chunked(3) .sumOf { group -> group .reduce { acc, it -> findCommon(acc, it) } .first() .toPriority() } } val testInput = readInput("Day03_test") check(part1(testInput) == 157) check(part2(testInput) == 70) val input = readInput("Day03") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
095d8f8e06230ab713d9ffba4cd13b87469f5cd5
1,020
advent-of-code-2022
Apache License 2.0
Kotlin/src/dev/aspid812/leetcode/problem0056/Solution.kt
Const-Grigoryev
367,924,342
false
{"Python": 35682, "Kotlin": 11162, "C++": 2688, "Java": 2168, "C": 1076}
package dev.aspid812.leetcode.problem0056 /* 56. Merge Intervals * ------------------- * * Given an array of `intervals` where `intervals[i] = [start_i, end_i]`, merge all overlapping intervals, and return * *an array of the non-overlapping intervals that cover all the intervals in the input*. * * ### Constraints: * * * `1 <= intervals.length <= 10^4` * * `intervals[i].length == 2` * * `0 <= start_i <= end_i <= 10^4` */ typealias Interval = IntArray class Solution { fun merge(intervals: Array<Interval>): Array<Interval> { intervals.sortBy { interval -> interval[0] } var span = intArrayOf(-1, -1) var (i, j) = Pair(0, 0) while (j < intervals.size) { if (span[1] < intervals[j][0]) { intervals[i] = intervals[j] span = intervals[i] i += 1 } else if (span[1] < intervals[j][1]) { span[1] = intervals[j][1] } j += 1 } return intervals.copyOfRange(0, i) } } fun makeIntervals(vararg intervals: IntRange): Array<Interval> { return intervals.map { range -> intArrayOf(range.start, range.endInclusive)}.toTypedArray() } fun main() { val s = Solution() // Since intervals [1,3] and [2,6] overlaps, merge them into [1,6]. val intervals1 = makeIntervals(1..3, 2..6, 8..10, 15..18) println("${s.merge(intervals1).contentDeepToString()} == [[1,6],[8,10],[15,18]]") // Intervals [1,4] and [4,5] are considered overlapping. val intervals2 = makeIntervals(1..4, 4..5) println("${s.merge(intervals2).contentDeepToString()} == [[1,5]]") }
0
Python
0
0
cea8e762ff79878e2d5622c937f34cf20f0b385e
1,665
LeetCode
MIT License
src/Day02.kt
ciprig
573,478,617
false
null
fun main() { fun compare(first: Char, second: Char): Int { return when (first - second) { 0 -> 3 1, -2 -> 0 -1, 2 -> 6 else -> throw IllegalArgumentException() } + when (second) { 'X' -> 1 'Y' -> 2 'Z' -> 3 else -> throw IllegalArgumentException() } } fun part1(input: List<String>): Int { return input.sumOf { compare(it[0] + ('X' - 'A'), it[2]) } } fun points(first: Char, second: Char): Int { val play = when (first) { 'A' -> 0 'B' -> 1 'C' -> 2 else -> throw IllegalArgumentException() } val result = when (second) { 'X' -> -1 'Y' -> 0 'Z' -> 1 else -> throw IllegalArgumentException() } val answer = (play + result + 3) % 3 return (result + 1) * 3 + (answer + 1) } fun part2(input: List<String>): Int { return input.sumOf { points(it[0], it[2]) } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day02_test") println(part1(testInput)) check(part1(testInput) == 15) val input = readInput("Day02") println(part1(input)) println(part2(testInput)) check(part2(testInput) == 12) println(part2(input)) }
0
Kotlin
0
0
e24dd65a22106bf5375d9d99c8b9d3b3a90e28da
1,451
aoc2022
Apache License 2.0
src/Day03.kt
realpacific
573,561,400
false
{"Kotlin": 59236}
fun main() { fun calculatePriority(item: Char) = if (item.isUpperCase()) item.code - 65 + 27 else item.code - 97 + 1 fun part1(input: List<String>): Int { var prioritySum = 0 input.forEach { rucksack -> val itemsCountInCompartment = rucksack.lastIndex / 2 val firstCompartment = rucksack.substring(0, itemsCountInCompartment + 1) val firstCompartmentItemCountMap = firstCompartment.toHashSet() val secondCompartment = rucksack.substring(itemsCountInCompartment + 1) val secondCompartmentItemCountMap = secondCompartment.toHashSet() val commonItem = firstCompartmentItemCountMap.intersect(secondCompartmentItemCountMap).first() prioritySum += calculatePriority(commonItem) } return prioritySum } fun part2(input: List<String>): Int { var prioritySum = 0 input.chunked(3).forEach { group -> val (first, second, third) = group.map(String::toHashSet) val badge = first.intersect(second).intersect(third).first() prioritySum += calculatePriority(badge) } return prioritySum } val input = readInput("Day03") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
f365d78d381ac3d864cc402c6eb9c0017ce76b8d
1,280
advent-of-code-2022
Apache License 2.0
src/main/kotlin/day12/day12.kt
corneil
572,437,852
false
{"Kotlin": 93311, "Shell": 595}
package day12 import main.utils.Edge import main.utils.Graph import main.utils.measureAndPrint import utils.Coord import utils.readFile import utils.readLines fun main() { val test = readLines( """Sabqponm abcryxxl accszExk acctuvwj abdefghi""" ) val input = readFile("day12") data class Cell( val c: Char, val pos: Coord ) : Comparable<Cell> { override fun compareTo(other: Cell): Int { var result = c.compareTo(other.c) if (result == 0) { result = pos.compareTo(other.pos) } return result } override fun equals(other: Any?): Boolean { if (this === other) return true other as Cell if (c != other.c) return false if (pos != other.pos) return false return true } override fun hashCode(): Int { return pos.hashCode() * c.hashCode() } fun actual(): Char = when (c) { 'S' -> 'a' 'E' -> 'z' else -> c } override fun toString(): String { return "Cell($c, $pos)" } } fun createGrid(input: List<String>): List<Edge<Cell>> { val edges = mutableListOf<Edge<Cell>>() val cells = input.mapIndexed { y, line -> line.mapIndexed { x, c -> Cell(c, Coord(x, input.lastIndex - y)) } }.flatMap { row -> row.map { it } }.associateBy { it.pos } cells.values.forEach { cell -> cell.pos.surrounds().forEach { coord -> val neighbour = cells[coord] if (neighbour != null) { val height = neighbour.actual() - cell.actual() if (height <= 1) { edges.add(Edge(cell, neighbour)) } } } } return edges } fun calculateSteps( edges: List<Edge<Cell>>, start: Cell, end: Cell ): Int? { val graph = Graph(edges, true) val path = graph.findPath(start, end) return if (path.isEmpty()) null else path.size - 1 } fun calcSolution1(input: List<String>): Int { val edges = createGrid(input) val end = edges.map { edge -> edge.c2 } .find { it.c == 'E' } ?: error("Cannot find E") val start = edges.map { edge -> edge.c1 } .find { it.c == 'S' } ?: error("Cannot find S") return calculateSteps(edges, start, end) ?: error("Cannot find solution from $start to $end") } fun calcSolution2(input: List<String>): Int { val edges = createGrid(input) val end = edges.map { edge -> edge.c2 } .find { it.c == 'E' } ?: error("Cannot find E") return edges.map { edge -> edge.c1 } .filter { it.actual() == 'a' } .mapNotNull { start -> calculateSteps(edges, start, end) } .min() } fun part1() { val testResult = measureAndPrint("Part 1 Test Time: ") { calcSolution1(test) } println("Part 1 Answer = $testResult") check(testResult == 31) val result = measureAndPrint("Part 1 Time: ") { calcSolution1(input) } println("Part 1 Answer = $result") check(result == 339) } fun part2() { val testResult = measureAndPrint("Part 2 Test Time: ") { calcSolution2(test) } println("Part 2 Answer = $testResult") check(testResult == 29) val result = measureAndPrint("Part 2 Time: ") { calcSolution2(input) } println("Part 2 Answer = $result") check(result == 332) } println("Day - 12") part1() part2() }
0
Kotlin
0
0
dd79aed1ecc65654cdaa9bc419d44043aee244b2
3,341
aoc-2022-in-kotlin
Apache License 2.0
src/nativeMain/kotlin/com.qiaoyuang.algorithm/special/Questions66.kt
qiaoyuang
100,944,213
false
{"Kotlin": 338134}
package com.qiaoyuang.algorithm.special fun test66() { printlnResult("happy" to 3, trie = "hap") printlnResult("happy" to 3, "happen" to 2, trie = "hap") } /** * Questions 66: Design a data structure that could insert a string and a value. And, it contains * a function that can calculate the sum of all values. */ private class MapSum { private val head = TrieNodeWithValue(' ') fun insert(word: String, value: Int) { var pointer = head word.forEach { c -> val nextPointer = pointer.next.find { it?.character == c } if (nextPointer == null) { var insertIndex = 0 for (i in pointer.next.indices) if (pointer.next[i] == null) { insertIndex = i break } val newNode = TrieNodeWithValue(c) pointer.next[insertIndex] = newNode pointer = newNode } else pointer = nextPointer } pointer.next[0] = TrieNodeWithValue(' ', value) } fun sum(trie: String): Int { var pointer = head trie.forEach { c -> val nextPointer = pointer.next.find { it?.character == c } if (nextPointer == null) return 0 else pointer = nextPointer } return dfs(pointer) } fun dfs(head: TrieNodeWithValue): Int = head.next[0]?.value ?: head.next.asSequence().filterNotNull().sumOf { dfs(it) } } private class TrieNodeWithValue( val character: Char, val value: Int? = null, ) { var next = Array<TrieNodeWithValue?>(8) { null } private set } private fun printlnResult(vararg wordWithValue: Pair<String, Int>, trie: String) { val map = MapSum() wordWithValue.forEach { (word, value) -> map.insert(word, value) } println("The sum of ${wordWithValue.toList()} is ${map.sum(trie)}") }
0
Kotlin
3
6
66d94b4a8fa307020d515d4d5d54a77c0bab6c4f
1,988
Algorithm
Apache License 2.0
advent-of-code/src/main/kotlin/DayFourteen.kt
pauliancu97
518,083,754
false
{"Kotlin": 36950}
import kotlin.math.min class DayFourteen { data class Reindeer( val name: String, val speed: Int, val upTime: Int, val downTime: Int ) { companion object { val REGEX = """([a-zA-Z]+) can fly (\d+) km\/s for (\d+) seconds, but then must rest for (\d+) seconds\.""" .toRegex() } fun getDistanceTraveled(time: Int): Int { val cycleTime = upTime + downTime val numOfCycles = time / cycleTime val distanceTraveledInCycles = numOfCycles * upTime * speed val remainingTime = time % cycleTime val remainingTimeUptime = min(remainingTime, upTime) val distanceTraveledInRest = remainingTimeUptime * speed return distanceTraveledInCycles + distanceTraveledInRest } } private fun String.toReindeer(): Reindeer? { val matchResult = Reindeer.REGEX.matchEntire(this) ?: return null val name = matchResult.groupValues.getOrNull(1) ?: return null val speed = matchResult.groupValues.getOrNull(2)?.toIntOrNull() ?: return null val upTime = matchResult.groupValues.getOrNull(3)?.toIntOrNull() ?: return null val downTime = matchResult.groupValues.getOrNull(4)?.toIntOrNull() ?: return null return Reindeer(name, speed, upTime, downTime) } private fun readReindeers(path: String) = readLines(path).mapNotNull { it.toReindeer() } private fun getFurthestDistance(reindeers: List<Reindeer>, time: Int): Int = reindeers.maxOfOrNull { it.getDistanceTraveled(time) } ?: 0 private fun getWinningReindeerNumPoints(reindeers: List<Reindeer>, time: Int): Int { val pointsMap = reindeers .associate { it.name to 0 } .toMutableMap() for (currentTime in 1..time) { val maxDistance = reindeers.maxOf { it.getDistanceTraveled(currentTime) } val awardedReindeers = reindeers .filter { it.getDistanceTraveled(currentTime) == maxDistance } .map { it.name } for (awardedReindeer in awardedReindeers) { pointsMap[awardedReindeer] = (pointsMap[awardedReindeer] ?: 0) + 1 } } return pointsMap.values.max() } fun solvePartOne() { val reindeers = readReindeers("day_fourteen.txt") val maxDistance = getFurthestDistance(reindeers, 2503) println(maxDistance) } fun solvePartTwo() { val reindeers = readReindeers("day_fourteen.txt") val maxPoints = getWinningReindeerNumPoints(reindeers, 2503) println(maxPoints) } } fun main() { DayFourteen().solvePartTwo() }
0
Kotlin
0
0
3ba05bc0d3e27d9cbfd99ca37ca0db0775bb72d6
2,720
advent-of-code-2015
MIT License
2020/src/main/kotlin/de/skyrising/aoc2020/day21/solution.kt
skyrising
317,830,992
false
{"Kotlin": 411565}
package de.skyrising.aoc2020.day21 import de.skyrising.aoc.* import java.util.* private fun solve(input: PuzzleInput): Pair<List<String>, Map<String, String>> { val allIngredients = mutableListOf<String>() val map = mutableMapOf<String, MutableSet<String>>() for (line in input.lines) { val split = line.split('(', limit = 2) if (split.size == 1) continue val allergens = split[1].substring(9, split[1].length - 1).split(", ") val ingredients = split[0].trim().split(' ') allIngredients.addAll(ingredients) for (allergen in allergens) { map[allergen]?.retainAll(ingredients) if (allergen !in map) map[allergen] = HashSet(ingredients) } } val found = mutableMapOf<String, String>() while (map.isNotEmpty()) { val iter = map.iterator() while (iter.hasNext()) { val (k, v) = iter.next() if (v.size == 1) { found[k] = v.single() iter.remove() } else { v.removeAll(found.values) } } } return Pair(allIngredients, found) } val test = TestInput(""" mxmxvkd kfcds sqjhc nhms (contains dairy, fish) trh fvjkl sbzzf mxmxvkd (contains dairy) sqjhc fvjkl (contains soy) sqjhc mxmxvkd sbzzf (contains fish) """) @PuzzleName("Allergen Assessment") fun PuzzleInput.part1(): Any { val (allIngredients, found) = solve(this) return allIngredients.count { it !in found.values } } fun PuzzleInput.part2(): Any { val (_, found) = solve(this) val sorted = TreeMap(found) return sorted.values.joinToString(",") { s -> s } }
0
Kotlin
0
0
19599c1204f6994226d31bce27d8f01440322f39
1,674
aoc
MIT License
src/Day01.kt
Lonexera
573,177,106
false
null
fun main() { fun List<String>.splitByEmpty(): List<List<String>> { return buildList { this@splitByEmpty.mapIndexedNotNull { index, string -> if (string.isBlank()) { index } else { null } } .zipWithNext() // 4,5 5,8 8,10 - no 0,4 .forEachIndexed { index, (start, end) -> if (index == 0) { this.add(this@splitByEmpty.subList(0, start).toList()) } this.add(this@splitByEmpty.subList(start + 1, end).toList()) } } } fun part1(input: List<String>): Int { return input .splitByEmpty() .maxOf { calories -> calories.sumOf { it.toInt() } } } fun part2(input: List<String>): Int { return input .splitByEmpty() .map { calories -> calories.sumOf { it.toInt() } } .sortedDescending() .take(3) .sum() } val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
c06d394cd98818ec66ba9c0311c815f620fafccb
1,302
kotlin-advent-of-code-2022
Apache License 2.0
src/main/kotlin/day10.kt
tobiasae
434,034,540
false
{"Kotlin": 72901}
class Day10 : Solvable("10") { override fun solveA(input: List<String>): String { return Math.abs(solve(input).filter { it < 0 }.sum()).toString() } override fun solveB(input: List<String>): String { solve(input).filter { it > 0 }.sorted().let { return it[it.size / 2].toString() } } /* The negative values are the solutions for part 1, the positive values for part 2 */ private fun solve(input: List<String>): List<Long> { return input.map { s -> val stack = mutableListOf<Char>() s.forEach { if (isOpening(it)) stack.add(it) else if (stack.size == 0) return@map -getValuePart1(it) else if (isValidPair(stack.last(), it)) stack.removeAt(stack.size - 1) else return@map -getValuePart1(it) } stack.map(this::getValuePart2).reduceRight { l, r -> r * 5 + l } } } private fun isOpening(open: Char) = listOf('(', '[', '{', '<').contains(open) private fun isClosing(close: Char) = listOf(')', ']', '}', '>').contains(close) private fun isValidPair(open: Char, close: Char): Boolean { return when (open) { '(' -> close == ')' '[' -> close == ']' '{' -> close == '}' '<' -> close == '>' else -> false } } private fun getValuePart1(close: Char): Long { return when (close) { ')' -> 3 ']' -> 57 '}' -> 1197 '>' -> 25137 else -> 0 } } private fun getValuePart2(close: Char): Long { return when (close) { '(' -> 1 '[' -> 2 '{' -> 3 '<' -> 4 else -> 0 } } }
0
Kotlin
0
0
16233aa7c4820db072f35e7b08213d0bd3a5be69
1,805
AdventOfCode
Creative Commons Zero v1.0 Universal
app/src/main/kotlin/de/tobiasdoetzer/aoc2021/Day3.kt
dobbsy
433,868,809
false
{"Kotlin": 13636}
package de.tobiasdoetzer.aoc2021 private fun part1(report: List<String>): Int { var gammaText = "" var epsilonText = "" val limit = report.size / 2 for (i in report[0].indices) { val numberOf0s = report.count { it[i] == '0' } if (numberOf0s > limit) { // more than half of the numbers in report have a 0 at position i gammaText += 0 epsilonText += 1 } else { // less than half of the numbers in report have a 1 ato position i gammaText += 1 epsilonText += 0 } } return gammaText.toInt(2) * epsilonText.toInt(2) } private fun part2(report: List<String>): Int { var oxygenGenList = report var scrubberRatingList = report for (i in report[0].indices) { if (oxygenGenList.size == 1) break val limit = oxygenGenList.size / 2.0 val numberOf0s = oxygenGenList.count { it[i] == '0' } oxygenGenList = when { numberOf0s > limit -> oxygenGenList.filter { it[i] == '0' } // more than half of the numbers have a 0 at position i numberOf0s < limit -> oxygenGenList.filter { it[i] == '1' } // less than half of the numbers have a 1 ato position i else -> oxygenGenList.filter { it[i] == '1' } // Exactly half the numbers have a 0/1 at position i } } for (i in report[0].indices) { if (scrubberRatingList.size == 1) break val limit = scrubberRatingList.size / 2.0 val numberOf0s = scrubberRatingList.count { it[i] == '0' } scrubberRatingList = when { numberOf0s > limit -> scrubberRatingList.filter { it[i] == '1' } // more than half of the numbers have a 0 at position i numberOf0s < limit -> scrubberRatingList.filter { it[i] == '0' } // less than half of the numbers have a 1 ato position i else -> scrubberRatingList.filter { it[i] == '0' } // Exactly half the numbers have a 0/1 at position i } } return oxygenGenList[0].toInt(2) * scrubberRatingList[0].toInt(2) } private fun main() { val input = readInput("day3_input.txt") println("The solution of part 1 is: ${part1(input)}") println("The solution of part 2 is: ${part2(input)}") }
0
Kotlin
0
0
28f57accccb98d8c2949171cd393669e67789d32
2,230
AdventOfCode2021
Apache License 2.0
src/Day20.kt
i-tatsenko
575,595,840
false
{"Kotlin": 90644}
import kotlin.math.abs fun main() { data class Node(val value: Long) { lateinit var next: Node lateinit var prev: Node override fun toString(): String = "${prev.value} < $value > ${next.value}" } val toLeft = {node: Node -> node.prev} val toRight = {node: Node -> node.next } fun doTheMagic(nodes: Array<Node>, mult: Int = 1, rounds: Int = 1): Long { lateinit var zeroNode: Node for (i in nodes.indices) { val current = nodes[i] current.next = if (i == nodes.size - 1) nodes[0] else nodes[i + 1] current.prev = if (i == 0) nodes[nodes.size - 1] else nodes[i - 1] if (current.value == 0L) zeroNode = current } val modOfMult = mult % (nodes.size - 1) for (r in 1..rounds) { for (node in nodes) { if (node.value == 0L) { continue } val direction = if (node.value > 0) toRight else toLeft var target = node val iterationCount = if (mult == 1) { if (node.value > nodes.size) node.value % (nodes.size - 1) else node.value } else { ((node.value % (nodes.size - 1)) * modOfMult) % (nodes.size - 1) } node.prev.next = node.next node.next.prev = node.prev for (iteration in 0 until if (node.value < 0) abs(iterationCount) + 1 else iterationCount) { target = direction(target) } node.next = target.next node.prev = target target.next = node node.next.prev = node } } var node = zeroNode var result = 0L for (index in 1..3000) { node = node.next if (index % 1000 == 0) { result += node.value } } return result * mult } fun part1(input: List<String>): Long { return doTheMagic(Array(input.size) { Node(input[it].toLong()) }) } fun part2(input: List<String>): Long { return doTheMagic(Array(input.size) { Node(input[it].toLong()) }, 811589153, 10) } // test if implementation meets criteria from the description, like: val testInput = readInput("Day20_test") check(part1(testInput) == 3L) check(part2(testInput) == 1623178306L) val input = readInput("Day20") println(part1(input)) check(part1(input) == 3700L) check(part2(input) == 10626948369382L) println(part2(input)) }
0
Kotlin
0
0
0a9b360a5fb8052565728e03a665656d1e68c687
2,623
advent-of-code-2022
Apache License 2.0
src/Day04.kt
JCampbell8
572,669,444
false
{"Kotlin": 10115}
fun main() { fun parsePairs(input: List<String>): List<List<IntRange>> { val map = input.map { it.split(",") } .map { it.map { it2 -> val split = it2.split("-") split[0].toInt()..split[1].toInt() } } return map } fun part1(input: List<String>): Int { return parsePairs(input) .filter { val intersect = it[0].intersect(it[1]) intersect.containsAll(it[0].toList()) || intersect.containsAll(it[1].toList()) }.size } fun part2(input: List<String>): Int { return parsePairs(input) .filter { it[0].intersect(it[1]).isNotEmpty() }.size } // test if implementation meets criteria from the description, like: val testInput = readInput("Day04_test") check(part1(testInput) == 2) check(part2(testInput) == 4) val input = readInput("Day04") println(part1(input)) println(part2(input)) }
0
Kotlin
0
1
0bac6b866e769d0ac6906456aefc58d4dd9688ad
1,056
advent-of-code-2022
Apache License 2.0
src/day19/Day19.kt
andreas-eberle
573,039,929
false
{"Kotlin": 90908}
package day19 import kotlinx.coroutines.async import kotlinx.coroutines.awaitAll import kotlinx.coroutines.runBlocking import readInput const val day = "19" fun main() = runBlocking { suspend fun calculatePart1Score(input: List<String>, steps: Int): Int { val blueprints = input.parseBlueprints() val blueprintOutcomes = blueprints.map { blueprint -> async { blueprint to blueprint.runSimulation(Material(1, 0, 0, 0), Material(0, 0, 0, 0), Material(0, 0, 0, 0), true, steps) } }.awaitAll() println("blueprintOutcomes: $blueprintOutcomes") return blueprintOutcomes.sumOf { it.first.id * it.second.geode } } suspend fun calculatePart2Score(input: List<String>, steps: Int): Int { val blueprints = input.take(3).parseBlueprints() val blueprintOutcomes = blueprints.map { blueprint -> async { blueprint to blueprint.runSimulation(Material(1, 0, 0, 0), Material(0, 0, 0, 0), Material(0, 0, 0, 0), true, steps) } }.awaitAll() println("blueprintOutcomes: $blueprintOutcomes") return blueprintOutcomes.fold(1) { acc, pair -> acc * pair.second.geode } } // test if implementation meets criteria from the description, like: val testInput = readInput("/day$day/Day${day}_test") val input = readInput("/day$day/Day${day}") // val part1TestPoints = calculatePart1Score(testInput, 24) // println("Part1 test points: $part1TestPoints") // check(part1TestPoints == 33) // // val part1points = calculatePart1Score(input, 24) // println("Part1 points: $part1points") val part2TestPoints = calculatePart2Score(testInput, 32) println("Part2 test points: $part2TestPoints") check(part2TestPoints == 62 * 56) val part2points = calculatePart2Score(input, 32) println("Part2 points: $part2points") } data class Material(val ore: Int, val clay: Int, val obsidian: Int, val geode: Int) { operator fun plus(o: Material) = Material(ore + o.ore, clay + o.clay, obsidian + o.obsidian, geode + o.geode) operator fun minus(b: BotBlueprint) = Material(ore - b.ore, clay - b.clay, obsidian - b.obsidian, geode) fun canProduce(b: BotBlueprint) = ore >= b.ore && clay >= b.clay && obsidian >= b.obsidian } data class BotBlueprint(val ore: Int, val clay: Int, val obsidian: Int) data class Blueprint(val id: Int, val botBlueprints: List<Pair<BotBlueprint, Material>>) fun List<String>.parseBlueprints(): List<Blueprint> = map { it.parseBlueprint() } val regex = """Blueprint (\d+): Each ore robot costs (\d+) ore. Each clay robot costs (\d+) ore. Each obsidian robot costs (\d+) ore and (\d+) clay. Each geode robot costs (\d+) ore and (\d+) obsidian.""".toRegex() fun String.parseBlueprint(): Blueprint { val matchedValues = regex.find(this)?.groupValues?.drop(1)?.map { it.toInt() } ?: error("pattern not found in $this") return Blueprint( matchedValues[0], listOf( BotBlueprint(matchedValues[1], 0, 0) to Material(1, 0, 0, 0), BotBlueprint(matchedValues[2], 0, 0) to Material(0, 1, 0, 0), BotBlueprint(matchedValues[3], matchedValues[4], 0) to Material(0, 0, 1, 0), BotBlueprint(matchedValues[5], 0, matchedValues[6]) to Material(0, 0, 0, 1), ) ) } fun Blueprint.runSimulation(currentProduction: Material, currentMaterials: Material, lastMaterials: Material, relax: Boolean, steps: Int): Material { val newMaterials = currentMaterials + currentProduction if (steps <= 1) { return newMaterials } val productionWithNewBots = botBlueprints .filter { (botBlueprint, _) -> currentMaterials.canProduce(botBlueprint) && (!lastMaterials.canProduce(botBlueprint) || relax) } .map { (botBlueprint, botProduction) -> runSimulation(currentProduction + botProduction, newMaterials - botBlueprint, currentMaterials, true, steps - 1) } val canNotAffordAll = botBlueprints.any { (botBlueprint, _) -> !currentMaterials.canProduce(botBlueprint) } val allProductions = productionWithNewBots + if (canNotAffordAll) { listOf(runSimulation(currentProduction, newMaterials, currentMaterials, false, steps - 1)) } else { emptyList() } return allProductions.maxBy { it.geode } }
0
Kotlin
0
0
e42802d7721ad25d60c4f73d438b5b0d0176f120
4,365
advent-of-code-22-kotlin
Apache License 2.0
src/Day05.kt
ekgame
573,100,811
false
{"Kotlin": 20661}
fun main() { data class MoveInstruction(val amount: Int, val from: Int, val to: Int) data class InputData(val stacks: Array<ArrayDeque<Char>>, val moves: List<MoveInstruction>) fun parseInput(input: String): InputData { fun parseStacks(data: String): Array<ArrayDeque<Char>> { val lines = data.lines().reversed() val numStacks = lines[0].replace(" ", "").length val stacks = Array(numStacks) { ArrayDeque<Char>() } lines.drop(1).forEach { line -> (0 until numStacks).forEach { index -> val char = line.getOrElse(index*4 + 1) { ' ' } if (char != ' ') { stacks[index].addLast(char) } } } return stacks } fun parseMoves(data: String): List<MoveInstruction> { val matcher = """move (\d+) from (\d+) to (\d+)""".toRegex(); return data.trim().lines().map { val result = matcher.find(it.trim()) ?: error("parsing failed") val (_, amount, from, to) = result.groupValues MoveInstruction(amount.toInt(), from.toInt() - 1, to.toInt() - 1) } } val (stacksInput, instructionsInput) = input.replace("\r", "").split("\n\n") return InputData(parseStacks(stacksInput), parseMoves(instructionsInput)); } fun part1(input: String): String { val (stacks, moves) = parseInput(input) moves.forEach { move -> repeat(move.amount) { stacks[move.to].addLast(stacks[move.from].removeLast()) } } return stacks.map { it.last() }.joinToString("") } fun part2(input: String): String { val (stacks, moves) = parseInput(input) moves.forEach { move -> (1..move.amount) .map { stacks[move.from].removeLast() } .reversed() .forEach { stacks[move.to].addLast(it) } } return stacks.map { it.last() }.joinToString("") } val testInput = readInputFull("05.test") check(part1(testInput) == "CMZ") check(part2(testInput) == "MCD") val input = readInputFull("05") println(part1(input)) println(part2(input)) }
0
Kotlin
0
2
0c2a68cedfa5a0579292248aba8c73ad779430cd
2,314
advent-of-code-2022
Apache License 2.0
src/Day21.kt
cypressious
572,898,685
false
{"Kotlin": 77610}
fun main() { abstract class Monkey(val name: String) class NumberMonkey(name: String, val number: Long) : Monkey(name) { override fun toString() = "NumberMonkey(name='$name', number=$number)" } class OperationMonkey( name: String, val leftName: String, val operation: Char, val rightName: String ) : Monkey(name) { lateinit var left: Monkey lateinit var right: Monkey fun apply(left: Long, right: Long) = when (operation) { '+' -> left + right '-' -> left - right '*' -> left * right else -> left / right } fun invertLeft(right: Long, result: Long) = when (operation) { '+' -> result - right '-' -> result + right '*' -> result / right else -> result * right } fun invertRight(left: Long, result: Long) = when (operation) { '+' -> result - left '-' -> left - result '*' -> result / left else -> left / result } override fun toString() = "OperationMonkey(name='$name', leftName='$leftName', operation=$operation, rightName='$rightName')" } val regex = ":? ".toRegex() fun parse(input: List<String>): Map<String, Monkey> { val monkeys = input.map { line -> val parts = line.split(regex) if (parts.size == 2) { NumberMonkey(parts[0], parts[1].toLong()) } else { OperationMonkey(parts[0], parts[1], parts[2].first(), parts[3]) } }.associateBy { it.name } for (monkey in monkeys.values.filterIsInstance<OperationMonkey>()) { monkey.left = monkeys.getValue(monkey.leftName) monkey.right = monkeys.getValue(monkey.rightName) } return monkeys } fun Monkey.getNumber(): Long { if (this is NumberMonkey) return number this as OperationMonkey return apply(left.getNumber(), right.getNumber()) } fun part1(input: List<String>): Long { val monkeys = parse(input) return monkeys.getValue("root").getNumber() } fun part2(input: List<String>): Long { val monkeys = parse(input) val root = monkeys.getValue("root") as OperationMonkey fun Monkey.findHuman(path: MutableSet<Monkey>): Monkey? { if (name == "humn") { path += this return this } if (this !is OperationMonkey) return null left.findHuman(path)?.let { path += this; return it } right.findHuman(path)?.let { path += this; return it } return null } val pathToHuman = mutableSetOf<Monkey>().also { root.findHuman(it) } fun Monkey.getHumanNumber(result: Long): Long { if (name == "humn") return result this as OperationMonkey return if (left in pathToHuman) { left.getHumanNumber(invertLeft(right.getNumber(), result)) } else { right.getHumanNumber(invertRight(left.getNumber(), result)) } } return if (root.left in pathToHuman) { root.left.getHumanNumber(root.right.getNumber()) } else { root.right.getHumanNumber(root.left.getNumber()) } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day21_test") check(part1(testInput) == 152L) check(part2(testInput) == 301L) val input = readInput("Day21") println(part1(input)) println(part2(input)) }
0
Kotlin
0
1
7b4c3ee33efdb5850cca24f1baa7e7df887b019a
3,694
AdventOfCode2022
Apache License 2.0
string-similarity/src/commonMain/kotlin/com/aallam/similarity/WeightedLevenshtein.kt
aallam
597,692,521
false
null
package com.aallam.similarity import kotlin.math.min /** * Implementation of Levenshtein that allows to define different weights for different character substitutions. * * @param weights the strategy to determine character operations weights. */ public class WeightedLevenshtein( private val weights: OperationsWeights ) { public fun distance(first: CharSequence, second: CharSequence, limit: Double = Double.MAX_VALUE): Double { if (first == second) return 0.0 if (first.isEmpty()) return second.length.toDouble() if (second.isEmpty()) return first.length.toDouble() // initial costs is the edit distance from an empty string, which corresponds to the characters to insert. // the array size is : length + 1 (empty string) var cost = DoubleArray(first.length + 1) var newCost = DoubleArray(first.length + 1) first.forEachIndexed { i, char -> cost[i + 1] = cost[i] + weights.insertion(char) } for (i in 1..second.length) { // calculate new costs from the previous row. // the first element of the new row is the edit distance (deletes) to match empty string val secondChar = second[i - 1] val deletionCost = weights.deletion(secondChar) newCost[0] = cost[0] + deletionCost var minCost = newCost[0] // fill in the rest of the row for (j in 1..first.length) { // if it's the same char at the same position, no edit cost. val firstChar = first[j - 1] val edit = if (firstChar == secondChar) 0.0 else weights.substitution(firstChar, secondChar) val replace = cost[j - 1] + edit val insert = cost[j] + weights.insertion(secondChar) val delete = newCost[j - 1] + weights.deletion(firstChar) newCost[j] = minOf(insert, delete, replace) minCost = min(minCost, newCost[j]) } if (minCost >= limit) return limit // flip references of current and previous row val swap = cost cost = newCost newCost = swap } return cost.last() } } /** * Used to indicate the cost of character operations (add, replace, delete). * The cost should always be in the range `[O, 1]`. * * Default implementation of all operations is `1.0`. * * Examples: * - In an OCR application, cost('o', 'a') could be 0.4. * - In a check-spelling application, cost('u', 'i') could be 0.4 because these are next to each other on the keyboard. */ public interface OperationsWeights { /** * Indicate the cost of substitution. * The cost in the range `[0, 1]`. * * @param first first character of the substitution. * @param second second character of the substitution. */ public fun substitution(first: Char, second: Char): Double = 1.0 /** * Get the cost to delete a given character. * The cost in the range `[0, 1]`. * * @param char the character being inserted. */ public fun deletion(char: Char): Double = 1.0 /** * Get the cost to insert a given character. * The cost in the range `[0, 1]`. * * @param char the character being inserted. */ public fun insertion(char: Char): Double = 1.0 }
0
Kotlin
0
1
40cd4eb7543b776c283147e05d12bb840202b6f7
3,391
string-similarity-kotlin
MIT License
src/Day04.kt
Narmo
573,031,777
false
{"Kotlin": 34749}
fun main() { fun IntRange.fullyContains(other: IntRange): Boolean = this.first <= other.first && this.last >= other.last fun findOverlaps(input: List<String>, shouldFullyContain: Boolean): Int = input.map { pair -> pair.split(",").map { range -> range.split("-").map { it.toInt() }.run { this[0]..this[1] } }.let { (first, second) -> if (shouldFullyContain) { first.fullyContains(second) || second.fullyContains(first) } else { first.intersect(second).isNotEmpty() } } }.count { it } fun part1(input: List<String>): Int = findOverlaps(input, true) fun part2(input: List<String>): Int = findOverlaps(input, false) val testInput = readInput("Day04_test") check(part1(testInput) == 2) check(part2(testInput) == 4) val input = readInput("Day04") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
335641aa0a964692c31b15a0bedeb1cc5b2318e0
847
advent-of-code-2022
Apache License 2.0
src/main/kotlin/days/Day15.kt
hughjdavey
433,597,582
false
{"Kotlin": 53042}
package days import util.Utils import java.util.PriorityQueue class Day15 : Day(15) { private val floor = inputList.flatMapIndexed { y, row -> row.mapIndexed { x, c -> Position(Utils.Coord(x, y), c.digitToInt()) } } override fun partOne(): Any { return leastRiskyPath(floor) } override fun partTwo(): Any { val origX = inputList.first().length val origY = inputList.size val fullFloor = (0 until origY * 5).flatMap { y -> (0 until origX * 5).map { x -> val origRisk = inputList[y % origY][x % origX] val computedRisk = (origRisk.digitToInt() + x / origX + y / origY) Position(Utils.Coord(x, y), if (computedRisk < 10) computedRisk else computedRisk % 10 + 1) } } return leastRiskyPath(fullFloor) } data class Position(val coord: Utils.Coord, val risk: Int) { var distance: Int = Int.MAX_VALUE var prev: Position? = null } private fun leastRiskyPath(floor: List<Position>): Int { val floorArr = floor.chunked(floor.maxOf { it.coord.x } + 1).map { it.toTypedArray() }.toTypedArray() val maxX = floorArr.first().size val maxY = floorArr.size dijkstra(floorArr, maxX, maxY) return generateSequence(floor.last()) { it.prev }.sumOf { it.risk } - floor.first().risk } // see https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm#Pseudocode // and https://en.wikipedia.org/wiki/Dijkstra's_algorithm#Using_a_priority_queue private fun dijkstra(floor: Array<Array<Position>>, maxX: Int, maxY: Int) { val positions = PriorityQueue<Position>(Comparator.comparingInt { it.distance }) floor[0][0].distance = 0 positions.add(floor[0][0]) while (positions.isNotEmpty()) { val u = positions.poll() val neighbours = u.coord.getAdjacent(false) .filter { (x, y) -> x in 0 until maxX && y in 0 until maxY } .map { (x, y) -> floor[y][x] } neighbours.forEach { v -> val alt = u.distance + v.risk if (alt < v.distance) { v.distance = alt v.prev = u positions.offer(v) } } } } }
0
Kotlin
0
0
a3c2fe866f6b1811782d774a4317457f0882f5ef
2,285
aoc-2021
Creative Commons Zero v1.0 Universal
advent-of-code/src/main/kotlin/com/akikanellis/adventofcode/year2022/Day09.kt
akikanellis
600,872,090
false
{"Kotlin": 142932, "Just": 977}
package com.akikanellis.adventofcode.year2022 import com.akikanellis.adventofcode.year2022.utils.Point import kotlin.math.absoluteValue object Day09 { fun numberOfPositionsTailVisited(input: String, numberOfKnots: Int) = input.lines() .filter { it.isNotBlank() } .map { it.split(" ") } .flatMap { (direction, times) -> (1..times.toInt()).map { Direction.valueOf(direction) } } .fold(Knots(numberOfKnots)) { knots, direction -> knots.move(direction) } .tail .positionsVisited .size private enum class Direction { U, D, L, R } private data class Knots(private val knots: List<Knot>) { constructor(numberOfKnots: Int) : this((1..numberOfKnots).map { Knot() }) val head = knots.first() val tail = knots.last() fun move(direction: Direction): Knots { val newHead = head.move(direction) val newKnots = knots .drop(1) .fold(listOf(newHead)) { latestKnots, tail -> latestKnots + tail.follow(latestKnots.last()) } return Knots(newKnots) } } private data class Knot( val currentPosition: Point = Point.ZERO, val positionsVisited: Set<Point> = setOf(currentPosition) ) { val x = currentPosition.x val y = currentPosition.y fun move(direction: Direction): Knot { val newPosition = when (direction) { Direction.U -> currentPosition.plusY() Direction.D -> currentPosition.minusY() Direction.L -> currentPosition.minusX() Direction.R -> currentPosition.plusX() } return Knot( currentPosition = newPosition, positionsVisited = positionsVisited + newPosition ) } fun follow(otherKnot: Knot): Knot { if (touches(otherKnot)) return this val newPosition = Point( x = when { otherKnot.x > x -> x + 1 otherKnot.x < x -> x - 1 else -> x }, y = when { otherKnot.y > y -> y + 1 otherKnot.y < y -> y - 1 else -> y } ) return Knot( currentPosition = newPosition, positionsVisited = positionsVisited + newPosition ) } private fun touches(otherKnot: Knot) = (otherKnot.x - x).absoluteValue <= 1 && (otherKnot.y - y).absoluteValue <= 1 } }
8
Kotlin
0
0
036cbcb79d4dac96df2e478938de862a20549dce
2,717
advent-of-code
MIT License
src/main/kotlin/com/dmc/advent2022/Day10.kt
dorienmc
576,916,728
false
{"Kotlin": 86239}
package com.dmc.advent2022 //--- Day 10: Cathode-Ray Tube --- class Day10 : Day<Int> { override val index = 10 fun parseInput(input: List<String>) : List<Int> = buildList { add(1) // start value input.forEach{ line -> when { line.startsWith("noop") -> { add(0) } line.startsWith("addx") -> { add(0) // First cycle there is no change add(line.substringAfter(" ").toInt()) // Second cycle the change is done } else -> { /*nothing*/ } } } } override fun part1(input: List<String>): Int { val parsedInput = parseInput(input) val signals = parsedInput.runningReduce(Int::plus) return signals.signalStrengths(20,40).sum() } fun part2AsString(input: List<String>): String { val parsedInput = parseInput(input) val signals = parsedInput.runningReduce(Int::plus) val pixels = signals.toPixels().map{ if(it) "#" else "."}.joinToString("") return pixels.drawGrid(40) } private fun String.drawGrid(width: Int) : String = this.windowed(width, width, false).joinToString(separator = "\n") override fun part2(input: List<String>): Int { // Not implemented return 0 } } fun List<Int>.signalStrengths(start: Int, stepSize: Int): List<Int> = (start..this.size step stepSize).map { cycle -> cycle * this[cycle - 1] } fun List<Int>.toPixels(): List<Boolean> = this.mapIndexed { index, signal -> (index % 40) in (signal-1..signal+1) } fun main() { val day = Day10() val testInput = readInput(day.index, true) check(day.part1(testInput) == 13140) val input = readInput(day.index) day.part1(input).println() day.part2AsString(testInput).println() day.part2AsString(input).println() }
0
Kotlin
0
0
207c47b47e743ec7849aea38ac6aab6c4a7d4e79
1,942
aoc-2022-kotlin
Apache License 2.0
src/main/kotlin/net/wrony/aoc2023/a14/14.kt
kopernic-pl
727,133,267
false
{"Kotlin": 52043}
package net.wrony.aoc2023.a14 import kotlin.io.path.Path import kotlin.io.path.readLines fun main() { Path("src/main/resources/14.txt").readLines().map { it.toCharArray() }.toTypedArray() .also { transpose(it).map { r -> shiftTheRow(r) }.toTypedArray().let { arr -> transpose(arr) } .let { arr -> calcLoad(arr) } .let { println(it) } }.let lit@{ var arr = it val hashToIdxAndWeight = mutableMapOf<Int, Pair<Int, Int>>() (0..10000).forEach {i -> arr.hash().let { h -> if (hashToIdxAndWeight.containsKey(h)) {println("cycle detected: ${hashToIdxAndWeight[h]} -> $i"); return@lit Triple(hashToIdxAndWeight, hashToIdxAndWeight[h]!!.first, i)} } hashToIdxAndWeight[arr.hash()] = i to calcLoad(arr) arr = cycle(arr) } Triple(hashToIdxAndWeight, 0, 0) }.let { (hashToIdxAndWeight, first , second) -> val nbofcycles : Long = 1000000000 (first..second).forEach { if ((nbofcycles - it) % (second-first) == 0L) { println("cycle index at mark: $it") return@let hashToIdxAndWeight.values.first { (idx, _) -> idx == it }.second } } }.let { println( "answer 2: $it" ) } } fun Array<CharArray>.hash(): Int { var hash = 0 for (r in this.indices) { for (c in this[r].indices) { hash = hash * 31 + this[r][c].hashCode() } } return hash } fun cycle(arr: Array<CharArray>): Array<CharArray> { var out = arr repeat(4) { out = transpose(out).map { r -> shiftTheRow(r) }.toTypedArray().let { transpose(it) }.let { rotateClockwise(it) } } return out } private fun calcLoad(arr: Array<CharArray>) = arr.map { r -> r.count { c -> c == 'O' } } .foldIndexed(0) { idx: Int, acc: Int, v: Int -> acc + v * (arr.size - idx) } fun shiftTheRow(r: CharArray): CharArray { val out = CharArray(r.size) { '.' } var lastFree = 0 for (i in r.indices) { when (r[i]) { 'O' -> { out[lastFree] = 'O'; lastFree++ } '#' -> { out[i] = '#'; lastFree = i + 1 } } } return out } private fun transpose(arr: Array<CharArray>): Array<CharArray> { val transpose = Array(arr.size) { CharArray(arr.size) } for (c in arr.indices) { for (r in arr[c].indices) { transpose[c][r] = arr[r][c] } } return transpose } fun rotateClockwise(arr: Array<CharArray>): Array<CharArray> { val rotated = Array(arr.size) { CharArray(arr.size) } for (r in arr.indices) { for (c in arr[r].indices) { rotated[c][arr.size - 1 - r] = arr[r][c] } } return rotated }
0
Kotlin
0
0
1719de979ac3e8862264ac105eb038a51aa0ddfb
2,905
aoc-2023-kotlin
MIT License
src/year2023/16/Day16.kt
Vladuken
573,128,337
false
{"Kotlin": 327524, "Python": 16475}
package year2023.`16` import readInput import utils.printDebug import utils.printlnDebug private const val CURRENT_DAY = "16" private data class Point( val x: Int, val y: Int, ) { val left get() = Point(x - 1, y) val right get() = Point(x + 1, y) val top get() = Point(x, y - 1) val bottom get() = Point(x, y + 1) override fun toString(): String = "[$x,$y]" } enum class PointConfig(val value: String) { Vertical("|"), Horizontal("-"), Angle1("/"), Angle2("\\"), EmptySpace("."); override fun toString(): String = value; } private fun String.toPointConfig(): PointConfig { return when (this) { "|" -> PointConfig.Vertical "-" -> PointConfig.Horizontal "/" -> PointConfig.Angle1 "\\" -> PointConfig.Angle2 "." -> PointConfig.EmptySpace else -> error("ILLEGAL PIPE $this") } } private fun parseMap(input: List<String>): Map<Point, PointConfig> { val mutableMap = mutableMapOf<Point, PointConfig>() input.forEachIndexed { y, line -> line.split("") .filter { it.isNotBlank() } .forEachIndexed { x, value -> mutableMap[Point(x, y)] = value.toPointConfig() } } return mutableMap } enum class Direction { BOTTOM, TOP, LEFT, RIGHT; override fun toString(): String { return when (this) { BOTTOM -> "B" TOP -> "T" LEFT -> "L" RIGHT -> "R" } } } private data class PointWithDirection( val point: Point, val direction: Direction ) private fun Direction.calculateNextPoint(currentPoint: Point): Point { return when (this) { Direction.LEFT -> currentPoint.left Direction.RIGHT -> currentPoint.right Direction.TOP -> currentPoint.top Direction.BOTTOM -> currentPoint.bottom } } private fun printMap( initialMap: Map<Point, PointConfig>, visitedMaps: Set<PointWithDirection>, ) { val number = initialMap.maxOf { it.key.x + 1 } val sortedPoints = initialMap.keys.toList() .sortedWith(compareBy({ it.y }, { it.x })) sortedPoints.forEachIndexed { index, point -> if (index % number == 0) { printlnDebug { "" } } printDebug { if (visitedMaps.any { it.point == point }) { "#" } else { "." } } } printlnDebug { "" } } private fun newPointWithDirection(p: Point, newDir: Direction): PointWithDirection { val newP = newDir.calculateNextPoint(p) return PointWithDirection(newP, newDir) } private fun processStartPoint( startPoint: Point, startDirection: Direction, configuration: Map<Point, PointConfig>, ): Int { val visitedPointsAndDirections = mutableSetOf<PointWithDirection>() val queue = ArrayDeque(listOf(PointWithDirection(startPoint, startDirection))) while (queue.isNotEmpty()) { val currentPoint = queue.removeFirst() val p = currentPoint.point val dir = currentPoint.direction val currentConfig = configuration[p] ?: continue if (visitedPointsAndDirections.contains(currentPoint)) continue visitedPointsAndDirections.add(currentPoint) when (currentConfig) { PointConfig.Vertical -> { when (dir) { Direction.LEFT, Direction.RIGHT -> { queue.add(newPointWithDirection(p, Direction.BOTTOM)) queue.add(newPointWithDirection(p, Direction.TOP)) } Direction.TOP, Direction.BOTTOM -> queue.add(newPointWithDirection(p, dir)) } } PointConfig.Horizontal -> when (dir) { Direction.LEFT, Direction.RIGHT -> queue.add(newPointWithDirection(p, dir)) Direction.TOP, Direction.BOTTOM -> { queue.add(newPointWithDirection(p, Direction.LEFT)) queue.add(newPointWithDirection(p, Direction.RIGHT)) } } PointConfig.Angle1 -> when (dir) { Direction.LEFT -> queue.add(newPointWithDirection(p, Direction.BOTTOM)) Direction.RIGHT -> queue.add(newPointWithDirection(p, Direction.TOP)) Direction.TOP -> queue.add(newPointWithDirection(p, Direction.RIGHT)) Direction.BOTTOM -> queue.add(newPointWithDirection(p, Direction.LEFT)) } PointConfig.Angle2 -> when (dir) { Direction.LEFT -> queue.add(newPointWithDirection(p, Direction.TOP)) Direction.RIGHT -> queue.add(newPointWithDirection(p, Direction.BOTTOM)) Direction.TOP -> queue.add(newPointWithDirection(p, Direction.LEFT)) Direction.BOTTOM -> queue.add(newPointWithDirection(p, Direction.RIGHT)) } PointConfig.EmptySpace -> queue.add(newPointWithDirection(p, dir)) } } // printMap( // initialMap = configuration, // visitedMaps = visitedPointsAndDirections, // ) return visitedPointsAndDirections.distinctBy { it.point }.size } fun main() { fun part1(input: List<String>): Int { val map = parseMap(input) return processStartPoint( startPoint = Point(0, 0), startDirection = Direction.RIGHT, configuration = map, ) } fun part2(input: List<String>): Int { val map = parseMap(input) val allVariants = map.keys.flatMap { listOf( PointWithDirection(it, Direction.RIGHT), PointWithDirection(it, Direction.LEFT), PointWithDirection(it, Direction.TOP), PointWithDirection(it, Direction.BOTTOM), ) } var counter = 0 return allVariants .maxOf { counter++ if (counter % 500 == 0) { printlnDebug { "Processed ${counter.toFloat() / allVariants.size * 100}%" } } processStartPoint( startPoint = it.point, startDirection = it.direction, configuration = map, ) } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day${CURRENT_DAY}_test") val part1Test = part1(testInput) println(part1Test) check(part1Test == 46) val part2Test = part2(testInput) println(part2Test) check(part2Test == 51) val input = readInput("Day$CURRENT_DAY") // Part 1 val part1 = part1(input) println(part1) check(part1 == 7496) // Part 2 val part2 = part2(input) println(part2) check(part2 == 7932) }
0
Kotlin
0
5
c0f36ec0e2ce5d65c35d408dd50ba2ac96363772
6,869
KotlinAdventOfCode
Apache License 2.0
src/Day03.kt
jstapels
572,982,488
false
{"Kotlin": 74335}
fun main() { fun charValue(c: Char) = when (c) { in 'A'..'Z' -> c.code - 'A'.code + 27 in 'a'..'z' -> c.code - 'a'.code + 1 else -> throw IllegalArgumentException() } fun part1(input: List<String>): Int { return input.asSequence() .map { it.toCharArray() } .map { Pair(it.slice(0 until it.size / 2), it.slice(it.size / 2 until it.size)) } .map { (l, r) -> l.intersect(r) } .map { charValue(it.single()) } .sum() } fun part2(input: List<String>): Int { return input.asSequence() .map { it.toCharArray() } .chunked(3) .map { (a, b, c) -> a.intersect(b.toSet()).intersect(c.toSet()) } .map { charValue(it.single()) } .sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day03_test") checkThat(part1(testInput), 157) checkThat(part2(testInput), 70) val input = readInput("Day03") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
0d71521039231c996e2c4e2d410960d34270e876
1,092
aoc22
Apache License 2.0
src/day05/Day05.kt
commanderpepper
574,647,779
false
{"Kotlin": 44999}
package day05 import readInput fun main(){ val input = readInput("day05") val stacks: List<MutableList<Char>> = createStacks(input) val instructions: List<Instruction> = parseInstructions(input) // println(partOne(instructions, stacks)) println(partTwo(instructions, stacks)) } private fun partTwo( instructions: List<Instruction>, stacks: List<MutableList<Char>> ) : String { instructions.forEach { instruction -> val boxesToMove = stacks[instruction.source].take(instruction.amount) repeat(instruction.amount) { stacks[instruction.source].removeAt(0) } stacks[instruction.target].addAll(0, boxesToMove) } return stacks.topCrates() } private fun partOne( instructions: List<Instruction>, stacks: List<MutableList<Char>> ): String { instructions.forEach { instruction -> repeat(instruction.amount) { val box = stacks[instruction.source].first() stacks[instruction.target].add(0, box) stacks[instruction.source].removeAt(0) } } return stacks.topCrates() } private fun List<MutableList<Char>>.topCrates(): String { return this.map { it.firstOrNull() ?: "" }.joinToString(separator = "") } private fun createStacks(input: List<String>): List<MutableList<Char>> { val stackRows = input.takeWhile { it.contains('[') } return (1..stackRows.last().length step 4).map { index -> stackRows .mapNotNull { it.getOrNull(index) } .filter { it.isUpperCase() } .toMutableList() } } private fun parseInstructions(input: List<String>): List<Instruction> = input .dropWhile { !it.startsWith("move") } .map { row -> row.split(" ").let { parts -> Instruction(parts[1].toInt(), parts[3].toInt() - 1, parts[5].toInt() - 1) } } // Subtract one from source and target to follow instructions from input private data class Instruction(val amount: Int, val source: Int, val target: Int)
0
Kotlin
0
0
fef291c511408c1a6f34a24ed7070ceabc0894a1
2,066
advent-of-code-kotlin-2022
Apache License 2.0
src/main/kotlin/day03_binary_diagnostic/BinaryDiagnostic.kt
barneyb
425,532,798
false
{"Kotlin": 238776, "Shell": 3825, "Java": 567}
package day03_binary_diagnostic import util.CountedToForeverException import util.countForever /** * Bit masking is the main idea here, along with avoiding needless redundant * processing. Since the gamma and epsilon rates are inverses, computing one * directly gives the other. * * Part two makes the masking more interesting, as there are a lot more ops to * perform. It also requires an unknown-endpoint iteration through the bits, to * repeatedly filter the collection of numbers. */ fun main() { util.solve(3687446, ::partOne) util.solve(4406844, ::partTwo) } fun partOne(input: String): Long { val lines = input.lines() val freqs = IntArray(lines.first().length) for (line in lines) { line.forEachIndexed { i, c -> freqs[i] += if (c == '1') 1 else -1 } } var gamma = 0L var epsilon = 0L freqs.forEach { c -> gamma = gamma shl 1 epsilon = epsilon shl 1 if (c > 0) ++gamma else ++epsilon } return gamma * epsilon } private fun Collection<Long>.findRating( width: Int, bitCrit: (Int) -> Boolean ): Long { countForever().fold(this) { numbers, i -> if (numbers.isEmpty()) throw NoSuchElementException() if (numbers.size == 1) return numbers.first() val mask = 1L shl (width - i - 1) val hot = bitCrit(numbers.fold(0) { n, line -> n + if (line and mask != 0L) 1 else -1 }) numbers.filter { if (it and mask != 0L) hot else !hot } } throw CountedToForeverException() } fun partTwo(input: String): Long { val lines = input.lines() val width = lines.first().length val numbers = lines.map { it.toLong(2) } val oxygen = numbers.findRating(width) { it >= 0 } val co2 = numbers.findRating(width) { it < 0 } return oxygen * co2 }
0
Kotlin
0
0
a8d52412772750c5e7d2e2e018f3a82354e8b1c3
1,855
aoc-2021
MIT License
src/Day10.kt
dustinlewis
572,792,391
false
{"Kotlin": 29162}
import kotlin.math.floor fun main() { fun part1(input: List<String>): Int { val instructions = input.map { val split = it.split(" ") if (split[0] == "noop") Pair(split[0], 0) else Pair(split[0], split[1].toInt()) } println(instructions) val register = mutableListOf<Int>() var lastIncrease = 0 instructions.forEach { val cycles = if(it.first == "noop") 1 else 2 val newRegisterValue = if(register.isEmpty()) 1 else register[register.lastIndex] + lastIncrease for (c in 1..cycles) { register.add(newRegisterValue) } lastIncrease = it.second } val signalStrengths = mutableListOf<Int>() for(i in 20..220 step 40) { signalStrengths.add(i * register[i - 1]) } println(signalStrengths) return signalStrengths.sum() } fun part2(input: List<String>): Int { val instructions = input.map { val split = it.split(" ") if (split[0] == "noop") Pair(split[0], 0) else Pair(split[0], split[1].toInt()) } val register = mutableListOf<Int>() var lastIncrease = 0 instructions.forEach { val cycles = if(it.first == "noop") 1 else 2 val newRegisterValue = if(register.isEmpty()) 1 else register[register.lastIndex] + lastIncrease for (c in 1..cycles) { register.add(newRegisterValue) } lastIncrease = it.second } val screenLength = 40 val screenRows = register .foldIndexed("") { index, acc, i -> val position = index - (floor((index) / screenLength.toDouble()) * screenLength).toInt() // val position = when { // index + 1 > 200 -> index - 200 // index + 1 > 160 -> index - 160 // index + 1 > 120 -> index - 120 // index + 1 > 80 -> index - 80 // index + 1 > 40 -> index - 40 // else -> index // } acc + if((i - 1..i + 1).contains(position)) "#" else "." } .chunked(screenLength) screenRows.forEach(::println) return input.size } val input = readInput("Day10") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
c8d1c9f374c2013c49b449f41c7ee60c64ef6cff
2,426
aoc-2022-in-kotlin
Apache License 2.0
Day 05 - Kotlin/source.kt
Lank891
433,842,037
false
{"TypeScript": 7986, "Scala": 7724, "Processing": 6002, "C++": 4359, "Dart": 3800, "Go": 3508, "Kotlin": 3409, "Python": 3330, "C": 3108, "Java": 3003, "C#": 2833, "Rust": 2624, "Ruby": 2441, "Haskell": 1526, "CoffeeScript": 1422, "JavaScript": 1399, "R": 846}
import java.io.File import kotlin.math.sign const val boardSize: Int = 1000; typealias XY = Pair<Int, Int>; typealias VentPath = Pair<XY, XY>; typealias Board = Array<Array<Int>> fun ventPathToString(path: VentPath): String { return "Path (${path.first.first}, ${path.first.second}) -> (${path.second.first}, ${path.second.second})" } fun printBoard(board: Board) { for(y in 0 until boardSize){ for(x in 0 until boardSize) { print("${if (board[x][y] == 0) '.' else board[x][y]} "); } println(); } } fun isVentPathOblique(path: VentPath): Boolean { return path.first.first != path.second.first && path.first.second != path.second.second; } fun commaSeparatedNumbersToXY(numbers: String): XY { val split: List<Int> = numbers.split(",").map{ str: String -> str.toInt()} return Pair(split[0], split[1]); } fun inputLineToVentPath(line: String): VentPath { val splits: List<String> = line.split("->").map{ str: String -> str.trim()}; return Pair(commaSeparatedNumbersToXY(splits[0]), commaSeparatedNumbersToXY(splits[1])); } fun addNotObliqueVent(board: Board, path: VentPath) { fun getXRange(path: VentPath): IntProgression { return if(path.first.first < path.second.first){ (path.second.first downTo path.first.first) } else { (path.first.first downTo path.second.first) } } fun getYRange(path: VentPath): IntProgression { return if(path.first.second < path.second.second){ (path.second.second downTo path.first.second) } else { (path.first.second downTo path.second.second) } } for(x in getXRange(path)) { for(y in getYRange(path)) { board[x][y]++; } } } fun addObliqueVent(board: Board, path: VentPath) { val (left: XY, right: XY) = if (path.first.first < path.second.first) Pair(path.first, path.second) else Pair(path.second, path.first); var yVal: Int = left.second; val yDiff: Int = -sign((left.second - right.second).toDouble()).toInt(); for(x in left.first..right.first) { board[x][yVal] += 1; yVal += yDiff; } } fun getOverlappedCells(board: Board): Int { var sum: Int = 0; for(column in board) { for(cell in column) { if(cell > 1) { sum++; } } } return sum; } fun main(args: Array<String>) { val vents: List<VentPath> = File("./input.txt").readLines().map{ str: String -> inputLineToVentPath(str)}; val (obliqueVents: List<VentPath>, notObliqueVents: List<VentPath>) = vents.partition { vent: VentPath -> isVentPathOblique(vent) }; /* println("--- OBLIQUE VENTS ---") obliqueVents.forEach { vent: VentPath -> println(ventPathToString(vent))}; println("--- NOT OBLIQUE VENTS ---") notObliqueVents.forEach { vent: VentPath -> println(ventPathToString(vent))}; */ val board: Board = Array(boardSize) { _ -> Array(boardSize) { _ -> 0 } }; // Part 1 notObliqueVents.forEach { vent: VentPath -> addNotObliqueVent(board, vent) }; println("Part 1 overlapped cells: ${getOverlappedCells(board)}"); //printBoard(board); // Part 2 obliqueVents.forEach { vent: VentPath -> addObliqueVent(board, vent) }; println("Part 2 overlapped cells: ${getOverlappedCells(board)}"); //printBoard(board); }
0
TypeScript
0
1
4164b707630e4d6e84ede983f494e56470f3d080
3,409
Advent-of-Code-2021
MIT License
src/main/kotlin/org/example/adventofcode/puzzle/Day07.kt
peterlambrechtDev
573,146,803
false
{"Kotlin": 39213}
package org.example.adventofcode.puzzle import org.example.adventofcode.util.FileLoader object Day07 { fun part1(filePath: String): Int { val stringLines = FileLoader.loadFromFile<String>(filePath) var tree: FileNode? = buildTree(stringLines) populateDirectorySizes(tree!!) val list = getListOfDirectories(tree) return list.filter { it.size < 100000 } .map { it.size } .sum() } fun part2(filePath: String): Int { val stringLines = FileLoader.loadFromFile<String>(filePath) var tree: FileNode? = buildTree(stringLines) populateDirectorySizes(tree!!) val list = getListOfDirectories(tree) val freeSpace = 70000000 - tree.size val amountToDelete = 30000000 - freeSpace return list.filter { it.size > amountToDelete } .sortedBy { it.size } .first().size } private fun buildTree(stringLines: List<String>): FileNode? { var tree: FileNode? = null var currentNode: FileNode? = null for (line in stringLines) { if (line.startsWith("$ cd")) { if (line.contains("..")) { currentNode = currentNode?.parent } else { val name = line.split(" ")[2] if (tree == null) { tree = FileNode(Type.FOLDER, name, 0, null, mutableListOf()) currentNode = tree } else { val newFileNode = FileNode(Type.FOLDER, name, 0, currentNode, mutableListOf()) currentNode?.children?.add(newFileNode) currentNode = newFileNode } } } else { if (line[0].isDigit()) { val fileParts = line.split(" ") currentNode?.children?.add( FileNode( Type.FILE, fileParts[1], fileParts[0].toInt(), currentNode, null ) ) } } } return tree } fun getListOfDirectories(node: FileNode): MutableList<FileNode> { val list = mutableListOf<FileNode>() if (node.type == Type.FOLDER) { list.add(node) for (child in node.children!!) { list.addAll(getListOfDirectories(child)) } } return list } fun populateDirectorySizes(node: FileNode): Int { if (node.size == 0) { for (child in node.children!!) { node.size += populateDirectorySizes(child) } } else { return node.size } return node.size } } data class FileNode( val type: Type, val name: String, var size: Int, var parent: FileNode?, var children: MutableList<FileNode>? ) { override fun toString(): String { return "{$type, $name, $size, children: $children}" } } enum class Type { FILE, FOLDER } fun main() { val day = "day07" val dayObj = Day07 println("Example 1: ${dayObj.part1("/${day}_example.txt")}") println("Solution 1: ${dayObj.part1("/${day}.txt")}") println("Example 2: ${dayObj.part2("/${day}_example.txt")}") println("Solution 2: ${dayObj.part2("/${day}.txt")}") }
0
Kotlin
0
0
aa7621de90e551eccb64464940daf4be5ede235b
3,532
adventOfCode2022
MIT License
src/Day04.kt
Riari
574,587,661
false
{"Kotlin": 83546, "Python": 1054}
import kotlin.math.abs fun main() { // Processes input into lists of ints for each pair of assignments fun processInput(input: List<String>): List<Int> { val regex = Regex("[0-9]+") val assignments = mutableListOf<Int>() for (line in input) { assignments.addAll(regex.findAll(line).toList().map { it.value.toInt() }) } return assignments } fun part1(assignments: List<Int>): Int { var fullyContained = 0 for (ranges in assignments.chunked(4)) { if ((ranges[0] >= ranges[2] && ranges[1] <= ranges[3]) || (ranges[0] <= ranges[2] && ranges[1] >= ranges[3])) { fullyContained++ } } return fullyContained } fun part2(assignments: List<Int>): Int { var overlaps = 0 for (ranges in assignments.chunked(4)) { if (!(ranges[0] > ranges[3] || ranges[1] < ranges[2])) { overlaps++ } } return overlaps } val testInput = processInput(readInput("Day04_test")) check(part1(testInput) == 2) check(part2(testInput) == 4) val input = processInput(readInput("Day04")) println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
8eecfb5c0c160e26f3ef0e277e48cb7fe86c903d
1,250
aoc-2022
Apache License 2.0
src/Day04.kt
mcrispim
573,449,109
false
{"Kotlin": 46488}
fun main() { fun Set<Int>.contains(s: Set<Int>): Boolean = this.intersect(s) == s fun part1(input: List<String>): Int { return input.count { line -> val limits = line.split("-", ",").map { it.toInt() } val (aStart, aEnd, bStart, bEnd) = limits val s1 = (aStart..aEnd).toSet() val s2 = (bStart..bEnd).toSet() s1.contains(s2) || s2.contains(s1) } } fun part2(input: List<String>): Int { return input.count { line -> val limits = line.split("-", ",").map { it.toInt() } val (aStart, aEnd, bStart, bEnd) = limits val s1 = (aStart..aEnd).toSet() val s2 = (bStart..bEnd).toSet() s1.subtract(s2) != s1 } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day04_test") check(part1(testInput) == 2) check(part2(testInput) == 4) val input = readInput("Day04") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
5fcacc6316e1576a172a46ba5fc9f70bcb41f532
1,048
AoC2022
Apache License 2.0
src/Day13.kt
Allagash
572,736,443
false
{"Kotlin": 101198}
import java.io.File // Advent of Code 2022, Day 13, Distress Signal fun compare(first: Packet, second: Packet) : Int { first.forEachIndexed { i, firstEl -> if (i > second.lastIndex) { return 1 // first is longer } val secondEl = second[i] val diff = if (firstEl.int != null && secondEl.int != null) { firstEl.int - secondEl.int } else if (firstEl.list != null && secondEl.list != null) { compare(firstEl.list, secondEl.list) } else { val firstPart = firstEl.int?.let { listOf(PacketElement(it, null)) } ?: firstEl.list val secondPart = secondEl.int?.let { listOf(PacketElement(it, null)) } ?: secondEl.list compare(firstPart!!, secondPart!!) } if (diff != 0) { return diff } } return first.size - second.size } data class PacketElement(val int: Int?, val list: List<PacketElement>?) typealias Packet = List<PacketElement> fun main() { fun readInputAsOneLine(name: String) = File("src", "$name.txt").readText().trim() fun getIndexMatchingBracket(input: String) : Int { check(input[0]=='[') var nested = 0 input.forEachIndexed { i, c -> if (c == '[') { nested++ } else if (c == ']') { nested-- } if (nested == 0) { return i } } check(false) return 0 } fun parsePacket(input: String) : Packet { check(input[0]=='[') check(input[input.lastIndex]==']') val sub = input.substring(1 until input.lastIndex) var idx = 0 val list = mutableListOf<PacketElement>() while(idx <= sub.lastIndex) { if (sub[idx] == '[') { val lastIdx = idx + getIndexMatchingBracket(sub.substring(idx)) val packet = parsePacket(sub.substring(idx..lastIdx)) list.add(PacketElement(null, packet)) idx = lastIdx + 2 // need move past right bracket and comma } else { var lastIdx = sub.indexOf(',', idx) if (lastIdx == -1) { lastIdx = sub.lastIndex + 1 } val number = sub.substring(idx until lastIdx).toInt() list.add(PacketElement(number, null)) idx = lastIdx + 1 } } return list.toList() } fun parse(input: String) = input.split("\n\n") .map {it.split("\n").map { parsePacket(it) }.let { it[0] to it[1] } } fun part1(input: String) = parse(input).foldIndexed(0) { i, acc, pair -> acc + if (compare(pair.first, pair.second) < 0) i + 1 else 0 // 1-based index } fun part2(input: String) : Int { val lines = input.split("\n").filter { it.isNotEmpty() }.toMutableList() lines.add("[[2]]") lines.add("[[6]]") val packets = lines.map { parsePacket(it) }.toMutableList() val two = packets[packets.lastIndex-1] val six = packets.last() packets.sortWith { first, second -> compare(first, second) } val twoIdx = packets.indexOf(two) + 1 // 1 based index val sixIdx = packets.indexOf(six) + 1 return twoIdx * sixIdx } val testInput = readInputAsOneLine("Day13_test") check(part1(testInput) == 13) check(part2(testInput) == 140) val input = readInputAsOneLine("Day13") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
8d5fc0b93f6d600878ac0d47128140e70d7fc5d9
3,573
AdventOfCode2022
Apache License 2.0
src/main/kotlin/Seeding.kt
alebedev
573,733,821
false
{"Kotlin": 82424}
import kotlin.math.abs fun main() = Seeding.solve() private object Seeding { fun solve() { var board = Board(readInput()) println("Initial") board.visualize() var i = 0 while (true) { println("$i") val direction = Direction.values()[i % 4] val (nextBoard, moved) = board.next(direction) if (moved == 0) { println("Stable after turn ${i + 1}") break } board = nextBoard i += 1 } // for (i in 0 until 10) { // board = board.next(direction) // println("after turn ${i + 1}") // board.visualize() // } // board.visualize() // println("Empty cells after 10 rounds: ${board.emptyCells()}") } private fun readInput(): Set<Pos> { val result = mutableSetOf<Pos>() generateSequence(::readLine).forEachIndexed { y, line -> line.toCharArray().forEachIndexed { x, char -> if (char == '#') result.add(Pos(x, y)) } } return result } class Board(val elves: Set<Pos>) { fun visualize() { val (xRange, yRange) = getBoundingRect() for (y in yRange) { for (x in xRange) { print(if (Pos(x, y) in elves) '#' else '.') } println() } println() } fun next(firstLook: Direction): Pair<Board, Int> { val firstLookIndex = Direction.values().indexOf(firstLook) val lookDirections = Direction.values().toList().subList(firstLookIndex, Direction.values().size) .plus(Direction.values().sliceArray(0 until firstLookIndex)) require(lookDirections.size == Direction.values().size && lookDirections.first() == firstLook) // println("Look directions: $lookDirections") val moves = mutableMapOf<Pos, Pos>() for (elf in elves) { var nextPos = elf if (elf.neighbours().any { elves.contains(it) }) { for (dir in lookDirections) { if (elf.directionNeighbours(dir.delta.x, dir.delta.y).none { pos -> elves.contains(pos) }) { nextPos = Pos(elf.x + dir.delta.x, elf.y + dir.delta.y) break } } // println("Move $elf -> $nextPos") } moves[elf] = nextPos } val targets = mutableSetOf<Pos>() val conflictingTargets = mutableSetOf<Pos>() for (move in moves.values) { if (move in targets) { conflictingTargets.add(move) } else { targets.add(move) } } val nextElves = moves.map { move -> if (move.value in conflictingTargets) { move.key } else { move.value } }.toSet() val moveCount = nextElves.count { it !in elves } return Pair(Board(nextElves), moveCount) } fun emptyCells(): Int { val (xRange, yRange) = getBoundingRect() return (1 + xRange.last - xRange.first) * (1 + yRange.last - yRange.first) - elves.size } private fun getBoundingRect(): Pair<IntRange, IntRange> { val minX = elves.minOf { it.x } val maxX = elves.maxOf { it.x } val minY = elves.minOf { it.y } val maxY = elves.maxOf { it.y } return Pair( minX..maxX, minY..maxY ) } } enum class Direction(val delta: Pos) { North(Pos(0, -1)), South(Pos(0, 1)), West(Pos(-1, 0)), East(Pos(1, 0)), } data class Pos(val x: Int, val y: Int) { fun neighbours(): List<Pos> = listOf( Pos(x - 1, y - 1), Pos(x, y - 1), Pos(x + 1, y - 1), Pos(x - 1, y), Pos(x + 1, y), Pos(x - 1, y + 1), Pos(x, y + 1), Pos(x + 1, y + 1) ) fun directionNeighbours(dx: Int, dy: Int): List<Pos> { require(abs(dx) <= 1 && abs(dy) <= 1 && abs(dx) + abs(dy) == 1) return if (dx != 0) { listOf(Pos(x + dx, y + dx), Pos(x + dx, y), Pos(x + dx, y - dx)) } else { listOf(Pos(x + dy, y + dy), Pos(x, y + dy), Pos(x - dy, y + dy)) } } } }
0
Kotlin
0
0
d6ba46bc414c6a55a1093f46a6f97510df399cd1
4,646
aoc2022
MIT License
src/main/kotlin/cc/stevenyin/leetcode/_0883_ProjectionAreaOf3DShapes.kt
StevenYinKop
269,945,740
false
{"Kotlin": 107894, "Java": 9565}
package cc.stevenyin.leetcode import kotlin.math.max /** * 883. Projection Area of 3D Shapes * https://leetcode.com/problems/projection-area-of-3d-shapes/ You are given an n x n grid where we place some 1 x 1 x 1 cubes that are axis-aligned with the x, y, and z axes. Each value v = grid[i][j] represents a tower of v cubes placed on top of the cell (i, j). We view the projection of these cubes onto the xy, yz, and zx planes. A projection is like a shadow, that maps our 3-dimensional figure to a 2-dimensional plane. We are viewing the "shadow" when looking at the cubes from the top, the front, and the side. Return the total area of all three projections. Example 1: <p> <img src="./shadow.png"></img> </p> Input: grid = [[1,2],[3,4]] Output: 17 Explanation: Here are the three projections ("shadows") of the shape made with each axis-aligned plane. Example 2: Input: grid = [[2]] Output: 5 Example 3: Input: grid = [[1,0],[0,2]] Output: 8 */ class _0883_ProjectionAreaOf3DShapes { fun projectionArea(grid: Array<IntArray>) = calcFrontView(grid) + calcSideView(grid) + calcTopView(grid) private fun calcTopView(grid: Array<IntArray>) = grid.fold(0) { sum, ints -> sum + ints.filter { i -> i > 0 }.size } private fun calcFrontView(grid: Array<IntArray>) = grid.fold(0) { sum, ints -> sum + ints.maxOrNull()!! } private fun calcSideView(grid: Array<IntArray>): Int { val cacheArray = IntArray(grid.size) for (i in grid.indices) { for (j in grid[i].indices) { cacheArray[j] = max(cacheArray[j], grid[i][j]); } } return cacheArray.sum(); } } fun main() { _0883_ProjectionAreaOf3DShapes().projectionArea(arrayOf(intArrayOf(1, 2), intArrayOf(3, 4))); }
0
Kotlin
0
1
748812d291e5c2df64c8620c96189403b19e12dd
1,765
kotlin-demo-code
MIT License
src/main/kotlin/me/peckb/aoc/_2015/calendar/day13/Day13.kt
peckb1
433,943,215
false
{"Kotlin": 956135}
package me.peckb.aoc._2015.calendar.day13 import javax.inject.Inject import me.peckb.aoc.generators.InputGenerator.InputGeneratorFactory import me.peckb.aoc.generators.PermutationGenerator import kotlin.math.max class Day13 @Inject constructor( private val permutationGenerator: PermutationGenerator, private val generatorFactory: InputGeneratorFactory ) { fun partOne(filename: String) = generatorFactory.forFile(filename).readAs(::happinessMeasurement) { input -> val seatingOptions = generateSeatingOptions(input) val people = seatingOptions.keys.toTypedArray() val peoplePermutations = permutationGenerator.generatePermutations(people) findBestArrangement(peoplePermutations, seatingOptions) } fun partTwo(filename: String) = generatorFactory.forFile(filename).readAs(::happinessMeasurement) { input -> val seatingOptions = generateSeatingOptions(input) var people = seatingOptions.keys.toTypedArray() people.forEach { neighbor -> seatingOptions.merge("me", mutableMapOf(neighbor to 0)) { cur, me -> (cur + me).toMutableMap() } seatingOptions[neighbor]!!["me"] = 0 } people = seatingOptions.keys.toTypedArray() val peoplePermutations = permutationGenerator.generatePermutations(people) findBestArrangement(peoplePermutations, seatingOptions) } private fun happinessMeasurement(line: String): HappinessMeasurement { // Alice would gain 54 happiness units by sitting next to Bob. val (occupantAndHappiness, neighbor) = line.split(" happiness units by sitting next to ") val (occupant, happiness) = occupantAndHappiness.split(" would ") val (gainOrLose, amount) = happiness.split(" ") val happinessChange = if (gainOrLose == "gain") amount.toInt() else -amount.toInt() return HappinessMeasurement(occupant, neighbor.dropLast(1), happinessChange) } private data class HappinessMeasurement(val occupant: String, val neighbor: String, val happinessChange: Int) private fun generateSeatingOptions(input: Sequence<HappinessMeasurement>): MutableMap<String, MutableMap<String, Int>> { val seatingOptions: MutableMap<String, MutableMap<String, Int>> = mutableMapOf() input.forEach { (occupant, neighbor, happinessChange) -> seatingOptions.merge(occupant, mutableMapOf(neighbor to happinessChange)) { cur, me -> (cur + me).toMutableMap() } } return seatingOptions } // "borrowed" from 2015 day 09, extract out if we use it a third time private fun findBestArrangement(peoplePermutations: List<Array<String>>, seatingOptions: MutableMap<String, MutableMap<String, Int>>): Int { var bestCost = peoplePermutations.first().toList().windowed(2).sumOf { (s, d) -> seatingOptions[s]!![d]!! + seatingOptions[d]!![s]!! } peoplePermutations.drop(1).map { permutation -> var cost = permutation.toList().windowed(2).sumOf { (s, d) -> seatingOptions[s]!![d]!! + seatingOptions[d]!![s]!! } val s = permutation[permutation.size - 1] val d = permutation[0] cost += seatingOptions[s]!![d]!! + seatingOptions[d]!![s]!! bestCost = max(bestCost, cost) } return bestCost } }
0
Kotlin
1
3
2625719b657eb22c83af95abfb25eb275dbfee6a
3,191
advent-of-code
MIT License
src/main/kotlin/com/nibado/projects/advent/y2017/Day24.kt
nielsutrecht
47,550,570
false
null
package com.nibado.projects.advent.y2017 import com.nibado.projects.advent.Day import com.nibado.projects.advent.resourceLines object Day24 : Day { private val input = resourceLines(2017, 24).map { it.split("/").map { it.toInt() } }.map { it[0] to it[1] }.sortedBy { it.first } private val solution: List<List<Pair<Int, Int>>> by lazy { solve() } override fun part1() = solution.last().map { it.first + it.second }.sum().toString() override fun part2(): String { val maxLength = solution.maxByOrNull { it.size }!!.size return solution.last { it.size == maxLength }.map { it.first + it.second }.sum().toString() } private fun solve(): List<List<Pair<Int, Int>>> { val solutions = mutableListOf<List<Pair<Int, Int>>>() search(listOf(), 0, input.toSet(), solutions) return solutions.map { it to it.map { it.first + it.second }.sum() }.filter { it.second > 1000 }.sortedBy { it.second }.map { it.first } } private fun search(current: List<Pair<Int, Int>>, port: Int, available: Set<Pair<Int, Int>>, solutions: MutableList<List<Pair<Int, Int>>>) { solutions.add(current) available.filter { it.first == port }.forEach { search(current + it, it.second, available.minus(it), solutions) } available.filter { it.second == port }.forEach { search(current + it, it.first, available.minus(it), solutions) } } }
1
Kotlin
0
15
b4221cdd75e07b2860abf6cdc27c165b979aa1c7
1,446
adventofcode
MIT License
src/main/kotlin/aoc2022/Day11.kt
j4velin
572,870,735
false
{"Kotlin": 285016, "Python": 1446}
package aoc2022 import readInput import separateBy import kotlin.math.floor /** * @property items the items currently held by this [Monkey] * @property operation a transformation operation representing the change in the "worry-level" * @property testDivisor the operand for the test operation to decide to which other monkey an item will be thrown * @property targetMonkeys a pair of [Monkey] indices - the first is the index of the monkey, to which this monkey will * throw an item, if the test hold - otherwise it is thrown to the [Monkey] at the second index * @property inspectionCount the amount of items this [Monkey] has inspected an item so far */ data class Monkey( val items: MutableList<Long>, val operation: (Long) -> Long, val testDivisor: Int, val targetMonkeys: Pair<Int, Int> ) { var inspectionCount = 0 private set companion object { fun fromStrings(input: List<String>): Monkey { val items = input[0].drop("Starting items: ".length).split(", ").map { it.toLong() }.toMutableList() val (op, operand) = input[1].drop("Operation: new = old ".length).split(" ", limit = 2) val operation: (Long) -> Long = when (op) { "*" -> { old -> old * if (operand == "old") old else operand.toLong() } "+" -> { old -> old + if (operand == "old") old else operand.toLong() } "-" -> { old -> old - if (operand == "old") old else operand.toLong() } "/" -> { old -> old / if (operand == "old") old else operand.toLong() } else -> throw UnsupportedOperationException("Unknown operation: ${input[1]}") } val divisor = input[2].drop("Test: divisible by ".length).toInt() val targetIndexTrue = input[3].drop("If true: throw to monkey ".length).toInt() val targetIndexFalse = input[4].drop("If false: throw to monkey ".length).toInt() return Monkey(items, operation, divisor, targetIndexTrue to targetIndexFalse) } } /** * Let this monkey take its turn. * * Applies [operation] and [reductionMethod] on each item and throws it to the corresponding other monkey. * * @param monkeys all the monkeys in the correct order * @param reductionMethod a method of keeping the worrying levels under control... */ fun takeTurn(monkeys: Array<Monkey>, reductionMethod: (Long) -> Long) { if (items.isNotEmpty()) { items.map { reductionMethod(operation(it)) }.forEach { inspectionCount++ if (it % testDivisor == 0L) { monkeys[targetMonkeys.first].items.add(it) } else { monkeys[targetMonkeys.second].items.add(it) } } items.clear() // we threw all our items to some other monkeys } } } fun main() { fun part1(input: List<String>): Int { val monkeys = input.filter { !it.startsWith("Monkey ") }.map { it.trim() }.separateBy { it.isBlank() } .map { Monkey.fromStrings(it) }.toTypedArray() repeat(20) { monkeys.forEach { it.takeTurn(monkeys) { n -> floor(n / 3f).toLong() } } } return monkeys.map { it.inspectionCount }.sortedDescending().take(2).reduce { a, b -> a * b } } fun part2(input: List<String>): Long { val monkeys = input.filter { !it.startsWith("Monkey ") }.map { it.trim() }.separateBy { it.isBlank() } .map { Monkey.fromStrings(it) }.toTypedArray() val commonDivisor = monkeys.map { it.testDivisor }.reduce { a, b -> a * b }.toLong() repeat(10000) { monkeys.forEach { it.takeTurn(monkeys) { n -> n % commonDivisor } } } return monkeys.map { it.inspectionCount.toLong() }.sortedDescending().take(2).reduce { a, b -> a * b } } val testInput = readInput("Day11_test", 2022) check(part1(testInput) == 10605) check(part2(testInput) == 2713310158) val input = readInput("Day11", 2022) println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
f67b4d11ef6a02cba5b206aba340df1e9631b42b
4,215
adventOfCode
Apache License 2.0
src/test/kotlin/be/brammeerten/y2023/Day7Test.kt
BramMeerten
572,879,653
false
{"Kotlin": 170522}
package be.brammeerten.y2023 import be.brammeerten.readFileAndSplitLines import be.brammeerten.toCharList import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test val POWERS: Map<Char, Int> = 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 ) val POWERS2: Map<Char, Int> = mapOf( 'A' to 13, 'K' to 12, 'Q' to 11, '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, 'J' to 0 ) class Day7Test { @Test fun `part 1`() { val sum = readFileAndSplitLines("2023/day7/exampleInput.txt", " ") .map { Hand(it[0].toCharList(), it[1].toInt()) } .sortedBy { it } .mapIndexed { i, hand -> (i + 1) * hand.bid } .sum() assertThat(sum).isEqualTo(6440); // assertThat(sum).isEqualTo(250946742); } @Test fun `part 2`() { val sum = readFileAndSplitLines("2023/day7/exampleInput.txt", " ") .map { Hand2(it[0].toCharList(), it[1].toInt()) } .sortedBy { it } .mapIndexed { i, hand -> (i + 1) * hand.bid } .sum() assertThat(sum).isEqualTo(5905); // assertThat(sum).isEqualTo(251824095); } data class Hand(val cards: List<Char>, val bid: Int, val strength: Int) : Comparable<Hand> { constructor(cards: List<Char>, bid: Int) : this(cards, bid, calcStrength(cards)) override fun compareTo(other: Hand): Int { if (strength < other.strength) return -1 if (strength > other.strength) return 1 for (i in cards.indices) { if (POWERS[cards[i]]!! < POWERS[other.cards[i]]!!) return -1 if (POWERS[cards[i]]!! > POWERS[other.cards[i]]!!) return 1 } throw RuntimeException("SHOULD NEVER HAPPEN") } } data class Hand2(val cards: List<Char>, val bid: Int, val strength: Int) : Comparable<Hand2> { constructor(cards: List<Char>, bid: Int) : this(cards, bid, calcStrength2(cards)) override fun compareTo(other: Hand2): Int { if (strength < other.strength) return -1 if (strength > other.strength) return 1 for (i in cards.indices) { if (POWERS2[cards[i]]!! < POWERS2[other.cards[i]]!!) return -1 if (POWERS2[cards[i]]!! > POWERS2[other.cards[i]]!!) return 1 } throw RuntimeException("SHOULD NEVER HAPPEN") } } } fun calcStrength(cards: List<Char>): Int { val counts = hashMapOf<Char, Int>() var max = 0 for (card in cards) { val c = counts.getOrDefault(card, 0) counts[card] = c + 1 if (c + 1 > max) max = c + 1 } if (max >= 4) return max + 1 if (max == 3) { // full house return if (counts.values.contains(2)) 4 else 3 } if (max == 2) { if (counts.values.count { it == 2 } == 2) return 2 } return max - 1 } fun calcStrength2(cards: List<Char>): Int { val counts = hashMapOf<Char, Int>() var max = 0 var jokers = 0 for (card in cards) { if (card == 'J') { jokers++ continue } val c = counts.getOrDefault(card, 0) counts[card] = c + 1 if (c + 1 > max) max = c + 1 } if ((max + jokers) >= 4) // five or four of a kind return (max + jokers) + 1 if ((max + jokers) == 3) { if (jokers >= 2) return 3 // three of a kind, not full house, otherwise would have had 4 of a kind if (jokers == 1) { return if (counts.values.count { it == 2 } == 2) 4 /* full house */ else 3 /* three of a kind */ } return if (counts.values.contains(2)) 4 /* full house */ else 3 /* three of a kind */ } if (jokers > 1) throw java.lang.RuntimeException("Not possible") if ((max + jokers) == 2) { if (jokers == 0) { // Can't get two pairs with 1 joker, otherwise would have had three of a kind if (counts.values.count { it == 2 } == 2) return 2 // Two pairs } } return (max + jokers) - 1 }
0
Kotlin
0
0
1defe58b8cbaaca17e41b87979c3107c3cb76de0
4,295
Advent-of-Code
MIT License
src/main/kotlin/dev/bogwalk/util/maths/reusable.kt
bog-walk
381,459,475
false
null
package dev.bogwalk.util.maths import java.math.BigInteger import kotlin.math.abs import kotlin.math.floor import kotlin.math.ln import kotlin.math.log10 import kotlin.math.sqrt /** * Calculates the sum of the first [this] natural numbers, based on the formula: * * {n}Sigma{k=1} k = n * (n + 1) / 2 * * Conversion of very large Doubles to Longs in this formula can lead to large rounding * losses, so Integer division by 2 is replaced with a single bitwise right shift, * as n >> 1 = n / (2^1). */ fun Int.gaussSum(): Long = 1L * this * (this + 1) shr 1 /** * Recursive calculation of the greatest common divisor of [n1] and [n2] using the Euclidean * algorithm. * * gcd(x, y) = gcd(|y % x|, |x|); where |y| >= |x| * * gcd(x, 0) = gcd(0, x) = |x| */ fun gcd(n1: Long, n2: Long): Long { val x = abs(n1) val y = abs(n2) if (x == 0L || y == 0L) return x + y val bigger = maxOf(x, y) val smaller = minOf(x, y) return gcd(bigger % smaller, smaller) } /** * Tail recursive solution allows the compiler to replace recursion with iteration for * optimum efficiency & the reduction of StackOverflowErrors. * * 13! overflows 32 bits and 21! overflows 64 bits and 59! produces a result that is greater * than 1e80 (postulated to be the number of particles in the universe). * * @throws IllegalArgumentException if calling Int is negative. */ tailrec fun Int.factorial(run: BigInteger = BigInteger.ONE): BigInteger { require(this >= 0) { "Integer must not be negative" } return when (this) { 0 -> BigInteger.ONE 1 -> run else -> (this - 1).factorial(run * this.toBigInteger()) } } /** * Two integers are co-prime (relatively/mutually prime) if the only positive integer that is a * divisor of both of them is 1. */ fun isCoPrime(x: Int, y: Int): Boolean = gcd(x.toLong(), y.toLong()) == 1L /** * Returns the corresponding term of the number if hexagonal, or null. * * Derivation solution is based on the formula: * * n(2n - 1) = hN, in quadratic form becomes: * * 0 = 2n^2 - n - hN, with a, b, c = 2, -1, -hN * * putting these values in the quadratic formula becomes: * * n = (1 +/- sqrt(1 + 8hN)) / 4 * * so the inverse function, positive solution becomes: * * n = (1 + sqrt(1 + 8h_n)) / 4 */ fun Long.isHexagonalNumber(): Int? { val n = 0.25 * (1 + sqrt(1 + 8.0 * this)) return if (n == floor(n)) n.toInt() else null } /** * Returns the corresponding term of the number if pentagonal, or null. * * Derivation solution is based on the formula: * * n(3n - 1)/2 = pN, in quadratic form becomes: * * 0 = 3n^2 - n - 2pN, with a, b, c = 3, -1, (-2pN) * * putting these values in the quadratic formula becomes: * * n = (1 +/- sqrt(1 + 24pN))/6 * * so the inverse function, positive solution becomes: * * n = (1 + sqrt(1 + 24pN))/6 */ fun Long.isPentagonalNumber(): Int? { val n = (1 + sqrt(1 + 24.0 * this)) / 6.0 return if (n == floor(n)) n.toInt() else null } /** * Checks if [this] is prime. * * This version will be used preferentially, unless the argument is expected to frequently * exceed Integer.MAX_VALUE (10-digits). * * SPEED (WORST for N > 1e13) 43.62ms for 14-digit prime * * SPEED (EQUAL for N > 1e12) 17.21ms for 13-digit prime * * SPEED (WORST for N > 1e11) 8.68ms for 12-digit prime * * SPEED (BETTER for N < 1e10) 1.65ms for 10-digit prime * * SPEED (BEST for N < 1e6) 6.4e5ns for 6-digit prime * * SPEED (EQUAL for N < 1e3) 6.2e5ns for 3-digit prime */ fun Int.isPrime(): Boolean { return when { this < 2 -> false this < 4 -> true // 2 & 3 are primes this % 2 == 0 -> false // 2 is the only even prime this < 9 -> true // 4, 6, & 8 already excluded this % 3 == 0 -> false // primes > 3 are of the form 6k(+/-1) (i.e. they are never multiples of 3) else -> { // n can only have 1 prime factor > sqrt(n): n itself! val max = sqrt(1.0 * this).toInt() var step = 5 // as multiples of prime 5 have not been assessed yet // 11, 13, 17, 19, & 23 will all bypass this loop while (step <= max) { if (this % step == 0 || this % (step + 2) == 0) return false step += 6 } true } } } /** * BigInteger built-in isProbablePrime() uses Miller-Rabin algorithm. * * Overall, this solution returns the most consistent performance for numbers of all sizes, at a * default certainty of 5. It is expected that performance will slow as the number of digits and * certainty tolerance increase. * * This version will be used for all numbers above Integer.MAX_VALUE (11-digits and up). * * SPEED (BEST for N > 1e14) 1.12ms for 15-digit prime * * SPEED (BEST for N > 1e13) 1.11ms for 14-digit prime * * SPEED (BEST for N > 1e12) 1.26ms for 13-digit prime * * SPEED (BETTER for N > 1e11) 1.56ms for 12-digit prime * * SPEED (BEST for N < 1e10) 1.46ms for 10-digit prime * * SPEED (BETTER for N < 1e6) 9.4e5ns for 6-digit prime * * SPEED (EQUAL for N < 1e3) 7.2e5ns for 3-digit prime * * @see <a href="https://developer.classpath.org/doc/java/math/BigInteger-source.html">Source * code line 1279</a> */ fun Long.isPrimeMRBI(certainty: Int = 5): Boolean { val n = BigInteger.valueOf(this) return n.isProbablePrime(certainty) } /** * Miller-Rabin probabilistic algorithm determines if a large number [this] is likely to be prime. * * - The number received [this], once determined to be odd, is expressed as n = 2^rs + 1, with s * being odd. * - A random integer, a, is chosen k times (higher k means higher accuracy), with 0 < a < n. * - Calculate a^s % n. If this equals 1 or this plus 1 equals n while s has the powers of 2 * previously factored out returned, then [this] passes as a strong probable prime. * - [this] should pass for all generated a. * * The algorithm's complexity is O(k*log^3*n). This algorithm uses a list of the first 5 primes * instead of randomly generated a, as this has been proven valid for numbers up to 2.1e12. * Providing a list of the first 7 primes gives test validity for numbers up to 3.4e14. * * SPEED (BETTER for N > 1e14) 28.86ms for 15-digit prime * * SPEED (BETTER for N > 1e13) 17.88ms for 14-digit prime * * SPEED (EQUAL for N > 1e12) 17.62ms for 13-digit prime * * SPEED (BEST for N > 1e11) 1.24ms for 12-digit prime * * SPEED (WORST for N < 1e10) 1.81ms for 10-digit prime * * SPEED (WORST for N < 1e6) 1.02ms for 6-digit prime * * SPEED (EQUAL for N < 1e3) 6.4e5ns for 3-digit prime */ private fun Long.isPrimeMR(kRounds: List<Long> = listOf(2, 3, 5, 7, 11)): Boolean { if (this in 2L..3L) return true if (this < 2L || this % 2L == 0L) return false val one = BigInteger.ONE val n = BigInteger.valueOf(this) val nMinus1 = n - one // write n as 2^r * s + 1 by first getting r, the largest power of 2 that divides (this - 1) // by getting the index of the right-most one bit val r: Int = nMinus1.lowestSetBit // x * 2^y == x << y val s = nMinus1 / BigInteger.valueOf(2L shl r - 1) rounds@for (a in kRounds) { if (a > this - 2L) break // calculate a^s % n var x = BigInteger.valueOf(a).modPow(s, n) if (x == one || x == nMinus1) continue@rounds for (i in 0 until r) { x = x.modPow(BigInteger.TWO, n) if (x == one) break if (x == nMinus1) continue@rounds } return false } return true } /** * Returns the corresponding term of the number if triangular, or null. * * Derivation solution is based on the formula: * * n(n + 1)/2 = tN, in quadratic form becomes: * * 0 = n^2 + n - 2tN, with a, b, c = 1, 1, (-2tN) * * putting these values in the quadratic formula becomes: * * n = (-1 +/- sqrt(1 + 8tN))/2 * * so the inverse function, positive solution becomes: * * n = (sqrt(1 + 8tN) - 1)/2 */ fun Long.isTriangularNumber(): Int? { val n = 0.5 * (sqrt(1 + 8.0 * this) - 1) return if (n == floor(n)) n.toInt() else null } /** * Calculates the least common multiple of a variable amount of [n]. * * lcm(x, y) = |x * y| / gcd(x, y) * * The original solution kept [n] as Long but consistently underperformed compared to the current * solution that converts all [n] to BigInteger before reducing, to leverage built-in methods. * * The BigInteger class has built-in gcd() with optimum performance, as it uses the Euclidean * algorithm initially along with MutableBigInteger instances to avoid frequent memory * allocations, then switches to binary gcd algorithm at smaller values to increase speed. * * SPEED 3.2e+04ns VS 6.8e+04ns for 3-element varargs with 3-digit result * * SPEED 1.01ms VS 7.34ms for 9-element (3-digit integers) varargs with 18-digit result * * Original solution has the worst time with a larger variation, whereas this solution has the worst * time more tight between 1.20-1.40ms. * * @throws IllegalArgumentException if any [n] == 0. */ fun lcm(vararg n: Long): Long { require(n.all { it != 0L }) { "Argument cannot be 0" } val nBI = n.map(BigInteger::valueOf) return nBI.reduce { acc, num -> acc.lcm(num) }.longValueExact() } /** * Calculates the least common multiple of 2 BigIntegers. * * Function extracted from the more general lcm() above that accepts a variable amount of Long * arguments, to allow solution sets to use the formula directly. */ fun BigInteger.lcm(other: BigInteger): BigInteger { return (this * other).abs() / this.gcd(other) } /** * Computes the common logarithm (base 10) of a BigInteger. * * Based on sections of java.math.BigInteger's source code for roundToDouble(). * * @throws IllegalArgumentException if this BigInteger is 0 or negative. * @see <a href="https://developer.classpath.org/doc/java/math/BigInteger-source.html">Source * code line 1686</a> */ fun BigInteger.log10(): Double { require(signum() == 1) { "Value must be positive" } // 'this' will fit in Long if no excessBits val excessBits = bitLength() - 63 return if (excessBits > 0) { log10(shr(excessBits).toDouble()) + excessBits * ln(2.0) / ln(10.0) } else { log10(this.toDouble()) } } /** * Calculates the sum of the digits of the number produced by [base]^[exp]. */ fun powerDigitSum(base: Int, exp: Int): Int { val num = base.toBigInteger().pow(exp).toString() return num.sumOf { it.digitToInt() } } /** * Prime decomposition repeatedly divides out all prime factors using an optimised Direct Search * Factorisation algorithm. * * Every prime number after 2 will be odd and there can be at most 1 prime factor * greater than sqrt([n]), which would be [n] itself if [n] is a prime. This is based on all * cofactors having been already tested following the formula: * * n / floor(sqrt(n) + 1) < sqrt(n) * * e.g. N = 12 returns {2=2, 3=1} -> 2^2 * 3^1 = 12 * * SPEED (WORSE for N with small factors) 59.05ms for N = 1e12 * SPEED (WORSE for N with large factors) 41.10ms for N = 600_851_475_143 * * If Sieve of Eratosthenes algorithm is used to generate the factors, the execution time is * improved: * * SPEED (BETTER for N with small factors) 14.36ms for N = 1e12 * SPEED (BETTER for N with large factors) 10.19ms for N = 600_851_475_143 * * @return map of prime factors (keys) and their exponents (values). * @throws IllegalArgumentException if [n] <= 1. */ private fun primeFactorsOG(n: Long): Map<Long, Int> { require(n > 1) { "Must provide a natural number greater than 1" } var num = n val primes = mutableMapOf<Long, Int>() val maxFactor = sqrt(num.toDouble()).toLong() val factors = listOf(2L) + (3L..maxFactor step 2L) factors.forEach { factor -> while (num % factor == 0L) { primes[factor] = primes.getOrDefault(factor, 0) + 1 num /= factor } } if (num > 2) primes[num] = primes.getOrDefault(num, 0) + 1 return primes } /** * Prime decomposition repeatedly divides out all prime factors using a Direct Search * Factorisation algorithm without any optimisation. * * This version will be used in future solutions. * * SPEED (BEST for N with small factors) 5742ns for N = 1e12 * SPEED (BEST for N with large factors) 5.3e+04ns for N = 600_851_475_143 * * @return map of prime factors (keys) and their exponents (values). * @throws IllegalArgumentException if [n] <= 1. */ fun primeFactors(n: Long): Map<Long, Int> { require(n > 1) { "Must provide a natural number greater than 1" } var num = n val primes = mutableMapOf<Long, Int>() var factor = 2L while (factor * factor <= num) { while (num % factor == 0L && num != factor) { primes[factor] = primes.getOrDefault(factor, 0) + 1 num /= factor } factor++ } if (num > 1) primes[num] = primes.getOrDefault(num, 0) + 1 return primes } /** * Sieve of Eratosthenes algorithm outputs all prime numbers less than or equal to [n]. * * SPEED (WORSE) 19.87ms for N = 1e6 */ private fun primeNumbersOG(n: Int): List<Int> { // create mask representing [2, max], with all even numbers except 2 (index 0) marked false val boolMask = BooleanArray(n - 1) { !(it != 0 && it % 2 == 0) } for (p in 3..(sqrt(1.0 * n).toInt()) step 2) { if (boolMask[p - 2]) { if (p * p > n) break // mark all multiples (composites of the divisors) that are >= p squared as false for (m in (p * p)..n step 2 * p) { boolMask[m - 2] = false } } } return boolMask.mapIndexed { i, isPrime -> if (isPrime) i + 2 else null }.filterNotNull() } /** * Still uses Sieve of Eratosthenes method to output all prime numbers less than or equal to [n], * but cuts processing time in half by only allocating mask memory to odd numbers and by only * looping through multiples of odd numbers. * * This version will be used in future solutions. * * SPEED (BETTER) 12.32ms for N = 1e6 */ fun primeNumbers(n: Int): List<Int> { if (n < 2) return emptyList() val oddSieve = (n - 1) / 2 // create mask representing [2, 3..n step 2] val boolMask = BooleanArray(oddSieve + 1) { true } // boolMask[0] corresponds to prime 2 and is skipped for (i in 1..(sqrt(1.0 * n).toInt() / 2)) { if (boolMask[i]) { // j = next index at which multiple of odd prime exists var j = 2 * i * (i + 1) while (j <= oddSieve) { boolMask[j] = false j += 2 * i + 1 } } } return boolMask.mapIndexed { i, isPrime -> if (i == 0) 2 else if (isPrime) 2 * i + 1 else null }.filterNotNull() } /** * Euclid's formula generates all Pythagorean triplets from 2 numbers, [m] and [n]. * * All triplets originate from a primitive one by multiplying them by d = gcd(a,b,c). * * @throws IllegalArgumentException if arguments do not follow [m] > [n] > 0, or if not exactly * one is even, or if they are not co-prime, i.e. gcd(m, n) != 1. */ fun pythagoreanTriplet(m: Int, n: Int, d: Int): Triple<Int, Int, Int> { require(n in 1 until m) { "Positive integers assumed to be m > n > 0" } require((m % 2 == 0) xor (n % 2 == 0)) { "Integers must be opposite parity" } require(isCoPrime(m, n)) { "Positive integers must be co-prime" } val a = (m * m - n * n) * d val b = 2 * m * n * d val c = (m * m + n * n) * d return Triple(minOf(a, b), maxOf(a, b), c) } /** * Returns the sum of elements in a Triple of numbers. */ fun Triple<Int, Int, Int>.sum(): Int = first + second + third /** * Calculates the sum of all divisors of [num], not inclusive of [num]. * * Solution optimised based on the following: * * - N == 1 has no proper divisor but 1 is a proper divisor of all other naturals. * * - A perfect square would duplicate divisors if included in the loop range. * * - Loop range differs for odd numbers as they cannot have even divisors. * * SPEED (WORSE) 6.91ms for N = 1e6 - 1 */ private fun sumProperDivisorsOG(num: Int): Int { if (num < 2) return 0 var sum = 1 var maxDivisor = sqrt(1.0 * num).toInt() if (maxDivisor * maxDivisor == num) { sum += maxDivisor maxDivisor-- } val range = if (num % 2 != 0) (3..maxDivisor step 2) else (2..maxDivisor) for (d in range) { if (num % d == 0) { sum += d + num / d } } return sum } /** * Calculates the sum of all divisors of [num], not inclusive of [num]. * * Solution above is further optimised by using prime factorisation to out-perform the original * method. * * This version will be used in future solutions. * * SPEED (BETTER) 10000ns for N = 1e6 - 1 */ fun sumProperDivisors(num: Int): Int { if (num < 2) return 0 var n = num var sum = 1 var p = 2 while (p * p <= num && n > 1) { if (n % p == 0) { var j = p * p n /= p while (n % p == 0) { j *= p n /= p } sum *= (j - 1) sum /= (p - 1) } if (p == 2) { p++ } else { p += 2 } } if (n > 1) { sum *= (n + 1) } return sum - num }
0
Kotlin
0
0
62b33367e3d1e15f7ea872d151c3512f8c606ce7
17,505
project-euler-kotlin
MIT License
string-similarity/src/commonMain/kotlin/com/aallam/similarity/OptimalStringAlignment.kt
aallam
597,692,521
false
null
package com.aallam.similarity import kotlin.math.min /** * Implementation of the Optimal String Alignment (sometimes called the restricted edit distance) variant * of the Damerau-Levenshtein distance. * * The difference between the two algorithms consists in that the Optimal String Alignment algorithm computes the number * of edit operations needed to make the strings equal under the condition that no substring is edited more than once, * whereas Damerau-Levenshtein presents no such restriction. */ public class OptimalStringAlignment { /** * Compute the distance between strings: the minimum number of operations needed to transform one string into the * other (insertion, deletion, substitution of a single character, or a transposition of two adjacent characters) * while no substring is edited more than once. * * @param first the first string to compare. * @param second the second string to compare. */ public fun distance(first: String, second: String): Int { if (first == second) return 0 val n = first.length val m = second.length if (n == 0) return m if (m == 0) return n // create the distance matrix H[0..first.length+1][0..second.length+1] val distanceMatrix = Array(n + 2) { IntArray(m + 2) } // initialize top row and leftmost column for (i in 0..n) distanceMatrix[i][0] = i for (j in 0..m) distanceMatrix[0][j] = j // fill the distance matrix for (i in 1..n) { for (j in 1..m) { val cost = if (first[i - 1] == second[j - 1]) 0 else 1 val substitution = distanceMatrix[i - 1][j - 1] + cost val insertion = distanceMatrix[i][j - 1] + 1 val deletion = distanceMatrix[i - 1][j] + 1 distanceMatrix[i][j] = minOf(substitution, insertion, deletion) // transposition check if (i > 1 && j > 1 && first[i - 1] == second[j - 2] && first[i - 2] == second[j - 1]) { distanceMatrix[i][j] = min(distanceMatrix[i][j], distanceMatrix[i - 2][j - 2] + cost) } } } return distanceMatrix[n][m] } }
0
Kotlin
0
1
40cd4eb7543b776c283147e05d12bb840202b6f7
2,244
string-similarity-kotlin
MIT License
2018/kotlin/day20p2/src/main.kt
sgravrock
47,810,570
false
{"Rust": 1263100, "Swift": 1167766, "Ruby": 641843, "C++": 529504, "Kotlin": 466600, "Haskell": 339813, "Racket": 264679, "HTML": 200276, "OpenEdge ABL": 165979, "C": 89974, "Objective-C": 50086, "JavaScript": 40960, "Shell": 33315, "Python": 29781, "Elm": 22980, "Perl": 10662, "BASIC": 9264, "Io": 8122, "Awk": 5701, "Raku": 5532, "Rez": 4380, "Makefile": 1241, "Objective-C++": 1229, "Tcl": 488}
import java.util.* import kotlin.math.min fun main(args: Array<String>) { val start = Date() val classLoader = RoomEx::class.java.classLoader val input = classLoader.getResource("input.txt").readText() println(numRoomsWithShortestPathOfAtLeast1000(input)) println("in ${Date().time - start.time}ms") } data class Coord(val x: Int, val y: Int) { fun neighbor(dir: Dir): Coord { return when (dir) { Dir.N -> Coord(x, y - 1) Dir.S -> Coord(x, y + 1) Dir.W -> Coord(x - 1, y) Dir.E -> Coord(x + 1, y) } } } enum class Dir { N, E, W, S } fun numRoomsWithShortestPathOfAtLeast1000(input: String): Int { val world = World.build(RoomExParser.parse(input)) val distancesToRooms = mutableMapOf<Coord, Int>() world.paths { dest, len -> distancesToRooms[dest] = min( len, distancesToRooms.getOrDefault(dest, Int.MAX_VALUE) ) } return distancesToRooms.values.count { it >= 1000 } } enum class Tile { Room, Wall, Hdoor, Vdoor } class World(private val grid: Map<Coord, Tile>) { fun paths(emit: (Coord, Int) -> Unit) { dfs(mutableListOf(Coord(0, 0)), emit) } private fun dfs(rooms: MutableList<Coord>, emit: (Coord, Int) -> Unit) { for (d in Dir.values()) { val doorCoord = rooms.last().neighbor(d) when (grid.getOrDefault(doorCoord, Tile.Wall)) { Tile.Hdoor, Tile.Vdoor -> { val nextRoomCoord = doorCoord.neighbor(d) if (!rooms.contains(nextRoomCoord)) { rooms.add(nextRoomCoord) emit(rooms.last(), rooms.size - 1) dfs(rooms, emit) rooms.removeAt(rooms.size - 1) } } Tile.Wall -> {} Tile.Room -> throw Exception("Can't happen: two adjacent rooms") } } } override fun toString(): String { val minX = grid.keys.asSequence().map { it.x }.min()!! - 1 val maxX = grid.keys.asSequence().map { it.x }.max()!! + 1 val minY = grid.keys.asSequence().map { it.y }.min()!! - 1 val maxY = grid.keys.asSequence().map { it.y }.max()!! + 1 return (minY..maxY).map { y -> (minX..maxX).map { x -> when (grid.getOrDefault(Coord(x, y), Tile.Wall)) { Tile.Room -> if (y == 0 && x == 0) 'X' else '.' Tile.Wall -> '#' Tile.Vdoor -> '|' Tile.Hdoor -> '-' } }.joinToString("") }.joinToString("\n") } companion object { fun build(input: RoomEx): World { val origin = Coord(0, 0) val tiles = mutableMapOf(origin to Tile.Room) input.walk(origin, { c, t -> tiles[c] = t }) return World(tiles) } } } interface RoomEx { fun walk(start: Coord, visit: (Coord, Tile) -> Unit): Set<Coord> } data class Expression(val els: List<RoomEx>) : RoomEx { override fun walk(start: Coord, visit: (Coord, Tile) -> Unit): Set<Coord> { return els.fold(setOf(start), { prevDests, el -> prevDests .flatMap { prev -> el.walk(prev, visit) } .toSet() }) } } data class AtomList(val els: List<Dir>): RoomEx { override fun walk(start: Coord, visit: (Coord, Tile) -> Unit): Set<Coord> { val dest = els.fold(start, { prev, dir -> val door = prev.neighbor(dir) visit(door, when(dir) { Dir.N, Dir.S -> Tile.Hdoor Dir.W, Dir.E -> Tile.Vdoor }) val room = door.neighbor(dir) visit(room, Tile.Room) room }) return setOf(dest) } } data class Options(val opts: List<RoomEx>) : RoomEx { override fun walk(start: Coord, visit: (Coord, Tile) -> Unit): Set<Coord> { return opts.flatMap { it.walk(start, visit) }.toSet() } } class RoomExParser(private val input: String) { companion object { fun parse(input: String): RoomEx { return RoomExParser(input).parse() } } var i: Int = 0 // RoomEx: BEGIN expression END fun parse(): RoomEx { require('^') val result = parseExpression() require('$') return result } // Expression: term expression | nothing private fun parseExpression(): RoomEx { val terms = mutableListOf<RoomEx>() var t = parseTerm() while (t != null) { terms.add(t) t = parseTerm() } if (terms.size == 1) { return terms[0] // elide unnecessary non-terminals } else { return Expression(terms) } } // Term: atomList | lparen options private fun parseTerm(): RoomEx? { var token = input[i++] return when (token) { 'N', 'E', 'W', 'S' -> { val atoms = mutableListOf<Dir>() while (token in listOf('N', 'E', 'W', 'S')) { atoms.add(dirFromChar(token)) token = input[i++] } i-- AtomList(atoms) } '(' -> parseOptions() else -> { i-- null } } } // options: expression pipe options | rparen private fun parseOptions(): Options { val expressions = mutableListOf<RoomEx>() while (true) { expressions.add(parseExpression()) val t = input[i++] if (t == ')') { break } else if (t != '|') { throw Error("Expected Rparen or Pipe but got $t") } } return Options(expressions) } private fun require(expected: Char) { val actual = input[i++] if (actual != expected) { throw Error("Expected $expected but got $actual") } } private fun dirFromChar(c: Char): Dir { return when(c) { 'N' -> Dir.N 'E' -> Dir.E 'S' -> Dir.S 'W' -> Dir.W else -> throw Exception("Invalid direction char: $c") } } }
0
Rust
0
0
ea44adeb128cf1e3b29a2f0c8a12f37bb6d19bf3
6,393
adventofcode
MIT License
src/main/kotlin/aoc2022/Day08.kt
j4velin
572,870,735
false
{"Kotlin": 285016, "Python": 1446}
package aoc2022 import Point import readInput data class Tree(val position: Point, val height: Int) fun main() { fun getAllTrees(map: Array<IntArray>): Set<Tree> { val trees = mutableSetOf<Tree>() for (y in map.indices) { for (x in map[0].indices) { trees.add(Tree(Point(x, y), map[y][x])) } } return trees } fun isTreeVisible(map: Array<IntArray>, tree: Tree): Boolean { // outter rows and columns are always visible if (tree.position.x == 0 || tree.position.y == 0 || tree.position.x == map[0].size - 1 || tree.position.y == map.size - 1) { return true } else { // search row var fromLeft = true for (x in 0 until tree.position.x) { if (map[tree.position.y][x] >= tree.height) { fromLeft = false break } } if (fromLeft) return true var fromRight = true for (x in tree.position.x + 1 until map[tree.position.y].size) { if (map[tree.position.y][x] >= tree.height) { fromRight = false break } } if (fromRight) return true // search column var fromTop = true for (y in 0 until tree.position.y) { if (map[y][tree.position.x] >= tree.height) { fromTop = false break } } if (fromTop) return true var fromBottom = true for (y in tree.position.y + 1 until map.size) { if (map[y][tree.position.x] >= tree.height) { fromBottom = false break } } if (fromBottom) return true } return false } fun getScenicScore(map: Array<IntArray>, tree: Tree): Int { // outter rows & columns don't see another tree in at least one direction -> 0 scenic value if (tree.position.x == 0 || tree.position.y == 0 || tree.position.x == map[0].size - 1 || tree.position.y == map.size - 1) { return 0 } // row var toLeft = 0 for (x in tree.position.x - 1 downTo 0) { toLeft++ if (map[tree.position.y][x] >= tree.height) { break } } var toRight = 0 for (x in tree.position.x + 1 until map[tree.position.y].size) { toRight++ if (map[tree.position.y][x] >= tree.height) { break } } // column var toTop = 0 for (y in tree.position.y - 1 downTo 0) { toTop++ if (map[y][tree.position.x] >= tree.height) { break } } var toBottom = 0 for (y in tree.position.y + 1 until map.size) { toBottom++ if (map[y][tree.position.x] >= tree.height) { break } } return toTop * toBottom * toLeft * toRight } fun part1(input: List<String>): Int { val map = input.map { row -> row.map { it.digitToInt() }.toIntArray() }.toTypedArray() return getAllTrees(map).filter { isTreeVisible(map, it) }.size } fun part2(input: List<String>): Int { val map = input.map { row -> row.map { it.digitToInt() }.toIntArray() }.toTypedArray() return getAllTrees(map).maxOf { getScenicScore(map, it) } } val testInput = readInput("Day08_test", 2022) check(part1(testInput) == 21) check(part2(testInput) == 8) val input = readInput("Day08", 2022) println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
f67b4d11ef6a02cba5b206aba340df1e9631b42b
3,818
adventOfCode
Apache License 2.0
app/src/main/java/com/betulnecanli/kotlindatastructuresalgorithms/CodingPatterns/MergeIntervals.kt
betulnecanli
568,477,911
false
{"Kotlin": 167849}
/* The "Merge Intervals" pattern is often used for problems involving intervals, time scheduling, or conflicting schedules. Let's tackle two problems: "Conflicting Appointments" and "Minimum Meeting Rooms." Usage: This technique is used to deal with overlapping intervals. */ //1. Conflicting Appointments data class Interval(val start: Int, val end: Int) fun canAttendAppointments(intervals: List<Interval>): Boolean { if (intervals.isEmpty()) { return true } intervals.sortedBy { it.start } for (i in 1 until intervals.size) { if (intervals[i].start < intervals[i - 1].end) { return false // Conflicting appointments } } return true } fun main() { val appointments = listOf( Interval(1, 4), Interval(2, 5), Interval(7, 9) ) val result = canAttendAppointments(appointments) println("Can attend all appointments: $result") } //2. Minimum Meeting Rooms data class Meeting(val start: Int, val end: Int) fun minMeetingRooms(meetings: List<Meeting>): Int { if (meetings.isEmpty()) { return 0 } val startTimes = meetings.map { it.start }.sorted() val endTimes = meetings.map { it.end }.sorted() var roomsNeeded = 0 var endIndex = 0 for (startTime in startTimes) { if (startTime < endTimes[endIndex]) { roomsNeeded++ } else { endIndex++ } } return roomsNeeded } fun main() { val meetings = listOf( Meeting(0, 30), Meeting(5, 10), Meeting(15, 20) ) val result = minMeetingRooms(meetings) println("Minimum Meeting Rooms Required: $result") } /* Conflicting Appointments: We use a data class Interval to represent the start and end times of intervals. The canAttendAppointments function checks if there are any conflicting appointments in the given list of intervals. We sort the intervals based on their start times and then iterate through them to check for conflicts. Minimum Meeting Rooms: We use a data class Meeting to represent the start and end times of meetings. The minMeetingRooms function calculates the minimum number of meeting rooms required to schedule all the given meetings. We sort the start and end times separately and use two pointers to track the ongoing meetings. */
2
Kotlin
2
40
70a4a311f0c57928a32d7b4d795f98db3bdbeb02
2,337
Kotlin-Data-Structures-Algorithms
Apache License 2.0
src/day04/Day04.kt
ivanovmeya
573,150,306
false
{"Kotlin": 43768}
package day04 import readInput fun main() { fun IntRange.hasOverlap(other: IntRange): Boolean { return !(this.last < other.first || this.first > other.last) } fun IntRange.fullyContains(other: IntRange): Boolean { return this.first >= other.first && this.last <= other.last } fun parseElfRanges(pairOfElfData: String) = pairOfElfData .split(',') .map { elfRange -> elfRange .split('-') .zipWithNext { start, end -> IntRange(start.toInt(), end.toInt()) } .first() } fun part1(input: List<String>): Long { return input.sumOf { pairOfElfData -> val (firstElfRange, secondElfRange) = parseElfRanges(pairOfElfData) if ( firstElfRange.fullyContains(secondElfRange) || secondElfRange.fullyContains(firstElfRange) ) 1L else 0L } } fun part2(input: List<String>): Long { return input.sumOf { pairOfElfData -> val (firstElfRange, secondElfRange) = parseElfRanges(pairOfElfData) if (firstElfRange.hasOverlap(secondElfRange)) 1L else 0L } } val testInput = readInput("day04/input_test") val test1Result = part1(testInput) val test2Result = part2(testInput) println(test1Result) println(test2Result) check(test1Result == 2L) check(test2Result == 4L) val input = readInput("day04/input") check(part1(input) == 466L) check(part2(input) == 865L) }
0
Kotlin
0
0
7530367fb453f012249f1dc37869f950bda018e0
1,528
advent-of-code-2022
Apache License 2.0
2021/src/test/kotlin/Day09.kt
jp7677
318,523,414
false
{"Kotlin": 171284, "C++": 87930, "Rust": 59366, "C#": 1731, "Shell": 354, "CMake": 338}
import kotlin.test.Test import kotlin.test.assertEquals class Day09 { data class Coord(val x: Int, val y: Int) data class Location(val coord: Coord, val height: Int) private val moves = listOf(Coord(-1, 0), Coord(1, 0), Coord(0, -1), Coord(0, 1)) @Test fun `run part 01`() { val heatmap = getHeatmap() val riskLevel = heatmap .sumOf { it.height.let { height -> if (moves.all { step -> heatmap .getAdjacents(it.coord, step) ?.let { adjacent -> adjacent.height > height } != false } ) height.inc() else 0 } } assertEquals(600, riskLevel) } @Test fun `run part 02`() { val heatmap = getHeatmap() val result = heatmap .fold(listOf<List<Coord>>()) { acc, it -> if (it.height != 9 && acc.none { b -> b.contains(it.coord) }) acc + listOf(heatmap.getAdjacentLowPoints(it.coord).map { l -> l.coord }) else acc } .sortedByDescending { it.count() } .take(3) .fold(1) { acc, it -> acc * it.count() } assertEquals(987840, result) } private fun List<Location>.getAdjacentLowPoints( coord: Coord, visited: MutableList<Coord> = mutableListOf() ): List<Location> = if (visited.contains(coord) || this.from(coord).height == 9) listOf() else { visited.add(coord) moves .mapNotNull { this.getAdjacents(coord, it) } .flatMap { this.getAdjacentLowPoints(it.coord, visited) } + this.from(coord) } private fun List<Location>.from(coord: Coord) = this .single { it.coord.x == coord.x && it.coord.y == coord.y } private fun List<Location>.getAdjacents(current: Coord, step: Coord) = this.firstOrNull { it.coord.x == current.x + step.x && it.coord.y == current.y + step.y } private fun getHeatmap() = Util.getInputAsListOfString("day09-input.txt") .map { it.map { c -> c.digitToInt() } } .let { it .first() .indices .flatMap { x -> List(it.size) { y -> Location(Coord(x, y), it[y][x]) } } } }
0
Kotlin
1
2
8bc5e92ce961440e011688319e07ca9a4a86d9c9
2,497
adventofcode
MIT License
src/main/kotlin/at/mpichler/aoc/solutions/year2021/Day10.kt
mpichler94
656,873,940
false
{"Kotlin": 196457}
package at.mpichler.aoc.solutions.year2021 import at.mpichler.aoc.lib.Day import at.mpichler.aoc.lib.PartSolution open class Part10A : PartSolution() { lateinit var lines: List<String> override fun parseInput(text: String) { lines = text.split("\n") } override fun compute(): Any { return lines.sumOf { getLineScore(it) } } fun getLineScore(line: String): Int { val score = mapOf(')' to 3, ']' to 57, '}' to 1197, '>' to 25_137) val stack = ArrayDeque<Char>() for (char in line) { if (!matchClosing(char, stack)) { return score[char]!! } } return 0 } fun matchClosing(char: Char, stack: MutableList<Char>): Boolean { val matches = mapOf('(' to ')', '[' to ']', '{' to '}', '<' to '>') if (char in listOf('(', '[', '{', '<')) { stack.add(char) } else { val openingChar = stack.removeLast() val needed = matches[openingChar] if (char != needed) { return false } } return true } override fun getExampleAnswer(): Int { return 26_397 } override fun getExampleInput(): String? { return """ [({(<(())[]>[[{[]{<()<>> [(()[<>])]({[<{<<[]>>( {([(<{}[<>[]}>{[]{[(<()> (((({<>}<{<{<>}{[]{[]{} [[<[([]))<([[{}[[()]]] [{[{({}]{}}([{[{{{}}([] {<[[]]>}<{[{[{[]{()[[[] [<(<(<(<{}))><([]([]() <{([([[(<>()){}]>(<<{{ <{([{{}}[<[[[<>{}]]]>[]] """.trimIndent() } } class Part10B : Part10A() { override fun config() { lines = lines.filter { isNotCorrupt(it) } } private fun isNotCorrupt(line: String): Boolean { return getLineScore(line) == 0 } override fun compute(): Long { val scores = lines.map { getCompletionScore(it) }.sorted() return scores[scores.size / 2] } private fun getCompletionScore(line: String): Long { val score = mapOf('(' to 1, '[' to 2, '{' to 3, '<' to 4) val stack = ArrayDeque<Char>() line.map { matchClosing(it, stack) } var points = 0L stack.reverse() for (char in stack) { points = points * 5 + score[char]!! } return points } override fun getExampleAnswer(): Int { return 288_957 } } fun main() { Day(2021, 10, Part10A(), Part10B()) }
0
Kotlin
0
0
69a0748ed640cf80301d8d93f25fb23cc367819c
2,526
advent-of-code-kotlin
MIT License
src/Day03.kt
max-zhilin
573,066,300
false
{"Kotlin": 114003}
fun main() { fun part1(input: List<String>): Int { var sum = 0 input.forEach { val (left, right) = it.chunked(it.length / 2) loop@ for (i in left) { for (j in right) { if (i == j) { val priority = if (i < 'a') i - 'A' + 27 else i - 'a' + 1 sum += priority break@loop } } } } return sum } fun part2(input: List<String>): Int { var sum = 0 val groups = input.chunked(3) groups.forEach { (one, two, three) -> loop@ for (i in one) { for (j in two) { for (k in three) { if (i == j && j == k) { val priority = if (i < 'a') i - 'A' + 27 else i - 'a' + 1 sum += priority break@loop } } } } } return sum } // test if implementation meets criteria from the description, like: val testInput = readInput("Day03_test") // println(part1(testInput)) check(part1(testInput) == 157) // println(part2(testInput)) check(part2(testInput) == 70) val input = readInput("Day03") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
d9dd7a33b404dc0d43576dfddbc9d066036f7326
1,435
AoC-2022
Apache License 2.0
src/day9/Code.kt
fcolasuonno
221,697,249
false
null
package day9 import java.io.File fun main() { val name = if (false) "test.txt" else "input.txt" val dir = ::main::class.java.`package`.name val input = File("src/$dir/$name").readLines() val parsed = parse(input) println("Part 1 = ${part1(parsed)}") println("Part 2 = ${part2(parsed)}") } private val lineStructure = """\((\d+)x(\d+)\)""".toRegex() fun parse(input: List<String>) = input.requireNoNulls() fun part1(input: List<String>): Any? = input.map { string -> generateSequence(0 to string) { (start, s) -> lineStructure.takeIf { start < s.length }?.find(s, start)?.let { val (rangeLength, repetitions) = it.destructured val pattern = s.substring(it.range.last + 1, (it.range.last + 1 + rangeLength.toInt())) val repeated = pattern.repeat(repetitions.toInt()) val replaceRange = s.replaceRange(it.range.first..(it.range.last + rangeLength.toInt()), repeated) (it.range.first + repeated.length) to replaceRange } }.last().second.length } interface Expandable { fun expandedCount(): Long } data class Node(val string: String) : Expandable { override fun expandedCount() = string.length.toLong() } data class Repetition(val repetition: Long, val string: String) : Expandable { override fun expandedCount() = repetition * string.toNodes().map { it.expandedCount() }.sum() } fun String.toNodes(): List<Expandable> = lineStructure.find(this)?.let { val (rangeLength, repetitions) = it.destructured val repetition = repetitions.toLong() val repeatEnd = it.range.last + 1 + rangeLength.toInt() listOf(Node(substring(0, it.range.first)), Repetition(repetition, substring(it.range.last + 1, repeatEnd))) + substring(repeatEnd).toNodes() } ?: listOf(Node(this)) fun part2(input: List<String>): Any? = input.map { string -> val nodes = string.toNodes() nodes.map { it.expandedCount() }.sum() }
0
Kotlin
0
0
73110eb4b40f474e91e53a1569b9a24455984900
1,940
AOC2016
MIT License
src/y2021/d05/Day05.kt
AndreaHu3299
725,905,780
false
{"Kotlin": 31452}
package y2021.d03 import kotlin.math.absoluteValue import kotlin.math.sign import println import readInput fun main() { val classPath = "y2021/d05" fun part1(input: List<String>): Int { val points = mutableMapOf<Pair<Int, Int>, Int>() input .forEach { val line = it.split(" -> ").map { c -> c.split(",").let { (x, y) -> Pair(x.toInt(), y.toInt()) } } if (line[0].second == line[1].second) { val x = listOf(line[0].first, line[1].first) val min = x.min() val max = x.max() for (i in min..max) { val p = Pair(i, line[0].second) if (points.containsKey(p)) { points[p] = points[p]!! + 1 } else { points[p] = 1 } } } else if (line[0].first == line[1].first) { val y = listOf(line[0].second, line[1].second) val min = y.min() val max = y.max() for (i in min..max) { val p = Pair(line[0].first, i) if (points.containsKey(p)) { points[p] = points[p]!! + 1 } else { points[p] = 1 } } } } return points.values.count { it > 1 } } fun part2(input: List<String>): Int { val points = mutableMapOf<Pair<Int, Int>, Int>() input .forEach { val line = it.split(" -> ").map { c -> c.split(",").let { (x, y) -> Pair(x.toInt(), y.toInt()) } } if (line[0].second == line[1].second) { val x = listOf(line[0].first, line[1].first) val min = x.min() val max = x.max() for (i in min..max) { val p = Pair(i, line[0].second) if (points.containsKey(p)) { points[p] = points[p]!! + 1 } else { points[p] = 1 } } } else if (line[0].first == line[1].first) { val y = listOf(line[0].second, line[1].second) val min = y.min() val max = y.max() for (i in min..max) { val p = Pair(line[0].first, i) if (points.containsKey(p)) { points[p] = points[p]!! + 1 } else { points[p] = 1 } } } else if ((line[0].first - line[1].first).absoluteValue == (line[0].second - line[1].second).absoluteValue) { val diff = (line[0].first - line[1].first).absoluteValue val deltaX = (line[0].first - line[1].first).sign val deltaY = (line[0].second - line[1].second).sign for (i in 0..diff) { val p = Pair(line[1].first + deltaX * i, line[1].second + deltaY * i) if (points.containsKey(p)) { points[p] = points[p]!! + 1 } else { points[p] = 1 } } } } return points.values.count { it > 1 } } // test if implementation meets criteria from the description, like: val testInput = readInput("${classPath}/test") part1(testInput).println() part2(testInput).println() val input = readInput("${classPath}/input") part1(input).println() part2(input).println() }
0
Kotlin
0
0
f883eb8f2f57f3f14b0d65dafffe4fb13a04db0e
3,954
aoc
Apache License 2.0
src/Day09.kt
erikthered
572,804,470
false
{"Kotlin": 36722}
import kotlin.math.absoluteValue fun main() { data class Point(var x: Int = 0, var y: Int = 0) { fun isTouching(other: Point) = ((this.x - other.x).absoluteValue <=1 && (this.y - other.y).absoluteValue <=1) } fun follow(curr: Point, next: Point) { if(!next.isTouching(curr)) { when { curr.x == next.x && curr.y > next.y -> next.y++ curr.x == next.x && curr.y < next.y -> next.y-- curr.x > next.x && curr.y == next.y -> next.x++ curr.x < next.x && curr.y == next.y -> next.x-- else -> { when { curr.x > next.x && curr.y > next.y -> { next.x++ next.y++ } curr.x > next.x && curr.y < next.y -> { next.x++ next.y-- } curr.x < next.x && curr.y > next.y -> { next.x-- next.y++ } curr.x < next.x && curr.y < next.y -> { next.x-- next.y-- } } } } } } fun part1(input: List<String>): Int { val tailVisited = mutableSetOf<Point>() val head = Point(0, 0) val tail = Point(0, 0) tailVisited.add(tail.copy()) var totalMoves = 0 for(move in input) { val (dir, amt) = move.split(" ").let { (d, a) -> Direction.valueOf(d) to a.toInt()} totalMoves += amt repeat(amt) { when(dir) { Direction.R -> head.x++ Direction.L -> head.x-- Direction.U -> head.y++ Direction.D -> head.y-- } follow(head, tail) tailVisited.add(tail.copy()) } } return tailVisited.size } fun part2(input: List<String>): Int { val ropeSize = 10 val knots = arrayListOf<Point>() repeat(ropeSize){ knots.add(Point()) } val tailVisited = mutableSetOf<Point>() for(move in input) { val (dir, amt) = move.split(" ").let { (d, a) -> Direction.valueOf(d) to a.toInt() } repeat(amt) { when(dir) { Direction.R -> knots.first().x++ Direction.L -> knots.first().x-- Direction.U -> knots.first().y++ Direction.D -> knots.first().y-- } knots.windowed(2).forEach { (curr, next) -> follow(curr, next) } tailVisited.add(knots.last().copy()) } } return tailVisited.size } // test if implementation meets criteria from the description, like: val testInput = readInput("Day09_test") check(part1(testInput) == 13) val test2Input = readInput("Day09_test2") check(part2(test2Input) == 36) val input = readInput("Day09") println(part1(input)) println(part2(input)) } enum class Direction{ R, L, U, D }
0
Kotlin
0
0
3946827754a449cbe2a9e3e249a0db06fdc3995d
3,377
aoc-2022-kotlin
Apache License 2.0
src/main/kotlin/day3.kt
tianyu
574,561,581
false
{"Kotlin": 49942}
private fun main() { part1("The total priorities of all misplaced items is:") { withRucksacks { sumOf { rucksack -> assert(rucksack.length % 2 == 0) { "Rucksack does not have even length: $this" } val (left, right) = rucksack.splitAt(rucksack.length / 2) val mistakes = left.toSet() intersect right.toSet() mistakes.single().priority() } } } part2("The sum of all badge priorities is:") { withRucksacks { chunked(3).sumOf { (a, b, c) -> val badges = a.toSet() intersect b.toSet() intersect c.toSet() badges.single().priority() } } } } private fun String.splitAt(index: Int) = substring(0, index) to substring(index, length) private fun Char.priority() = when (this) { in 'a'..'z' -> this - 'a' + 1 in 'A'..'Z' -> this - 'A' + 27 else -> throw AssertionError("Cannot get priority of '$this'") } private inline fun <T> withRucksacks(action: Sequence<String>.() -> T) = withInputLines("day3.txt", action)
0
Kotlin
0
0
6144cc0ccf1a51ba2e28c9f38ae4e6dd4c0dc1ea
1,011
AdventOfCode2022
MIT License
src/day4/Day04.kt
MatthewWaanders
573,356,006
false
null
package day4 import utils.readInput fun main() { val testInput = readInput("Day04_test", "day4") check(part1(testInput) == 2) check(part2(testInput) == 4) val input = readInput("Day04", "day4") println(part1(input)) println(part2(input)) } fun part1(input: List<String>) = input .map { pair -> pair.split(",").map { range -> val (start, end) = range.split("-"); Pair(start.toInt(), end.toInt()) } } .sumOf { rangePair -> if ((rangePair[0].second >= rangePair[1].second && rangePair[0].first <= rangePair[1].first) || (rangePair[1].second >= rangePair[0].second && rangePair[1].first <= rangePair[0].first)) 1 else 0 as Int } fun part2(input: List<String>) = input .map { pair -> pair.split(",").map { range -> val (start, end) = range.split("-"); generateRange(start.toInt(), end.toInt()) } } .sumOf { rangePair -> if (rangePair[0].any { rangePair[1].contains(it) } || rangePair[1].any { rangePair[0].contains(it) }) 1 else 0 as Int } fun generateRange(start: Int, end: Int): IntRange { return start..end }
0
Kotlin
0
0
f58c9377edbe6fc5d777fba55d07873aa7775f9f
1,056
aoc-2022
Apache License 2.0
src/main/kotlin/mirecxp/aoc23/day05/Day05.kt
MirecXP
726,044,224
false
{"Kotlin": 42343}
package mirecxp.aoc23.day05 import mirecxp.aoc23.day04.toNumList import mirecxp.aoc23.readInput import java.util.* //https://adventofcode.com/2023/day/5 class Day05(private val inputPath: String) { private val lines: List<String> = readInput(inputPath) class RangeMap(val target: Long, val source: Long, val length: Long) { fun getSourceRange() = LongRange(source, source + length - 1) fun getTargetRange() = LongRange(target, target + length - 1) } // https://www.reddit.com/r/adventofcode/comments/18b4b0r/comment/kc2hh66/?utm_source=share&utm_medium=web3x&utm_name=web3xcss&utm_term=1&utm_content=share_button fun solve2() { val seeds: List<LongRange> = lines.first().substringAfter(" ").split(" ").map { it.toLong() }.chunked(2) .map { it.first()..<it.first() + it.last() } val maps: List<Map<LongRange, LongRange>> = lines.drop(2).joinToString("\n").split("\n\n").map { section -> section.lines().drop(1).associate { it.split(" ").map { it.toLong() }.let { (dest, source, length) -> source..(source + length) to dest..(dest + length) } } } val res = seeds.flatMap { seedsRange: LongRange -> maps.fold(listOf(seedsRange)) { aac: List<LongRange>, map: Map<LongRange, LongRange> -> aac.flatMap { map.entries.mapNotNull { (source, dest) -> (maxOf(source.first, it.first) to minOf(source.last, it.last)).let { (start, end) -> if (start <= end) (dest.first - source.first).let { (start + it)..(end + it) } else null } } } } }.minOf { it.first } println(res) } fun solve(part2: Boolean): String { println("Solving day 5 for ${lines.size} lines [$inputPath]") val rangeChain = LinkedList<LinkedList<RangeMap>>() var seeds = lines.first().substringAfter("seeds: ").toNumList() var rangeMapList = LinkedList<RangeMap>() lines.subList(2, lines.size - 1).forEach { line -> if (line.contains(":")) { // new mapping stage if (rangeMapList.isNotEmpty()) rangeChain.add(rangeMapList) rangeMapList = LinkedList<RangeMap>() } else if (line.isEmpty()) { //ignore } else { line.toNumList().apply { rangeMapList.add( RangeMap(target = get(0), source = get(1), length = get(2)) ) } } } rangeChain.add(rangeMapList) //last one // checkOverlaps(rangeChain) // OOM :( val result = if (part2) { //part 2 var min = Long.MAX_VALUE seeds.chunked(2) { chunk: List<Long> -> val start = chunk[0] val len = chunk[1] LongRange(start, start + len - 1) }.forEachIndexed { i, rng: LongRange -> println("Solving chunk $i, min so far = $min") var current: Long = 0 rng.forEachIndexed { index, seed -> val output = processSeedToMap(seed, rangeChain) val diff = seed - output if (current != diff) { println("It changed: $current -> $diff [$index]") current = diff } if (output < min) { min = output } } } min } else { //part 1 seeds.minOfOrNull { seed -> processSeedToMap(seed, rangeChain) } } val solution = "$result" println(solution) return solution } fun processSeedToMap(seed: Long, rangeChain: LinkedList<LinkedList<RangeMap>>): Long { var output: Long = seed rangeChain.forEachIndexed { chainIndex, rangeList -> val r: RangeMap? = rangeList.firstOrNull { output >= it.source && output <= it.source + it.length - 1 // it.getSourceRange().contains(output) } // print("chain ($chainIndex): $output->") r?.let { val i = output - r.source output = r.target + i } // if no range, output is not modified // println(output) } // println("seed $seed mapped to $output") return output } fun checkOverlaps(rangeChain: LinkedList<LinkedList<RangeMap>>) { //check overlapping var isOverlapping = false rangeChain.forEachIndexed { indexChain: Int, mapList: MutableList<RangeMap> -> mapList.forEachIndexed { indexList, rangeMap -> val srcR = rangeMap.getSourceRange() val dstR = rangeMap.getTargetRange() for (i in indexList + 1 until mapList.size) { val srcR1 = mapList[i].getSourceRange() val dstR1 = mapList[i].getTargetRange() if (srcR.intersect(srcR1).isNotEmpty()) { println("Overlap found: source chain $indexChain, range $indexList with range $i") isOverlapping = true } if (dstR.intersect(dstR1).isNotEmpty()) { println("Overlap found: target chain $indexChain, range $indexList with range $i") isOverlapping = true } } } } if (isOverlapping) println("OVERLAP FOUND") } } fun main(args: Array<String>) { val testProblem = Day05("test/day05t") check(testProblem.solve(part2 = false) == "35") check(testProblem.solve(part2 = true) == "46") val problem = Day05("real/day05a") // problem.solve2() problem.solve(part2 = false) problem.solve(part2 = true) }
0
Kotlin
0
0
6518fad9de6fb07f28375e46b50e971d99fce912
6,056
AoC-2023
MIT License
src/main/kotlin/year2021/day-09.kt
ppichler94
653,105,004
false
{"Kotlin": 182859}
package year2021 import lib.Grid2d import lib.Position import lib.TraversalBreadthFirstSearch import lib.aoc.Day import lib.aoc.Part fun main() { Day(9, 2021, PartA9(), PartB9()).run() } open class PartA9 : Part() { protected lateinit var heightmap: Grid2d<Int> override fun parse(text: String) { val content = text.split("\n").map { it.map { c -> c.digitToInt() } } heightmap = Grid2d(content) } override fun compute(): String { val minima = getMinima() return minima.sumOf { heightmap[it] + 1 }.toString() } protected fun getMinima() = buildList { val limits = heightmap.limits val moves = Position.moves() for (y in limits[1]) { for (x in limits[0]) { val pos = Position.at(x, y) val neighborHeight = pos.neighbours(moves, limits).map { heightmap[it] } if (neighborHeight.all { heightmap[pos] < it }) { add(pos) } } } } override val exampleAnswer: String get() = "15" } class PartB9 : PartA9() { override fun compute(): String { val minima = getMinima() val sizes = minima.map(::getBasinSize).sorted() return sizes.takeLast(3).reduce(Int::times).toString() } private fun getBasinSize(position: Position): Int { val limits = heightmap.limits val moves = Position.moves() val traversal = TraversalBreadthFirstSearch<Position> { pos, _ -> pos.neighbours(moves, limits).filter { heightmap[pos] < heightmap[it] && heightmap[it] < 9 } } return traversal.startFrom(position).traverseAll().visited.size } override val exampleAnswer: String get() = "1134" }
0
Kotlin
0
0
49dc6eb7aa2a68c45c716587427353567d7ea313
1,850
Advent-Of-Code-Kotlin
MIT License
2021/src/day09/day9.kt
scrubskip
160,313,272
false
{"Kotlin": 198319, "Python": 114888, "Dart": 86314}
package day09 import java.io.File fun main() { val heightMap = parseData(File("src/day09", "day9input.txt").readLines()) println(getRiskFactor(heightMap.findLowPointHeights())) val lowPoints = heightMap.findLowPoints() val largest3 = lowPoints.map { heightMap.findBasinSize(it) }.sortedDescending().take(3) .fold(1) { acc, value -> acc * value } println(largest3) } fun parseData(input: List<String>): HeightMap { return HeightMap(input.map { it.toCharArray().map { digit -> digit.digitToInt() }.toIntArray() }.toTypedArray()) } fun getRiskFactor(input: List<Int>): Int { return input.sumOf { it + 1 } } data class HeightMap(val heightData: Array<IntArray>) { fun findLowPointHeights(): List<Int> { return heightData.mapIndexed { rowIndex, ints -> val maxCol = ints.size - 1 ints.filterIndexed { colIndex, height -> isLowPoint(rowIndex, colIndex, height, maxCol) } }.flatMap { it.toList() } } fun findLowPoints(): List<Pair<Int, Int>> { val lowPointCoords = mutableListOf<Pair<Int, Int>>() heightData.forEachIndexed { rowIndex, ints -> val maxCol = ints.size - 1 ints.forEachIndexed { colIndex, height -> if (isLowPoint(rowIndex, colIndex, height, maxCol)) { lowPointCoords.add(Pair(rowIndex, colIndex)) } } } return lowPointCoords } fun get(coordinate: Pair<Int, Int>): Int { return heightData[coordinate.first][coordinate.second] } fun findBasinSize(start: Pair<Int, Int>): Int { // flood fill looking for 9s val seenLocations = mutableSetOf<Pair<Int, Int>>() var candidateLocations = mutableListOf<Pair<Int, Int>>() candidateLocations.add(start) while (candidateLocations.size > 0) { val candidate = candidateLocations.removeFirst() if (get(candidate) == 9 || seenLocations.contains(candidate)) { continue } seenLocations.add(candidate) // add neighbors val rowIndex = candidate.first val colIndex = candidate.second if (rowIndex > 0) candidateLocations.add(Pair(rowIndex - 1, colIndex)) if (colIndex > 0) candidateLocations.add(Pair(rowIndex, colIndex - 1)) if (rowIndex < heightData.size - 1) candidateLocations.add(Pair(rowIndex + 1, colIndex)) if (colIndex < heightData[rowIndex].size - 1) candidateLocations.add(Pair(rowIndex, colIndex + 1)) } return seenLocations.size } fun isLowPoint(rowIndex: Int, colIndex: Int, height: Int, maxCol: Int): Boolean { val neighbors = buildList { if (rowIndex > 0) add(heightData[rowIndex - 1][colIndex]) if (colIndex > 0) add(heightData[rowIndex][colIndex - 1]) if (rowIndex < heightData.size - 1) add(heightData[rowIndex + 1][colIndex]) if (colIndex < maxCol) add(heightData[rowIndex][colIndex + 1]) } val returnValue = neighbors.all { height < it } if (returnValue) { println("Found low point $rowIndex $colIndex $height") } return returnValue } override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as HeightMap if (!heightData.contentDeepEquals(other.heightData)) return false return true } override fun hashCode(): Int { return heightData.contentDeepHashCode() } }
0
Kotlin
0
0
a5b7f69b43ad02b9356d19c15ce478866e6c38a1
3,658
adventofcode
Apache License 2.0
src/y2023/Day14.kt
gaetjen
572,857,330
false
{"Kotlin": 325874, "Mermaid": 571}
package y2023 import util.Cardinal import util.Pos import util.get import util.readInput import util.set import util.timingStatistics import util.transpose object Day14 { enum class TileType(val c: Char) { ROLLER('O'), FIXED('#'), EMPTY('.') } data class Tile( val type: TileType, val pos: Pos, ) private fun parse(input: List<String>): MutableList<MutableList<Tile>> { return input.mapIndexed { row, s -> s.mapIndexedNotNull { col, c -> when (c) { '#' -> { Tile( TileType.FIXED, row to col ) } 'O' -> { Tile( TileType.ROLLER, row to col ) } '.' -> { Tile( TileType.EMPTY, row to col ) } else -> { null } } }.toMutableList() }.toMutableList() } fun part1(input: List<String>): Int { val rocks = parse(input) rocks.flatten().forEach { if (it.type == TileType.ROLLER) { roll(it.pos, Cardinal.NORTH, rocks) } } return rocks.transpose().sumOf { load(it) } } fun load(row: List<Tile>): Int { return row.indices .reversed() .zip(row) .filter { it.second.type == TileType.ROLLER } .sumOf { it.first + 1 } } fun Pos.coerce(maxes: Pos): Pos = first.coerceIn(0, maxes.first) to second.coerceIn(0, maxes.second) fun roll(pos: Pos, dir: Cardinal, rocks: MutableList<MutableList<Tile>>) { val newPos = dir.of(pos).coerce(rocks.size - 1 to rocks[0].size - 1) if (rocks[newPos].type != TileType.EMPTY) { return } rocks[newPos] = Tile(TileType.ROLLER, newPos) rocks[pos] = Tile(TileType.EMPTY, pos) roll(newPos, dir, rocks) } fun part2(input: List<String>): Int { val rocks = parse(input) val cycle = listOf( Cardinal.NORTH to { it: List<Tile> -> it.sortedBy { it.pos.first } }, Cardinal.WEST to { it: List<Tile> -> it.sortedBy { it.pos.second } }, Cardinal.SOUTH to { it: List<Tile> -> it.sortedByDescending { it.pos.first } }, Cardinal.EAST to { it: List<Tile> -> it.sortedByDescending { it.pos.second } }, ) val stateHistory = mutableListOf( rocksToString(rocks) to rocks.transpose().sumOf { load(it) } ) while (stateHistory.last() !in stateHistory.subList(0, stateHistory.size - 1)) { cycle.forEach { (dir, sort) -> sort(rocks.flatten().filter { it.type == TileType.ROLLER }).forEach { roll(it.pos, dir, rocks) } } stateHistory.add(rocksToString(rocks) to rocks.transpose().sumOf { load(it) }) } val cycleStart = stateHistory.indexOfFirst { it == stateHistory.last() } val cycleLength = stateHistory.size - cycleStart - 1 val targetIdx = (1_000_000_000 - cycleStart) % cycleLength + cycleStart return stateHistory[targetIdx].second } private fun rocksToString(rocks: MutableList<MutableList<Tile>>) = rocks.joinToString("\n") { row -> row.joinToString("") { it.type.c.toString() } } } fun main() { val testInput = """ O....#.... O.OO#....# .....##... OO.#O....O .O.....O#. O.#..O.#.# ..O..#O..O .......O.. #....###.. #OO..#.... """.trimIndent().split("\n") println("------Tests------") println(Day14.part1(testInput)) println(Day14.part2(testInput)) println("------Real------") val input = readInput(2023, 14) println("Part 1 result: ${Day14.part1(input)}") println("Part 2 result: ${Day14.part2(input)}") timingStatistics { Day14.part1(input) } timingStatistics { Day14.part2(input) } }
0
Kotlin
0
0
d0b9b5e16cf50025bd9c1ea1df02a308ac1cb66a
4,383
advent-of-code
Apache License 2.0
src/main/kotlin/Day09.kt
alex859
573,174,372
false
{"Kotlin": 80552}
import Movement.* import kotlin.math.absoluteValue fun main() { val testInput = readInput("Day09_test.txt") check(testInput.readMovements().tailPositions().size == 13) // check(testInput.result2() == 24933642) val input = readInput("Day09.txt") println(input.readMovements().tailPositions().size) // println(input.result2()) } internal fun List<Movement>.tailPositions() = fold( emptySet<Position>() to Rope(head = Position(5, 5), tail = Position(5, 5)) ) { (positions, rope), movement -> val next = rope.moveHead(movement) (positions + next.tail) to next }.first internal fun String.readMovements(): List<Movement> { val result = mutableListOf<Movement>() lines().forEach { val (type, steps) = it.split(" ") repeat(steps.toInt()) { result.add( when (type) { "R" -> Right "U" -> Up "D" -> Down "L" -> Left else -> error("unknown $type") } ) } } return result } fun Rope.moveHead(move: Movement): Rope { val newHead = head.move(move) val leftDistance = (newHead.left - tail.left) val bottomDistance = (newHead.bottom - tail.bottom) val newTail = if (head.left == tail.left || head.bottom == tail.bottom) { if (leftDistance.absoluteValue > 1 || bottomDistance.absoluteValue > 1) { head.copy() } else tail } else { if (head.bottom > tail.bottom) { if (head.left > tail.left) { when (move) { Up, Right -> head.copy() Down, Left -> tail } } else { when (move) { Up, Left -> head.copy() Down, Right -> tail } } } else { if (head.left > tail.left) { when (move) { Down, Right -> head.copy() Up, Left -> tail } } else { when (move) { Down, Left -> head.copy() Up, Right -> tail } } } } return copy(head = newHead, tail = newTail) } private fun Position.move(move: Movement) = when (move) { Right -> copy(left = left + 1) Left -> copy(left = left - 1) Up -> copy(bottom = bottom + 1) Down -> copy(bottom = bottom - 1) } enum class Movement { Right, Left, Up, Down } data class Position( val left: Int, val bottom: Int ) data class Rope( val head: Position, val tail: Position )
0
Kotlin
0
0
fbbd1543b5c5d57885e620ede296b9103477f61d
2,814
advent-of-code-kotlin-2022
Apache License 2.0
src/Day12.kt
kenyee
573,186,108
false
{"Kotlin": 57550}
fun main() { // ktlint-disable filename val paths = mutableSetOf<String>() fun isValidStep( visited: Array<BooleanArray>, grid: List<String>, row: Int, col: Int, curHeight: Char ): Boolean { val numRows = grid.size val numCols = grid[0].length if (row < 0 || row >= numRows) return false if (col < 0 || col >= numCols) return false if (visited[row][col]) return false val checkHeight = grid[row][col] if (curHeight == 'a' || curHeight == 'b') { if (checkHeight == 'S' || checkHeight == 'a') return true return false } if (curHeight == 'E') { if (checkHeight == 'z' || checkHeight == 'y') return true return false } if (curHeight > checkHeight && curHeight - 1 != checkHeight) return false return true } fun searchStart( visited: Array<BooleanArray>, grid: List<String>, startRow: Int, startCol: Int, endChar: Char = 'S' ): String { val queue = ArrayDeque<Pair<Position, String>>() queue.add(Pair(Position(startCol, startRow), "")) visited[startRow][startCol] = true while (queue.isNotEmpty()) { val (curPos, curPath) = queue.removeFirst() val thisHeight = grid[curPos.y][curPos.x] val path = curPath + thisHeight if (thisHeight == endChar) { paths.add(path) println("Found path $path") return path } for (direction in Direction.values()) { if (isValidStep(visited, grid, curPos.y + direction.deltaY, curPos.x + direction.deltaX, thisHeight)) { queue.add(Pair(Position(curPos.x + direction.deltaX, curPos.y + direction.deltaY), path)) visited[curPos.y + direction.deltaY][curPos.x + direction.deltaX] = true } } } return "" } fun processInput(input: List<String>, endChar: Char = 'S'): Int { val numCols = input[0].length val visited = Array(input.size) { BooleanArray(numCols) { false } } paths.clear() var result = "" for (i in input.indices) { val line = input[i] val startIndex = line.indexOf('E') if (startIndex > -1) { result = searchStart(visited, input, i, startIndex, endChar) break } } return result.length - 1 /* start is not a step but is recorded */ } fun part1(input: List<String>): Int { return processInput(input) } fun part2(input: List<String>): Int { return processInput(input, 'a') } // test if implementation meets criteria from the description, like: val testInput = readInput("Day12_test") println("Test Fewest steps: ${part1(testInput)}") check(part1(testInput) == 31) println("Test Fewest steps to bottom: ${part2(testInput)}") check(part2(testInput) == 29) val input = readInput("Day12_input") println("Fewest steps: ${part1(input)}") println("Fewest steps to bottom: ${part2(input)}") }
0
Kotlin
0
0
814f08b314ae0cbf8e5ae842a8ba82ca2171809d
3,260
KotlinAdventOfCode2022
Apache License 2.0
src/main/kotlin/day14/Day14.kt
TheSench
572,930,570
false
{"Kotlin": 128505}
package day14 import runDay import utils.Point fun main() { fun part1(input: List<String>) = input .map { it.toLine() } .toGrid() .dropSand() .size fun part2(input: List<String>) = input .map { it.toLine() } .toGrid() .addFloor() .dropSand() .size (object {}).runDay( part1 = ::part1, part1Check = 24, part2 = ::part2, part2Check = 93, ) } typealias Line = List<Point> typealias Lines = List<Line> typealias Grid = Set<Point> fun String.toLine() = split(" -> ") .map { it.split(",", limit = 2) .map { num -> num.toInt() } } .map { nums -> Point(nums.first(), nums.last()) } fun Lines.toGrid(): Set<Point> { val grid = mutableSetOf<Point>() this.forEach { it.addToGrid(grid) } return grid } fun Line.addToGrid(grid: MutableSet<Point>) { this.windowed(2).forEach { (it.first()..it.last()).forEach { point -> grid.add(point) } } } fun Grid.dropSand(start: Point = Point(500, 0)): Set<Point> { val stones = this val sand = mutableSetOf<Point>() val maxY = stones.maxOf { it.y } val pointsToRevisit = ArrayDeque<Point>() var pointConsidering = start while (pointConsidering.y < maxY) { val next = pointConsidering.next(stones, sand) pointConsidering = when (next) { null -> { sand.add(pointConsidering) if (pointsToRevisit.size == 0) break pointsToRevisit.removeFirst() } else -> { pointsToRevisit.addFirst(pointConsidering) next } } } return sand } fun Grid.addFloor(center: Point = Point(500, 0)): Grid { val maxY = this.maxOf { it.y } + 2 val minX = center.x - maxY val maxX = center.x + maxY return this + (Point(minX, maxY)..Point(maxX, maxY)).toSet() } fun Point.next(stones: Grid, sand: Grid) = listOf( this + Point(0, 1), this + Point(-1, 1), this + Point(1, 1), ).firstOrNull { it !in stones && it !in sand }
0
Kotlin
0
0
c3e421d75bc2cd7a4f55979fdfd317f08f6be4eb
2,189
advent-of-code-2022
Apache License 2.0
src/main/kotlin/se/saidaspen/aoc/aoc2022/Day08.kt
saidaspen
354,930,478
false
{"Kotlin": 301372, "CSS": 530}
package se.saidaspen.aoc.aoc2022 import se.saidaspen.aoc.util.* fun main() = Day08.run() object Day08 : Day(2022, 8) { override fun part1(): Any { val map = toMapInt(input) var visible = 0 for (p in map.keys) { if (map.keys.filter { it.y == p.y && it.x < p.x }.any { map[it]!! >= map[p]!! }) { visible++ continue } if (map.keys.filter { it.y == p.y && it.x > p.x }.all { map[it]!! < map[p]!! }) { visible++ continue } if (map.keys.filter { it.x == p.x && it.y < p.y }.all { map[it]!! < map[p]!! }) { visible++ continue } if (map.keys.filter { it.x == p.x && it.y > p.y }.all { map[it]!! < map[p]!! }) { visible++ continue } } return visible } override fun part2(): Any { val map = toMapInt(input) var bestScenicScore = 0 for (p in map.keys) { val left = map.keys.filter { it.y == p.y && it.x < p.x} var leftScore : Int = left.reversed().indexOfFirst { map[it]!! >= map[p]!! } + 1 if (leftScore == 0) leftScore = left.size val right = map.keys.filter { it.y == p.y && it.x > p.x} var rightScore = right.indexOfFirst { map[it]!! >= map[p]!! } + 1 if (rightScore == 0) rightScore = right.size val top = map.keys.filter { it.x == p.x && it.y < p.y} var topScore = top.reversed().indexOfFirst { map[it]!! >= map[p]!! } + 1 if (topScore == 0) topScore = top.size val bottom = map.keys.filter { it.x == p.x && it.y > p.y} var bottomScore = bottom.indexOfFirst { map[it]!! >= map[p]!! } + 1 if (bottomScore == 0) bottomScore = bottom.size val score = leftScore * rightScore * topScore * bottomScore if (score > bestScenicScore) bestScenicScore = score } return bestScenicScore } }
0
Kotlin
0
1
be120257fbce5eda9b51d3d7b63b121824c6e877
2,077
adventofkotlin
MIT License
lib/src/main/kotlin/com/bloidonia/advent/day11/Day11.kt
timyates
433,372,884
false
{"Kotlin": 48604, "Groovy": 33934}
package com.bloidonia.advent.day11 import com.bloidonia.advent.readList data class Octopus(val x: Int, val y: Int, var power: Int, var willFlash: Boolean = false) data class OctopusGrid(val width: Int, val octopi: List<Octopus>) { constructor(width: Int, octopi: IntArray) : this( width, octopi.mapIndexed { idx, power -> Octopus(idx.mod(width), idx / width, power) } ) private val height: Int get() { return octopi.size / width } fun update(): Long { octopi.forEach { if (++it.power > 9) { it.willFlash = true } } val flashers = ArrayDeque(octopi.filter { it.willFlash }) while (flashers.isNotEmpty()) { val next = flashers.removeFirst() flashers.addAll(trigger(next)) } // Reset var flashes = 0L octopi.forEach { if (it.power > 9) { it.power = 0 flashes++ } it.willFlash = false } return flashes } fun update(steps: Int): Long = (1..steps).sumOf { update() } fun allFlashStep(): Int = generateSequence(0) { update(); it + 1 }.first { octopi.all { it.power == 0 } } private fun trigger(next: Octopus): List<Octopus> { val result = mutableListOf<Octopus>() listOf(-1, 0, 1).forEach { dx -> listOf(-1, 0, 1).forEach { dy -> octopusAt(next.x + dx, next.y + dy)?.apply { if (!willFlash) { power++ if (power > 9) { willFlash = true result.add(this) } } } } } return result } private fun octopusAt(x: Int, y: Int): Octopus? = if (x in 0 until width && y in 0 until height) { octopi[y * width + x] } else { null } override fun toString(): String = octopi.chunked(width).joinToString("\n") { o -> o.map { it.power }.joinToString("") } } fun List<String>.readOctopi() = OctopusGrid(first().length, joinToString("").map { "$it".toInt() }.toIntArray()) fun main() { println(readList("/day11input.txt").readOctopi().update(100)) println(readList("/day11input.txt").readOctopi().allFlashStep()) }
0
Kotlin
0
1
9714e5b2c6a57db1b06e5ee6526eb30d587b94b4
2,393
advent-of-kotlin-2021
MIT License
src/main/kotlin/days/day18/Day18.kt
Stenz123
725,707,248
false
{"Kotlin": 123279, "Shell": 862}
package days.day18 import days.Day import kotlin.math.abs class Day18 : Day() { override fun partOne(): Any { val digMap = mutableSetOf(Coordinate(0, 0)) readInput().forEach { val direction = it[0] val numberOfSteps = it.split(" ")[1].toInt() val currentCoordinate = digMap.last() digMap.addAll(currentCoordinate.goXInDirextion((numberOfSteps - 1).toLong(), direction)) } var result = 0L val digMapList = digMap.toList() for (i in 0 .. digMap.size-2) { result += determinante(digMapList[i], digMapList[i+1]) } result+= determinante(digMapList.last(), digMapList.first()) return (result+digMapList.size)/2 + 1 } override fun partTwo(): Any { val digMap = mutableSetOf(Coordinate(0, 0)) readInput().forEach { val directionNumber = it[it.length - 2] val numberOfSteps = it.substringAfter("#").dropLast(2).toLong(radix = 16) when (directionNumber) { '0' -> digMap.add(Coordinate(digMap.last().x + numberOfSteps, digMap.last().y))//R '1' -> digMap.add(Coordinate(digMap.last().x, digMap.last().y - numberOfSteps))//D '2' -> digMap.add(Coordinate(digMap.last().x - numberOfSteps, digMap.last().y))//L '3' -> digMap.add(Coordinate(digMap.last().x, digMap.last().y + numberOfSteps))//U else -> { throw Exception() } } } val digMapList = digMap.toList() var borderLength = 0L var area = 0L for (i in 0 .. digMap.size-2) { borderLength += abs(digMapList[i].x-digMapList[i+1].x) borderLength += abs(digMapList[i].y-digMapList[i+1].y) area += determinante(digMapList[i], digMapList[i+1]) } area+= determinante(digMapList.last(), digMapList.first()) borderLength += abs(digMapList.last().x-digMapList.first().x) borderLength += abs(digMapList.last().y-digMapList.first().y) return (abs(area)+borderLength) /2L + 1L } } fun determinante(c1: Coordinate, c2: Coordinate):Long { return (c1.y + c2.y) * (c1.x - c2.x) } class Coordinate(val x: Long, val y: Long) { fun goXInDirextion(number: Long, direction: Char): List<Coordinate> { val result = mutableListOf(this) for (i in 0..number) { when (direction) { 'U' -> result.add(result.last().up()) 'D' -> result.add(result.last().down()) 'L' -> result.add(result.last().left()) 'R' -> result.add(result.last().right()) } } return result } fun up(): Coordinate { return Coordinate(x, y - 1) } fun down(): Coordinate { return Coordinate(x, y + 1) } fun left(): Coordinate { return Coordinate(x - 1, y) } fun right(): Coordinate { return Coordinate(x + 1, y) } fun getNeighbours(): List<Coordinate> { return listOf( Coordinate(x - 1, y), Coordinate(x, y - 1), Coordinate(x, y + 1), Coordinate(x + 1, y), ) } override fun toString(): String { return "($x, $y)" } override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as Coordinate if (x != other.x) return false if (y != other.y) return false return true } override fun hashCode(): Int { var result = x.hashCode() result = 31 * result + y.hashCode() return result } }
0
Kotlin
1
0
3de47ec31c5241947d38400d0a4d40c681c197be
3,755
advent-of-code_2023
The Unlicense
src/twentytwo/Day06.kt
Monkey-Matt
572,710,626
false
{"Kotlin": 73188}
package twentytwo fun main() { // test if implementation meets criteria from the description, like: val testInput = readInput("Day06_test") println(part1(testInput)) check(part1(testInput) == 7) println(part2(testInput)) check(part2(testInput) == 19) println("---") val input = readInput("Day06_input") println(part1(input)) println(part2(input)) testAlternativeSolutions() } private fun part1(input: String): Int { return positionOfFirstUniqueChain(input, 4) } private fun part2(input: String): Int { return positionOfFirstUniqueChain(input, 14) } private fun positionOfFirstUniqueChain(input: String, chainLength: Int): Int { val recentChainChars = MutableList(chainLength) { ' ' } input.forEachIndexed { index, char -> recentChainChars[index % chainLength] = char if (index >= chainLength && recentChainChars.toSet().size == chainLength) return index+1 } error("no answer") } // ------------------------------------------------------------------------------------------------ private fun testAlternativeSolutions() { val testInput = readInput("Day06_test") check(part1AlternativeSolution(testInput) == 7) check(part2AlternativeSolution(testInput) == 19) println("Alternative Solutions:") val input = readInput("Day06_input") println(part1AlternativeSolution(input)) println(part2AlternativeSolution(input)) } private fun part1AlternativeSolution(input: String): Int { return positionOfFirstUniqueChainAlternative(input, 4) } private fun part2AlternativeSolution(input: String): Int { return positionOfFirstUniqueChainAlternative(input, 14) } private fun positionOfFirstUniqueChainAlternative(input: String, chainLength: Int): Int { val position = input.windowed(chainLength).indexOfFirst { it.toSet().size == chainLength } return position + chainLength }
1
Kotlin
0
0
600237b66b8cd3145f103b5fab1978e407b19e4c
1,900
advent-of-code-solutions
Apache License 2.0
advent-of-code-2023/src/main/kotlin/eu/janvdb/aoc2023/day10/day10.kt
janvdbergh
318,992,922
false
{"Java": 1000798, "Kotlin": 284065, "Shell": 452, "C": 335}
package eu.janvdb.aoc2023.day10 import eu.janvdb.aocutil.kotlin.point2d.Point2D import eu.janvdb.aocutil.kotlin.readLines //const val FILENAME = "input10-test1.txt" //const val FILENAME = "input10-test2.txt" const val FILENAME = "input10.txt" fun main() { val lines = readLines(2023, FILENAME) val loop = Loop.create(lines) println(loop.links.size / 2) println(loop.countInside()) loop.print() } data class Point(val location: Point2D, val ch: Char) { fun isStart() = ch == 'S' fun getLinks(): List<Link> { return when (ch) { '-' -> listOf(Link(location, location.left()), Link(location, location.right())) '|' -> listOf(Link(location, location.up()), Link(location, location.down())) 'L' -> listOf(Link(location, location.right()), Link(location, location.up())) 'J' -> listOf(Link(location, location.left()), Link(location, location.up())) '7' -> listOf(Link(location, location.left()), Link(location, location.down())) 'F' -> listOf(Link(location, location.right()), Link(location, location.down())) 'S' -> listOf( Link(location, location.left()), Link(location, location.right()), Link(location, location.up()), Link(location, location.down()) ) '.' -> emptyList() else -> throw IllegalArgumentException("Unknown character: $ch") } } } data class Link(val from: Point2D, val to: Point2D) data class Loop(val points: Map<Point2D, Point>, val links: Set<Link>) { private val minX = links.minBy { it.from.x }.from.x private val maxX = links.maxBy { it.from.x }.from.x private val minY = links.minBy { it.from.y }.from.y private val maxY = links.maxBy { it.from.y }.from.y fun countInside(): Int { return (minX..maxX).flatMap { x -> (minY..maxY) .map { y -> Point2D(x, y) } } .count { !has(it) && hasInside(it) } } private fun has(point: Point2D) = links.any { it.from == point } private fun hasInside(point: Point2D): Boolean { fun hasLink(from: Point2D, to: Point2D) = Link(from, to) in links || Link(to, from) in links val wallsLeft = (minX..point.x).count { x -> hasLink(Point2D(x, point.y - 1), Point2D(x, point.y)) } val wallsRight = (point.x..maxX).count { x -> hasLink(Point2D(x, point.y), Point2D(x, point.y + 1)) } val wallsUp = (minY..point.y).count { y -> hasLink(Point2D(point.x, y), Point2D(point.x - 1, y)) } val wallsDown = (point.y..maxY).count { y -> hasLink(Point2D(point.x + 1, y), Point2D(point.x, y)) } return wallsLeft % 2 == 1 && wallsRight % 2 == 1 && wallsUp % 2 == 1 && wallsDown % 2 == 1 } fun print() { for (y in minY..maxY) { for (x in minX..maxX) { val point = Point2D(x, y) if (has(point)) { print(points[point]!!.ch) } else if (hasInside(point)) { print('I') } else { print('O') } } println() } } companion object { fun create(lines: List<String>): Loop { val allPoints = lines .flatMapIndexed { y, line -> line.mapIndexed { x, ch -> Point(Point2D(x, y), ch) } } .associateBy { it.location } val allLinks = allPoints.values.asSequence() .flatMap { it.getLinks() }.toSet() val recursiveLinksPerLocation = allLinks .asSequence() .filter { allLinks.contains(Link(it.to, it.from)) } .groupBy { it.from } .mapValues { entry -> entry.value.map { it.to } } val start = allPoints.values.find { it.isStart() }!!.location val visitedPoints = mutableListOf(start) val foundLinks = mutableSetOf<Link>() do { val last = visitedPoints.last() val next = recursiveLinksPerLocation[last]!!.find { it !in visitedPoints } if (next != null) { foundLinks.add(Link(last, next)) visitedPoints.add(next) } } while (next != null) foundLinks.add(Link(visitedPoints.last(), start)) return Loop(allPoints, foundLinks) } } }
0
Java
0
0
78ce266dbc41d1821342edca484768167f261752
3,779
advent-of-code
Apache License 2.0
src/main/kotlin/day10.kt
kevinrobayna
436,414,545
false
{"Ruby": 195446, "Kotlin": 42719, "Shell": 1288}
import java.util.* fun day10ProblemReader(string: String): List<Int> { return string .split("\n") .map { line -> line.toInt() } .toList() } // https://adventofcode.com/2020/day/10 class Day10( private val numbers: List<Int> ) { fun solvePart1(): Int { var n1 = 0 var n3 = 0 numbers.sorted().fold(0) { a, b -> when (b - a) { 1 -> n1++ 3 -> n3++ } b } return n1 * (n3 + 1) } // This does not work on big set fun solvePart2_naive(): Long { val max = numbers.maxOrNull()!!.plus(3) var solutions = 0L val solutionsToExplore: Queue<List<Int>> = LinkedList() solutionsToExplore.add(listOf(0)) do { val solution = solutionsToExplore.remove() val maxVal = solution.maxOrNull() if (maxVal != null) { if (max == maxVal.plus(3)) { solutions += 1L } for (x in 1..3) { if (numbers.contains(maxVal.plus(x))) { val newSolution = solution.toMutableList() newSolution.add(maxVal.plus(x)) solutionsToExplore.add(newSolution) } } } } while (solutionsToExplore.isNotEmpty()) return solutions } fun solvePart2(): Long { val k = longArrayOf(1, 0, 0, 0) numbers.sorted().fold(0) { a, b -> val d = b - a k.copyInto(k, d, 0, k.size - d) k.fill(0, 0, d) k[0] += k.sum() b } return k[0] } } fun main() { val problem = day10ProblemReader(Day10::class.java.getResource("day10.txt").readText()) println("solution = ${Day10(problem).solvePart1()}") println("solution part2 = ${Day10(problem).solvePart2()}") }
0
Kotlin
0
0
9e48ecdebdb4c479ef00f0fd3b1a44a211fb6577
1,958
adventofcode_2020
MIT License
src/Day09.kt
zirman
572,627,598
false
{"Kotlin": 89030}
import kotlin.math.absoluteValue data class Knot(val row: Int, val col: Int) fun main() { fun iterateTailKnot(h: Knot, t: Knot): Knot { val (hr, hc) = h var (tr, tc) = t val dr = hr - tr val dc = hc - tc val m = dr.absoluteValue + dc.absoluteValue if ((m == 1 || (m == 2 && dc.absoluteValue == 1 && dr.absoluteValue == 1)).not()) { if (dc > 0) { tc += 1 } else if (dc < 0) { tc -= 1 } if (dr > 0) { tr += 1 } else if (dr < 0) { tr -= 1 } } return Knot(tr, tc) } fun part1(input: List<String>): Int { val visited = mutableSetOf<Knot>() var headKnot = Knot(0, 0) var tailKnot = Knot(0, 0) visited.add(Knot(0, 0)) input.forEach { line -> val (dir, numStr) = line.split(" ") val n = numStr.toInt() fun iterate(n: Int, knot: Knot) { repeat(n) { headKnot = knot tailKnot = iterateTailKnot(headKnot, tailKnot) visited.add(tailKnot) } } when (dir) { "L" -> { iterate(n, headKnot.copy(col = headKnot.col - 1)) } "R" -> { iterate(n, headKnot.copy(col = headKnot.col + 1)) } "D" -> { iterate(n, headKnot.copy(row = headKnot.row + 1)) } "U" -> { iterate(n, headKnot.copy(row = headKnot.row - 1)) } } } return visited.size } fun part2(input: List<String>): Int { val visited = mutableSetOf<Knot>() var knots = (1..10).map { Knot(0, 0) } visited.add(Knot(0, 0)) fun iterateTailKnots(n: Int, knot: Knot) { repeat(n) { knots = buildList { var tailKnot = knot add(tailKnot) for (i in 1 until knots.size) { tailKnot = iterateTailKnot(tailKnot, knots[i]) add(tailKnot) } } } visited.add(knots.last()) } input.forEach { line -> val (dir, numstr) = line.split(" ") val n = numstr.toInt() when (dir) { "L" -> { iterateTailKnots(n, knots[0].copy(col = knots[0].col - 1)) } "R" -> { iterateTailKnots(n, knots[0].copy(row = knots[0].col + 1)) } "D" -> { iterateTailKnots(n, knots[0].copy(row = knots[0].row + 1)) } "U" -> { iterateTailKnots(n, knots[0].copy(row = knots[0].row - 1)) } } } return visited.size } // test if implementation meets criteria from the description, like: check(part1(readInput("Day09_test")) == 13) val input = readInput("Day09") println(part1(input)) check(part2(readInput("Day09_test2")) == 36) println(part2(input)) }
0
Kotlin
0
1
2ec1c664f6d6c6e3da2641ff5769faa368fafa0f
3,338
aoc2022
Apache License 2.0
src/Day05.kt
mzlnk
573,124,510
false
{"Kotlin": 14876}
import java.lang.StringBuilder import java.util.Stack fun main() { fun part1(input: List<String>): String { val stackLines = input.takeWhile { it[1] != '1' }.reversed() val numbersLine = input[stackLines.size] val instructionLines = input.subList(stackLines.size + 2, input.size) val stacksSize = numbersLine.split(' ').last().toInt() val stacks = ArrayList<Stack<Char>>() for (idx: Int in 0 until stacksSize) { stacks.add(Stack()) } for (stackLine: String in stackLines) { for ((stackIdx, offset) in (0..stacks.size).zip(1 until stackLine.length step 4)) { val letter = stackLine[offset] if (letter.isLetter()) { stacks[stackIdx].push(stackLine[offset]) } } } for (instruction: String in instructionLines) { val pattern = Regex("move (\\d+) from (\\d+) to (\\d+)") val (amount, from, to) = pattern.find(instruction)!!.destructured for (i: Int in 0 until amount.toInt()) { val popped = stacks[from.toInt() - 1].pop() stacks[to.toInt() - 1].push(popped) } } return stacks.map { it.pop() }.joinTo(buffer = StringBuilder(), separator = "").toString() } // FIXME: refactor it fun part2(input: List<String>): String { val printStacks: (ArrayList<ArrayList<Char>>) -> Unit = { stacks -> for((index: Int, stack: ArrayList<Char>) in stacks.withIndex()) { println("Stack $index: $stack") }} val stackLines = input.takeWhile { it[1] != '1' }.reversed() val numbersLine = input[stackLines.size] val instructionLines = input.subList(stackLines.size + 2, input.size) val stacksSize = numbersLine.split(' ').last().toInt() val stacks = ArrayList<ArrayList<Char>>() for (idx: Int in 0 until stacksSize) { stacks.add(ArrayList()) } for (stackLine: String in stackLines) { for ((stackIdx, offset) in (0..stacks.size).zip(1 until stackLine.length step 4)) { val letter = stackLine[offset] if (letter.isLetter()) { stacks[stackIdx].add(stackLine[offset]) } } } for (instruction: String in instructionLines) { val pattern = Regex("move (\\d+) from (\\d+) to (\\d+)") val (amount, from, to) = pattern.find(instruction)!!.destructured val taken = stacks[from.toInt() - 1].takeLast(amount.toInt()) printStacks(stacks) for(i in taken.indices) { stacks[from.toInt() - 1].removeLast() } stacks[to.toInt() - 1].addAll(taken) printStacks(stacks) } return stacks.map { it.last() }.joinTo(buffer = StringBuilder(), separator = "").toString() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day05_test") check(part1(testInput) == "CMZ") check(part2(testInput) == "MCD") val input = readInput("Day05") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
3a8ec82e9a8b4640e33fdd801b1ef87a06fa5cd5
3,231
advent-of-code-2022
Apache License 2.0
src/Day05.kt
kuolemax
573,740,719
false
{"Kotlin": 21104}
import java.util.* import kotlin.collections.ArrayList fun main() { fun part1(input: List<String>): String { val (startRow, stackList) = parseStacks(input) val moveRows = input.subList(startRow, input.size) return moveCargo(moveRows, stackList) } fun part2(input: List<String>): String { val (startRow, stackList) = parseStacks(input) val moveRows = input.subList(startRow, input.size) return multiMoveCargo(moveRows, stackList) } // test if implementation meets criteria from the description, like: val testInput = readInput("Day05_test") check(part1(testInput) == "CMZ") check(part2(testInput) == "MCD") val input = readInput("Day05") println(part1(input)) println(part2(input)) } private fun parseStacks(input: List<String>): Pair<Int, MutableList<MutableList<String>>> { // 找到 move 所在行,索引即 Cargo 所在行数 val moveRow = input.first { it -> it.startsWith("move") } val moveIndex = input.indexOf(moveRow) // 前 moveIndex - 2 是矩阵 val columNumOfRow = moveIndex - 2 val matrix = input.subList(0, columNumOfRow) // 找到 move 前倒数第二行,提取数字,数字个数即 Stack 数 val columnNumStr = input[columNumOfRow] val stackNum = (columnNumStr.length + 2) / 4 // 每行第 2 + (col - 1) * 4 个数字即 Cargo 存储的值 val stackList = ArrayList<Stack<String>>() (0 until stackNum).forEach { col -> matrix.forEach { row -> val index = 2 + col * 4 val cargoValue = row.substring(index - 1, index) if (cargoValue.isNotBlank()) { if (stackList.isEmpty() || stackList.size < col + 1) { stackList.add(Stack()) } stackList[col].add(0, cargoValue) } } } return moveIndex to stackList.toMutableList() } private fun moveCargo(moveList: List<String>, stacks: MutableList<MutableList<String>>): String { // 提取移动的起始点和个数 val moveOperationList = parseMoveOperations(moveList) moveOperationList.forEach { (moveNum, popIndex, addIndex) -> (0 until moveNum).forEach { _ -> val popValue = stacks[popIndex - 1].removeLast() stacks[addIndex - 1].add(popValue) } } return stacks.joinToString("") { it.last() } } private fun multiMoveCargo(moveList: List<String>, stacks: MutableList<MutableList<String>>): String { // 提取移动的起始点和个数 val moveOperationList = parseMoveOperations(moveList) moveOperationList.forEach { (moveNum, popIndex, addIndex) -> val popStack = stacks[popIndex - 1] val popCargos = popStack.subList(popStack.size - moveNum, popStack.size) stacks[addIndex - 1].addAll(popCargos) stacks[popIndex - 1] = popStack.subList(0, popStack.size - moveNum) } return stacks.joinToString("") { it.last() } } private fun parseMoveOperations(moveList: List<String>): List<Triple<Int, Int, Int>> { val regexPattern = Regex("move (\\d+) from (\\d+) to (\\d+)") val moveOperationList = moveList.map { row -> val find = regexPattern.find(row) Triple(find!!.groupValues[1].toInt(), find.groupValues[2].toInt(), find.groupValues[3].toInt()) } return moveOperationList }
0
Kotlin
0
0
3045f307e24b6ca557b84dac18197334b8a8a9bf
3,370
aoc2022--kotlin
Apache License 2.0
src/main/kotlin/day5.kt
Arch-vile
572,557,390
false
{"Kotlin": 132454}
package day5 import aoc.utils.Matrix import aoc.utils.readInput fun part1(): String { return solve(::makeMove) } fun part2(): String { return solve(::makeMove2) } fun solve(mover: (Int, Int, Int, MutableList<MutableList<String>>) -> Unit): String { val crates = createCrates() readInput("day5-input.txt") .drop(10) .map { it.split(" ") } .forEach { mover(it[1].toInt(), it[3].toInt() - 1, it[5].toInt() - 1, crates) } return crates.joinToString("") { it.last() } } private fun createCrates(): MutableList<MutableList<String>> { val read = readInput("day5-input.txt") .take(8) .map { it.windowed(3,4) } .map { it.map { it.replace("[", "").replace("]","").replace(" ","")} } return Matrix(read).rotateCW().values().map { it.filter { it != "" }.toMutableList() }.toMutableList() } fun makeMove2(amount: Int, from: Int, to: Int, crates: MutableList<MutableList<String>>) { val toMove = crates[from].takeLast(amount) crates[from] = crates[from].dropLast(amount).toMutableList() crates[to] = crates[to].plus(toMove).toMutableList() } fun makeMove(amount: Int, from: Int, to: Int, crates: MutableList<MutableList<String>>) { repeat(amount) { val toMove = crates[from].last() crates[from] = crates[from].dropLast(1).toMutableList() crates[to] = crates[to].plus(toMove).toMutableList() } }
0
Kotlin
0
0
e737bf3112e97b2221403fef6f77e994f331b7e9
1,417
adventOfCode2022
Apache License 2.0
src/Day08.kt
Vlisie
572,110,977
false
{"Kotlin": 31465}
import java.io.File fun main() { fun part1(file: File): Int { var visibleTrees = 0 val grid = file.readLines() .map { string -> string.chunked(1) .map { it.toInt() } } //Outer trees visibleTrees += (2 * (grid.size + grid[0].size) - 4) //-1 om buitenste ring te skippen for (rowTree in 1 until grid.size - 1) { for (colTree in 1 until grid[rowTree].size - 1) { val treeHeight = grid[rowTree][colTree] val treesHeightLeft = grid[rowTree].slice(0 until colTree).max() val treesHeightRight = grid[rowTree].slice(colTree + 1 until grid[rowTree].size).max() val treesHeightUp = grid.slice(0 until rowTree).map { it[colTree] }.max() val treesHeightDown = grid.slice(rowTree + 1 until grid.size).map { it[colTree] }.max() if (treeHeight > treesHeightLeft || treeHeight > treesHeightRight || treeHeight > treesHeightUp || treeHeight > treesHeightDown ) { visibleTrees++ } } } return visibleTrees } fun part2(file: File): Int { val scenicScore: Int val grid = file.readLines() .map { string -> string.chunked(1) .map { it.toInt() } } //gestolen functie fun List<List<Int>>.viewFrom(x: Int, y: Int): List<List<Int>> { return listOf( (y - 1 downTo 0).map { this[it][x] }, // Up (y + 1 until grid.size).map { this[it][x] }, // Down this[y].take(x).asReversed(), // Left this[y].drop(x + 1) // Right ) } //gestolen functie fun List<List<Int>>.scoreAt(x: Int, y: Int): Int = viewFrom(x, y).map { direction -> direction.takeUntil { it >= this[y][x] }.count() }.product() scenicScore = (1 until grid.size - 1).maxOf { y -> (1 until grid[0].size - 1).maxOf { x -> grid.scoreAt(x, y) } } //-1 om buitenste ring te skippen /* for (rowTree in 1 until grid.size - 1) { for (colTree in 1 until grid[rowTree].size - 1) { grid.scoreAt(colTree, rowTree) val treeHeight = grid[rowTree][colTree] val scenicLengthLeft = grid[rowTree].slice(0 until colTree) .reversed() .takeWhile { it < treeHeight }.count() val scenicLengthRight = grid[rowTree].slice(colTree + 1 until grid[rowTree].size) .takeWhile { it < treeHeight }.count() val scenicLengthUp = grid.slice(0 until rowTree) .map { it[colTree] }.reversed() .takeWhile { it < treeHeight }.count() val scenicLengthDown = grid.slice(rowTree + 1 until grid.size) .map { it[colTree] } .takeWhile { it < treeHeight }.count() val score = scenicLengthLeft * scenicLengthRight * scenicLengthUp * scenicLengthDown if (scenicScore < score) { scenicScore = score } } }*/ return scenicScore } // test if implementation meets criteria from the description, like: val testInput = File("src/input", "testInput.txt") println("Part 1 ----------- TEST") val test1 = part1(testInput) println(test1) check(test1 == 21) println("Part 2 ----------- TEST") val test2 = part2(testInput) println(test2) check(test2 == 8) val input = File("src/input", "input8.txt") println("Part 1 -----------") println(part1(input)) println("Part 2 -----------") println(part2(input)) }
0
Kotlin
0
0
b5de21ed7ab063067703e4adebac9c98920dd51e
3,974
AoC2022
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/MaximumProductOfWordLengths.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2021 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import kotlin.math.max /** * 318. Maximum Product of Word Lengths * @see <a href="https://leetcode.com/problems/maximum-product-of-word-lengths/">Source</a> */ fun interface MaximumProductOfWordLengths { fun maxProduct(words: Array<String>): Int } fun Char.bitNumber(): Int { return this.code - 'a'.code } /** * Approach 1: Optimize noCommonLetters function : Bitmasks + Precomputation */ class MaxProductBitmasks : MaximumProductOfWordLengths { override fun maxProduct(words: Array<String>): Int { val n: Int = words.size val masks = IntArray(n) val lens = IntArray(n) var bitmask: Int for (i in 0 until n) { bitmask = 0 for (ch in words[i].toCharArray()) { // add a bit number bit_number in bitmask bitmask = bitmask or (1 shl ch.bitNumber()) } masks[i] = bitmask lens[i] = words[i].length } var maxVal = 0 for (i in 0 until n) { for (j in i + 1 until n) { if (masks[i] and masks[j] == 0) { maxVal = max(maxVal, lens[i] * lens[j]) } } } return maxVal } } /** * Approach 2: Optimise Number of Comparisons : Bitmasks + Pre-computation + Hashmap */ class MaxProductHashmap : MaximumProductOfWordLengths { override fun maxProduct(words: Array<String>): Int { val hashmap: MutableMap<Int, Int> = HashMap() var bitmask: Int for (word in words) { bitmask = 0 for (ch in word.toCharArray()) { // add bit number bitNumber in bitmask bitmask = bitmask or (1 shl ch.bitNumber()) } // there could be different words with the same bitmask // ex. ab and aabb hashmap[bitmask] = max(hashmap.getOrDefault(bitmask, 0), word.length) } var maxProd = 0 for (x in hashmap.keys) { for (y in hashmap.keys) { if (x and y == 0) { maxProd = max( maxProd, hashmap.getOrDefault(x, 0) * hashmap.getOrDefault(y, 0), ) } } } return maxProd } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
2,959
kotlab
Apache License 2.0
src/main/kotlin/ru/timakden/aoc/year2022/Day07.kt
timakden
76,895,831
false
{"Kotlin": 321649}
package ru.timakden.aoc.year2022 import arrow.core.tail import ru.timakden.aoc.util.measure import ru.timakden.aoc.util.readInput import ru.timakden.aoc.year2022.Day07.Node.Directory import ru.timakden.aoc.year2022.Day07.Node.File /** * [Day 7: No Space Left On Device](https://adventofcode.com/2022/day/7). */ object Day07 { @JvmStatic fun main(args: Array<String>) { measure { val input = readInput("year2022/Day07") println("Part One: ${part1(input)}") println("Part Two: ${part2(input)}") } } fun part1(input: List<String>): Int { val directories = mutableListOf<Directory>() val directoriesToCheck = ArrayDeque<Directory>().apply { add(buildTree(input)) } while (directoriesToCheck.isNotEmpty()) { val current = directoriesToCheck.removeFirst() if (current.size <= 100000) { directories.add(current) } directoriesToCheck += current.children.filterIsInstance<Directory>() } return directories.sumOf { it.size } } fun part2(input: List<String>): Int { val totalDiskSpace = 70000000 val requiredForUpdateSpace = 30000000 val root = buildTree(input) val totalUsedSpace = root.size val currentUnusedSpace = totalDiskSpace - totalUsedSpace val toBeFreedSpace = requiredForUpdateSpace - currentUnusedSpace val directories = mutableListOf<Directory>() val directoriesToCheck = ArrayDeque<Directory>().apply { add(root) } while (directoriesToCheck.isNotEmpty()) { val current = directoriesToCheck.removeFirst() if (current.size >= toBeFreedSpace) { directories.add(current) } directoriesToCheck += current.children.filterIsInstance<Directory>() } return directories.minByOrNull { it.size }?.size ?: 0 } private fun buildTree(input: List<String>): Directory { var current = Directory("/", null) input.tail().forEach { line -> if (line.startsWith('$')) { if (line.startsWith("$ cd")) { val nextDirectory = line.substringAfter("cd ") current = if (nextDirectory == "..") checkNotNull(current.parent) else current.children .filter { it.name == nextDirectory } .filterIsInstance<Directory>() .firstOrNull() ?: Directory(nextDirectory, current) } } else if (line.startsWith("dir")) { current.children += Directory(line.substringAfter("dir "), current) } else if (line.isBlank()) { // ignore } else { val (size, name) = line.split(' ') current.children += File(name, size.toInt(), current) } } while (current.parent != null) { current = checkNotNull(current.parent) } return current } sealed interface Node { val size: Int val name: String val parent: Directory? data class File( override val name: String, override val size: Int, override val parent: Directory? ) : Node data class Directory( override val name: String, override val parent: Directory? ) : Node { val children = mutableSetOf<Node>() override val size: Int by lazy { children.sumOf { it.size } } } } }
0
Kotlin
0
3
acc4dceb69350c04f6ae42fc50315745f728cce1
3,618
advent-of-code
MIT License
src/main/kotlin/dev/patbeagan/days/Day03.kt
patbeagan1
576,401,502
false
{"Kotlin": 57404}
package dev.patbeagan.days /** * [Day 3](https://adventofcode.com/2022/day/3) */ class Day03 : AdventDay<Int> { override fun part1(input: String) = parseInput(input) .sumOf { rucksack -> rucksack.getMatchingItems().sumOf { it.toPriority()!! } } override fun part2(input: String) = parseInput(input) .chunked(3) .sumOf { ElfSquad(it[0], it[1], it[2]).findBadge().toPriority()!! } fun parseInput(input: String) = input .trim() .split("\n") .map { Rucksack( it.substring(0, it.length / 2), it.substring(it.length / 2, it.length) ) } private fun Char.toPriority() = when (this) { in CharRange('a', 'z') -> this.code - 96 in CharRange('A', 'Z') -> this.code - 38 else -> null } data class Rucksack( val compartment1: String, val compartment2: String, ) { fun getMatchingItems() = compartment1.toSet() intersect compartment2.toSet() fun contents() = compartment1 + compartment2 } data class ElfSquad( val rucksack1: Rucksack, val rucksack2: Rucksack, val rucksack3: Rucksack, ) { private val contents = setOf( rucksack1, rucksack2, rucksack3 ) fun findBadge() = contents .fold(rucksack1.contents().toSet()) { acc, each -> acc intersect each.contents().toSet() }.first() } }
0
Kotlin
0
0
4e25b38226bcd0dbd9c2ea18553c876bf2ec1722
1,562
AOC-2022-in-Kotlin
Apache License 2.0
src/aoc22/Day09.kt
mihassan
575,356,150
false
{"Kotlin": 123343}
@file:Suppress("PackageDirectoryMismatch") package aoc22.day09 import kotlin.math.abs import kotlin.math.sign import lib.Collections.headTail import lib.Solution data class Point(val x: Int, val y: Int) { val absoluteValue by lazy { Point(abs(x), abs(y)) } val signValue by lazy { Point(sign(x.toDouble()).toInt(), sign(y.toDouble()).toInt()) } } operator fun Point.plus(o: Point): Point = Point(x + o.x, y + o.y) operator fun Point.minus(o: Point): Point = Point(x - o.x, y - o.y) operator fun Point.times(s: Int): Point = Point(x * s, y * s) infix fun Point.touches(o: Point): Boolean = (this - o).absoluteValue.let { (x, y) -> x <= 1 && y <= 1 } enum class Direction(val delta: Point) { R(Point(1, 0)), L(Point(-1, 0)), U(Point(0, 1)), D(Point(0, -1)) } fun String.toDirection(): Direction = when (this) { "R" -> Direction.R "L" -> Direction.L "U" -> Direction.U "D" -> Direction.D else -> error("Invalid direction.") } data class Step(val direction: Direction, val stepCount: Int) { val breakdown: List<Direction> = List(stepCount) { direction } } fun String.toStep(): Step = split(" ").let { (d, s) -> Step(d.toDirection(), s.toInt()) } typealias Input = List<Direction> typealias Output = Int private val solution = object : Solution<Input, Output>(2022, "Day09") { val KNOT_COUNT = mapOf(Part.PART1 to 2, Part.PART2 to 10) override fun parse(input: String): Input = input.lines().flatMap { it.toStep().breakdown } override fun format(output: Output): String = "$output" override fun solve(part: Part, input: Input): Output { val knotCount = checkNotNull(KNOT_COUNT[part]) val initialKnots = List(knotCount) { Point(0, 0) } val ropeSequence = input.runningFold(initialKnots, ::moveRope) return ropeSequence.map { it.last() }.toSet().size } private fun moveRope(knots: List<Point>, direction: Direction): List<Point> { val (head, tail) = knots.headTail() val newHead = checkNotNull(head) + direction.delta return tail.runningFold(newHead) { acc, knot -> followNextKnot(knot, acc) } } private fun followNextKnot(followedKnot: Point, followingKnot: Point): Point = if (followingKnot touches followedKnot) followedKnot else followedKnot + (followingKnot - followedKnot).signValue } fun main() = solution.run()
0
Kotlin
0
0
698316da8c38311366ee6990dd5b3e68b486b62d
2,332
aoc-kotlin
Apache License 2.0
src/Day04/Day04.kt
G-lalonde
574,649,075
false
{"Kotlin": 39626}
package Day04 import readInput fun main() { fun part1(input: List<String>): Int { var fullyContainedCount = 0 for (line in input) { val (start1, end1) = line.split(",")[0].split("-").map { it.toInt() } val (start2, end2) = line.split(",")[1].split("-").map { it.toInt() } if (start1 <= start2 && end1 >= end2) { fullyContainedCount++ } else if (start2 <= start1 && end2 >= end1) { fullyContainedCount++ } } return fullyContainedCount } fun part2(input: List<String>): Int { var fullyContainedCount = 0 for (line in input) { val (start1, end1) = line.split(",")[0].split("-").map { it.toInt() } val (start2, end2) = line.split(",")[1].split("-").map { it.toInt() } if (!(start1 < start2 && end1 < start2 || start1 > end2 && end1 > end2)) { fullyContainedCount++ } } return fullyContainedCount } // test if implementation meets criteria from the description, like: val testInput = readInput("Day04/Day04_test") check(part1(testInput) == 2) { "Got instead : ${part1(testInput)}" } check(part2(testInput) == 4) { "Got instead : ${part2(testInput)}" } val input = readInput("Day04/Day04") println("Answer for part 1 : ${part1(input)}") println("Answer for part 2 : ${part2(input)}") }
0
Kotlin
0
0
3463c3228471e7fc08dbe6f89af33199da1ceac9
1,455
aoc-2022
Apache License 2.0
src/main/kotlin/_2022/Day14.kt
novikmisha
572,840,526
false
{"Kotlin": 145780}
package _2022 import readInput fun main() { fun printMap(map: Map<Pair<Int, Int>, Item>) { val minX = map.keys.minBy { it.first }.first - 1 val maxX = map.keys.maxBy { it.first }.first + 1 val minY = 0 val maxY = map.keys.maxBy { it.second }.second + 1 for (y in minY..maxY) { for (x in minX..maxX) { print(map.getOrDefault(Pair(x, y), Item.AIR).mapChar) } println() } } fun buildRockMap(input: List<String>): MutableMap<Pair<Int, Int>, Item> { val rockMap = mutableMapOf<Pair<Int, Int>, Item>() input.forEach { for (rockPair in it.split(" -> ") .map { singleRockLine -> singleRockLine.split(",").map(String::toInt) }.windowed(2)) { val (firstRock, secondRock) = rockPair.sortedBy { rock -> rock[0] } for (x in firstRock[0]..secondRock[0]) { val (firstRock, secondRock) = rockPair.sortedBy { rock -> rock[1] } for (y in firstRock[1]..secondRock[1]) { rockMap[Pair(x, y)] = Item.ROCK } } } } return rockMap } fun getNextSandPosition(sand: Pair<Int, Int>, rockMap: MutableMap<Pair<Int, Int>, Item>): Pair<Int, Int> { var flag = true val maxY = rockMap.keys.maxBy { it.second }.second + 1 var result = Pair(sand.first, sand.second) while (flag) { if (result.second == maxY) { return result } var maybeNextPosition = Pair(result.first, result.second + 1) if (!rockMap.containsKey(maybeNextPosition)) { result = maybeNextPosition continue } maybeNextPosition = Pair(result.first - 1, result.second + 1) if (!rockMap.containsKey(maybeNextPosition)) { result = maybeNextPosition continue } maybeNextPosition = Pair(result.first + 1, result.second + 1) if (!rockMap.containsKey(maybeNextPosition)) { result = maybeNextPosition continue } flag = false } return result } fun part1(input: List<String>): Int { val rockMap = buildRockMap(input) var flag = true var count = 0 val maxY = rockMap.keys.maxBy { it.second }.second + 1 while (flag) { count++ var sand = Pair(500, 0) val nextSandPosition = getNextSandPosition(sand, rockMap) sand = nextSandPosition if (sand.second >= maxY) { flag = false } rockMap[sand] = Item.SAND // printMap(rockMap) } return count - 1 } fun part2(input: List<String>): Int { val rockMap = buildRockMap(input) val maxY = rockMap.keys.maxBy { it.second }.second + 2 val minX = rockMap.keys.minBy { it.first }.first - 400 val maxX = rockMap.keys.maxBy { it.first }.first + 400 for (x in minX..maxX) { rockMap[Pair(x, maxY)] = Item.ROCK } var flag = true var count = 0 while (flag) { count++ var sand = Pair(500, 0) val nextSandPosition = getNextSandPosition(sand, rockMap) if (sand.first == nextSandPosition.first && sand.second == nextSandPosition.second) { flag = false } sand = nextSandPosition rockMap[sand] = Item.SAND // printMap(rockMap) } return count } // test if implementation meets criteria from the description, like: val testInput = readInput("Day14_test") println(part1(testInput)) println(part2(testInput)) val input = readInput("Day14") println(part1(input)) println(part2(input)) } enum class Item(val mapChar: Char) { ROCK('#'), SAND('0'), AIR('.') }
0
Kotlin
0
0
0c78596d46f3a8bf977bf356019ea9940ee04c88
4,106
advent-of-code
Apache License 2.0
src/Day14.kt
Flame239
570,094,570
false
{"Kotlin": 60685}
import kotlin.math.max private fun map(): Array<BooleanArray> { var maxY = 0 val rocks: List<List<C>> = readInput("Day14").map { it.split(" -> ") .map { c -> c.split(",").map(String::toInt) } .map { c -> C(c[0], c[1].also { y -> maxY = max(maxY, y) }) } } val w = 1000 val map = Array(w) { BooleanArray(maxY + 3) } rocks.forEach { it.windowed(2).forEach { (l, r) -> for (i in l.x toward r.x) map[i][l.y] = true for (j in l.y toward r.y) map[l.x][j] = true } } for (i in 0 until w) { map[i][map[0].lastIndex] = true } return map } private fun part1(map: Array<BooleanArray>): Int { var step = 0 val maxY = map[0].lastIndex - 2 while (true) { var x = 500 var y = 0 while (true) { if (y == maxY) return step if (!map[x][y + 1]) { y++ } else if (!map[x - 1][y + 1]) { y++ x-- } else if (!map[x + 1][y + 1]) { y++ x++ } else { map[x][y] = true break } } step++ } } private fun part2(map: Array<BooleanArray>): Int { var step = 0 while (true) { var x = 500 var y = 0 if (map[x][y]) return step while (true) { if (!map[x][y + 1]) { y++ } else if (!map[x - 1][y + 1]) { y++ x-- } else if (!map[x + 1][y + 1]) { y++ x++ } else { map[x][y] = true break } } step++ } } fun main() { println(part1(map())) println(part2(map())) }
0
Kotlin
0
0
27f3133e4cd24b33767e18777187f09e1ed3c214
1,821
advent-of-code-2022
Apache License 2.0
kotlin/MaxFlowDinic.kt
dirask
202,550,220
true
{"Java": 491556, "C++": 207948, "Kotlin": 23977, "CMake": 346}
// https://en.wikipedia.org/wiki/Dinic%27s_algorithm in O(V^2 * E) object MaxFlowDinic { data class Edge(val t: Int, val rev: Int, val cap: Int, var f: Int = 0) fun addEdge(graph: Array<ArrayList<Edge>>, s: Int, t: Int, cap: Int) { graph[s].add(Edge(t, graph[t].size, cap)) graph[t].add(Edge(s, graph[s].size - 1, 0)) } fun dinicBfs(graph: Array<out List<Edge>>, src: Int, dest: Int, dist: IntArray): Boolean { dist.fill(-1) dist[src] = 0 val Q = IntArray(graph.size) var sizeQ = 0 Q[sizeQ++] = src var i = 0 while (i < sizeQ) { val u = Q[i++] for (e in graph[u]) { if (dist[e.t] < 0 && e.f < e.cap) { dist[e.t] = dist[u] + 1 Q[sizeQ++] = e.t } } } return dist[dest] >= 0 } fun dinicDfs(graph: Array<out List<Edge>>, ptr: IntArray, dist: IntArray, dest: Int, u: Int, f: Int): Int { if (u == dest) return f while (ptr[u] < graph[u].size) { val e = graph[u][ptr[u]] if (dist[e.t] == dist[u] + 1 && e.f < e.cap) { val df = dinicDfs(graph, ptr, dist, dest, e.t, Math.min(f, e.cap - e.f)) if (df > 0) { e.f += df graph[e.t][e.rev].f -= df return df } } ++ptr[u] } return 0 } fun maxFlow(graph: Array<out List<Edge>>, src: Int, dest: Int): Int { var flow = 0 val dist = IntArray(graph.size) while (dinicBfs(graph, src, dest, dist)) { val ptr = IntArray(graph.size) while (true) { val df = dinicDfs(graph, ptr, dist, dest, src, Int.MAX_VALUE) if (df == 0) break flow += df } } return flow } // Usage example @JvmStatic fun main(args: Array<String>) { val graph = (1..3).map { arrayListOf<Edge>() }.toTypedArray() addEdge(graph, 0, 1, 3) addEdge(graph, 0, 2, 2) addEdge(graph, 1, 2, 2) val maxFlow = maxFlow(graph, 0, 2) println(4 == maxFlow) } }
0
Java
1
2
75f52966780cdc6af582e00f9460f17a4a80d19e
2,285
codelibrary
The Unlicense
kotlin/src/com/s13g/aoc/aoc2020/Day7.kt
shaeberling
50,704,971
false
{"Kotlin": 300158, "Go": 140763, "Java": 107355, "Rust": 2314, "Starlark": 245}
package com.s13g.aoc.aoc2020 import com.s13g.aoc.Result import com.s13g.aoc.Solver typealias Baggage = Map<String, Map<String, Int>> /** * --- Day 7: Handy Haversacks --- * https://adventofcode.com/2020/day/7 */ class Day7 : Solver { override fun solve(lines: List<String>): Result { val allBags = parseBags(lines) val resultA = allBags.keys.map { hasGoldenBag(it, allBags) }.count { it } val resultB = countWithin("shiny gold", allBags) - 1 return Result("$resultA", "$resultB") } private val mainBagSplit = """(.+) bags contain (.+)""".toRegex() private val numBagRegex = """(^\d+) (.+) bag(|s)""".toRegex() private fun parseBags(lines: List<String>): Baggage { val allBags = mutableMapOf<String, MutableMap<String, Int>>() for (line in lines) { val (bagKey, bagValue) = mainBagSplit.find(line)!!.destructured allBags[bagKey] = mutableMapOf() if (bagValue.trim() != "no other bags.") { for (inside in bagValue.split(",")) numBagRegex.find(inside.trim())!!.destructured.let { (num, name) -> allBags[bagKey]!![name] = num.toInt() } } } return allBags } // Part 1 private fun hasGoldenBag(col: String, bags: Baggage): Boolean { for (bag in bags[col] ?: emptyMap()) if (bag.key == "shiny gold" || hasGoldenBag(bag.key, bags)) return true return false; } // Part 2 private fun countWithin(col: String, bags: Baggage): Int = (bags[col] ?: emptyMap()).map { countWithin(it.key, bags) * it.value }.sum() + 1 }
0
Kotlin
1
2
7e5806f288e87d26cd22eca44e5c695faf62a0d7
1,523
euler
Apache License 2.0
app/src/main/kotlin/day11/Day11.kt
W3D3
433,748,408
false
{"Kotlin": 72893}
package day11 import common.InputRepo import common.readSessionCookie import common.solve data class Coord(val x: Int, val y: Int) class Octopus(val pos: Coord, var energy: Int) { private val flashedAtTime: MutableSet<Int> = mutableSetOf() fun increase(time: Int): Boolean { energy++ if ((energy > 9) and !flashedAtTime.contains(time)) { return true } return false } fun flash(time: Int): Set<Coord> { if ((energy > 9) and !flashedAtTime.contains(time)) { flashedAtTime.add(time) return neighbors } return emptySet() } fun resetIfFlashed(time: Int) { if (flashedAtTime.contains(time)) { energy = 0 } } val neighbors: Set<Coord> by lazy { mutableSetOf( Coord(pos.x + 1, pos.y), Coord(pos.x, pos.y + 1), Coord(pos.x - 1, pos.y), Coord(pos.x, pos.y - 1), Coord(pos.x + 1, pos.y + 1), Coord(pos.x - 1, pos.y - 1), Coord(pos.x - 1, pos.y + 1), Coord(pos.x + 1, pos.y - 1), ) .filter { coord -> (coord.x >= 0) and (coord.x < 10) } .filter { coord -> (coord.y >= 0) and (coord.y < 10) } .toSet() } override fun toString(): String { return energy.toString() } } fun main(args: Array<String>) { val day = 11 val input = InputRepo(args.readSessionCookie()).get(day = day) solve(day, input, ::solveDay11Part1, ::solveDay11Part2) } private fun parseInput(input: List<String>): List<List<Octopus>> { return input.mapIndexed { x, line -> line.mapIndexed { y, c -> Octopus(Coord(x, y), c.digitToInt()) } } } private fun printMap(map: List<List<Octopus>>) { map.forEach { line -> line.forEach { print(it) }; println() } println() } fun solveDay11Part1(input: List<String>): Int { val map = parseInput(input) printMap(map) val flashCount = IntArray(100) for (t in 0 until 100) { var toFlash = map.flatten() .map { octopus -> if (octopus.increase(t)) octopus else null } .filterNotNull() .toMutableSet() do { flashCount[t] += toFlash.size println("Flashing ${flashCount[t]} at time $t") val toIncrease = toFlash.flatMap { octopus -> octopus.flash(t) } val toFlashNextIteration = mutableSetOf<Octopus>() for ((x, y) in toIncrease) { val octopus = map[x][y] if (octopus.increase(t)) { toFlashNextIteration.add(octopus) } } toFlash = toFlashNextIteration } while (toFlash.isNotEmpty()) map.flatten() .forEach { octopus -> octopus.resetIfFlashed(t) } printMap(map) } return flashCount.sum() } fun solveDay11Part2(input: List<String>): Int { val map = parseInput(input) printMap(map) val flashCount = IntArray(10000) // TODO fix & refactor for (t in 0 until 10000) { var toFlash = map.flatten() .map { octopus -> if (octopus.increase(t)) octopus else null } .filterNotNull() .toMutableSet() do { flashCount[t] += toFlash.size println("Flashing ${flashCount[t]} at time $t") val toIncrease = toFlash.flatMap { octopus -> octopus.flash(t) } val toFlashNextIteration = mutableSetOf<Octopus>() for ((x, y) in toIncrease) { val octopus = map[x][y] if (octopus.increase(t)) { toFlashNextIteration.add(octopus) } } toFlash = toFlashNextIteration } while (toFlash.isNotEmpty()) map.flatten() .forEach { octopus -> octopus.resetIfFlashed(t) } printMap(map) if (flashCount[t] == 100) { return t + 1 // adjust that our days start with 0 } } return flashCount.indexOfFirst { it == 10 * 10 } }
0
Kotlin
0
0
df4f21cd99838150e703bcd0ffa4f8b5532c7b8c
4,084
AdventOfCode2021
Apache License 2.0
src/Day13.kt
MerickBao
572,842,983
false
{"Kotlin": 28200}
import java.util.LinkedList fun main() { fun compare(a: String, b: String): Int { val mapA = HashMap<Int, Int>() val mapB = HashMap<Int, Int>() val q = LinkedList<Int>() for (i in a.indices) { if (a[i] == '[') q.offerLast(i) else if (a[i] == ']') mapA[q.pollLast()] = i } for (i in b.indices) { if (b[i] == '[') q.offerLast(i) else if (b[i] == ']') mapB[q.pollLast()] = i } var idx1 = 0 var idx2 = 0 while (idx1 < a.length && idx2 < b.length) { if (a[idx1] == '[') { if (b[idx2] == '[') { // println("" + a.length + " " + b.length + " " + idx1 + " " + idx2) val cmp = compare(a.substring(idx1 + 1, mapA[idx1]!!), b.substring(idx2 + 1, mapB[idx2]!!)) if (cmp == 0) { idx1 = mapA[idx1]!! + 2 idx2 = mapB[idx2]!! + 2 } else return cmp } else { val idx = idx2 while (idx2 < b.length && b[idx2].isDigit()) idx2++ val cmp = compare(a.substring(idx1 + 1, mapA[idx1]!!), b.substring(idx, idx2)) if (cmp == 0) { idx1 = mapA[idx1]!! + 2 idx2++ } else return cmp } } else { if (b[idx2] == '[') { val idx = idx1 while (idx1 < a.length && a[idx1].isDigit()) idx1++ val cmp = compare(a.substring(idx, idx1), b.substring(idx2 + 1, mapB[idx2]!!)) if (cmp == 0) { idx1++ idx2 = mapB[idx2]!! + 2 } else return cmp } else { var numa = 0 var numb = 0 while (idx1 < a.length && a[idx1].isDigit()) numa = numa * 10 + (a[idx1++] - '0') while (idx2 < b.length && b[idx2].isDigit()) numb = numb * 10 + (b[idx2++] - '0') if (numa < numb) return 1 else if (numa > numb) return -1 idx1++ idx2++ } } } if (idx1 >= a.length) { if (idx2 >= b.length) return 0 return 1 } return -1 } fun game(input: List<String>) { val all = arrayListOf<String>() for (s in input) { if (s == "") continue all.add(s) } var cnt = 0 var idx = 0 while (idx < all.size) { if (compare(all[idx], all[idx + 1]) == 1) cnt += idx / 2 + 1 idx += 2 } println(cnt) all.add("[[2]]") all.add("[[6]]") all.sortWith { o1: String, o2: String -> compare(o2, o1) } println((all.indexOf("[[2]]") + 1) * (all.indexOf("[[6]]") + 1)) } val input = readInput("Day13") game(input) }
0
Kotlin
0
0
70a4a52aa5164f541a8dd544c2e3231436410f4b
3,077
aoc-2022-in-kotlin
Apache License 2.0
scripts/Day13.kts
matthewm101
573,325,687
false
{"Kotlin": 63435}
import java.io.File import kotlin.math.max sealed class Data { data class Packet(val data: List<Data>) : Data(), Comparable<Packet> { override fun toString() = data.joinToString(separator = ",", prefix = "[", postfix = "]") { it.toString() } override fun compareTo(other: Packet): Int { for (i in 0 until max(data.size, other.data.size)) { if (i >= data.size) return -1 if (i >= other.data.size) return 1 val e1 = data[i] val e2 = other.data[i] when (e1) { is Num -> when (e2) { is Num -> if (e1.num != e2.num) return e1.num - e2.num is Packet -> { val result = Packet(listOf(e1)).compareTo(e2) if (result != 0) return result } } is Packet -> when (e2) { is Num -> { val result = e1.compareTo(Packet(listOf(e2))) if (result != 0) return result } is Packet -> { val result = e1.compareTo(e2) if (result != 0) return result } } } } return 0 } } data class Num(val num: Int) : Data(), Comparable<Num> { override fun toString() = num.toString() override fun compareTo(other: Num) = num - other.num } } sealed class Token { object In: Token() object Out: Token() data class Num(val num: Int): Token() } fun parsePacket(line: String): Data.Packet? { val tokens: List<Token> = line.fold<List<Token?>>(listOf()) { prev, c -> when(c) { '[' -> prev.plus(Token.In) ']' -> prev.plus(Token.Out) ',' -> prev.plus(null) else -> if (prev.last() != null && prev.last() is Token.Num) prev.dropLast(1).plus(Token.Num((prev.last() as Token.Num).num * 10 + c.digitToInt())) else prev.plus(Token.Num(c.digitToInt())) } }.filterNotNull() val packetStack: MutableList<MutableList<Data>> = mutableListOf() var finalPacket: Data.Packet? = null tokens.forEach { when(it) { is Token.In -> packetStack.add(mutableListOf()) is Token.Out -> { val p = packetStack.removeLast() if (packetStack.isEmpty()) finalPacket = Data.Packet(p) else packetStack.last().add(Data.Packet(p)) } is Token.Num -> packetStack.last().add(Data.Num(it.num)) } } return finalPacket } data class PacketPair(val left: Data.Packet, val right: Data.Packet) { fun ordered() = left < right } val packets = File("../inputs/13.txt").readLines().mapNotNull { parsePacket(it) } val packetPairs = packets.chunked(2).map { PacketPair(it[0], it[1]) } val indexSum = packetPairs.mapIndexed{ index, packetPair -> if (packetPair.ordered()) index + 1 else 0 }.sum() println("There sum of the indices of the ordered pairs is $indexSum.") val divider1 = Data.Packet(listOf(Data.Packet(listOf(Data.Num(2))))) val divider2 = Data.Packet(listOf(Data.Packet(listOf(Data.Num(6))))) val sortedPackets = packets.plus(divider1).plus(divider2).sorted() val index1 = sortedPackets.indexOf(divider1) val index2 = sortedPackets.indexOf(divider2) println("The product of the indices of the divider packets is ${(index1 + 1) * (index2 + 1)}.")
0
Kotlin
0
0
bbd3cf6868936a9ee03c6783d8b2d02a08fbce85
3,699
adventofcode2022
MIT License
src/Day22.kt
Tomcat88
572,566,485
false
{"Kotlin": 52372}
import java.awt.geom.Point2D object Day22 { val directions = listOf( 1 to 0, // R 0 to 1, // D -1 to 0, // L 0 to -1, // U ) fun parseBoard(board: String): Map<IntPair, Char> { return board.split("\n").flatMapIndexed { y, row -> row.toCharArray().mapIndexed { x, c -> when (c) { ' ' -> null '.', '#' -> (x to y) to c else -> error("unknown board cell") } } }.filterNotNull().toMap() } fun parsePath(path: String): List<IntPair> { var acc = "" return path.map { c -> if (c.isDigit()) { acc += c null } else { val r = acc.toInt() to when (c) { 'R' -> 1 'L' -> -1 else -> error("unknown turning options") } acc = "" r } }.filterNotNull() + (acc.toInt() to 0) } private fun Map<IntPair, Char>.getNextPos(from: IntPair, dir: IntPair): IntPair? { return this[from + dir].let { v -> when (v) { '#' -> null '.' -> from + dir null -> { if (dir.first == 1) { this.filterKeys { it.second == from.second }.minBy { it.key.first } .takeIf { it.value == '.' }?.key } else if (dir.first == -1) { this.filterKeys { it.second == from.second }.maxBy { it.key.first } .takeIf { it.value == '.' }?.key } else if (dir.second == 1) { this.filterKeys { it.first == from.first }.minBy { it.key.second } .takeIf { it.value == '.' }?.key } else if (dir.second == -1) { this.filterKeys { it.first == from.first }.maxBy { it.key.second } .takeIf { it.value == '.' }?.key } else error("unknown wrapping") } else -> error("unknown val") } } } fun part1(board: Map<IntPair, Char>, path: List<IntPair>) { var didx = 0 var start = board.filter { e -> e.key.second == 0 && e.value == '.' } .minBy { it.key.first }.key var dir = directions[0].log() start.log() path.forEach { (times, rotation) -> var i = 0 while (i < times) { val nextPos = board.getNextPos(start, dir) ?: break start = nextPos i++ } didx += rotation if (didx < 0) didx = directions.size - 1 dir = directions[didx % directions.size] } //144168 low //144169 low //144252 high start.log().let { (1000 * (it.second + 1)) + (4 * (it.first + 1)) }.log() dir.log() } fun part2(input: List<String>) { } @JvmStatic fun main(args: Array<String>) { val input = downloadAndReadInput("Day22", "\n\n").filter { it.isNotBlank() } val (boardStr, pathStr) = input val board = parseBoard(boardStr) val path = parsePath(pathStr.removeSuffix("\n")).log() part1(board, path) } }
0
Kotlin
0
0
6d95882887128c322d46cbf975b283e4a985f74f
3,464
advent-of-code-2022
Apache License 2.0
src/test/kotlin/io/noobymatze/aoc/y2022/Day13.kt
noobymatze
572,677,383
false
{"Kotlin": 90710}
package io.noobymatze.aoc.y2022 import io.noobymatze.aoc.Aoc import io.noobymatze.aoc.y2022.Day13.Order.* import kotlin.test.Test class Day13 { @Test fun test() { val result = Aoc.getInput(13) .split("\n\n") .asSequence() .map { it.lines().map { parse(tokenize(it)) as Expr.Seq } } .withIndex() .filter { it.value[0].compare(it.value[1]) == LT } .sumOf { it.index + 1 } println(result) } @Test fun test2() { val result = (Aoc.getInput(13) + "\n\n[[2]]\n[[6]]") .split("\n\n") .asSequence() .flatMap { it.lines().map { parse(tokenize(it)) as Expr.Seq } } .sortedWith { a, b -> a.compare(b).value } .withIndex() .toList() .filter { it.value.stringify() == "[[6]]" || it.value.stringify() == "[[2]]" } .map { it.index + 1 } .reduce { a, b -> a * b } println(result) } enum class Order(val value: Int) { LT(-1), EQ(0), GT(1) } sealed interface Expr { data class Number(val value: Int): Expr data class Seq(val expressions: List<Expr>): Expr fun stringify(): String = when (this) { is Number -> value.toString() is Seq -> "[${expressions.joinToString(",") { it.stringify() }}]" } fun compare(right: Expr): Order = when { this is Number && right is Number -> when { value < right.value -> LT value > right.value -> GT else -> EQ } this is Seq && right is Seq -> { val rest = expressions.zip(right.expressions) .map { (a, b) -> a.compare(b) } .dropWhile { it == EQ } when { rest.isNotEmpty() -> rest[0] expressions.size < right.expressions.size -> LT expressions.size == right.expressions.size -> EQ else -> GT } } this is Seq && right is Number -> compare(Seq(listOf(right))) this is Number && right is Seq -> Seq(listOf(this)).compare(right) else -> throw IllegalArgumentException() } } private fun tokenize(input: String): MutableList<String> = input.replace("[", " [ ") .replace("]", " ] ") .replace(",", " ") .split(" ") .filter { it.isNotBlank() }.toMutableList() private fun parse(tokens: MutableList<String>): Expr { if (tokens.isEmpty()) throw IllegalArgumentException() return when (val next = tokens.removeFirst()) { "[" -> { val expressions = mutableListOf<Expr>() while (tokens[0] != "]") { expressions.add(parse(tokens)) } tokens.removeFirst() // ']' Expr.Seq(expressions) } else -> Expr.Number(next.toInt()) } } }
0
Kotlin
0
0
da4b9d894acf04eb653dafb81a5ed3802a305901
3,137
aoc
MIT License
src/Day04.kt
Inn0
573,532,249
false
{"Kotlin": 16938}
fun main() { fun createList(input: List<String>): MutableList<Int> { val output = mutableListOf<Int>() var counter = input[0].toInt() while(counter <= input[1].toInt()){ output.add(counter) counter++ } return output } fun readPairs(input: List<String>): MutableList<MutableList<MutableList<Int>>> { val pairs = mutableListOf<MutableList<MutableList<Int>>>() input.forEach { val elves = it.split(",") val range = mutableListOf<MutableList<Int>>() for (elf in elves) { val elfRange = elf.split("-") range.add(createList(elfRange)) } pairs.add(range) } return pairs } fun isSubset(list1: List<Int>, list2: List<Int>): Boolean { return (list1.containsAll(list2) || list2.containsAll(list1)) } fun amountOfOverlap(list1: List<Int>, list2: List<Int>): Boolean { for (list1Item in list1) { if(list2.contains(list1Item)){ return true } } for (list2Item in list2) { if(list1.contains(list2Item)){ return true } } return false } fun part1(input: List<String>): Int { val pairs = readPairs(input) var counter = 0 pairs.forEach { if(isSubset(it[0], it[1])){ counter++ } } return counter } fun part2(input: List<String>): Int { val pairs = readPairs(input) var counter = 0 pairs.forEach { if(amountOfOverlap(it[0], it[1])){ counter++ } } return counter } // test if implementation meets criteria from the description, like: val testInput = readInput("Day04_test") check(part1(testInput) == 2) check(part2(testInput) == 4) val input = readInput("Day04") println("Part 1: " + part1(input)) println("Part 2: " + part2(input)) }
0
Kotlin
0
0
f35b9caba5f0c76e6e32bc30196a2b462a70dbbe
2,073
aoc-2022
Apache License 2.0