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/jsTest/kotlin/io/github/offlinebrain/khexagon/algorythm/PathfindingTest.kt
OfflineBrain
663,452,814
false
null
import io.github.offlinebrain.khexagon.algorythm.AccessibilityTrie import io.github.offlinebrain.khexagon.algorythm.aStar import io.github.offlinebrain.khexagon.coordinates.AxisPoint import io.github.offlinebrain.khexagon.math.circle import io.github.offlinebrain.khexagon.math.distanceTo import io.kotest.core.spec.style.StringSpec import io.kotest.matchers.collections.shouldBeSameSizeAs import io.kotest.matchers.shouldBe data class TestAxisPoint( override val q: Int, override val r: Int, val cost: Int = 1, ) : AxisPoint { override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is TestAxisPoint) return false if (q != other.q) return false if (r != other.r) return false return true } override fun hashCode(): Int { var result = q result = 31 * result + r return result } } class AccessibilityTrieTest : StringSpec({ val origin = TestAxisPoint(0, 0) val heuristic: (TestAxisPoint, TestAxisPoint) -> Int = { a, b -> a distanceTo b } val neighbors: (TestAxisPoint) -> List<TestAxisPoint> = { point -> listOf( TestAxisPoint(point.q + 1, point.r), TestAxisPoint(point.q + 1, point.r - 1), TestAxisPoint(point.q, point.r - 1), TestAxisPoint(point.q - 1, point.r), TestAxisPoint(point.q - 1, point.r + 1), TestAxisPoint(point.q, point.r + 1) ) } "Builds correct AccessMap" { val walkable = mutableSetOf<TestAxisPoint>() circle(radius = 3) { q, r -> walkable.add(TestAxisPoint(q, r)) } val expectedAccessibility = walkable - origin val trie = AccessibilityTrie( origin = origin, maxMoveCost = 3, neighbors = neighbors, isWalkable = { walkable.contains(it) }, heuristic = heuristic, movementCost = { a, b -> if (a == b) 0.0 else b.cost.toDouble() } ) trie.accessible shouldBeSameSizeAs expectedAccessibility trie.accessible shouldBe expectedAccessibility } "Retrieves path correctly" { val trie = AccessibilityTrie( origin = origin, maxMoveCost = 2, neighbors = neighbors, isWalkable = { true }, heuristic = heuristic, movementCost = { a, b -> if (a == b) 0.0 else b.cost.toDouble() } ) val point = TestAxisPoint(1, 1) trie[point] shouldBe listOf(TestAxisPoint(0, 0), TestAxisPoint(0, 1), point) } "Finds shortest path considering move cost" { val highCostPoints = setOf(TestAxisPoint(0, 1, 10), TestAxisPoint(1, 0, 10)) val target = TestAxisPoint(1, 1) val walkable = mutableSetOf<TestAxisPoint>() circle(radius = 3) { q, r -> val element = TestAxisPoint(q, r) if (highCostPoints.contains(element).not()) { print(element) walkable.add(element) } } walkable.addAll(highCostPoints) val trie = AccessibilityTrie( origin = origin, maxMoveCost = 5, neighbors = { point -> neighbors(point).mapNotNull { n -> walkable.find { n == it } } }, isWalkable = { walkable.contains(it) }, heuristic = heuristic, movementCost = { a, b -> if (a == b) 0.0 else b.cost.toDouble() } ) val path = trie[target] val expectedPath = listOf( TestAxisPoint(0, 0), // Original starting point TestAxisPoint(-1, 1), TestAxisPoint(-1, 2), TestAxisPoint(0, 2), target // Final destination ) path shouldBe expectedPath } }) data class PathTestPoint( override val q: Int, override val r: Int, val walkable: Boolean, val cost: Int = 1, ) : AxisPoint { override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is PathTestPoint) return false if (q != other.q) return false if (r != other.r) return false return true } override fun hashCode(): Int { var result = q result = 31 * result + r return result } } class PathfindingTest : StringSpec({ data class TestCase( val from: PathTestPoint, val to: PathTestPoint, val map: Set<PathTestPoint>, val expected: List<PathTestPoint>, ) fun neighbors(point: PathTestPoint): List<PathTestPoint> { return listOf( PathTestPoint(point.q - 1, point.r, true), PathTestPoint(point.q + 1, point.r, true), PathTestPoint(point.q, point.r - 1, true), PathTestPoint(point.q, point.r + 1, true), PathTestPoint(point.q - 1, point.r + 1, true), PathTestPoint(point.q + 1, point.r - 1, true), ) } fun neighborsProvider(map: Set<PathTestPoint>) = { point: PathTestPoint -> neighbors(point).mapNotNull { map.firstOrNull { p -> p == it } } } val testCases = listOf( // Case 1: Direct path between two points TestCase( from = PathTestPoint(0, 0, walkable = true), to = PathTestPoint(0, 2, walkable = true), map = setOf( PathTestPoint(0, 0, walkable = true), PathTestPoint(0, 1, walkable = true), PathTestPoint(0, 2, walkable = true) ), expected = listOf( PathTestPoint(0, 0, walkable = true), PathTestPoint(0, 1, walkable = true), PathTestPoint(0, 2, walkable = true) ) ), // Case 2: Path around an obstacle TestCase( from = PathTestPoint(0, 0, walkable = true), to = PathTestPoint(0, 2, walkable = true), map = setOf( PathTestPoint(0, 0, walkable = true), PathTestPoint(0, 1, walkable = false), // Obstacle PathTestPoint(0, 2, walkable = true), PathTestPoint(1, 0, walkable = true), // Alternate path PathTestPoint(1, 1, walkable = true) // Alternate path ), expected = listOf( PathTestPoint(0, 0, walkable = true), PathTestPoint(1, 0, walkable = true), PathTestPoint(1, 1, walkable = true), PathTestPoint(0, 2, walkable = true) ) ), // Case 3: No path between two points TestCase( from = PathTestPoint(0, 0, walkable = true), to = PathTestPoint(0, 2, walkable = true), map = setOf( PathTestPoint(0, 0, walkable = true), PathTestPoint(0, 1, walkable = false), // Obstacle PathTestPoint(0, 2, walkable = true), PathTestPoint(1, 0, walkable = false), // Obstacle PathTestPoint(1, 1, walkable = false) // Obstacle ), expected = emptyList() // There is no path ), TestCase( from = PathTestPoint(5, 5, walkable = true), to = PathTestPoint(13, 13, walkable = true), map = setOf( // Build a 20x20 grid *(0 until 20).flatMap { i -> (0 until 20).map { j -> if ((i in 7..10) && (j in 7..10)) PathTestPoint(i, j, walkable = false) else PathTestPoint(i, j, walkable = true) } }.toTypedArray(), ), expected = listOf( PathTestPoint(5, 5, walkable = true), PathTestPoint(5, 6, walkable = true), PathTestPoint(5, 7, walkable = true), PathTestPoint(5, 8, walkable = true), PathTestPoint(5, 9, walkable = true), PathTestPoint(5, 10, walkable = true), PathTestPoint(5, 11, walkable = true), PathTestPoint(6, 11, walkable = true), PathTestPoint(7, 11, walkable = true), PathTestPoint(8, 11, walkable = true), PathTestPoint(9, 11, walkable = true), PathTestPoint(10, 11, walkable = true), PathTestPoint(11, 11, walkable = true), PathTestPoint(11, 12, walkable = true), PathTestPoint(12, 12, walkable = true), PathTestPoint(12, 13, walkable = true), PathTestPoint(13, 13, walkable = true) ) ), TestCase( from = PathTestPoint(0, 0, walkable = true), to = PathTestPoint(2, 0, walkable = true), map = setOf( PathTestPoint(0, 0, walkable = true, cost = 1), PathTestPoint(1, 0, walkable = true, cost = 3), // High cost path PathTestPoint(2, 0, walkable = true, cost = 1), PathTestPoint(0, 1, walkable = true, cost = 1), // Low cost alternative path PathTestPoint(1, 1, walkable = true, cost = 1), // Low cost alternative path PathTestPoint(2, 1, walkable = true, cost = 1) // Low cost alternative path ), expected = listOf( PathTestPoint(0, 0, walkable = true, cost = 1), PathTestPoint(0, 1, walkable = true, cost = 1), PathTestPoint(1, 1, walkable = true, cost = 1), PathTestPoint(2, 0, walkable = true, cost = 1) ) ) ) testCases.forEachIndexed { idx, testCase -> "[$idx] should find path from ${testCase.from} to ${testCase.to}".config( invocations = 1, threads = 1, enabled = true ) { val result = aStar( from = testCase.from, to = testCase.to, neighbors = neighborsProvider(testCase.map), isWalkable = { it.walkable }, heuristic = { a, b -> a distanceTo b }, movementCost = { a, b -> if (a == b) 0.0 else b.cost.toDouble() } ) result shouldBe testCase.expected } } })
0
Kotlin
0
1
1bf3b6f073fbad98eeb10ea83730e883cf8ed7d5
10,377
khexagon
MIT License
src/main/kotlin/github/walkmansit/aoc2020/Day07.kt
walkmansit
317,479,715
false
null
package github.walkmansit.aoc2020 class Day07(val input: List<String>) : DayAoc<Int, Int> { private class Graph { private val nodes: MutableMap<String, Node> = mutableMapOf() fun addNodeWithParent(parentName: String, name: String, weight: Int) { fun findWithCreate(value: String): Node { return if (!nodes.containsKey(value)) { val newNode = Node(value) nodes[value] = newNode newNode } else nodes[value]!! } val parent = findWithCreate(parentName) var node = findWithCreate(name) parent.kids.add(node to weight) node.parents[parent.value] = parent } fun countParentsForNode(name: String): Int { fun getUniqueParents(node: Node, result: MutableSet<String>) { for ((k, v) in node.parents) { result.add(k) getUniqueParents(v, result) } } if (nodes.containsKey(name)) { val targetNode = nodes[name]!! val result = mutableSetOf<String>() getUniqueParents(targetNode, result) return result.size } return 0 } fun countKidsForNode(name: String): Int { fun getKidsCountWithWeight(node: Node): Int { if (node.kids.isEmpty()) return 1 return node.kids.asSequence().map { it.second * getKidsCountWithWeight(it.first) }.sum() + 1 } if (nodes.containsKey(name)) { val targetNode = nodes[name]!! return getKidsCountWithWeight(targetNode) } return 0 } private class Node(val value: String) { val parents: MutableMap<String, Node> = mutableMapOf() val kids: MutableList<Pair<Node, Int>> = mutableListOf() } companion object { fun fromInput(lines: List<String>): Graph { // val lines = inp.split(".\n") val gph = Graph() for (i in lines.indices) { val lineParts = lines[i].dropLast(1).split(" bags contain ") val parent = lineParts[0] val components = lineParts[1].split(", ") for (component in components) { val compParts = component.split(" ") if (compParts[0] != "no") gph.addNodeWithParent(parent, "${compParts[1]} ${compParts[2]}", compParts[0].toInt()) } } return gph } } } override fun getResultPartOne(): Int { return Graph.fromInput(input).countParentsForNode("shiny gold") } override fun getResultPartTwo(): Int { return Graph.fromInput(input).countKidsForNode("shiny gold") - 1 } }
0
Kotlin
0
0
9c005ac4513119ebb6527c01b8f56ec8fd01c9ae
3,056
AdventOfCode2020
MIT License
2021/src/main/kotlin/com/trikzon/aoc2021/Day9.kt
Trikzon
317,622,840
false
{"Kotlin": 43720, "Rust": 21648, "C#": 12576, "C++": 4114, "CMake": 397}
package com.trikzon.aoc2021 import java.util.* import kotlin.collections.ArrayList fun main() { val input = getInputStringFromFile("/day9.txt") benchmark(Part.One, ::day9Part1, input, 498, 50) benchmark(Part.Two, ::day9Part2, input, 1071000, 50) } fun day9Part1(input: String): Int { val grid = Array(input.lines().size) { Array(input.lines()[0].length) { 0 } } for (x in input.lines().indices) { for (y in input.lines()[x].indices) { grid[x][y] = input.lines()[x][y].digitToInt() } } var riskLevels = 0 for (x in grid.indices) { for (y in grid[0].indices) { val height = grid[x][y] var lowest = true if (x > 0) { if (grid[x - 1][y] <= height) { lowest = false } } if (y > 0) { if (grid[x][y - 1] <= height) { lowest = false } } if (x < grid.size - 1) { if (grid[x + 1][y] <= height) { lowest = false } } if (y < grid[0].size - 1) { if (grid[x][y + 1] <= height) { lowest = false } } if (lowest) { riskLevels += height + 1 } } } return riskLevels } fun day9Part2(input: String): Int { val grid = Array(input.lines().size) { Array(input.lines()[0].length) { false } } for (x in input.lines().indices) { for (y in input.lines()[x].indices) { grid[x][y] = input.lines()[x][y].digitToInt() == 9 } } val basins = ArrayList<Int>() for (x in grid.indices) { for (y in grid[0].indices) { if (grid[x][y]) continue grid[x][y] = true val coordStack = Stack<Pair<Int, Int>>().apply { push(Pair(x, y)) } var size = 1 while (!coordStack.empty()) { val (peekX, peekY) = coordStack.peek() var neighbors = 0 if (peekX > 0) { if (!grid[peekX - 1][peekY]) { neighbors += 1 grid[peekX - 1][peekY] = true coordStack.push(Pair(peekX - 1, peekY)) } } if (peekY > 0) { if (!grid[peekX][peekY - 1]) { neighbors += 1 grid[peekX][peekY - 1] = true coordStack.push(Pair(peekX, peekY - 1)) } } if (peekX < grid.size - 1) { if (!grid[peekX + 1][peekY]) { neighbors += 1 grid[peekX + 1][peekY] = true coordStack.push(Pair(peekX + 1, peekY)) } } if (peekY < grid[0].size - 1) { if (!grid[peekX][peekY + 1]) { neighbors += 1 grid[peekX][peekY + 1] = true coordStack.push(Pair(peekX, peekY + 1)) } } size += neighbors if (neighbors == 0) { coordStack.pop() } } basins.add(size) } } val largestBasins = Array(3) { 0 } for (i in 0 until 3) { var largest = 0 for (basin in basins) { if (basin > largest) { largest = basin } } largestBasins[i] = largest basins.remove(largest) } return largestBasins[0] * largestBasins[1] * largestBasins[2] }
0
Kotlin
1
0
d4dea9f0c1b56dc698b716bb03fc2ad62619ca08
3,785
advent-of-code
MIT License
src/main/kotlin/_0040_CombinationSumII.kt
ryandyoon
664,493,186
false
null
// https://leetcode.com/problems/combination-sum-ii fun combinationSum2(candidates: IntArray, target: Int): List<List<Int>> { candidates.sort() return mutableSetOf<List<Int>>().also { buildCombinations(candidates, startIndex = 0, target = target, combination = mutableListOf(), combinations = it) }.toList() } private fun buildCombinations( candidates: IntArray, startIndex: Int, target: Int, combination: MutableList<Int>, combinations: MutableSet<List<Int>> ) { if (target == 0) { combinations.add(combination.toList()) return } var index = startIndex while (index <= candidates.lastIndex) { val candidate = candidates[index] if (candidate <= target) { combination.add(candidate) buildCombinations( candidates = candidates, startIndex = index + 1, target = target - candidate, combination = combination, combinations = combinations ) combination.removeLast() } while (index <= candidates.lastIndex && candidates[index] == candidate) { index++ } } }
0
Kotlin
0
0
7f75078ddeb22983b2521d8ac80f5973f58fd123
1,208
leetcode-kotlin
MIT License
kotlin/1799-maximize-score-after-n-operations.kt
neetcode-gh
331,360,188
false
{"JavaScript": 473974, "Kotlin": 418778, "Java": 372274, "C++": 353616, "C": 254169, "Python": 207536, "C#": 188620, "Rust": 155910, "TypeScript": 144641, "Go": 131749, "Swift": 111061, "Ruby": 44099, "Scala": 26287, "Dart": 9750}
class Solution { fun maxScore(nums: IntArray): Int { val cache = IntArray(1 shl nums.size) { -1 } fun dfs(mask: Int, op: Int): Int { if (cache[mask] != -1) return cache[mask] for (i in 0 until nums.size) { for (j in i + 1 until nums.size) { if ((1 shl i) and mask > 0 || (1 shl j) and mask > 0) continue val newMask = mask or (1 shl i) or (1 shl j) val score = op * gcd(nums[i], nums[j]) cache[mask] = maxOf( if (cache[mask] != -1) cache[mask] else 0, score + dfs(newMask, op + 1) ) } } return if (cache[mask] != -1) cache[mask] else 0 } return dfs(0, 1) } fun gcd(_x: Int, _y: Int): Int { var x = _x var y = _y while (x != y) { if (x > y) x -= y else y -= x } return x } }
337
JavaScript
2,004
4,367
0cf38f0d05cd76f9e96f08da22e063353af86224
1,066
leetcode
MIT License
src/main/kotlin/g2701_2800/s2791_count_paths_that_can_form_a_palindrome_in_a_tree/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g2701_2800.s2791_count_paths_that_can_form_a_palindrome_in_a_tree // #Hard #Dynamic_Programming #Depth_First_Search #Tree #Bit_Manipulation #Bitmask // #2023_08_06_Time_683_ms_(100.00%)_Space_54_MB_(100.00%) class Solution { private fun getMap(parent: List<Int>, s: String, dp: IntArray, idx: Int): Int { if (dp[idx] < 0) { dp[idx] = 0 dp[idx] = getMap(parent, s, dp, parent[idx]) xor (1 shl s[idx].code - 'a'.code) } return dp[idx] } fun countPalindromePaths(parent: List<Int>, s: String): Long { val n: Int = parent.size val dp = IntArray(n) var ans: Long = 0 val mapCount: MutableMap<Int, Int> = HashMap() dp.fill(-1) dp[0] = 0 for (i in 0 until n) { val currMap = getMap(parent, s, dp, i) // if map are same, two points can form a path; val evenCount = mapCount[currMap] ?: 0 mapCount.put(currMap, evenCount + 1) } for (key in mapCount.keys) { val value = mapCount[key]!! ans += value.toLong() * (value - 1) shr 1 for (i in 0..25) { val base = 1 shl i // if this map at i is 1, which means odd this bit if (key and base > 0 && mapCount.containsKey(key xor base)) { // key ^ base is the map that is 0 at bit i, odd pairs with even, // can pair and no duplicate ans += value.toLong() * mapCount[key xor base]!! } } } return ans } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,617
LeetCode-in-Kotlin
MIT License
kotlin/0399-evaluate-division.kt
neetcode-gh
331,360,188
false
{"JavaScript": 473974, "Kotlin": 418778, "Java": 372274, "C++": 353616, "C": 254169, "Python": 207536, "C#": 188620, "Rust": 155910, "TypeScript": 144641, "Go": 131749, "Swift": 111061, "Ruby": 44099, "Scala": 26287, "Dart": 9750}
class Solution { fun calcEquation(equations: List<List<String>>, values: DoubleArray, queries: List<List<String>>): DoubleArray { val adj = HashMap<String, ArrayList<Pair<String, Double>>>().apply { for (i in equations.indices) { val (a, b) = equations[i] val value = values[i] this[a] = getOrDefault(a, arrayListOf()).apply { add(b to value) } this[b] = getOrDefault(b, arrayListOf()).apply { add(a to (1.0 / value)) } } } fun bfs( start: String, end: String ): Double { if (start !in adj || end !in adj) return -1.0 val visit = HashSet<String>() with (LinkedList<Pair<String, Double>>()) { addLast(start to 1.0) visit.add(start) while (isNotEmpty()) { val (cur, totVal) = removeFirst() if (cur == end) return totVal adj[cur]?.forEach { val (next, nextVal) = it if (next !in visit) { addLast(next to (totVal * nextVal)) visit.add(next) } } } } return -1.0 } val res = DoubleArray(queries.size) for (i in queries.indices) { val (a, b) = queries[i] res[i] = bfs(a, b) } return res } }
337
JavaScript
2,004
4,367
0cf38f0d05cd76f9e96f08da22e063353af86224
1,582
leetcode
MIT License
src/pl/shockah/aoc/y2021/Day3.kt
Shockah
159,919,224
false
null
package pl.shockah.aoc.y2021 import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.Test import pl.shockah.aoc.AdventTask import pl.shockah.unikorn.collection.Array2D import pl.shockah.unikorn.collection.takeRows class Day3: AdventTask<Array2D<Boolean>, Int, Long>(2021, 3) { override fun parseInput(rawInput: String): Array2D<Boolean> { val lines = rawInput.lines() return Array2D(lines[0].length, lines.size) { x, y -> lines[y][x] == '1' } } override fun part1(input: Array2D<Boolean>): Int { val mostCommonBits = (0 until input.width) .map { x -> (0 until input.height) .asSequence() .map { y -> input[x, y] } .groupBy { it } .map { it.value } .sortedByDescending { it.size } .map { it.first() } .first() } val gammaRate = mostCommonBits.joinToString("") { if (it) "1" else "0" }.toInt(2) val epsilonRate = (1 shl input.width) - gammaRate - 1 return gammaRate * epsilonRate } override fun part2(input: Array2D<Boolean>): Long { fun getCommonBit(index: Int, values: Array2D<Boolean>, ascending: Boolean, onEqual: Boolean): Boolean { val unsorted = values .getColumn(index) .groupBy { it } .map { it.value } if (unsorted.size == 2 && unsorted[0].size == unsorted[1].size) return onEqual val sorted = if (ascending) unsorted.sortedBy { it.size } else unsorted.sortedByDescending { it.size } return sorted .map { it.first() } .first() } var current1 = input var current2 = input for (index in 0 until input.width) { val mostCommonBit = getCommonBit(index, current1, false, onEqual = true) val leastCommonBit = getCommonBit(index, current2, true, onEqual = false) current1 = if (current1.height > 1) current1.takeRows { it[index] == mostCommonBit } else current1 current2 = if (current2.height > 1) current2.takeRows { it[index] == leastCommonBit } else current2 } val oxygenRating = current1.getRow(0).joinToString("") { if (it) "1" else "0" }.toInt(2) val scrubberRating = current2.getRow(0).joinToString("") { if (it) "1" else "0" }.toInt(2) return oxygenRating.toLong() * scrubberRating.toLong() } class Tests { private val task = Day3() private val rawInput = """ 00100 11110 10110 10111 10101 01111 00111 11100 10000 11001 00010 01010 """.trimIndent() @Test fun part1() { val input = task.parseInput(rawInput) Assertions.assertEquals(198, task.part1(input)) } @Test fun part2() { val input = task.parseInput(rawInput) Assertions.assertEquals(230, task.part2(input)) } } }
0
Kotlin
0
0
9abb1e3db1cad329cfe1e3d6deae2d6b7456c785
2,596
Advent-of-Code
Apache License 2.0
src/day01/Day01.kt
wasabi-muffin
726,936,666
false
{"Kotlin": 10804}
package day01 import base.Day fun main() = Day01.run() object Day01 : Day<Int>("01") { override val test1Expected: Int = 142 override val test2Expected: Int = 281 override fun part1(input: List<String>): Int = input.sumOf { line -> line.first { it.isDigit() }.digitToInt() * 10 + line.last { it.isDigit() }.digitToInt() } override fun part2(input: List<String>): Int { return input.sumOf { line -> val firstWord = line.findAnyOf(strings = words, ignoreCase = true)?.toIndexedValue() val lastWord = line.findLastAnyOf(strings = words, ignoreCase = true)?.toIndexedValue() val firstDigit = line.withIndex().firstOrNull { it.value.isDigit() } val lastDigit = line.withIndex().lastOrNull { it.value.isDigit() } getNumber(firstWord, firstDigit) { word, digit -> digit < word } * 10 + getNumber(lastWord, lastDigit) { word, digit -> word < digit } } } private val words: List<String> = listOf( "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", ) private fun getNumber(word: IndexedValue<String>?, digit: IndexedValue<Char>?, useDigitWhen: (word: Int, digit: Int) -> Boolean) = when { word == null && digit == null -> 0 digit == null -> words.indexOf(word?.value) + 1 word == null || useDigitWhen(word.index, digit.index) -> digit.value.digitToInt() else -> words.indexOf(word.value) + 1 } private fun <T> Pair<Int, T>?.toIndexedValue(): IndexedValue<T>? { if (this == null) return null return IndexedValue(first, second) } }
0
Kotlin
0
0
544cdd359e4456a74b1584cbf1e5dddca97f1394
1,728
advent-of-code-2023
Apache License 2.0
src/Day01.kt
sjgoebel
573,578,579
false
{"Kotlin": 21782}
fun main() { fun part1(input: List<String>): Int { val nums = mutableListOf<Int>() var sum = 0 for (s in input) { if (s != "") { sum += Integer.parseInt(s) } else { nums.add(sum) sum = 0 } } nums.add(sum) //print(nums) return nums.max() } fun part2(input: List<String>): Int { val nums = mutableListOf<Int>() var sum = 0 for (s in input) { if (s != "") { sum += Integer.parseInt(s) } else { nums.add(sum) sum = 0 } } nums.add(sum) var result = 0 for (item in 1..3) { result += nums.max() nums.remove(nums.max()) } return result } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") check(part1(testInput) == 24000) val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
ae1588dbbb923dbcd4d19fd1495ec4ebe8f2593e
1,113
advent-of-code-2022-kotlin
Apache License 2.0
src/Day11.kt
chasegn
573,224,944
false
{"Kotlin": 29978}
import java.lang.IllegalArgumentException /** * Day 11 for Advent of Code 2022 * https://adventofcode.com/2022/day/11 */ class Day11 : Day { override val inputFileName: String = "Day11" override val test1Expected: Long? = null // override val test1Expected: Long = 10605 override val test2Expected: Long = 2713310158 /** * Accepted solution: 95472 */ override fun part1(input: List<String>): Long { val monkeys = buildMonkeys(input) return engageMonkeyBusiness(monkeys, 20, true, 3) } /** * Accepted solution: 17926061332 */ override fun part2(input: List<String>): Long { val monkeys = buildMonkeys(input) val lcm = monkeys .map { it.testDivisor } .reduce { acc, l -> acc * l } return engageMonkeyBusiness(monkeys, 10000, false, lcm) } private fun engageMonkeyBusiness(monkeys: List<Monkey>, rounds: Int, canRelax: Boolean, factor: Long): Long { for (round in 1..rounds) { for (monkey in monkeys) { monkey.items.forEach { item -> val worry = when (canRelax) { true -> monkey.inspectAndRelax(item, factor) false -> monkey.inspectNoRelax(item, factor) } if (monkey.testWorry(worry)) { monkeys[monkey.targets.first].items.add(worry) } else { monkeys[monkey.targets.second].items.add(worry) } } monkey.items.removeAll { true } } // for printing output when (canRelax) { true -> { printMonkeyInventory(round, monkeys) } false -> { val interestingRounds = intArrayOf(1, 20, 1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000) if (interestingRounds.contains(round)) { printMonkeyInspections(round, monkeys) } } } } val topTwo = monkeys.map { it.inspections }.sortedDescending().take(2) println(topTwo[0] * topTwo[1]) return topTwo[0] * topTwo[1] } private fun printMonkeyInventory(round: Int, monkeys: List<Monkey>) { println("After round $round, the monkeys are holding items with these worry levels:") for (monkey in monkeys) { println("Monkey ${monkey.id}: ${monkey.items}") } println() } private fun printMonkeyInspections(round: Int, monkeys: List<Monkey>) { println("=== After round $round ===") monkeys.forEach{ println("Monkey ${it.id} inspected ${it.inspections} times") } println() } private fun buildMonkeys(input: List<String>): MutableList<Monkey> { val monkeys = mutableListOf<Monkey>() input.chunked(7).forEach { inputChunk -> val monkeyId = inputChunk[0].split(' ')[1].split(':')[0].toInt() val startingItems = inputChunk[1].split(':')[1].trim().split(", ").map { it.toLong() }.toMutableList() val operation = inputChunk[2].trim() val test = inputChunk[3].trim().split(' ')[3].toLong() val targetA = inputChunk[4].trim().split(' ')[5].toInt() val targetB = inputChunk[5].trim().split(' ')[5].toInt() monkeys.add(Monkey(monkeyId, startingItems, operation, test, Pair(targetA, targetB))) } return monkeys } class Monkey(val id: Int, val items: MutableList<Long>, operation: String, val testDivisor: Long, val targets: Pair<Int, Int>) { val operation: ItemInspection var inspections = 0L init { this.operation = buildInspection(operation) } private fun buildInspection(input: String): ItemInspection { val tokens = input.removePrefix("Operation: new = old ").split(" ") val operator: (ItemWorryLevel, ItemWorryLevel) -> ItemWorryLevel = when (tokens[0]) { "*" -> Long::times "+" -> Long::plus else -> throw IllegalArgumentException("unknown operation: ${tokens[0]}") } val arg = tokens[1].toLongOrNull() return { old -> if (arg == null) operator(old, old) else operator(old, arg) } } fun inspectAndRelax(input: Long, factor: Long): Long { inspections++ return operation(input) / factor } fun inspectNoRelax(input: Long, factor: Long): Long { inspections++ return operation(input) % factor } fun testWorry(input: Long): Boolean { return input.mod(testDivisor) == 0L } } } private typealias ItemWorryLevel = Long private typealias ItemInspection = (ItemWorryLevel) -> ItemWorryLevel
0
Kotlin
0
0
2b9a91f083a83aa474fad64f73758b363e8a7ad6
4,997
advent-of-code-2022
Apache License 2.0
src/adventofcode/Day13.kt
Timo-Noordzee
573,147,284
false
{"Kotlin": 80936}
package adventofcode import org.openjdk.jmh.annotations.* import java.util.concurrent.TimeUnit private sealed interface Packet : Comparable<Packet> { class IntPacket(val value: Int) : Packet { override fun compareTo(other: Packet) = when (other) { is IntPacket -> value.compareTo(other.value) is ListPacket -> ListPacket(this).compareTo(other) } } class ListPacket(val packets: List<Packet>) : Packet { constructor(value: Packet) : this(listOf(value)) val size get() = packets.size private operator fun get(i: Int) = packets[i] override fun compareTo(other: Packet): Int { val left = this val right = if (other is ListPacket) other else ListPacket(other) return when (other) { is IntPacket -> compareTo(ListPacket(listOf(other))) is ListPacket -> { for (i in 0 until left.size.coerceAtMost(right.size)) { val result = left[i].compareTo(right[i]) if (result != 0) return result } return left.size.compareTo(right.size) } } } } companion object { fun fromInput(input: String): Packet { val numberBuilder = StringBuilder(2) val stack = ArrayDeque<Packet?>() input.forEach { char -> when (char) { '[' -> stack.add(null) ',' -> { if (numberBuilder.isNotEmpty()) { stack.add(IntPacket(numberBuilder.toString().toInt())) numberBuilder.clear() } } ']' -> { if (numberBuilder.isNotEmpty()) { stack.add(IntPacket(numberBuilder.toString().toInt())) numberBuilder.clear() } val subPackets = buildList { var current = stack.removeLast() while (current != null) { add(0, current) current = stack.removeLast() } } stack.add(ListPacket(subPackets)) } else -> numberBuilder.append(char) } } return checkNotNull(stack.single()) } } } @State(Scope.Benchmark) @Fork(1) @Warmup(iterations = 0) @Measurement(iterations = 10, time = 2, timeUnit = TimeUnit.SECONDS) class Day13 { var input: List<String> = emptyList() @Setup fun setup() { input = readInput("Day13") } private fun parseInput() = input.filter { it.isNotEmpty() }.map { Packet.fromInput(it) } @Benchmark fun part1(): Int = parseInput().chunked(2).withIndex().sumOf { (index, pair) -> val (left, right) = pair val result = left.compareTo(right) if (result == -1) index + 1 else 0 } @Benchmark fun part2(): Int { val divider1 = Packet.ListPacket(Packet.ListPacket(Packet.IntPacket(2))) val divider2 = Packet.ListPacket(Packet.ListPacket(Packet.IntPacket(6))) val packets = (parseInput() + listOf(divider1, divider2)).sorted() return (packets.binarySearch(divider1) + 1) * (packets.binarySearch(divider2) + 1) } } fun main() { val day13 = Day13() // test if implementation meets criteria from the description, like: day13.input = readInput("Day13_test") check(day13.part1() == 13) check(day13.part2() == 140) day13.input = readInput("Day13") println(day13.part1()) println(day13.part2()) }
0
Kotlin
0
2
10c3ab966f9520a2c453a2160b143e50c4c4581f
3,856
advent-of-code-2022-kotlin
Apache License 2.0
src/main/kotlin/days/Day3.kt
hughjdavey
159,955,618
false
null
package days class Day3 : Day(3) { private val claims = inputList.map { Claim(it) } private val maxX = claims.map { it.maxX() }.sorted().last() private val maxY = claims.map { it.maxY() }.sorted().last() private val grid = Array(maxX + 1) { Array<MutableSet<Int>>(maxY + 1) { mutableSetOf() } } init { // fill our 2d array of sets so it represents the piece of fabric with all claims marked. do in init as both parts use it claims.forEach { claim -> claim.getAllCoords().forEach { grid[it.first][it.second].add(claim.number) } } } override fun partOne(): Int { return grid.flatMap { it.asList() }.filter { squareInch -> squareInch.size > 1 }.count() } override fun partTwo(): Int { val overlappingClaims = grid.flatMap { it.asList() }.filter { squareInch -> squareInch.size > 1 }.flatten() return claims.map { it.number }.first { claimId -> !overlappingClaims.contains(claimId) } } class Claim(private val claimString: String) { val number = claimString.substring(idx('#') + 1, idx('@') - 1).toInt() val fromLeft = claimString.substring(idx('@') + 2, idx(',')).toInt() val fromTop = claimString.substring(idx(',') + 1, idx(':')).toInt() val width = claimString.substring(idx(':') + 2, idx('x')).toInt() val height = claimString.substring(idx('x') + 1).toInt() private fun idx(char: Char) = claimString.indexOf(char) /** * Get the highest x coordinate this claim reaches */ fun maxX() = this.fromLeft + this.width /** * Get the highest y coordinate this claim reaches */ fun maxY() = this.fromTop + this.height /** * Get all coordinates that this claim encompasses */ fun getAllCoords(): List<Pair<Int, Int>> { return (fromLeft + 1..fromLeft + width).flatMap { x -> // fromLeft + 1 to fromLeft + width == x coords from top left to top right (fromTop + 1..fromTop + height).map { y -> // fromTop + 1 to fromTop + height == y coords from top left to bottom right Pair(x, y) } } } } }
0
Kotlin
0
0
4f163752c67333aa6c42cdc27abe07be094961a7
2,232
aoc-2018
Creative Commons Zero v1.0 Universal
src/main/kotlin/_2021/Day8.kt
thebrightspark
227,161,060
false
{"Kotlin": 548420}
package _2021 import REGEX_LINE_SEPARATOR import REGEX_WHITESPACE import aoc fun main() { aoc(2021, 8) { aocRun { input -> input.split(REGEX_LINE_SEPARATOR).sumOf { line -> line.substringAfter(" | ").split(REGEX_WHITESPACE).count { digit -> digit.length.let { it == 2 || it == 3 || it == 4 || it == 7 } } } } aocRun { input -> input.split(REGEX_LINE_SEPARATOR) .mapTo(mutableListOf()) { line -> lateinit var signals: List<String> lateinit var code: List<String> line.split(" | ").let { lineParts -> signals = lineParts[0].split(REGEX_WHITESPACE).map { it.sortChars() } code = lineParts[1].split(REGEX_WHITESPACE).map { it.sortChars() } } val output = run { val digits = mutableMapOf<String, Int>() lateinit var one: String lateinit var four: String lateinit var seven: String val fiveSegmentDigits = mutableListOf<String>() val sixSegmentDigits = mutableListOf<String>() // Find the digits with unique amounts of segments, and collect digits with 5 and 6 segments signals.forEach { when (it.length) { 2 -> { one = it digits[it] = 1 } 3 -> { seven = it digits[it] = 7 } 4 -> { four = it digits[it] = 4 } // 2, 3, 5 5 -> fiveSegmentDigits += it // 0, 6, 9 6 -> sixSegmentDigits += it 7 -> digits[it] = 8 } } if (code.none { it.length == 5 || it.length == 6 }) { // If there's no 5 or 6 segment digits in the code, then there's no need to figure them out return@run code.map { digits[it] }.joinToString("") } // Determine the 5 segment digits // 3 is the only digit that has all the segments in 7 // 2 is the only digit that doesn't have two of the segments in 4 // 5 is just the remaining digit val sevenSegments = seven.toCharArray() val three = fiveSegmentDigits.single { it.containsAllSegments(sevenSegments) } digits[three] = 3 val fourSegments = four.toCharArray() val two = fiveSegmentDigits.single { it.countMissingSegments(fourSegments) == 2 } digits[two] = 2 val five = fiveSegmentDigits.single { it != three && it != two } digits[five] = 5 // Determine the 6 segment digits // 6 is the only digit that doesn't have one of the segments in 1 // 0 is the only digit that doesn't have one of the segments in 5 // 9 is just the remaining digit val oneSegments = one.toCharArray() val six = sixSegmentDigits.single { it.countMissingSegments(oneSegments) == 1 } digits[six] = 6 val fiveSegments = five.toCharArray() val zero = sixSegmentDigits.single { it.countMissingSegments(fiveSegments) == 1 } digits[zero] = 0 val nine = sixSegmentDigits.single { it != six && it != zero } digits[nine] = 9 return@run code.map { digits[it] }.joinToString("") } // println("${code.joinToString(" ")} = $output") return@mapTo output } .sumOf { it.toInt() } } } } private fun String.sortChars(): String = this.toCharArray().sorted().joinToString("") private fun String.containsAllSegments(otherDigitChars: CharArray): Boolean = this.toCharArray().let { chars -> otherDigitChars.all { chars.contains(it) } } private fun String.countMissingSegments(otherDigitChars: CharArray): Int = otherDigitChars.toMutableSet().also { it.removeAll(this.toCharArray().toSet()) }.size
0
Kotlin
0
0
ac62ce8aeaed065f8fbd11e30368bfe5d31b7033
3,549
AdventOfCode
Creative Commons Zero v1.0 Universal
AoC2021day08-SevenSegment/src/main/kotlin/Main.kt
mcrispim
533,770,397
false
{"Kotlin": 29888}
import java.io.File fun main() { val inputFile = File("data.txt") val inputLines = inputFile.readLines() var result = 0 for (line in inputLines) { val data = line.split(" | ") val leftData = data.first().split(" ") val rightdata = data.last().split(" ") val rosetta = crackCode(leftData) val number = translate(rightdata, rosetta) result += number } println(result) } private fun crackCode(data: List<String>): MutableMap<Char, Char> { val timesUsed = mutableMapOf('a' to 0, 'b' to 0, 'c' to 0, 'd' to 0, 'e' to 0, 'f' to 0, 'g' to 0) data.forEach { seq -> seq.forEach { c -> timesUsed[c] = timesUsed[c]?.plus(1) ?: 0 } } val rosetta = mutableMapOf<Char, Char>() // segments that are used in a unique number of digits rosetta[ timesUsed.entries.filter { it.value == 6 }.first().key ] = '2' rosetta[ timesUsed.entries.filter { it.value == 4 }.first().key ] = '5' rosetta[ timesUsed.entries.filter { it.value == 9 }.first().key ] = '6' // The digit '1' uses segments 3 and 6, so... rosetta[ data.filter { it.length == 2 }.first().filter { it !in rosetta.keys }.first() ] = '3' // The digit '7' uses segments 3, 6 and 1, so... rosetta[ data.filter { it.length == 3 }.first().filter { it !in rosetta.keys }.first() ] = '1' // The digit '4' uses segments 2, 3, 6 and 4, so... rosetta[ data.filter { it.length == 4 }.first().filter { it !in rosetta.keys }.first() ] = '4' // Only rest the segment '7' rosetta[ "abcdefg".filter { it !in rosetta.keys }.first() ] = '7' return rosetta } private fun translate(data: List<String>, rosetta: Map<Char, Char>): Int { val segmentsOf = mapOf( setOf('1','2','3','5','6','7') to '0', setOf('3','6') to '1', setOf('1','3','4','5','7') to '2', setOf('1','3','4','6','7') to '3', setOf('2','3','4','6') to '4', setOf('1','2','4','6','7') to '5', setOf('1','2','4','5','6','7') to '6', setOf('1','3','6') to '7', setOf('1','2','3','4','5','6','7') to '8', setOf('1','2','3','4','6','7') to '9' ) var result = "" for (pattern in data) { val thisDigit = mutableSetOf<Char>() for (c in pattern) { thisDigit.add(rosetta[c]!!) } result += segmentsOf[thisDigit] } return result.toInt() }
0
Kotlin
0
0
ac4aa71c9b5955fa4077ae40fc7e3fc3d5242523
2,440
AoC2021
MIT License
src/main/kotlin/Day1.kt
cbrentharris
712,962,396
false
{"Kotlin": 171464}
import kotlin.String import kotlin.collections.List object Day1 { fun part1(input: List<String>): String = input.sumOf(::findFirstAndLastDigit).toString() private fun findFirstAndLastDigit(i: String): Int { val digits = i.filter { it.isDigit() } return (digits.take(1) + digits.takeLast(1)).toInt() } fun part2(input: List<String>): String = input.sumOf(::findFirstAndLastDigitV2).toString() private fun findFirstAndLastDigitV2(i: String): Int { val words = listOf("zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine") val newI = words.zip(words.indices) .map { (word, index) -> word to word.first() + index.toString() + word.last() } .fold(i) { acc, (word, replacement) -> acc.replace(word, replacement) } return findFirstAndLastDigit(newI) } }
0
Kotlin
0
1
f689f8bbbf1a63fecf66e5e03b382becac5d0025
864
kotlin-kringle
Apache License 2.0
src/main/kotlin/days/Day25.kt
andilau
573,139,461
false
{"Kotlin": 65955}
package days import kotlin.math.pow @AdventOfCodePuzzle( name = "Full of Hot Air", url = "https://adventofcode.com/2022/day/25", date = Date(day = 25, year = 2022) ) class Day25(val input: List<String>) : Puzzle { override fun partOne() = input.sumOf(::snafuToDecimal).toSnafu() override fun partTwo() = Unit companion object { fun snafuToDecimal(snafu: String): Long { var answer = 0L snafu.reversed().mapIndexed { ix, char -> val decoded = DECODING[char] ?: error("Unknown char: $char") answer += 5.0.pow(ix).toLong() * decoded } return answer } private fun Long.toSnafu() = toSnafuNumber(this).toList().joinToString("") fun toSnafuNumber(number: Long) = number.decimalToSnafuReversed().toList().reversed().joinToString("") private fun Long.decimalToSnafuReversed() = sequence { var number = this@decimalToSnafuReversed var carry = 0 while (number > 0) { val element = number.mod(5) number /= 5 val char = when (element + carry) { 3 -> '='.also { carry = 1 } 4 -> '-'.also { carry = 1 } 5 -> '0'.also { carry = 1 } 6 -> '1'.also { carry = 1 } 0, 1, 2 -> (element + carry).digitToChar().also { carry = 0 } else -> error("Invalid digit: ${element + carry}") } yield(char) } if (carry > 0) yield(carry.digitToChar()) } private val ENCODING: Map<Int, Char> = mapOf( -2 to '=', -1 to '-', 0 to '0', 1 to '1', 2 to '2', ) private val DECODING: Map<Char, Int> = buildMap { ENCODING.forEach { (k, v) -> put(v, k) } } } }
0
Kotlin
0
0
da824f8c562d72387940844aff306b22f605db40
1,945
advent-of-code-2022
Creative Commons Zero v1.0 Universal
src/main/kotlin/model/method/HalfDivisionMethod.kt
Roggired
348,065,860
false
null
package model.method import model.equation.Equation import kotlin.math.abs import kotlin.math.sign class HalfDivisionMethod( equation: Equation, leftBound: Double, rightBound: Double, accuracy: Double ): Method(equation, leftBound, rightBound, accuracy) { private val solutions: ArrayList<Double> = ArrayList() private var step = 1 override fun getTable(): ArrayList<Array<String>> { val table: ArrayList<Array<String>> = ArrayList() val titles = arrayOf("Step №", "a", "b", "x", "f(a)", "f(b)", "f(x)", "|b-a|") table.add(titles) calcInRange(leftBound, rightBound, table) return table } private fun calcInRange(a: Double, b: Double, table: ArrayList<Array<String>>): Int { var a = a var b = b var x = (a + b) / 2 var fx = equation.evaluate(x) var fa = equation.evaluate(a) var fb = equation.evaluate(b) var dif = abs(b - a) var signOnAB = fa.sign * fb.sign addToTable(step, a, fa, b, fb, x, fx, dif, table) addSolutions(a, fa, b, fb, x, fx, dif) while (dif > accuracy && abs(fx) > accuracy && signOnAB <= 0) { step++ val leftSign = fa.sign * fx.sign val rightSign = fx.sign * fb.sign if (leftSign <= 0 && rightSign <= 0) { step = calcInRange(a, x, table) step = calcInRange(x, b, table) return step } if (leftSign <= 0) { signOnAB = leftSign b = x fb = fx } if (rightSign <= 0) { signOnAB = rightSign a = x fa = fx } x = (a + b) / 2 fx = equation.evaluate(x) dif = abs(b - a) addToTable(step, a, fa, b, fb, x, fx, dif, table) addSolutions(a, fa, b, fb, x, fx, dif) } return step + 1 } private fun addToTable(step: Int, a: Double, fa: Double, b: Double, fb: Double, x: Double, fx: Double, dif: Double, table: ArrayList<Array<String>>) { table.add(arrayOf(step.toString(), a.toString(), b.toString(), x.toString(), fa.toString(), fb.toString(), fx.toString(), dif.toString())) } private fun addSolutions(a: Double, fa: Double, b: Double, fb: Double, x: Double, fx: Double, dif: Double) { if (abs(fa) <= accuracy && !solutions.contains(a)) solutions.add(a) if (abs(fb) <= accuracy && !solutions.contains(b)) solutions.add(b) if ((abs(fx) <= accuracy || dif <= accuracy) && !solutions.contains(x)) solutions.add(x) } override fun getSolutions(): ArrayList<Double> { return solutions } override fun getStepQuantity(): Int = step }
0
Kotlin
0
2
983935fc1ca2a6da564ff8300c2a53cc85dd8701
2,807
maths_lab2
MIT License
src/main/kotlin/days/Day4.kt
andilau
433,504,283
false
{"Kotlin": 137815}
package days @AdventOfCodePuzzle( name = "<NAME>", url = "https://adventofcode.com/2021/day/4", date = Date(day = 4, year = 2021) ) class Day4(input: List<String>) : Puzzle { private val draws = readDraws(input) private val boards = readBoards(input) override fun partOne() = draws.firstNotNullOf { draw -> boards .firstOrNull { board -> board.markForBingo(draw) } ?.let { draw * it.unmarked().sum() } } override fun partTwo() = boards .associateWith { board -> draws.first { board.markForBingo(it) } } .maxByOrNull { draws.indexOf(it.value) } ?.let { it.key.unmarked().sum() * it.value } ?: error("") private fun readDraws(input: List<String>) = input.first().split(',').map(String::toInt) private fun readBoards(input: List<String>) = input .asSequence() .drop(1) .filter { it.isNotEmpty() } .chunked(5) { it.joinToString(" ") } .map { BingoBoard.from(it) } .toSet() data class BingoBoard(val numbers: List<Int>) { private val marked = mutableSetOf<Int>() init { require(numbers.size == 25) } fun markForBingo(number: Int): Boolean { marked += number return isBingo(number) } fun unmarked() = (numbers subtract marked) private fun isBingo(number: Int) = winnerRanges .filter { range -> range.contains(numbers.indexOf(number)) } .map { range -> range.map { numbers[it] }.toSet() } .any { marked.containsAll(it) } companion object { fun from(input: String) = BingoBoard( input .trim() .split(whitespaces) .map(String::toInt) ) private val whitespaces = Regex("\\s+") private val winnerRanges = listOf( 0..4, 5..9, 10..14, 15..19, 20..24, 0..24 step 5, 1..24 step 5, 2..24 step 5, 3..24 step 5, 4..24 step 5, ) } } }
0
Kotlin
0
0
b3f06a73e7d9d207ee3051879b83e92b049a0304
2,213
advent-of-code-2021
Creative Commons Zero v1.0 Universal
src/AoC6.kt
Pi143
317,631,443
false
null
import java.io.File fun main() { //testsDay6() println("Starting Day 6 A Test 1") calculateDay6PartA("Input/2020_Day6_A_Test1") println("Starting Day 6 A Real") calculateDay6PartA("Input/2020_Day6_A") println("Starting Day 6 B Test 1") calculateDay6PartB("Input/2020_Day6_A_Test1") println("Starting Day 6 B Real") calculateDay6PartB("Input/2020_Day6_A") } fun testsDay6(){ } fun calculateDay6PartA(file: String): Int { val day6Data = readDay6Data(file, false) var answerCount = 0 for (answer in day6Data) { answerCount += answer.size println(answer) } println("$answerCount is amount of 'yes' answers-") return answerCount } fun calculateDay6PartB(file: String): Int { val day6Data = readDay6Data(file, true) var answerCount = 0 for (answer in day6Data) { answerCount += answer.size println(answer) } println("$answerCount is amount of 'yes' answers-") return answerCount } fun readDay6Data(input: String, union: Boolean): MutableList<Set<Char>> { val answerList: MutableList<Set<Char>> = ArrayList() val lines = File(localdir + input).readLines() var checkedAnswers: Set<Char> = mutableSetOf() if(union) { checkedAnswers = checkedAnswers + "abcdefghijklmnopqrstuvwxyz".toCharArray().toSet() } for (line in lines) { if (line.isBlank()) { answerList.add(checkedAnswers) checkedAnswers = mutableSetOf() if(union) { checkedAnswers = checkedAnswers + "abcdefghijklmnopqrstuvwxyz".toCharArray().toSet() } } else { val information = line.toCharArray() if(union){ checkedAnswers = checkedAnswers.intersect(information.toSet()) }else { checkedAnswers = checkedAnswers + information.toSet() } } } answerList.add(checkedAnswers) return answerList }
0
Kotlin
0
1
fa21b7f0bd284319e60f964a48a60e1611ccd2c3
1,982
AdventOfCode2020
MIT License
leetcode2/src/leetcode/house-robber.kt
hewking
68,515,222
false
null
package leetcode /** * 198. 打家劫舍 * https://leetcode-cn.com/problems/house-robber/ * Created by test * Date 2019/9/14 16:09 * Description * 系统,如果两间相邻的房屋在同一晚上被小偷闯入,系统会自动报警。 给定一个代表每个房屋存放金额的非负整数数组,计算你在不触动警报装置的情况下,能够偷窃到的最高金额。 示例 1: 输入: [1,2,3,1] 输出: 4 解释: 偷窃 1 号房屋 (金额 = 1) ,然后偷窃 3 号房屋 (金额 = 3)。   偷窃到的最高金额 = 1 + 3 = 4 。 示例 2: 输入: [2,7,9,3,1] 输出: 12 解释: 偷窃 1 号房屋 (金额 = 2), 偷窃 3 号房屋 (金额 = 9),接着偷窃 5 号房屋 (金额 = 1)。   偷窃到的最高金额 = 2 + 9 + 1 = 12 。 */ object HouseRobber { @JvmStatic fun main(args: Array<String>) { val sum = Solution().rob(arrayOf(2,7,9,3,1).toIntArray()) print(sum) } /** * 思路: * 动态规划问题,重要的是找到状态转移公式 * 1. 设 f(n) 为n个房子的最大金额,An 为第n个房子的最大金额 * 2. n = 1 : f(1) = A1 * 3. n = 2 : f(2) = Max(A1 + A2) * 4. n = 3 : f(3) = Max(f(1) + A3,f(2)) * 5. f(0) = 0 * 6. 公式:f(n) = Max(f(n-2) + An ,f(n-1)) */ class Solution { fun rob(nums: IntArray): Int { var prevSum = 0 var currSum = 0 for (i in nums.indices) { val tmp = currSum currSum = Math.max(prevSum + nums[i],currSum) prevSum = tmp } return currSum } } }
0
Kotlin
0
0
a00a7aeff74e6beb67483d9a8ece9c1deae0267d
1,650
leetcode
MIT License
src/Day11_part2.kt
armandmgt
573,595,523
false
{"Kotlin": 47774}
fun main() { data class Monkey( val id: Int, var inspections: Long = 0, val divisor: Long, val items: MutableList<Long>, val operation: (Long, Long) -> Long, val destination: (Long) -> Int ) { override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as Monkey if (id != other.id) return false return true } override fun hashCode(): Int { return id } } val multiplication = Regex("new = old \\* (\\d+)") val square = Regex("new = old \\* old") val addition = Regex("new = old \\+ (\\d+)") fun makeOperation(operation: String): (Long, Long) -> Long { when { multiplication.matches(operation) -> { val (factor) = multiplication.find(operation)!!.destructured return fun(modulus: Long, old: Long): Long { return (old * factor.toLong()) % modulus } } square.matches(operation) -> return fun(modulus: Long, old: Long): Long { return (old * old) % modulus } addition.matches(operation) -> { val (operand) = addition.find(operation)!!.destructured return fun(modulus: Long, old: Long): Long { return (old + operand.toLong()) % modulus } } } throw IllegalArgumentException("operation non matched: $operation") } fun makeDestination(divisor: Long, destTrueId: Int, destFalseId: Int): (Long) -> Int { return fun(worriness: Long): Int = if (worriness % divisor == 0L) destTrueId else destFalseId } fun parseMonkeyList(input: List<String>): List<Monkey> { val monkeys = mutableListOf<Monkey>() input.chunked(7).forEach { monkeyDef -> val (id) = Regex("Monkey (\\d+):").find(monkeyDef[0])!!.destructured val (items) = Regex("Starting items: (.*)").find(monkeyDef[1])!!.destructured val (operation) = Regex("Operation: (.*)").find(monkeyDef[2])!!.destructured val (divisor) = Regex("Test: divisible by (.*)").find(monkeyDef[3])!!.destructured val (destTrue) = Regex("If true: throw to monkey (.*)").find(monkeyDef[4])!!.destructured val (destFalse) = Regex("If false: throw to monkey (.*)").find(monkeyDef[5])!!.destructured monkeys.add( Monkey( id.toInt(), divisor = divisor.toLong(), items = items.split(", ").map { it.toLong() }.toMutableList(), operation = makeOperation(operation), destination = makeDestination(divisor.toLong(), destTrue.toInt(), destFalse.toInt()) ) ) } return monkeys } fun part2(input: List<String>): Long { val monkeys = parseMonkeyList(input) val modulus = monkeys.fold(1L) { acc, m -> acc * m.divisor } repeat(10000) { monkeys.forEach { monkey -> // println("Monkey ${monkey.id}:") monkey.items.forEach { item -> // println(" Monkey inspects an item with a worry level of $item.") val newVal = monkey.operation(modulus, item) // println(" Worry level after is $newVal.") monkey.inspections += 1 val destMonkey = monkey.destination(newVal) // println(" Item with worry level $newVal is thrown to monkey $destMonkey.") monkeys[destMonkey].items.add(newVal) } monkey.items.clear() } if (it + 1 == 1 || it + 1 == 20 || (it + 1) % 1000 == 0) { println("== After round ${it + 1} ==") monkeys.forEach { m -> println("Monkey ${m.id} inspected items ${m.inspections} times.") } } } return top(2, monkeys.map { it.inspections }).fold(1) { acc, i -> acc * i } } // test if implementation meets criteria from the description, like: val testInput = readInput("resources/Day11_test") check(part2(testInput) == 2713310158) val input = readInput("resources/Day11") println(part2(input)) }
0
Kotlin
0
1
0d63a5974dd65a88e99a70e04243512a8f286145
4,455
advent_of_code_2022
Apache License 2.0
src/test/kotlin/be/brammeerten/y2023/Day8Other2Test.kt
BramMeerten
572,879,653
false
{"Kotlin": 170522}
package be.brammeerten.y2023 import be.brammeerten.extractRegexGroups import be.brammeerten.readFile import be.brammeerten.toCharList import org.junit.jupiter.api.Test class Day8Other2Test { @Test fun `part 2`() { val lines = readFile("2023/day8/input.txt") val instructions = lines[0].toCharList() val startPositions = mutableListOf<String>() val paths = lines.drop(2).associate { val values = extractRegexGroups("^(...) = \\((...), (...)\\)$", it) if (values[0][2] == 'A') startPositions.add(values[0]) values[0] to Path(values[1], values[2]) } println("Start: " + startPositions.size) val history = mutableListOf<Pair<Pair<Int, Int>, List<Int>>>() for (posI in 0 until startPositions.size) { val temp = findForStartPos(startPositions[posI], instructions, paths) val important = temp.second.drop(temp.first) history.add((temp.first to important.size) to important.mapIndexed { i, value -> if (value[2] == 'Z') i else -1 }.filter { it != -1 }) println("Size: " + history[posI].first + ": " + history[posI].second.size + "zs") } var count: Long = 0 val posFewestZs = 4 while (true) { if (count == 0L) count += history[posFewestZs].first.first + history[posFewestZs].second[0] // TODO assumes there is only 1 z per cycle else count += history[posFewestZs].first.second val found = !history.asSequence() .filter { !it.second.contains(((count-it.first.first) % it.first.second).toInt()) } .any() if (found) break; } // println("Done calculating history: " + count + 1) } private fun findForStartPos(startPos: String, instructions: List<Char>, paths: Map<String, Path>): Pair<Int, List<String>> { val output = mutableListOf<String>() var instructionI = 0 var pos = startPos while(true) { val isLeft = instructions[instructionI] == 'L' pos = if (isLeft) paths[pos]!!.toLeft else paths[pos]!!.toRight var searchI = instructionI while(output.size > searchI) { if (output[searchI] == pos) break; searchI += instructions.size } // TODO gevonden if (output.size > searchI) { return searchI to output } output.add(pos) instructionI = (instructionI + 1) % instructions.size } } }
0
Kotlin
0
0
1defe58b8cbaaca17e41b87979c3107c3cb76de0
2,683
Advent-of-Code
MIT License
src/main/kotlin/com/anahoret/aoc2022/day04/main.kt
mikhalchenko-alexander
584,735,440
false
null
package com.anahoret.aoc2022.day04 import java.io.File private fun parseRange(str: String): IntRange { val (min, max) = str.split("-").map(String::toInt) return IntRange(min, max) } private fun parsePair(str: String): Pair<IntRange, IntRange> { val (first, second) = str.split(",") .map(::parseRange) return first to second } private infix fun IntRange.overlaps(other: IntRange): Boolean { return first in other || last in other || other.first in this || other.last in this } private operator fun IntRange.contains(other: IntRange): Boolean { return other.first in this && other.last in this } fun main() { val sectionPairs = File("src/main/kotlin/com/anahoret/aoc2022/day04/input.txt") .readText() .split("\n") .filter(String::isNotEmpty) .map(::parsePair) // Part 1 sectionPairs .count { (first, second) -> first in second || second in first } .let(::println) // Part 2 sectionPairs .count { (first, second) -> first overlaps second } .let(::println) }
0
Kotlin
0
0
b8f30b055f8ca9360faf0baf854e4a3f31615081
1,080
advent-of-code-2022
Apache License 2.0
src/main/kotlin/com/hj/leetcode/kotlin/problem875/Solution.kt
hj-core
534,054,064
false
{"Kotlin": 619841}
package com.hj.leetcode.kotlin.problem875 /** * LeetCode page: [875. Koko Eating Bananas](https://leetcode.com/problems/koko-eating-bananas/); */ class Solution { /* Complexity: * Time O(NLogM) and Space O(1) where N is the size of piles and M is the largest value in piles; */ fun minEatingSpeed(piles: IntArray, h: Int): Int { require(h >= piles.size) { "The constraints of the problem are not satisfied." } var lowerBound = 1 var upperBound = piles.max()!! while (lowerBound < upperBound) { val mid = lowerBound + (upperBound - lowerBound) / 2 val canEatAll = canEatAllBananas(mid, piles, h) if (canEatAll) { upperBound = mid } else { lowerBound = mid + 1 } } return lowerBound } private fun canEatAllBananas(speed: Int, piles: IntArray, timeLimit: Int): Boolean { var currTime = 0 for (pile in piles) { currTime += computeEatingTime(speed, pile) if (currTime > timeLimit) return false } return true } private fun computeEatingTime(speed: Int, pile: Int): Int { val time = pile / speed return if (time * speed < pile) time + 1 else time } }
1
Kotlin
0
1
14c033f2bf43d1c4148633a222c133d76986029c
1,298
hj-leetcode-kotlin
Apache License 2.0
year2016/src/main/kotlin/net/olegg/aoc/year2016/day4/Day4.kt
0legg
110,665,187
false
{"Kotlin": 511989}
package net.olegg.aoc.year2016.day4 import net.olegg.aoc.someday.SomeDay import net.olegg.aoc.year2016.DayOf2016 /** * See [Year 2016, Day 4](https://adventofcode.com/2016/day/4) */ object Day4 : DayOf2016(4) { private val ROOM_PATTERN = "^(.+)-(\\d+)\\[(.+)]$".toRegex() private const val A_CODE = 'a'.code override fun first(): Any? { val rooms = lines .map { line -> val match = checkNotNull(ROOM_PATTERN.matchEntire(line)) val (name, id, checksum) = match.destructured Triple(name.replace("-", ""), id.toInt(), checksum) } return rooms.filter { room -> room.third == room.first .groupingBy { it } .eachCount() .toList() .sortedWith(compareBy({ -it.second }, { it.first })) .take(5) .map { it.first } .joinToString(separator = "") }.sumOf { it.second } } override fun second(): Any? { val rooms = lines .mapNotNull { line -> ROOM_PATTERN.matchEntire(line)?.let { match -> val (name, id, _) = match.destructured Pair(name, id.toInt()) } } val decrypted = rooms.associate { (name, id) -> name .map { char -> if (char == '-') ' ' else ((char.code - A_CODE + id) % 26 + A_CODE).toChar() } .joinToString(separator = "") to id } return decrypted["northpole object storage"] } } fun main() = SomeDay.mainify(Day4)
0
Kotlin
1
7
e4a356079eb3a7f616f4c710fe1dfe781fc78b1a
1,428
adventofcode
MIT License
src/Day04.kt
iam-afk
572,941,009
false
{"Kotlin": 33272}
fun main() { fun part1(input: List<String>): Int = input.map { it.split(',', '-').map(String::toInt) } .count { (p1, q1, p2, q2) -> p1 <= p2 && q2 <= q1 || p2 <= p1 && q1 <= q2 } fun part2(input: List<String>): Int = input.map { it.split(',', '-').map(String::toInt) } .count { (p1, q1, p2, q2) -> q1 >= p2 && q2 >= p1 } // 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
b30c48f7941eedd4a820d8e1ee5f83598789667b
645
aockt
Apache License 2.0
src/main/kotlin/io/github/mikaojk/day2/part1/day2Part1.kt
MikAoJk
573,000,620
false
{"Kotlin": 15562}
package io.github.mikaojk.day2.part1 import io.github.mikaojk.common.getFileAsString fun day2Part1(): Int { val opponent = Player(score = 0) val you = Player(score = 0) val game = getFileAsString("src/main/resources/day2/game.txt") val rounds = game.split("\\n".toRegex()).map { round -> Round( opponentHand = Hand.values().find { it.aliasOpponent == round[0].toString() }!!, yourHand = Hand.values().find { it.aliasYour == round[2].toString() }!!, opponent = opponent, you = you ) } rounds.forEach { round -> calculateScore(round.opponent, round.opponentHand, round.you, round.yourHand) } return you.score } fun calculateScore(opponentPlayer: Player, opponentHand: Hand, youPlayer: Player, yourHand: Hand) { if (outComeHands(opponentHand, yourHand) == OutCome.YOUWIN) { youPlayer.score += (6 + yourHand.value) opponentPlayer.score += opponentHand.value } else if (outComeHands(opponentHand, yourHand) == OutCome.OPPONENTWIN) { opponentPlayer.score += (6 + opponentHand.value) youPlayer.score += yourHand.value } else { opponentPlayer.score += (3 + opponentHand.value) youPlayer.score += (3 + yourHand.value) } } fun outComeHands(opponentHand: Hand, yourHand: Hand): OutCome { return if (opponentHand == Hand.ROCK && yourHand == Hand.PAPER) { OutCome.YOUWIN } else if (opponentHand == Hand.ROCK && yourHand == Hand.SCISSORS) { OutCome.OPPONENTWIN } else if (opponentHand == Hand.PAPER && yourHand == Hand.ROCK) { OutCome.OPPONENTWIN } else if (opponentHand == Hand.PAPER && yourHand == Hand.SCISSORS) { OutCome.YOUWIN } else if (opponentHand == Hand.SCISSORS && yourHand == Hand.ROCK) { OutCome.YOUWIN } else if (opponentHand == Hand.SCISSORS && yourHand == Hand.PAPER) { OutCome.OPPONENTWIN } else { OutCome.DRAW } } enum class OutCome { OPPONENTWIN, YOUWIN, DRAW } data class Player( var score: Int ) data class Round( val opponentHand: Hand, val yourHand: Hand, val opponent: Player, val you: Player ) enum class Hand(val aliasOpponent: String, val aliasYour: String, val value: Int) { ROCK("A", "X", 1), PAPER("B", "Y", 2), SCISSORS("C", "Z", 3) }
0
Kotlin
0
0
eaa90abc6f64fd42291ab42a03478a3758568ecf
2,367
aoc2022
MIT License
AtCoder/abc209/D.kt
thedevelopersanjeev
112,687,950
false
null
private fun readLn() = readLine() ?: "" private fun readLns() = readLn().split(" ") private fun readInts() = readLns().map { it.toInt() } private const val MAXN = 100005 private const val LOG = 20 private var adj = Array(MAXN) { ArrayList<Int>() } private var depth = Array(MAXN) { 0 } private var up = Array(MAXN) { Array(LOG) { 0 } } private fun dfs(u: Int, par: Int) { for (v in adj[u]) { if (v == par) continue depth[v] = depth[u] + 1 up[v][0] = u for (i in 1 until LOG) { up[v][i] = up[up[v][i - 1]][i - 1] } dfs(v, u) } } private fun lca(a: Int, b: Int): Int { var (u, v) = listOf(a, b) if (depth[u] < depth[v]) { val temp = u u = v v = temp } val (k, one) = listOf(depth[u] - depth[v], 1) for (i in LOG - 1 downTo 0) { if (k.and(one.shl(i)) != 0) u = up[u][i] } if (u == v) return u for (i in LOG - 1 downTo 0) { if (up[u][i] != up[v][i]) { u = up[u][i] v = up[v][i] } } return up[u][0] } fun main() { val (n, q) = readInts() for (i in 1 until n) { val (u, v) = readInts() adj[u].add(v) adj[v].add(u) } dfs(1, 1) repeat(q) { val (u, v) = readInts() val w = lca(u, v) when ((depth[u] + depth[v] - 2 * depth[w]) % 2) { 0 -> println("Town") 1 -> println("Road") } } }
0
C++
58
146
610520cc396fb13a03c606b5fb6739cfd68cc444
1,459
Competitive-Programming
MIT License
src/main/kotlin/o9referenzdatentypen/Fraction.kt
lm41
636,474,764
false
null
package o9referenzdatentypen /** * Programmieren Trainieren Seite 192 * W.9.2 <NAME> * * Erweitert um [Fraction.divide] und weitere helper wie [Fraction.shorten] und [Fraction.gcd] * */ fun main() { val a = Fraction(numerator = 1, denominator = 2) val b = Fraction(numerator = 1, denominator = 4) val f = Fraction(numerator = 8, denominator = 4) val c = a.add(b) val d = a.multiply(b) println(c.toString()) println(d.toString()) println(f) println(b.divide(a)) } /** * Represents a fraction with a numerator and a denominator. * * @property numerator The numerator of the fraction. * @property denominator The denominator of the fraction. */ data class Fraction( private val numerator: Int, private val denominator: Int ) { /** * Adds [other] to this fraction and returns the result as a new fraction. * * @param other The fraction to add to this fraction. * @return A new fraction that is the sum of this fraction and [other]. */ fun add(other: Fraction): Fraction { val newNumerator = (this.numerator * other.denominator) + (other.numerator * this.denominator) val newDominator = this.denominator * other.denominator return this.copy(numerator = newNumerator, denominator = newDominator).shorten() } /** * Multiplies this fraction by [other] and returns the result as a new fraction. * * @param other The fraction to multiply with this fraction. * @return A new fraction that is the product of this fraction and [other]. */ fun multiply(other: Fraction): Fraction { val newNumerator = this.numerator * other.numerator val newDominator = this.denominator * other.denominator return this.copy(numerator = newNumerator, denominator = newDominator).shorten() } /** * Divides this fraction by [other] and returns the result as a new fraction. * * @param other The fraction to divide this fraction by. * @return A new fraction that is the quotient of this fraction divided by [other]. */ fun divide(other: Fraction) : Fraction { return this.multiply(other.copy(numerator = other.denominator, denominator = other.numerator)) } /** * Returns a new fraction that is a simplified version of this fraction. * * @return A new fraction that has the same value as this fraction but with the numerator and denominator * divided by their greatest common divisor. */ private fun shorten(): Fraction { val gcd = gcd() return this.copy(numerator = this.numerator / gcd, denominator = this.denominator / gcd) } /** * Calculates and returns the greatest common divisor (GCD) of the numerator and denominator of this Fraction. * This function uses the Euclidean algorithm to calculate the GCD. * * @return the GCD of the numerator and denominator of this Fraction. */ private fun gcd(): Int { var num1 = this.numerator var num2 = this.denominator while (num2 != 0) { val remainder = num1 % num2 num1 = num2 num2 = remainder } return num1 } /** * Returns a string representation of this fraction. * * If the denominator of the fraction is 1, only the numerator is returned. Otherwise, * the string representation of the numerator and denominator is returned. * * @return A string representation of this fraction. */ override fun toString(): String { val gcd = gcd() val copy = this.copy(numerator = this.numerator / gcd, denominator = this.denominator / gcd) return if (copy.denominator == 1) { "${copy.numerator}" } else "${copy.numerator}/${copy.denominator}" } }
0
Kotlin
0
0
bba220a34daed25dc5baa9a844ca54f3b8564390
3,849
pro-train-kotlin
MIT License
src/leetcodeProblem/leetcode/editor/en/RemoveDuplicatesFromSortedListIi.kt
faniabdullah
382,893,751
false
null
//Given the head of a sorted linked list, delete all nodes that have duplicate //numbers, leaving only distinct numbers from the original list. Return the linked //list sorted as well. // // // Example 1: // // //Input: head = [1,2,3,3,4,4,5] //Output: [1,2,5] // // // Example 2: // // //Input: head = [1,1,1,2,3] //Output: [2,3] // // // // Constraints: // // // The number of nodes in the list is in the range [0, 300]. // -100 <= Node.val <= 100 // The list is guaranteed to be sorted in ascending order. // // Related Topics Linked List Two Pointers 👍 3700 👎 134 package leetcodeProblem.leetcode.editor.en import leetcode_study_badge.data_structure.ListNode class RemoveDuplicatesFromSortedListIi { fun solution() { } //below code is used to auto submit for leetcode.com (using ide plugin) //leetcode submit region begin(Prohibit modification and deletion) /** * Example: * var li = ListNode(5) * var v = li.`val` * Definition for singly-linked list. * class ListNode(var `val`: Int) { * var next: ListNode? = null * } */ class Solution { // sentinel Algorithm fun deleteDuplicates(head: ListNode?): ListNode? { val sentinel = ListNode(0, head) var preD: ListNode? = sentinel var head = head while (head != null) { if (head.next != null && head.`val` == head.next?.`val`) { while (head?.next != null && head?.`val` == head?.next?.`val`) { head = head?.next } preD?.next = head?.next } else { preD = preD?.next } head = head?.next } return sentinel.next } } //leetcode submit region end(Prohibit modification and deletion) } fun main() {}
0
Kotlin
0
6
ecf14fe132824e944818fda1123f1c7796c30532
1,911
dsa-kotlin
MIT License
src/Day2/Day2.kt
tomashavlicek
571,148,506
false
{"Kotlin": 3033}
package Day2 import readInput fun main() { data class Operation(val operation: String, val amount: Int) fun part1(input: List<String>): Int { var horizontalPosition = 0 var depth = 0 val operations = input.map { it.split(' ') }.map { Operation(operation = it[0], amount = it[1].toInt()) } for ((direction, amount) in operations) { when (direction) { "forward" -> horizontalPosition += amount "down" -> depth += amount "up" -> depth -= amount } } return horizontalPosition * depth } fun part2(input: List<String>): Int { var horizontalPosition = 0 var depth = 0 var aim = 0 val operations = input.map { it.split(' ') }.map { Operation(operation = it[0], amount = it[1].toInt()) } for ((direction, amount) in operations) { when (direction) { "forward" -> { horizontalPosition += amount depth += aim * amount } "down" -> aim += amount "up" -> aim -= amount } } return horizontalPosition * depth } // test if implementation meets criteria from the description, like: val testInput = readInput("Day2/Day2_test") check(part1(testInput) == 150) check(part2(testInput) == 900) val input = readInput("Day2/Day2") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
52f7febaacaab3ee9809899d21077fecac39c13b
1,508
aoc-2021-in-kotlin
Apache License 2.0
src/Day05.kt
JonasDBB
573,382,821
false
{"Kotlin": 17550}
import java.util.Stack private fun setupStacks(input: List<String>): MutableList<Stack<Char>> { val listLineI = input.indexOfFirst { it[1] == '1' } var nrOfStacks = input[listLineI].count { !it.isWhitespace() } // this only works until 99 stacks, but input only goes to 9 anyway so w/e if (nrOfStacks > 10) nrOfStacks -= (nrOfStacks - 10) / 2 + 1 val stacks: MutableList<Stack<Char>> = mutableListOf() for (i in 0 until nrOfStacks) stacks.add(Stack<Char>()) for (i in listLineI - 1 downTo 0) { for (j in 1..(nrOfStacks * 4 - 2) step 4) { if (j >= input[i].length) break if (!input[i][j].isWhitespace()) { stacks[((j - 1) / 4)].push(input[i][j]) } } } return stacks } private fun part1(input: List<String>, stacks: MutableList<Stack<Char>>) { val firstMove = input.indexOfFirst { it.startsWith("move") } for (i in firstMove until input.size) { val words = input[i].split(" ") val src = words[3].toInt() - 1 val dst = words[5].toInt() - 1 for (j in 0 until words[1].toInt()) { stacks[dst].push(stacks[src].pop()) } } for (stk in stacks) print(stk.peek()) println() } // lots of duplication, but didn't feel like making it better now private fun part2(input: List<String>, stacks: MutableList<Stack<Char>>) { val firstMove = input.indexOfFirst { it.startsWith("move") } for (i in firstMove until input.size) { val words = input[i].split(" ") // probably very inefficient, but I don't care atm val tmp = Stack<Char>() val src = words[3].toInt() - 1 val dst = words[5].toInt() - 1 for (j in 0 until words[1].toInt()) { tmp.push(stacks[src].pop()) } for (j in 0 until words[1].toInt()) { stacks[dst].push(tmp.pop()) } } for (stk in stacks) print(stk.peek()) println() } fun main() { val input = readInput("05") println("part 1") part1(input, setupStacks(input)) println("part 2") // re make stacks so they are reset to the input part2(input, setupStacks(input)) }
0
Kotlin
0
0
199303ae86f294bdcb2f50b73e0f33dca3a3ac0a
2,193
AoC2022
Apache License 2.0
src/chapter5/section2/ex10_Size.kt
w1374720640
265,536,015
false
{"Kotlin": 1373556}
package chapter5.section2 import chapter5.section1.Alphabet import edu.princeton.cs.algs4.Queue /** * size()方法 * 为TrieST和TST实现最为即时的size()方法(在每个结点中保存子树中的键的总数) * * 解:参考二叉查找树的实现[chapter3.section2.BinarySearchTree] */ class InstantTrieST<V : Any>(private val alphabet: Alphabet) : StringST<V> { private inner class Node { val next = arrayOfNulls<Node>(alphabet.R()) var value: V? = null var size = 0 fun isEmpty() = size == 0 fun resize() { var count = if (value == null) 0 else 1 next.forEach { if (it != null) count += it.size } size = count } } private val root = Node() override fun put(key: String, value: V) { put(root, key, value, 0) } private fun put(node: Node, key: String, value: V, d: Int) { if (d == key.length) { if (node.value == null) node.size++ node.value = value return } val index = alphabet.toIndex(key[d]) var nextNode = node.next[index] if (nextNode == null) { nextNode = Node() node.next[index] = nextNode } put(nextNode, key, value, d + 1) node.resize() } override fun get(key: String): V? { return get(root, key, 0)?.value } private fun get(node: Node, key: String, d: Int): Node? { if (d == key.length) return node val index = alphabet.toIndex(key[d]) val nextNode = node.next[index] ?: return null return get(nextNode, key, d + 1) } override fun delete(key: String) { delete(root, key, 0) } private fun delete(node: Node, key: String, d: Int): Node? { if (d == key.length) { if (node.value == null) throw NoSuchElementException() node.value = null node.size-- return if (node.isEmpty()) null else node } val index = alphabet.toIndex(key[d]) val nextNode = node.next[index] ?: throw NoSuchElementException() node.next[index] = delete(nextNode, key, d + 1) node.resize() return if (node.isEmpty()) null else node } override fun contains(key: String): Boolean { return get(key) != null } override fun isEmpty(): Boolean { return root.isEmpty() } override fun size(): Int { return root.size } override fun keys(): Iterable<String> { val queue = Queue<String>() keys(root, queue, "") return queue } private fun keys(node: Node, queue: Queue<String>, key: String) { if (node.value != null) { queue.enqueue(key) } for (i in node.next.indices) { val nextNode = node.next[i] ?: continue keys(nextNode, queue, key + alphabet.toChar(i)) } } override fun longestPrefixOf(s: String): String? { val length = longestPrefixOf(root, s, 0, 0) return if (length == 0) null else s.substring(0, length) } private fun longestPrefixOf(node: Node, s: String, d: Int, length: Int): Int { val index = alphabet.toIndex(s[d]) val nextNode = node.next[index] ?: return length var newLength = length if (nextNode.value != null) { newLength = d + 1 } return if (d == s.length - 1) newLength else longestPrefixOf(nextNode, s, d + 1, newLength) } override fun keysWithPrefix(s: String): Iterable<String> { val queue = Queue<String>() val node = get(root, s, 0) ?: return queue keys(node, queue, s) return queue } override fun keysThatMatch(s: String): Iterable<String> { val queue = Queue<String>() keysThatMatch(root, queue, s, "") return queue } private fun keysThatMatch(node: Node, queue: Queue<String>, match: String, real: String) { val d = real.length if (d == match.length) { if (node.value != null) { queue.enqueue(real) } return } val char = match[d] if (char == '.') { for (i in node.next.indices) { val nextNode = node.next[i] ?: continue keysThatMatch(nextNode, queue, match, real + alphabet.toChar(i)) } } else { val index = alphabet.toIndex(char) val nextNode = node.next[index] ?: return keysThatMatch(nextNode, queue, match, real + char) } } } class InstantTST<V : Any> : StringST<V> { private inner class Node(val char: Char) { var value: V? = null var left: Node? = null var mid: Node? = null var right: Node? = null var size = 0 fun resize() { var count = if (value == null) 0 else 1 left?.let { count += it.size } right?.let { count += it.size } mid?.let { count += it.size } size = count } } private var root: Node? = null // 符号表应该支持以空字符串为键,空字符串不含任何字符,需要特殊处理 private var emptyKeyValue: V? = null override fun put(key: String, value: V) { if (key == "") { emptyKeyValue = value return } root = put(root, key, value, 0) } private fun put(node: Node?, key: String, value: V, d: Int): Node { val char = key[d] val result = node ?: Node(char) when { char < result.char -> result.left = put(result.left, key, value, d) char > result.char -> result.right = put(result.right, key, value, d) else -> { if (d == key.length - 1) { if (result.value == null) result.size++ result.value = value } else { result.mid = put(result.mid, key, value, d + 1) } } } result.resize() return result } override fun get(key: String): V? { if (key == "") return emptyKeyValue return get(root, key, 0)?.value } private fun get(node: Node?, key: String, d: Int): Node? { if (node == null) return null val char = key[d] return when { char < node.char -> get(node.left, key, d) char > node.char -> get(node.right, key, d) else -> if (d == key.length - 1) node else get(node.mid, key, d + 1) } } override fun delete(key: String) { if (key == "") { if (emptyKeyValue == null) throw NoSuchElementException() emptyKeyValue = null return } root = delete(root, key, 0) } private fun delete(node: Node?, key: String, d: Int): Node? { if (node == null) throw NoSuchElementException() val char = key[d] when { char < node.char -> node.left = delete(node.left, key, d) char > node.char -> node.right = delete(node.right, key, d) else -> { if (d == key.length - 1) { if (node.value == null) throw NoSuchElementException() node.value = null node.size-- } else { node.mid = delete(node.mid, key, d + 1) } if (node.left == null && node.right == null && node.mid == null && node.value == null) { return null } } } node.resize() return node } override fun contains(key: String): Boolean { return get(key) != null } override fun isEmpty(): Boolean { return size() == 0 } override fun size(): Int { var size = if (emptyKeyValue == null) 0 else 1 root?.let { size += it.size } return size } override fun keys(): Iterable<String> { val queue = Queue<String>() if (emptyKeyValue != null) { queue.enqueue("") } keys(root, queue, "") return queue } private fun keys(node: Node?, queue: Queue<String>, key: String) { if (node == null) return keys(node.left, queue, key) if (node.value != null) { queue.enqueue(key + node.char) } keys(node.mid, queue, key + node.char) keys(node.right, queue, key) } override fun longestPrefixOf(s: String): String? { val length = longestPrefixOf(root, s, 0, 0) return if (length == 0) { if (emptyKeyValue == null) null else "" } else { s.substring(0, length) } } private fun longestPrefixOf(node: Node?, key: String, d: Int, length: Int): Int { if (node == null || d == key.length) return length var newLength = length val char = key[d] when { char < node.char -> newLength = longestPrefixOf(node.left, key, d, newLength) char > node.char -> newLength = longestPrefixOf(node.right, key, d, newLength) else -> { if (node.value != null) { newLength = d + 1 } newLength = longestPrefixOf(node.mid, key, d + 1, newLength) } } return newLength } override fun keysWithPrefix(s: String): Iterable<String> { if (s == "") return keys() val queue = Queue<String>() keysWithPrefix(root, queue, s, 0) return queue } private fun keysWithPrefix(node: Node?, queue: Queue<String>, key: String, d: Int) { if (node == null) return if (d == key.length) { keys(node, queue, key) return } val char = key[d] when { char < node.char -> keysWithPrefix(node.left, queue, key, d) char > node.char -> keysWithPrefix(node.right, queue, key, d) else -> keysWithPrefix(node.mid, queue, key, d + 1) } } override fun keysThatMatch(s: String): Iterable<String> { val queue = Queue<String>() if (s == "") { if (emptyKeyValue != null) queue.enqueue("") return queue } keysThatMatch(root, queue, s, "") return queue } private fun keysThatMatch(node: Node?, queue: Queue<String>, match: String, real: String) { if (node == null) return val d = real.length val char = match[d] when { char == '.' -> { keysThatMatch(node.left, queue, match, real) if (d == match.length - 1) { if (node.value != null) queue.enqueue(real + node.char) } else { keysThatMatch(node.mid, queue, match, real + node.char) } keysThatMatch(node.right, queue, match, real) } char < node.char -> keysThatMatch(node.left, queue, match, real) char > node.char -> keysThatMatch(node.right, queue, match, real) else -> { if (d == match.length - 1) { if (node.value != null) queue.enqueue(real + node.char) } else { keysThatMatch(node.mid, queue, match, real + node.char) } } } } } fun main() { testStringST { InstantTrieST(Alphabet.EXTENDED_ASCII) } testStringST { InstantTST() } }
0
Kotlin
1
6
879885b82ef51d58efe578c9391f04bc54c2531d
11,634
Algorithms-4th-Edition-in-Kotlin
MIT License
code/day_13/src/jvm8Main/kotlin/task1.kt
dhakehurst
725,945,024
false
{"Kotlin": 105846}
package day_13 import korlibs.datastructure.getCyclicOrNull data class Size( val cols: Int, val rows: Int ) class Grid<T>( /** * list of rows */ val lines: List<List<T>> ) { val size get() = Size(lines[0].size, lines.size) fun getOrNull(x: Int, y: Int): T? = lines.getOrNull(y)?.getCyclicOrNull(x) val columns: List<List<T>> by lazy { val l = mutableListOf<List<T>>() for (i in 0 until size.cols) { l.add(lines.map { it[i] }) } l } override fun toString(): String { return lines.joinToString(separator = "\n") {it.joinToString(separator = "")} } } fun Grid<Char>.flip(x: Int, y: Int):Grid<Char> { val flines = lines.map { it.toMutableList() //clone it } val c = flines[y][x] when(c) { '.' -> flines[y][x] = '#' '#' -> flines[y][x] = '.' } return Grid(flines) } fun List<String>.toGrids(): List<Grid<Char>> { val grids = mutableListOf<Grid<Char>>() var l = mutableListOf<String>() for (line in this) { when { line.isBlank() -> { grids.add(Grid(l.map { it.toList() })) l = mutableListOf<String>() } else -> l.add(line) } } grids.add(Grid(l.map { it.toList() })) return grids } // adapted from [https://www.geeksforgeeks.org/longest-palindromic-substring/] fun palindromesIn(str: String): List<Pair<Int,Int>> { val n = str.length val table = Array(n) { BooleanArray(n) } var maxLength = 1 val at = mutableListOf<Pair<Int,Int>>() for (i in 0..<n) table[i][i] = true var start = 0 for (i in 0..<n - 1) { if (str[i] == str[i + 1]) { table[i][i + 1] = true start = i maxLength = 2 at.add(Pair(start,maxLength)) } } for (k in 3..n) { for (i in 0..<n - k + 1) { val j = i + k - 1 if (table[i + 1][j - 1] && str[i] == str[j] ) { table[i][j] = true at.add(Pair(i,k)) } } } return at } // (point, length) fun reflectPoint(l: List<Char>): List<Pair<Int,Int>> { val lp = palindromesIn(String(l.toCharArray())) val l2= lp.mapNotNull { when { it.first!=0 && (it.first + it.second)!=l.size -> null it.second%2 != 0 -> null it.second > 0 -> Pair(it.first + it.second / 2,it.second) else -> null } } return l2 } fun reflectVert(g: Grid<Char>, orig:Int): Int { val points = g.lines.map { reflectPoint(it).toSet() } val ps = points.reduce { acc, it -> acc.intersect(it) }.filter { it.first!=orig } return when { ps.size==0 -> 0 else -> ps.maxBy { it.second }.first } } fun reflectHoriz(g: Grid<Char>, orig:Int): Int { val points = g.columns.map { reflectPoint(it).toSet() } val ps = points.reduce { acc, it -> acc.intersect(it) }.filter { it.first!=orig } return when { ps.size==0 -> 0 else -> ps.maxBy { it.second }.first } } fun task1(lines: List<String>): Int { var total = 0 val grids = lines.toGrids() for (g in grids.indices) { val grid=grids[g] println(g) println(grid) val rv = reflectVert(grid,-1) println("rv: $rv") total += if (0 == rv) { val rh = reflectHoriz(grid,-1) println("rh: $rh") if (0==rh) { 0 } else { (100 * (rh)) } } else { rv } } return total }
0
Kotlin
0
0
be416bd89ac375d49649e7fce68c074f8c4e912e
3,699
advent-of-code
Apache License 2.0
archive/2022/Day01.kt
mathijs81
572,837,783
false
{"Kotlin": 167658, "Python": 725, "Shell": 57}
package aoc2022 fun main() { fun part1(input: List<String>): Int { var sum = 0 var max = 0 for (line in input) { if (line.trim().isEmpty()) { max = max.coerceAtLeast(sum) sum = 0 } else { sum += line.toInt() } } max = max.coerceAtLeast(sum) return max } fun part2(input: List<String>): Int { val list = mutableListOf<Int>() var sum = 0 for (line in input) { if (line.trim().isEmpty()) { list.add(sum) sum = 0 } else { sum += line.toInt() } } list.add(sum) list.sortWith(Comparator.naturalOrder<Int>().reversed()) return list.subList(0, 3).sum() } // test if implementation meets criteria from the description, like: val testInput = readAsLines("Day01_test") check(part1(testInput) == 24000) check(part2(testInput) == 45000) val input = readAsLines("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
2
92f2e803b83c3d9303d853b6c68291ac1568a2ba
1,123
advent-of-code-2022
Apache License 2.0
src/commonMain/kotlin/advent2020/day13/Day13Puzzle.kt
jakubgwozdz
312,526,719
false
null
package advent2020.day13 fun part1(input: String): String { val ts = input.trim().lines()[0].toInt() val wait = buses(input).map { it to it - ts % it }.minByOrNull { it.second }!! return (wait.first * wait.second).toString() } fun part2(input: String): String { var multiple = 1L var result = 0L busesWithOffsets(input).forEach { (bus, offset) -> while ((result + offset) % bus != 0L) result += multiple multiple *= bus } return result.toString() } private fun busesWithOffsets(input: String) = sequence { val line = input.trim().lines()[1].split(',') var offset = 0L line.forEach { if (it != "x") yield(it.toLong() to offset % it.toLong()) offset++ } } private fun buses(input: String) = busesWithOffsets(input).map {it.first}
0
Kotlin
0
2
e233824109515fc4a667ad03e32de630d936838e
815
advent-of-code-2020
MIT License
src/Year2021Day03.kt
zhangt2333
575,260,256
false
{"Kotlin": 34993}
// https://github.com/Mistborn94/advent-of-code-2021/blob/main/src/main/kotlin/day3/Day3.kt fun main() { fun bitmask(size: Int) = 2.pow(size) - 1 fun part1(lines: List<String>): Int { val gamma = lines .map { it.toList().map(Char::digitToInt) } .reduce { l1, l2 -> l1.zip(l2, Int::plus) } .map { if (it >= lines.size - it) 1 else 0 } .digitsToInt(2) return gamma * (gamma.inv() and bitmask(lines.first().length)) } tailrec fun calcRating(G: List<List<Int>>, focusBit: Int, colIndex: Int = 0): Int { return if (G.size == 1) { G.first().digitsToInt(2) } else { val numberOfOne = G.sumOf { it[colIndex] } val comparisonBit = if (numberOfOne >= G.size - numberOfOne) focusBit else 1 - focusBit calcRating(G.filter { it[colIndex] == comparisonBit }, focusBit, colIndex + 1) } } fun part2(lines: List<String>): Int { val G = lines.map { it.toList().map(Char::digitToInt) } return calcRating(G, 1) * calcRating(G, 0) } val testLines = readLines(true) assertEquals(198, part1(testLines)) assertEquals(230, part2(testLines)) val lines = readLines() println(part1(lines)) println(part2(lines)) }
0
Kotlin
0
0
cdba887c4df3a63c224d5a80073bcad12786ac71
1,294
aoc-2022-in-kotlin
Apache License 2.0
src/main/java/challenges/educative_grokking_coding_interview/top_k_elements/_1/KthLargest.kt
ShabanKamell
342,007,920
false
null
package challenges.educative_grokking_coding_interview.top_k_elements._1 import java.util.* /** Given an infinite stream of integers (sorted or unsorted), nums, design a class to find the kth largest element in a stream. Note: It is the kth largest element in the sorted order, not the kth distinct element. The class should have the following functions, inputs, and return values: Init(): It takes an array of integers and an integer k and initializes the class object. Add(value): It takes one integer value, appends it to the stream, and calls the Return kth largest() function. Return kth largest(): It returns an integer value that represents the kth largest element in the stream. https://www.educative.io/courses/grokking-coding-interview-patterns-java/mE90WX1DE7E */ internal class KthLargest(var k: Int, nums: IntArray) { var topKHeap: PriorityQueue<Int> = PriorityQueue() private fun printHeapWithMarkers(arr: PriorityQueue<Int>, pvalue: Int): String { var out = "[" val value: Iterator<*> = arr.iterator() for (i in arr.indices) { if (pvalue == i) { out += '«' out += value.next().toString() + '»' + ", " } else if (i != arr.size - 1) out += value.next().toString() + ", " else out += value.next().toString() } out += "]" return out } // adds element in the topKHeap fun add(`val`: Int) { topKHeap.offer(`val`) if (topKHeap.size > k) { topKHeap.poll() } } // returns kth largest element from topKHeap fun returnKthLargest(): Int { return topKHeap.peek() } companion object { @JvmStatic fun main(args: Array<String>) { val nums = intArrayOf(3, 6, 9, 10) var temp = intArrayOf(3, 6, 9, 10) println("Initial stream: " + Arrays.toString(nums)) println("k: " + 3) val kLargest = KthLargest(3, nums) val `val` = intArrayOf(4, 7, 10, 8, 15) println() for (i in `val`.indices) { println("\tAdding a new number " + `val`[i] + " to the stream") temp = temp.copyOf(temp.size + 1) temp[temp.size - 1] = `val`[i] println("\t\tNumber stream: " + Arrays.toString(temp)) kLargest.add(`val`[i]) println("\tKth largest element in the stream: " + kLargest.returnKthLargest()) println(String(CharArray(100)).replace('\u0000', '-')) } } } // constructor to initialize topKHeap and add values in it init { for (num in nums) { topKHeap.offer(num) } while (topKHeap.size > k) { topKHeap.poll() } } }
0
Kotlin
0
0
ee06bebe0d3a7cd411d9ec7b7e317b48fe8c6d70
2,801
CodingChallenges
Apache License 2.0
implementation/src/main/kotlin/io/github/tomplum/aoc/display/DisplayAnalyser.kt
TomPlum
431,391,240
false
{"Kotlin": 114607}
package io.github.tomplum.aoc.display import io.github.tomplum.aoc.display.DisplayValues.* class DisplayAnalyser(data: List<String>) { private val entries = data.map { entry -> val values = entry.trim().split(" | ") val signalPatterns = SignalPatterns(values[0].trim().split(" ")) val outputValues = values[1].trim().split(" ") OutputEntry(signalPatterns, outputValues) } fun countUniqueSegmentsInstances(): Int = entries.map { entry -> entry.outputValues }.sumOf { value -> listOf(ONE, FOUR, SEVEN, EIGHT).sumOf { displayValues -> value.count { outputValue -> outputValue.length == displayValues.wires.size } } } fun getOutputValueSum(): Int = entries.sumOf { (signalPatterns, outputValues) -> // We know 1, 4, 7 and 8 because they have unique numbers of segments per digit val one = ONE.withMapping(signalPatterns.findPatternWithSameLengthAs(ONE)) val four = FOUR.withMapping(signalPatterns.findPatternWithSameLengthAs(FOUR)) val seven = SEVEN.withMapping(signalPatterns.findPatternWithSameLengthAs(SEVEN)) val eight = EIGHT.withMapping(signalPatterns.findPatternWithSameLengthAs(EIGHT)) // There are three numbers that require exactly 6 segments to be illuminated val sixLengthPatterns = signalPatterns.getPatternsWithLength(6) val nine = NINE.withMapping(sixLengthPatterns.find { pattern -> four.matchesPattern(pattern) }!!) val zero = ZERO.withMapping(sixLengthPatterns.find { pattern -> !nine.matches(pattern) && one.matchesPattern(pattern) }!!) val six = SIX.withMapping(sixLengthPatterns.find { pattern -> !nine.matches(pattern) && !zero.matches(pattern) }!!) // There are three numbers that require exactly 5 segments to be illuminated val fiveLengthPatterns = signalPatterns.getPatternsWithLength(5) val three = THREE.withMapping(fiveLengthPatterns.find { pattern -> one.matchesPattern(pattern) }!!) val five = FIVE.withMapping(fiveLengthPatterns.find { pattern -> !three.matches(pattern) && nine.containsAll(pattern) }!!) val two = TWO.withMapping(fiveLengthPatterns.find { pattern -> !three.matches(pattern) && !five.matches(pattern) }!!) // Now we have all the wires mapped, matches the output values and build the output value outputValues.map { value -> listOf(zero, one, two, three, four, five, six, seven, eight, nine).find { number -> number.matchesMappingLength(value) && number.containsAll(value) }?.value ?: throw IllegalArgumentException("No matching value for $value") }.joinToString("").toInt() } }
0
Kotlin
0
0
cccb15593378d0bb623117144f5b4eece264596d
2,698
advent-of-code-2021
Apache License 2.0
src/Day01.kt
rifkinni
573,123,064
false
{"Kotlin": 33155, "Shell": 125}
import java.util.Collections.max class Day01 { fun parseSupplies(input: List<String>): List<Int> { return input.joinToString(",").split(",,").map { collection -> collection.split(",").map { num -> Integer.parseInt(num) }.sum() } } } fun main() { fun part1(input: List<String>): Int { val elfSupplies = Day01().parseSupplies(input) return max(elfSupplies) } fun part2(input: List<String>): Int { val elfSupplies = Day01().parseSupplies(input) return elfSupplies.sortedDescending().slice(0..2).sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") check(part1(testInput) == 24000 ) check(part2(testInput) == 45000 ) val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
c2f8ca8447c9663c0ce3efbec8e57070d90a8996
871
2022-advent
Apache License 2.0
app/src/main/java/com/betulnecanli/kotlindatastructuresalgorithms/SortingAlgorithms/MergeSort/MergeSort.kt
betulnecanli
568,477,911
false
{"Kotlin": 167849}
package com.betulnecanli.kotlindatastructuresalgorithms.SortingAlgorithms.MergeSort //Merge sort is one of the most efficient sorting algorithms. With a time complexity of //O(n log n), it’s one of the fastest of all general-purpose sorting algorithms. The idea //behind merge sort is divide and conquer — to break a big problem into several //smaller, easier-to-solve problems, and then combine those solutions into a final //result. The merge sort mantra is to split first and merge after. private fun <T : Comparable<T>> merge(left: List<T>, right: List<T>): List<T> { // 1 var leftIndex = 0 var rightIndex = 0 // 2 val result = mutableListOf<T>() // 3 while (leftIndex < left.size && rightIndex < right.size) { val leftElement = left[leftIndex] val rightElement = right[rightIndex] // 4 if (leftElement < rightElement) { result.add(leftElement) leftIndex += 1 } else if (leftElement > rightElement) { result.add(rightElement) rightIndex += 1 } else { result.add(leftElement) leftIndex += 1 result.add(rightElement) rightIndex += 1 } } // 5 if (leftIndex < left.size) { result.addAll(left.subList(leftIndex, left.size)) } if (rightIndex < right.size) { result.addAll(right.subList(rightIndex, right.size)) } return result } //1. The leftIndex and rightIndex variables track your progress as you parse //through the two lists. //2. The result list will house the combined lists. //3. Starting from the beginning, you compare the elements in the left and right //lists sequentially. When you reach the end of either list, there’s nothing else to //compare. //4. The smaller of the two elements goes into the result list. If the elements are //equal, they can both be added. //5. The first loop guarantees that either left or right is empty. Since both lists are //sorted, this ensures that the leftover elements are greater than or equal to the //ones currently in result. In this scenario, you can add the rest of the elements //without comparison. fun <T : Comparable<T>> List<T>.mergeSort(): List<T> { if (this.size < 2) return this val middle = this.size / 2 val left = this.subList(0, middle).mergeSort() val right = this.subList(middle, this.size).mergeSort() return merge(left, right) } //The best, worst and average time complexity of merge sort is O(n log n).
2
Kotlin
2
40
70a4a311f0c57928a32d7b4d795f98db3bdbeb02
3,027
Kotlin-Data-Structures-Algorithms
Apache License 2.0
src/main/kotlin/com/hj/leetcode/kotlin/problem662/Solution.kt
hj-core
534,054,064
false
{"Kotlin": 619841}
package com.hj.leetcode.kotlin.problem662 import com.hj.leetcode.kotlin.common.model.TreeNode /** * LeetCode page: [662. Maximum Width of Binary Tree](https://leetcode.com/problems/maximum-width-of-binary-tree/); */ class Solution { /* Complexity: * Time O(N) and Space O(N) where N is the number of nodes in root; */ fun widthOfBinaryTree(root: TreeNode?): Int { if (root == null) return 0 var maxWidth = 0L /* It is intent to be the level-ordered index of node. * However, in order to avoid number overflow(for example, in the case of a vertical zigzag tree), * the indices are normalized as following: * When computing the indices of nodes in next level using BFS, the indices of nodes in current level * are shifted such that the leftmost node in current level has an index of 0. */ val nodeIndex = hashMapOf<TreeNode, Long>() val bfsQueue = ArrayDeque<TreeNode>() nodeIndex[root] = 0L bfsQueue.addLast(root) while (bfsQueue.isNotEmpty()) { val levelMaxWidth = levelMaxWidth(bfsQueue, nodeIndex) if (maxWidth < levelMaxWidth) { maxWidth = levelMaxWidth } updateNextLevel(bfsQueue, nodeIndex) } return maxWidth.toInt() } private fun levelMaxWidth( bfsQueue: ArrayDeque<TreeNode>, nodeIndex: Map<TreeNode, Long> ): Long { val leftmostIndex = checkNotNull(nodeIndex[bfsQueue.first()]) val rightmostIndex = checkNotNull(nodeIndex[bfsQueue.last()]) return rightmostIndex - leftmostIndex + 1 } private fun updateNextLevel( bfsQueue: ArrayDeque<TreeNode>, nodeIndex: MutableMap<TreeNode, Long> ) { val indexShift = checkNotNull(nodeIndex[bfsQueue.first()]) * (-1) repeat(bfsQueue.size) { val node = bfsQueue.removeFirst() // Normalize the index to avoid number overflow of indices in next level val normalizedIndex = checkNotNull(nodeIndex[node]) + indexShift node.left?.let { nodeIndex[it] = normalizedIndex * 2 bfsQueue.addLast(it) } node.right?.let { nodeIndex[it] = normalizedIndex * 2 + 1 bfsQueue.addLast(it) } } } }
1
Kotlin
0
1
14c033f2bf43d1c4148633a222c133d76986029c
2,392
hj-leetcode-kotlin
Apache License 2.0
src/main/kotlin/aoc2015/Day06.kt
w8mr
572,700,604
false
{"Kotlin": 140954}
package aoc2015 import aoc.parser.Parsers.eol import aoc.parser.Parsers.number import aoc.parser.and import aoc.parser.asParser import aoc.parser.oneOrMore import aoc.parser.seq class Day06 { enum class Instruction(val text: String) { On("turn on"), Off("turn off"), Toggle("toggle") } data class Instr(val instruction: Instruction, val topLeft: Pair<Int, Int>, val bottomRight: Pair<Int, Int>) val instruction = Instruction::class.asParser(Instruction::text) val coordinate = seq(number and ",", number) val line = seq(instruction and " ", coordinate and " through ", coordinate and eol, ::Instr) val parser = oneOrMore(line) private fun solve(input: String, action: (Instruction, Int) -> Int): IntArray { val parsed = parser(input) val lights = IntArray(1000 * 1000) parsed.forEach { instr -> (instr.topLeft.first..instr.bottomRight.first).forEach { row -> (instr.topLeft.second..instr.bottomRight.second).forEach { col -> val index = row * 1000 + col lights[index] = action(instr.instruction, lights[index]) } } } return lights } fun part1(input: String): Int { val lights = solve(input) { instruction, current -> when (instruction) { Instruction.On -> 1 Instruction.Off -> 0 Instruction.Toggle -> 1 - current } } return lights.count { it == 1 } } fun part2(input: String): Int { val lights = solve(input) { instruction, current -> when (instruction) { Instruction.On -> current + 1 Instruction.Off -> maxOf(0, current - 1) Instruction.Toggle -> current + 2 } } return lights.sum() } }
0
Kotlin
0
0
e9bd07770ccf8949f718a02db8d09daf5804273d
1,900
aoc-kotlin
Apache License 2.0
advent-of-code-2022/src/main/kotlin/year_2022/Day03.kt
rudii1410
575,662,325
false
{"Kotlin": 37749}
package year_2022 import util.Runner fun main() { fun getCharScore(ch: Char) = if (ch.isUpperCase()) (ch - 'A' + 1) + 26 else (ch - 'a' + 1) fun MutableMap<Char, Int>.addScore(key: Char) { this[key] = this.getOrDefault(key, 0) + 1 } fun MutableMap<Char, Int>.calculate(minimum: Int): Int { return this.map { if (it.value == minimum) getCharScore(it.key) else 0 }.sum() } fun String.distinctForEach(cb: (Char) -> Unit) = this.toCharArray().distinct().forEach(cb) fun part1(input: List<String>): Int { var result = 0 input.forEach { i -> val dict = mutableMapOf<Char, Int>() i.chunked(i.length / 2).forEach { ruckSack -> ruckSack.distinctForEach { dict.addScore(it) } } result += dict.calculate(2) } return result } Runner.run(::part1, 157) fun part2(input: List<String>): Int { var result = 0 input.chunked(3).forEach { group -> val dict = mutableMapOf<Char, Int>() group.forEach { r -> r.distinctForEach { dict.addScore(it) } } result += dict.calculate(3) } return result } Runner.run(::part2, 70) }
1
Kotlin
0
0
ab63e6cd53746e68713ddfffd65dd25408d5d488
1,260
advent-of-code
Apache License 2.0
src/Day01.kt
kuolemax
573,740,719
false
{"Kotlin": 21104}
fun main() { fun countPerCalories(input: List<String>): MutableList<Int> { val arr = mutableListOf<Int>() var index = 0 var newStart = 0 val lines = input.iterator() while (lines.hasNext()) { val next = lines.next() if (next.isNotBlank()) { // 连续的值,累加 if (index == newStart) { arr.add(next.toInt()) } else { arr[index] = arr[index] + next.toInt() } newStart++ } else { // 空行,重新累加 index++ newStart = index } } return arr } fun part1(input: List<String>): Int { val arr = countPerCalories(input) return arr.max() } fun part2(input: List<String>): Int { val calories = countPerCalories(input) calories.sortDescending() return calories.subList(0, 3).sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") check(part1(testInput) == 24000) check(part2(testInput) == 45000) val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
3045f307e24b6ca557b84dac18197334b8a8a9bf
1,302
aoc2022--kotlin
Apache License 2.0
src/main/kotlin/days/Day13.kt
mir47
318,882,845
false
null
package days class Day13 : Day(13) { private val schedule = inputList[1].split(',').map { if (it == "x") -1 else it.toInt() } override fun partOne(): Any { val arrival = inputList[0].toInt() val result = schedule .filter { it != -1 } .map { Pair(it, arrival + it - (arrival % it)) } .minByOrNull { it.second } ?: Pair(0,0) return result.first * (result.second - arrival) } override fun partTwo(): Any { val n = mutableListOf<Long>() val a = mutableListOf<Long>() for ((i, time) in schedule.withIndex()) { if (time > 0) { n.add(time.toLong()) a.add((time - i).toLong()) } } return chineseRemainder(n.toLongArray(), a.toLongArray()) } // TIL: Chinese remainder theorem, thanks to: // https://github.com/agrison/advent-of-code-2020/blob/master/src/main/kotlin/days/Day13.kt // https://rosettacode.org/wiki/Chinese_remainder_theorem#Kotlin private fun chineseRemainder(n: LongArray, a: LongArray): Long { val prod: Long = n.fold(1) { acc, i -> acc * i } var sum = 0L for (i in n.indices) { val p = prod / n[i] sum += a[i] * multInv(p, n[i]) * p } return sum % prod } /* returns x where (a * x) % b == 1 */ private fun multInv(a: Long, b: Long): Long { if (b == 1L) return 1L var aa = a var bb = b var x0 = 0L var x1 = 1L while (aa > 1) { val q = aa / bb var t = bb bb = aa % bb aa = t t = x0 x0 = x1 - q * x0 x1 = t } if (x1 < 0) x1 += b return x1 } }
0
Kotlin
0
0
4c15e214f7164523f04d4b741102a279c38e2072
1,782
advent-of-code-2020
Creative Commons Zero v1.0 Universal
src/Day14.kt
iownthegame
573,926,504
false
{"Kotlin": 68002}
import kotlin.math.max import kotlin.math.min class RockLine(val fromPoint: Position, val toPoint: Position) fun main() { fun parseMap(input: List<String>, extendsFloor: Boolean): Array<Array<Char>> { val rockLines = mutableListOf<RockLine>() var maxX: Int = 0 var maxY: Int = 0 for (line in input) { val splits = line.split(" -> ") var previousRockPoint: Position? = null for (rock in splits) { val splits2 = rock.split(",") val x = splits2.last().toInt() val y = splits2.first().toInt() maxX = max(maxX, x) maxY = max(maxY, y) val point = Position(x, y) if (previousRockPoint != null) { rockLines.add(RockLine(previousRockPoint, point)) } previousRockPoint = point } } val extendedX = if (extendsFloor) 2 else 0 val extendedY = if (extendsFloor) maxY else 0 val map = Array(maxX + 1 + extendedX) { Array(maxY + 1 + extendedY) { '.' } } for (rockLine in rockLines) { val fromPoint = rockLine.fromPoint val toPoint = rockLine.toPoint if (fromPoint.x == toPoint.x) { val i = fromPoint.x if (fromPoint.y > toPoint.y) { for (j in toPoint.y..fromPoint.y) { map[i][j] = '#' } } else { for (j in fromPoint.y..toPoint.y) { map[i][j] = '#' } } } else if (fromPoint.y == toPoint.y) { val j = fromPoint.y if (fromPoint.x > toPoint.x) { for (i in toPoint.x..fromPoint.x) { map[i][j] = '#' } } else { for (i in fromPoint.x..toPoint.x) { map[i][j] = '#' } } } else { throw Exception(" error") } } return map } fun moveSand(map: Array<Array<Char>>, sandPosition: Position, width: Int, height: Int): Position { fun canMove(position: Position): Boolean { if ((position.x in 0 until width) && (position.y in 0 until height)) { return map[position.x][position.y] == '.' } return false } val currentSandPosition = Position(sandPosition.x, sandPosition.y) while(true) { val stepDownPosition = Position(currentSandPosition.x + 1, currentSandPosition.y) val stepDownLeftPosition = Position(currentSandPosition.x + 1, currentSandPosition.y - 1) val stepDownRightPosition = Position(currentSandPosition.x + 1, currentSandPosition.y + 1) val tryPositions = arrayOf(stepDownPosition, stepDownLeftPosition, stepDownRightPosition) var moved = false for (position in tryPositions) { if (canMove(position)) { currentSandPosition.x = position.x currentSandPosition.y = position.y moved = true // println("move sand to $currentSandPosition") break } } if (!moved) { // time to rest // println("rest at $currentSandPosition") return currentSandPosition } } } fun sandReachesLowestRock(map: Array<Array<Char>>, width: Int, height: Int, position: Position): Boolean { var maxX: Int = 0 for (j in 0 until height) { for (i in width-1 downTo 0 ) { if (map[i][j] == '#') { maxX = max(maxX, i) break } } } return position.x == maxX } fun getFloorX(map: Array<Array<Char>>, width: Int, height: Int): Int { var maxX: Int = 0 for (j in 0 until height) { for (i in width-1 downTo 0 ) { if (map[i][j] == '#') { maxX = max(maxX, i) break } } } return maxX + 2 } fun printMap(map: Array<Array<Char>>, width: Int, height: Int) { // print var minX: Int = 10000 var minY: Int = 10000 var maxX: Int = 0 var maxY: Int = 0 for (i in 0 until width) { for (j in 0 until height) { if (map[i][j] == 'O' || map[i][j] == '+' ) { minY = min(minY, j) break } } for (j in (height - 1) downTo 0) { if (map[i][j] == 'O' || map[i][j] == '+' ) { maxY = max(maxY, j) break } } } for (j in 0 until height) { for (i in 0 until width) { if (map[i][j] == 'O' || map[i][j] == '+' ) { minX = min(minX, i) break } } for (i in width-1 downTo 0 ) { if (map[i][j] == 'O' || map[i][j] == '+' ) { maxX = max(maxX, i) break } } } // println("minX: $minX, maxX: $maxX, minY: $minY, maxY: $maxY") for (i in minX..maxX) { for (j in minY..maxY) { print(map[i][j]) } println() } } fun part1(input: List<String>): Int { val map = parseMap(input, false) val width = map.size val height = map[0].size var steps = 0 val sandPosition = Position(0, 500) map[sandPosition.x][sandPosition.y] = '+' while(true) { val restPosition = moveSand(map, sandPosition, width, height) map[restPosition.x][restPosition.y] = 'O' if (sandReachesLowestRock(map, width, height, restPosition)) { break } steps += 1 } // printMap(map, width, height) return steps } fun part2(input: List<String>): Int { val map = parseMap(input, true) val width = map.size val height = map[0].size var steps = 0 val sandPosition = Position(0, 500) map[sandPosition.x][sandPosition.y] = '+' val floorX = getFloorX(map, width, height) for (j in 0 until height) { map[floorX][j] = '#' } while(true) { val restPosition = moveSand(map, sandPosition, width, height) map[restPosition.x][restPosition.y] = 'O' steps += 1 if (restPosition.x == sandPosition.x && restPosition.y == sandPosition.y) { break } } // printMap(map, width, height) return steps } // test if implementation meets criteria from the description, like: val testInput = readTestInput("Day14_sample") check(part1(testInput) == 24) check(part2(testInput) == 93) val input = readTestInput("Day14") println("part 1 result: ${part1(input)}") println("part 2 result: ${part2(input)}") }
0
Kotlin
0
0
4e3d0d698669b598c639ca504d43cf8a62e30b5c
7,412
advent-of-code-2022
Apache License 2.0
semestr.06/ТРСиПВ/bellman/src/main/kotlin/bellman/graph/algorithm/plainBellmanFord.kt
justnero
43,222,066
false
null
package bellman.graph.algorithm import bellman.graph.INFINITE import bellman.graph.InputGraph import bellman.graph.PlainAdjacency import bellman.graph.PlainAdjacencyList import bellman.graph.Util.AdjacencyMatrixUtil.toPlainAdjacencyList import bellman.graph.Util.PlainAdjacencyListUtil.edgeNumber import bellman.graph.Util.PlainAdjacencyListUtil.get fun bellmanFord(graph: InputGraph) = with(graph) { bellmanFord( adjacencyMatrix.toPlainAdjacencyList(), sourceVertex, vertexNumber) } fun bellmanFord(plainAdjacencyList: PlainAdjacencyList, sourceVertex: Int, vertexNumber: Int): IntArray = IntArray(vertexNumber, { INFINITE }) .apply { this[sourceVertex] = 0 } .apply { while (plainAdjacencyList.relaxAll(this)); } //TODO:Need optimization fun PlainAdjacencyList.relaxAll(distance: IntArray, from: Int = 0, to: Int = edgeNumber - 1) = (from..to) .map { relax(it, distance) } .onEach { if (it) return@relaxAll true } .let { false } fun PlainAdjacencyList.relax(index: Int, distance: IntArray): Boolean { val lastValue = distance[get(index, PlainAdjacency.DESTINATION)] if (distance[get(index, PlainAdjacency.SOURCE)] < INFINITE) { distance[get(index, PlainAdjacency.DESTINATION)] = minOf(distance[get(index, PlainAdjacency.DESTINATION)].toLong(), distance[get(index, PlainAdjacency.SOURCE)].toLong() + get(index, PlainAdjacency.WEIGHT)) .toInt() } val isRelaxed = lastValue != distance[get(index, PlainAdjacency.DESTINATION)] return isRelaxed }
0
Java
6
16
14f58f135e57475b98826c4128b2b880b6a2cb9a
1,746
university
MIT License
2023/src/main/kotlin/net/daams/solutions/8b.kt
Michiel-Daams
573,040,288
false
{"Kotlin": 39925, "Nim": 34690}
package net.daams.solutions import net.daams.Solution class `8b`(input: String): Solution(input) { override fun run() { val splitInput = input.split("\n") val directions = splitInput.first() val elements = splitInput.subList(2, splitInput.size).map { Element(it.split(" = ")[0]) } elements.forEachIndexed { index, element -> val connectedElements = splitInput[index + 2].split(" = ")[1].replace("""[()]""".toRegex(), "").split(", ") element.left = elements.find { it.value == connectedElements[0] }!! element.right = elements.find { it.value == connectedElements[1] }!! } val currentElements = elements.filter { it.value.endsWith("A") } val loopLengths = mutableListOf<Long>() currentElements.forEach { var loop = true var currentElement = it var stepCounter: Long = 0 while (loop) { for (i in 0 .. directions.lastIndex) { currentElement = if (directions[i] == 'L') currentElement.left!! else currentElement.right!! stepCounter++ if (currentElement.value.endsWith("Z")) { loop = false break } } } loopLengths.add(stepCounter) } var lowestLoop: Long = loopLengths[0] for (i in 1 .. loopLengths.lastIndex) { lowestLoop = lcm(lowestLoop, loopLengths[i]) } println(lowestLoop) } private fun gcd(a: Long, b: Long): Long { return if (a == 0.toLong()) b else gcd(b % a, a) } private fun lcm(a: Long, b: Long): Long { return (a / gcd(a, b)) * b } }
0
Kotlin
0
0
f7b2e020f23ec0e5ecaeb97885f6521f7a903238
1,771
advent-of-code
MIT License
src/Day08.kt
maewCP
579,203,172
false
{"Kotlin": 59412}
fun main() { val verbose = false fun part1(input: List<String>): Int { var result = 0 val trees = mutableListOf<MutableList<Pair<Int, Boolean>>>() input.forEach { line -> val treeRow = mutableListOf<Pair<Int, Boolean>>() line.toList().forEach { height -> treeRow.add(Pair(height.toString().toInt(), false)) } trees.add(treeRow) } (0 until trees.size).forEach { i -> var maxHeight = -1 (0 until trees[i].size).forEach { j -> if (trees[i][j].first > maxHeight) { trees[i][j] = Pair(trees[i][j].first, true) } maxHeight = maxHeight.coerceAtLeast(trees[i][j].first) } maxHeight = -1 (0 until trees[i].size).reversed().forEach { j -> if (trees[i][j].first > maxHeight) { trees[i][j] = Pair(trees[i][j].first, true) } maxHeight = maxHeight.coerceAtLeast(trees[i][j].first) } } (0 until trees[0].size).forEach { j -> var maxHeight = -1 (0 until trees.size).forEach { i -> if (trees[i][j].first > maxHeight) { trees[i][j] = Pair(trees[i][j].first, true) } maxHeight = maxHeight.coerceAtLeast(trees[i][j].first) } maxHeight = -1 (0 until trees.size).reversed().forEach { i -> if (trees[i][j].first > maxHeight) { trees[i][j] = Pair(trees[i][j].first, true) } maxHeight = maxHeight.coerceAtLeast(trees[i][j].first) } } trees.forEach { row -> row.forEach { tree -> if (verbose) print(if (tree.second) "1" else "0") if (tree.second) result++ } if (verbose) println() } return result } fun part2(input: List<String>): Int { var result = 0 val trees = mutableListOf<MutableList<Pair<Int, Int>>>() input.forEach { line -> val treeRow = mutableListOf<Pair<Int, Int>>() line.toList().forEach { height -> treeRow.add(Pair(height.toString().toInt(), 0)) } trees.add(treeRow) } (0 until trees.size).forEach { i -> (0 until trees[i].size).forEach { j -> var u = 0 var d = 0 var l = 0 var r = 0 if (i > 0) run breakFor@{ (i - 1 downTo 0).forEach { a -> u++ if (trees[a][j].first >= trees[i][j].first) return@breakFor } } if (i < trees.size - 1) run breakFor@{ (i + 1 until trees.size).forEach { a -> d++ if (trees[a][j].first >= trees[i][j].first) return@breakFor } } if (j > 0) run breakFor@{ (j - 1 downTo 0).forEach { a -> l++ if (trees[i][a].first >= trees[i][j].first) return@breakFor } } if (j < trees[0].size - 1) run breakFor@{ (j + 1 until trees[0].size).forEach { a -> r++ if (trees[i][a].first >= trees[i][j].first) return@breakFor } } if (verbose) println("[$i][$j] U$u D$d L$l R$r") trees[i][j] = Pair(trees[i][j].first, u * d * l * r) } } trees.forEach { row -> row.forEach { tree -> if (verbose) print("[" + tree.second + "]") result = result.coerceAtLeast(tree.second) } if (verbose) println() } return result } // test if implementation meets criteria from the description, like: val testInput = readInput("Day08_test") check(part1(testInput) == 21) check(part2(testInput) == 8) val input = readInput("Day08") part1(input).println() part2(input).println() }
0
Kotlin
0
0
8924a6d913e2c15876c52acd2e1dc986cd162693
4,351
advent-of-code-2022-kotlin
Apache License 2.0
src/main/kotlin/leetcode/dynamic/word_break/WordBreak.kt
Pawlllosss
526,668,214
false
{"Kotlin": 61939}
package leetcode.dynamic.word_break import trie.structure.Trie fun main() { println(wordBreak("leetcode", listOf("leet", "code"))) println(wordBreakWithTrie("leetcode", listOf("leet", "code"))) } fun wordBreak(s: String, wordDict: List<String>): Boolean { val wordBreakMatch = BooleanArray(s.length) for (index in s.indices) { for (word in wordDict) { if ((isFirstString(index, word) || isPreviousSubstringMatching( index, word, wordBreakMatch )) && containsWordDictInSubstring(s, index, word) ) { wordBreakMatch[index] = true break } } } return wordBreakMatch.last() } fun isFirstString(index: Int, word: String): Boolean = (index - word.length) < 0 fun isPreviousSubstringMatching(index: Int, word: String, wordBreakMatch: BooleanArray): Boolean = wordBreakMatch[index - word.length] fun containsWordDictInSubstring(s: String, index: Int, word: String): Boolean { val startIndex = index - word.length + 1 if (startIndex < 0) { return false } val substring = s.substring(startIndex, index + 1) return substring == word } // time limit exceeded for some of cases fun wordBreakWithTrie(s: String, wordDict: List<String>): Boolean { val prefixTree = buildPrefixTree(wordDict) return prefixTree.matchesPrefixes(s) } fun buildPrefixTree(wordDict: List<String>): Trie { val trie = Trie(Trie.Node(' ', true, HashMap())) wordDict.forEach(trie::getOrAddChild) return trie }
0
Kotlin
0
0
94ad00ca3e3e8ab7a2cb46f8846196ae7c55c8b4
1,615
Kotlin-algorithms
MIT License
tasks-3/lib/src/main/kotlin/flows/algo/Scaling.kt
AzimMuradov
472,473,231
false
{"Kotlin": 127576}
package flows.algo import flows.structures.Matrix import flows.structures.Network import kotlin.math.* /** * The Flow Scaling Algorithm. */ public fun <V> Network<V>.calculateMaxflowByScaling(): UInt { var maxflow = 0u val residualNetworkCapacities = Matrix.empty(keys = graph.vertices, noValue = 0u).apply { for ((v, u, cap) in graph.edges) { set(v, u, cap) } } var scale = 2.0.pow(floor(log2(graph.edges.maxOf { it.value }.toDouble()))).toUInt() while (scale >= 1u) { while (true) { val path = bfs(residualNetworkCapacities, scale) val augFlow = path.minOfOrNull { (v, p) -> residualNetworkCapacities[p, v] } ?: break maxflow += augFlow for ((v, p) in path) { residualNetworkCapacities[p, v] -= augFlow residualNetworkCapacities[v, p] += augFlow } } scale /= 2u } return maxflow } private fun <V> Network<V>.bfs( residualNetworkCapacities: Matrix<V, UInt>, minCap: UInt, ): Sequence<Pair<V, V>> { val parents: MutableMap<V, V?> = graph.vertices.associateWithTo(mutableMapOf()) { null } val isVisited = graph.vertices.associateWithTo(mutableMapOf()) { false }.apply { set(source, true) } val deque = ArrayDeque<V>().apply { add(source) } while (deque.isNotEmpty()) { val v = deque.removeLast() for ((u, cap) in residualNetworkCapacities[v]) { if (!isVisited.getValue(u) && cap >= minCap) { parents[u] = v if (u != sink) { isVisited[u] = true deque.add(u) } else { break } } } } return generateSequence(sink) { v -> parents.getValue(v) }.zipWithNext() }
0
Kotlin
0
0
01c0c46df9dc32c2cc6d3efc48b3a9ee880ce799
1,870
discrete-math-spbu
Apache License 2.0
src/Day01.kt
mlidal
572,869,919
false
{"Kotlin": 20582}
fun main() { fun part1(input: List<String>): Int { val calories = mutableListOf<Int>() var calorieSum = 0 input.forEach { if (it.isNotBlank()) { calorieSum += it.toInt() } else { calories.add(calorieSum) calorieSum = 0 } } calories.add(calorieSum) return calories.max() } fun part2(input: List<String>): Int { val calories = mutableListOf<Int>() var calorieSum = 0 input.forEach { if (it.isNotBlank()) { calorieSum += it.toInt() } else { calories.add(calorieSum) calorieSum = 0 } } calories.add(calorieSum) calories.sortDescending() return calories.take(3).sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") check(part1(testInput) == 24000) check(part2(testInput) == 45000) val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
bea7801ed5398dcf86a82b633a011397a154a53d
1,136
AdventOfCode2022
Apache License 2.0
src/Day17.kt
simonbirt
574,137,905
false
{"Kotlin": 45762}
import kotlin.math.min fun main() { Day17.printSolutionIfTest(3068, 56000011) } object Day17: Day<Long, Long>(17) { private fun <T> Sequence<T>.repeat() = sequence { while (true) yieldAll(this@repeat) } private val shapes = listOf( "####", """ .#. ### .#. """.trimIndent(), """ ..# ..# ### """.trimIndent(), """ # # # # """.trimIndent(), """ ## ## """.trimIndent()) private fun parseShape(shapeDef: String): Shape{ return Shape(shapeDef.split("\n")) } class Shape(def: List<String>) { private val def = def.map { it.toList() }.reversed() private val width = def[0].length private var overlap = -3 private var x = 2 fun touchesBelow(stack: List<List<Char>>):Boolean { if (overlap < 0) return false //for (i in 0 .. overlap) { // compare top of stack to bottom of shape, overlapped by rows val rowsToCompare = min(overlap+1, def.size) if (compareRows(stack.subList(stack.lastIndex - overlap, stack.lastIndex - overlap + rowsToCompare), def.subList(0, rowsToCompare))) return true //} return false } private fun compareRows(base: List<List<Char>>, shape: List<List<Char>>): Boolean { shape.forEachIndexed{index, value -> if (compareRow(base[index], value)) return true} return false } private fun compareRow(base: List<Char>, shape: List<Char>):Boolean{ shape.forEachIndexed{ index, value -> if (base[index + x] == '#' && value == '#') return true} return false } fun move(dir: Char, stack: List<List<Char>>) { x = when(dir) { '<' -> if (!isBlockedLeft(stack)) x-1 else x else -> if (!isBlockedRight(stack)) x+1 else x } //println("Move $dir to $x") } private fun isBlockedLeft(stack: List<List<Char>>): Boolean { if (x==0) return true (0 until min(overlap, def.size)).forEach{ row -> if (isBlockedLeft(def[row], stack[stack.lastIndex - (overlap-1) + row])) return true } return false } private fun isBlockedLeft(shape: List<Char>, base: List<Char>):Boolean { val shapeLeftIndex = x + shape.indexOfFirst { it == '#' } return base[shapeLeftIndex-1] == '#' } private fun isBlockedRight(stack: List<List<Char>>): Boolean { if (x==7-width) return true (0 until min(overlap, def.size)).forEach{ row -> if (isBlockedRight(def[row], stack[stack.lastIndex - (overlap-1) + row])) return true } return false } private fun isBlockedRight(shape: List<Char>, base: List<Char>):Boolean { val shapeRightIndex = x + shape.indexOfLast { it == '#' } return base[shapeRightIndex+1] == '#' } private val paddings = listOf("", ".","..","...","....",".....","......",".......").map {it.toList()} fun stamp(stack: MutableList<MutableList<Char>>):Int { val padLeft = paddings[x] val padRight = paddings[7-(x+width)] val paddedShape = def.map { l -> (padLeft + l + padRight) } val rowsToCombine = min(overlap, def.size) var index = 0 val minStackIndex = stack.lastIndex - (overlap-1) (0 until rowsToCombine).forEach{ row -> val stackIndex = minStackIndex + row combineStackRow(paddedShape[index++], stack[stackIndex]) } (index until paddedShape.size).forEach{ stack.add(paddedShape[it].toMutableList()) } return minStackIndex } private fun combineStackRow(shapeRow: List<Char>, stackRow: MutableList<Char>) { shapeRow.forEachIndexed{index, value -> if (value == '#') stackRow[index] = value} } fun reset() { x = 2 overlap = -3 } fun drop() { //println("Move down") overlap++ } } /* #### .#. ### .#. ..# ..# ### # # # # ## ## */ override fun part1(lines: List<String>):Long = solve(lines, 2022L) private fun solve(lines: List<String>, count: Long): Long { val shapeSeq = shapes.map { parseShape(it) }.asSequence().repeat().iterator() val directions = lines[0].asSequence().repeat().asIterable().iterator() val stack = mutableListOf("#######".toMutableList()) var stackSize = 0L (1..count).forEach { stackSize += drop(shapeSeq, directions, stack) if (it%100000 == 0L){ println(it) } } stackSize += stack.size return stackSize - 1 } private fun drop (shapes: Iterator<Shape>, directions: Iterator<Char>, stack: MutableList<MutableList<Char>>):Int { val shape = shapes.next() while (true) { shape.move(directions.next(), stack) if(shape.touchesBelow(stack)){ break } else { shape.drop() } } val minIndex = shape.stamp(stack) var test=0 (minIndex..min(minIndex+3, stack.lastIndex)).forEach{ stack[it].forEachIndexed{index, c -> if (c == '#') test = test or (1 shl index) } } shape.reset() if (test == 0b1111111){ stack.subList(0, minIndex).clear() return minIndex } return 0 } override fun part2(lines: List<String>) = solve(lines, 1_000_000_000_000L) }
0
Kotlin
0
0
962eccac0ab5fc11c86396fc5427e9a30c7cd5fd
5,932
advent-of-code-2022
Apache License 2.0
ASCII Text Signature/task/test/Authors.kt
Perl99
273,730,854
false
null
import java.util.* private class Letter( val rows: List<String> ) { init { if (rows.distinctBy { it.length }.size != 1) { throw IllegalStateException("Bad letter. Not equal width in lines: ${rows.distinctBy { it.length }}") } } val width get() = rows[0].length val height get() = rows.size } private class Font( val charsToLetters: MutableMap<Char, Letter>, val height: Int ) { operator fun get(char: Char) = charsToLetters[char] } private fun makeLetters(fontStr: String): Font { val scanner = Scanner(fontStr) val h = scanner.nextInt() val n = scanner.nextInt() val charsToLetters = mutableMapOf<Char, Letter>() repeat(n) { val char = scanner.next()[0] val w = scanner.nextInt() scanner.nextLine() val rows = mutableListOf<String>() repeat(h) { rows += scanner.nextLine().trimEnd('\n') } charsToLetters[char] = Letter(rows) } val letterA = charsToLetters['a']!! charsToLetters[' '] = Letter(List(letterA.height) { " ".repeat(letterA.width) }) return Font(charsToLetters, h) } /** Wrap with eights. */ fun framed(lines: List<String>): String { val builder = StringBuilder() builder.append("8".repeat(lines[0].length + 8) + "\n") lines.forEach { line -> builder.append("88 $line 88\n") } builder.append("8".repeat(lines[0].length + 8)) return builder.toString() } private fun centeredLines(lines: List<String>): List<String> { val maxLen = lines.map { it.length }.max()!! return lines.map { line -> val need = maxLen - line.length " ".repeat(need / 2) + line + " ".repeat((need + 1) / 2) } } fun authors(input: String): String { val roman = makeLetters(romanFontStr) val medium = makeLetters(mediumFontStr) val scanner = Scanner(input) val name = scanner.next() + " " + scanner.next() scanner.nextLine() val status = scanner.nextLine() val nameLetters = name.map { roman[it] ?: throw IllegalArgumentException("unknown letter $it in roman font") } val statusLetters = status.map { medium[it] ?: throw IllegalArgumentException("unknown letter $it in medium font") } val lines = mutableListOf<String>() repeat(roman.height) { i -> lines += nameLetters.map { it.rows[i] }.joinToString("") } repeat(medium.height) { i -> lines += statusLetters.map { it.rows[i] }.joinToString("") } return framed(centeredLines(lines)) }
0
Kotlin
0
0
4afb085918697c41a5722f50e8a7bb65fcab0854
2,569
hyperskill-kotlin-ascii-text-signature
MIT License
src/year2022/day12/Solution.kt
TheSunshinator
572,121,335
false
{"Kotlin": 144661}
package year2022.day12 import io.kotest.matchers.shouldBe import utils.MapDetails import utils.detailsSequence import utils.findShortestRoute import utils.readInput fun main() { val testInput = readInput("12", "test_input").map(String::toList) val realInput = readInput("12", "input").map(String::toList) findShortestRoute( map = testInput, start = testInput.detailsSequence().first { it.value == 'S' }.position, end = testInput.detailsSequence().first { it.value == 'E' }.position, movementCost = ::movementCost, )!!.cost .also(::println) shouldBe 31 findShortestRoute( map = realInput, start = realInput.detailsSequence().first { it.value == 'S' }.position, end = realInput.detailsSequence().first { it.value == 'E' }.position, movementCost = ::movementCost, )!!.cost .let(::println) testInput.detailsSequence() .filter { it.value.adjustedValue == 'a' } .map { start -> findShortestRoute( map = testInput, start = start.position, end = testInput.detailsSequence().first { it.value == 'E' }.position, movementCost = ::movementCost, )?.cost } .filterNotNull() .min() .also(::println) shouldBe 29 realInput.detailsSequence() .filter { it.value.adjustedValue == 'a' } .map { start -> findShortestRoute( map = realInput, start = start.position, end = realInput.detailsSequence().first { it.value == 'E' }.position, movementCost = ::movementCost, )?.cost } .filterNotNull() .min() .let(::println) } private fun movementCost(start: MapDetails<Char>, end: MapDetails<Char>): Int? { val startValue = start.value.adjustedValue val endValue = end.value.adjustedValue return when { endValue - startValue <= 1 -> 1 else -> null } } private val Char.adjustedValue get() = when (this) { 'E' -> 'z' 'S' -> 'a' else -> this }
0
Kotlin
0
0
d050e86fa5591447f4dd38816877b475fba512d0
2,166
Advent-of-Code
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/UniquePaths.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2023 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode /** * 62. Unique Paths * @see <a href="https://leetcode.com/problems/unique-paths">Source</a> */ fun interface UniquePaths { operator fun invoke(m: Int, n: Int): Int } /** * Approach 1: Brute-Force */ class UniquePathsBruteForce : UniquePaths { override fun invoke(m: Int, n: Int): Int { return perform(m, n, 0, 0) } /** * Calculate the number of unique paths from the top-left corner (0,0) to the * bottom-right corner (m-1, n-1) in a grid of size m x n. * * @param m The number of rows in the grid. * @param n The number of columns in the grid. * @param i The current row index. * @param j The current column index. * @return The number of unique paths from (0,0) to (m-1, n-1). */ private fun perform(m: Int, n: Int, i: Int = 0, j: Int = 0): Int { // base case: If the current position is out of bounds, there is no path. if (i >= m || j >= n) return 0 // base case: If we have reached the destination, there is one unique path. if (i == m - 1 && j == n - 1) return 1 // recursive case: Sum the paths going right and down from the current position. return perform(m, n, i + 1, j) + perform(m, n, i, j + 1) } } /** * Approach 2: Dynamic Programming - Memoization */ class UniquePathsDpMemo : UniquePaths { /** * Calculate the number of unique paths from the top-left corner (0,0) to the * bottom-right corner (m-1, n-1) in a grid of size m x n using memoization. * * @param m The number of rows in the grid. * @param n The number of columns in the grid. * @return The number of unique paths from (0,0) to (m-1, n-1). */ override fun invoke(m: Int, n: Int): Int { // Create a HashMap to memoize results. val memo = HashMap<Pair<Int, Int>, Int>() /** * Recursive function to find unique paths. * * @param i The current row index. * @param j The current column index. * @return The number of unique paths from (i, j) to (m-1, n-1). */ fun dfs(i: Int, j: Int): Int { if (i >= m || j >= n) return 0 if (i == m - 1 && j == n - 1) return 1 // Check if the result for this cell is already memoized. if (memo.containsKey(Pair(i, j))) { return memo[Pair(i, j)]!! } // Calculate the number of paths recursively. val paths = dfs(i + 1, j) + dfs(i, j + 1) // Memoize the result before returning. memo[Pair(i, j)] = paths return paths } // Start the calculation from the top-left corner (0,0). return dfs(0, 0) } } /** * Approach 3: Dynamic Programming - Tabulation */ class UniquePathsDpTabulation : UniquePaths { override fun invoke(m: Int, n: Int): Int { if (m == 0 && n == 0) return 0 // Create a 2D array to store the number of unique paths for each cell. val dp = Array(m) { IntArray(n) { 1 } } // Calculate the number of unique paths using dynamic programming. for (i in 1 until m) { for (j in 1 until n) { dp[i][j] = dp[i - 1][j] + dp[i][j - 1] } } // The result is stored in the bottom-right corner of the grid. return dp[m - 1][n - 1] } } /** * Approach 4: Space Optimized Dynamic Programming */ class UniquePathsDpOpt : UniquePaths { override fun invoke(m: Int, n: Int): Int { if (m == 0 && n == 0) return 0 // Create an array to store the number of unique paths for each column. val dp = IntArray(n) { 1 } // Calculate the number of unique paths using dynamic programming. for (i in 1 until m) { for (j in 1 until n) { dp[j] += dp[j - 1] } } // The result is stored in the last column of the array. return dp[n - 1] } } /** * Approach 5: Math */ class UniquePathsMath : UniquePaths { override fun invoke(m: Int, n: Int): Int { if (m == 0 && n == 0) return 0 var ans = 1 var i = m + n - 2 var j = 1 while (i >= maxOf(m, n)) { ans = ans * i / j i-- j++ } return ans } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
4,982
kotlab
Apache License 2.0
src/Day01.kt
Kbzinho-66
572,299,619
false
{"Kotlin": 34500}
fun main() { fun part1(calories: List<Int>): Int { return calories[0] } fun part2(calories: List<Int>): Int { return calories.slice(0..2).sum() } fun getCalories(input: List<String>): List<Int> { var carried = 0 val caloriesPerElf: MutableList<Int> = mutableListOf() val it: ListIterator<String> = input.listIterator() while (it.hasNext()) { val cal = it.next() if (cal.isNotEmpty()) carried += cal.toInt() // Esses ifs tão separados pra pegar o último número do arquivo if (cal.isEmpty() || !it.hasNext()) { caloriesPerElf.add(carried) carried = 0 } } return caloriesPerElf.sortedDescending() } // Testar os casos básicos val testInput = readInput("../inputs/Day01_test") val testCalories = getCalories(testInput) sanityCheck(part1(testCalories), 24000) sanityCheck(part2(testCalories), 45000) val input = readInput("../inputs/Day01") val caloriesPerElf = getCalories(input) println("Parte 1 = ${part1(caloriesPerElf)}") println("Parte 2 = ${part2(caloriesPerElf)}") }
0
Kotlin
0
0
e7ce3ba9b56c44aa4404229b94a422fc62ca2a2b
1,197
advent_of_code_2022_kotlin
Apache License 2.0
kotlin/0662-maximum-width-of-binary-tree.kt
neetcode-gh
331,360,188
false
{"JavaScript": 473974, "Kotlin": 418778, "Java": 372274, "C++": 353616, "C": 254169, "Python": 207536, "C#": 188620, "Rust": 155910, "TypeScript": 144641, "Go": 131749, "Swift": 111061, "Ruby": 44099, "Scala": 26287, "Dart": 9750}
/** * Example: * var ti = TreeNode(5) * var v = ti.`val` * Definition for a binary tree node. * class TreeNode(var `val`: Int) { * var left: TreeNode? = null * var right: TreeNode? = null * } */ /* * BFS solution */ class Solution { fun widthOfBinaryTree(root: TreeNode?): Int { root?: return 0 val q = ArrayDeque<Triple<TreeNode?, Int, Int>>() var res = 0 var prevLevel = 0 var prevNum = 1 q.add(Triple(root, 1, 0)) while (q.isNotEmpty()) { val (node, num, level) = q.poll() if (level > prevLevel) { prevLevel = level prevNum = num } res = maxOf(res, num - prevNum + 1) node?.left?.let { q.add(Triple(node.left, 2 * num, level + 1)) } node?.right?.let { q.add(Triple(node.right, 2 * num + 1, level + 1)) } } return res } } /* * DFS solution */ class Solution { fun widthOfBinaryTree(root: TreeNode?): Int { var width = 0 val levelMap = HashMap<Int, Int>() fun dfs(node: TreeNode?, depth: Int, pos: Int, levelMap: HashMap<Int, Int>) { node?: return if(!levelMap.contains(depth)) levelMap[depth] = pos width = maxOf(width, (pos - levelMap[depth]!! + 1)) dfs(node.left, depth+1, 2*pos, levelMap) dfs(node.right, depth+1, 2*pos+1, levelMap) } dfs(root, 0, 0, levelMap) return width } }
337
JavaScript
2,004
4,367
0cf38f0d05cd76f9e96f08da22e063353af86224
1,623
leetcode
MIT License
src/main/kotlin/com/sk/topicWise/tree/medium/2385. Amount of Time for Binary Tree to Be Infected.kt
sandeep549
262,513,267
false
{"Kotlin": 530613}
package com.sk.topicWise.tree.medium import com.sk.topicWise.tree.TreeNode import kotlin.collections.ArrayDeque import kotlin.collections.HashMap class Solution2385 { fun amountOfTime(root: TreeNode?, start: Int): Int { var amount = 0 // if subtree does not contain infected node, return maximum depth // if subtree contains infected node, return infected node depth (use negative value to distinguish this case) fun traverse(root: TreeNode?, start: Int): Int { if (root == null) { return 0 } val left = traverse(root.left, start) val right = traverse(root.right, start) return if (root.`val` == start) { // we are at the initially infected node // use maximum subtree depth as the initial amount value amount = maxOf(left, right) -1 } else if (left >= 0 && right >= 0) { // this subtree does not contain infected node // return maximum subtree depth for further calculations maxOf(left, right) + 1 } else { // one of the subtrees contains initially infected node // sum depth of initially infected node (negative value) and max depth of the other subtree (positive value) amount = maxOf(amount, Math.abs(left - right)) minOf(left, right) - 1 } } traverse(root, start) return amount } fun amountOfTime2(root: TreeNode?, start: Int): Int { val adjMap = HashMap<Int, MutableList<Int>>() //adjacency list fun createGraph(root: TreeNode?, parent: Int) { if (root == null) return val child = root.`val` if (parent != -1) { adjMap.getOrPut(parent) { mutableListOf() }.add(child) adjMap.getOrPut(child) { mutableListOf() }.add(parent) } createGraph(root.left, child) createGraph(root.right, child) } createGraph(root, -1) val queue = ArrayDeque<Int>() queue.add(start) val seen = HashSet<Int>() seen.add(start) var time = 0 while (queue.isNotEmpty()) { var n = queue.size while (n-- > 0) { val node = queue.removeFirst() adjMap[node]?.forEach { neighbour -> if (!seen.contains(neighbour)) { queue.add(neighbour) seen.add(neighbour) } } // why below code section throw error on LC ? // for (neighbour in adjMap[node]!!) { // if (!seen.contains(neighbour)) { // queue.add(neighbour) // seen.add(neighbour) // } // } } time++ } return time - 1 } } fun main() { val s = Solution2385() val root = TreeNode(1) root.left = TreeNode(5) root.left!!.right = TreeNode(4) root.left!!.right!!.left = TreeNode(9) root.left!!.right!!.right = TreeNode(2) root.right = TreeNode(3) root.right!!.left = TreeNode(10) root.right!!.right = TreeNode(6) println(s.amountOfTime2(root, 3)) }
1
Kotlin
0
0
cf357cdaaab2609de64a0e8ee9d9b5168c69ac12
3,372
leetcode-kotlin
Apache License 2.0
src/main/java/me/olegthelilfix/leetcoding/old/IntegerToRoman.kt
olegthelilfix
300,408,727
false
null
package me.olegthelilfix.leetcoding.old data class RomanNumber(val letter: String, val value: Int) val numberOrder : List<RomanNumber> = listOf( RomanNumber("M", 1000), RomanNumber("CM", 900), RomanNumber("D", 500), RomanNumber("CD", 400), RomanNumber("C", 100), RomanNumber("XC", 90), RomanNumber("L", 50), RomanNumber("XL", 40), RomanNumber("X", 10), RomanNumber("IX", 9), RomanNumber("V", 5), RomanNumber("IV", 4), RomanNumber("I", 1), ) fun intToRoman(num: Int): String { var result = "" var buffer = num var letterIndex = 0 var romanNumber = numberOrder[letterIndex++] while (buffer > 0) { if((buffer - romanNumber.value) < 0) { romanNumber = numberOrder[letterIndex++] } else { buffer -= romanNumber.value result += romanNumber.letter } } return result } val letters = mapOf( "M" to 1000, "CM" to 900, "D" to 500, "CD" to 400, "C" to 100, "XC" to 90, "L" to 50, "XL" to 40, "X" to 10, "IX" to 9, "V" to 5, "IV" to 4, "I" to 1 ) fun romanToInt(s: String): Int { var i = 0 var result = 0 while (i < s.length) { val l1 = letters[s[i].toString()] ?: 0 var l2 = 0 if (i < s.length - 1 && letters.containsKey(s[i].toString() + s[i+1].toString())) { l2 = letters[s[i].toString() + s[i+1].toString()] ?: 0 i++ } result += if (l1 > l2) l1 else l2 i++ } return result } fun main() { println(romanToInt("IV")) for (i in 1 .. 10000) { val n = intToRoman(i) val n2 = romanToInt(n) if (n2 != i) { println("$i!=$n2") } } }
0
Kotlin
0
0
bf17d2f6915b7a491d93f57f8e7461adda7029c0
1,880
MyKata
MIT License
src/test/kotlin/nl/dirkgroot/adventofcode/year2022/Day16Test.kt
dirkgroot
317,968,017
false
{"Kotlin": 187862}
package nl.dirkgroot.adventofcode.year2022 import io.kotest.core.spec.style.StringSpec import io.kotest.matchers.shouldBe import nl.dirkgroot.adventofcode.util.input import nl.dirkgroot.adventofcode.util.invokedWith import java.util.* private fun solution1(input: String) = parse(input).maxPressureRelease() private fun solution2(input: String) = parse(input).maxPressureRelease2() private fun Map<String, Valve>.maxPressureRelease(): Int { val cache = mutableMapOf<String, Int>() fun analyze(remaining: Set<String>, current: String, minutesPassed: Int, pressure: Int): Int { return if (remaining.isEmpty()) pressure else remaining.maxOf { next -> val minutesToOpen = cache.getOrPut(current + next) { walkingTime(this, current, next) + 1 } if (minutesToOpen + minutesPassed >= 30) pressure else { val nextReleases = (30 - minutesPassed - minutesToOpen) * getValue(next).flowRate analyze(remaining - next, next, minutesPassed + minutesToOpen, pressure + nextReleases) } } } val withFlowRate = filter { (_, valve) -> valve.flowRate > 0 } return analyze(withFlowRate.keys, "AA", 0, 0) } private fun Map<String, Valve>.maxPressureRelease2(): Int { val cache = mutableMapOf<String, Int>() val cache2 = mutableMapOf<String, Int>() val withFlowRate = filter { (_, valve) -> valve.flowRate > 0 } fun analyze(remaining: Set<String>, current: String, minutesPassed: Int, resetAt: Int): Int { return if (remaining.isEmpty()) 0 else remaining.maxOf { next -> val minutesToOpen = cache.getOrPut(current + next) { walkingTime(this, current, next) + 1 } if (minutesToOpen + minutesPassed >= 26) 0 else { val nextReleases = (26 - minutesPassed - minutesToOpen) * getValue(next).flowRate nextReleases + if (remaining.size - 1 == resetAt) { val key = (remaining - next).sorted().joinToString("") + "AA" + "0" cache2.getOrPut(key) { analyze(remaining - next, "AA", 0, resetAt) } } else { val key = (remaining - next).sorted().joinToString("") + next + (minutesPassed + minutesToOpen) cache2.getOrPut(key) { analyze(remaining - next, next, minutesPassed + minutesToOpen, resetAt) } } } } } return (1 until withFlowRate.size).maxOf { resetAt -> cache2.clear() analyze(withFlowRate.keys, "AA", 0, resetAt) } } private const val INFINITY = 100000000 private fun walkingTime(valves: Map<String, Valve>, start: String, end: String): Int { val dist = mutableMapOf<String, Int>() val prev = mutableMapOf<String, String>() val q = PriorityQueue<String> { o1, o2 -> dist.getValue(o1).compareTo(dist.getValue(o2)) } valves.keys.forEach { dist[it] = INFINITY } dist[start] = 0 q.add(start) while (q.isNotEmpty()) { val u = q.poll() if (u == end || dist[u] == INFINITY) break valves.getValue(u).tunnelsTo.forEach { v -> val alt = dist.getValue(u) + 1 if (alt < dist.getValue(v)) { dist[v] = alt prev[v] = u q.add(v) } } } return dist.getValue(end) } private fun parse(input: String) = input.lineSequence().map { line -> val match = "Valve ([A-Z]{2}) has flow rate=(\\d+); tunnels? leads? to valves? (.*)".toRegex().matchEntire(line) ?: throw IllegalStateException() Valve(match.groupValues[1], match.groupValues[2].toInt(), match.groupValues[3].split(", ")) }.map { it.name to it }.toMap() private data class Valve(val name: String, val flowRate: Int, val tunnelsTo: List<String>) //===============================================================================================\\ private const val YEAR = 2022 private const val DAY = 16 class Day16Test : StringSpec({ "example part 1" { ::solution1 invokedWith exampleInput shouldBe 1651 } "part 1 solution" { ::solution1 invokedWith input(YEAR, DAY) shouldBe 1724 } "example part 2" { ::solution2 invokedWith exampleInput shouldBe 1707 } "part 2 solution" { ::solution2 invokedWith input(YEAR, DAY) shouldBe 2283 } }) private val exampleInput = """ Valve AA has flow rate=0; tunnels lead to valves DD, II, BB Valve BB has flow rate=13; tunnels lead to valves CC, AA Valve CC has flow rate=2; tunnels lead to valves DD, BB Valve DD has flow rate=20; tunnels lead to valves CC, AA, EE Valve EE has flow rate=3; tunnels lead to valves FF, DD Valve FF has flow rate=0; tunnels lead to valves EE, GG Valve GG has flow rate=0; tunnels lead to valves FF, HH Valve HH has flow rate=22; tunnel leads to valve GG Valve II has flow rate=0; tunnels lead to valves AA, JJ Valve JJ has flow rate=21; tunnel leads to valve II """.trimIndent()
1
Kotlin
1
1
ffdffedc8659aa3deea3216d6a9a1fd4e02ec128
5,145
adventofcode-kotlin
MIT License
src/main/kotlin/d11/D11_1.kt
MTender
734,007,442
false
{"Kotlin": 108628}
package d11 import input.Input import kotlin.math.abs fun expandUniverse(universe: List<String>): List<String> { var expanded = universe.map { "" }.toMutableList() // expand columns for (colI in universe[0].indices) { val col = universe.map { it[colI] }.joinToString("") expanded = if (col.any { it == '#' }) { expanded .mapIndexed { index, row -> row + universe[index][colI] } .toMutableList() } else { expanded .mapIndexed { index, row -> row + universe[index][colI] + universe[index][colI] } .toMutableList() } } // expand rows for (rowI in universe.lastIndex downTo 0) { val row = universe[rowI] if (row.all { it == '.' }) { expanded.add(rowI, expanded[rowI]) } } return expanded } fun findDistance(g1: Galaxy, g2: Galaxy): Int { val loc1 = g1.loc val loc2 = g2.loc return abs(loc1.first - loc2.first) + abs(loc1.second - loc2.second) } fun main() { val lines = Input.read("input.txt") val universe = expandUniverse(lines) val galaxies = findGalaxies(universe) val pairs = findPairs(galaxies) var sum = 0 pairs.forEach { sum += findDistance(it.first, it.second) } println(sum) }
0
Kotlin
0
0
a6eec4168b4a98b73d4496c9d610854a0165dbeb
1,332
aoc2023-kotlin
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/LongestIncreasingSubsequence.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 /** * 300. Longest Increasing Subsequence * https://leetcode.com/problems/longest-increasing-subsequence/ */ sealed interface LongestIncreasingSubsequence { operator fun invoke(nums: IntArray): Int /** * Approach 1: Dynamic Programming */ data object DynamicProgramming : LongestIncreasingSubsequence { override operator fun invoke(nums: IntArray): Int { val dp = IntArray(nums.size) { 1 } for (i in 1 until nums.size) { for (j in 0 until i) { if (nums[i] > nums[j]) { dp[i] = max(dp[i], dp[j] + 1) } } } var longest = 0 for (c in dp) { longest = max(longest, c) } return longest } } /** * Approach 2: Intelligently Build a Subsequence */ data object BuildSubsequence : LongestIncreasingSubsequence { override operator fun invoke(nums: IntArray): Int { val sub = ArrayList<Int>() if (nums.isNotEmpty()) { sub.add(nums[0]) } else { return 0 } for (i in 1 until nums.size) { val num = nums[i] if (num > sub[sub.size - 1]) { sub.add(num) } else { // Find the first element in sub that is greater than or equal to num var j = 0 while (num > sub[j]) { j += 1 } sub[j] = num } } return sub.size } } /** * Approach 3: Improve With Binary Search */ data object BinarySearch : LongestIncreasingSubsequence { override operator fun invoke(nums: IntArray): Int { val sub = ArrayList<Int>() if (nums.isNotEmpty()) { sub.add(nums[0]) } else { return 0 } for (i in 1 until nums.size) { val num = nums[i] if (num > sub[sub.size - 1]) { sub.add(num) } else { val j = bs(sub, num) sub[j] = num } } return sub.size } private fun bs(sub: ArrayList<Int>, num: Int): Int { var left = 0 var right = sub.size - 1 var mid: Int while (left < right) { mid = (left + right) / 2 if (sub[mid] == num) { return mid } if (sub[mid] < num) { left = mid + 1 } else { right = mid } } return left } } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
3,568
kotlab
Apache License 2.0
src/questions/CousinsBinaryTree.kt
realpacific
234,499,820
false
null
package questions import _utils.UseCommentAsDocumentation import questions.common.TreeNode import utils.shouldBe /** * Given the root of a binary tree with unique values and the values of two different nodes of the tree x and y, * return true if the nodes corresponding to the values x and y in the tree are cousins, or false otherwise. * * Two nodes of a binary tree are cousins if they have the same depth with different parents. * * [Source](https://leetcode.com/problems/cousins-in-binary-tree/) */ @UseCommentAsDocumentation private fun isCousins(root: TreeNode?, x: Int, y: Int): Boolean { val yInfo = traverse(x = y, current = root, parent = null, depth = 0)!! val xInfo = traverse(x = x, current = root, parent = null, depth = 0, maxDepth = yInfo.first)!! return xInfo.first == yInfo.first // same depth && xInfo.second != null && xInfo.second != yInfo.second // different parent } private fun traverse( x: Int, current: TreeNode?, parent: TreeNode?, depth: Int, maxDepth: Int? = null ): Pair<Int, TreeNode?>? { if (current == null) { return null // NOT FOUND } if (current.`val` == x) { return Pair(depth, parent) } // It shouldn't exceed any farther than maxDepth if (maxDepth != null && depth > maxDepth) { return null } val leftTraverse = traverse(x, current = current.left, parent = current, depth = depth + 1) if (leftTraverse != null) { return leftTraverse } val rightTraverse = traverse(x, current = current.right, parent = current, depth = depth + 1) if (rightTraverse != null) { return rightTraverse } return null } fun main() { isCousins(root = TreeNode.from(arrayOf(1, 2, 3, null, 4, null, 5)), x = 5, y = 4) shouldBe true isCousins(root = TreeNode.from(1, 2, 3, 4), x = 4, y = 3) shouldBe false isCousins(root = TreeNode.from(arrayOf(1, 2, 3, null, 4)), x = 2, y = 3) shouldBe false isCousins(root = TreeNode.from(arrayOf(1, 2, 3, null, null, 4, 5)), x = 4, y = 5) shouldBe false isCousins( root = TreeNode.from( arrayOf( 1, 2, 4, 3, 19, 10, 5, 15, 8, null, null, 13, 14, null, 6, null, 17, null, null, null, null, 18, null, 7, 11, null, null, null, null, null, 9, 16, 12, null, null, 20 ) ), x = 11, y = 17 ) shouldBe true }
4
Kotlin
5
93
22eef528ef1bea9b9831178b64ff2f5b1f61a51f
2,965
algorithms
MIT License
src/main/kotlin/se/saidaspen/aoc/aoc2021/Day05.kt
saidaspen
354,930,478
false
{"Kotlin": 301372, "CSS": 530}
package se.saidaspen.aoc.aoc2021 import se.saidaspen.aoc.util.Day import se.saidaspen.aoc.util.P import se.saidaspen.aoc.util.ints import kotlin.math.sign fun main() = Day05.run() object Day05 : Day(2021, 5) { val lines = input.lines().map { ints(it) }.map { P(P(it[0], it[1]), P(it[2], it[3])) } override fun part1() = countCrosses(lines.filter { it.first.first == it.second.first || it.first.second == it.second.second }) override fun part2() = countCrosses(lines) private fun countCrosses(lines: List<P<P<Int, Int>, P<Int, Int>>>) = lines.flatMap { toPoints(it) }.groupingBy { it }.eachCount().count { it.value >= 2 } private fun toPoints(l: Pair<Pair<Int, Int>, Pair<Int, Int>>): List<P<Int, Int>> { val list = mutableListOf<P<Int, Int>>() var curr = l.first val dx = (l.second.first - l.first.first).sign val dy = (l.second.second - l.first.second).sign while (curr != l.second) { list.add(curr) curr = P(curr.first + dx, curr.second + dy) } list.add(l.second) return list } }
0
Kotlin
0
1
be120257fbce5eda9b51d3d7b63b121824c6e877
1,118
adventofkotlin
MIT License
src/aoc2022/day10/Day10.kt
svilen-ivanov
572,637,864
false
{"Kotlin": 53827}
package aoc2022.day10 import readInput import kotlin.math.abs fun main() { fun part1(input: List<String>) { var x = 1 val valByCycle = mutableListOf(x) for (line in input) { val commandLine = line.split(" ") val commandName = commandLine[0] val arg = if (commandLine.size > 1) commandLine.last().toInt() else null when (commandName) { "noop" -> { valByCycle.add(x) } "addx" -> { requireNotNull(arg) valByCycle.add(x) valByCycle.add(x) x += arg } } } val res = (0..5).map { 40 * it + 20 }.sumOf { it * valByCycle[it] } println(res) } fun printScreen(screen: MutableList<String>) { screen.forEachIndexed { index, s -> print(s) if ((index + 1) % 40 == 0) { println() } } } fun part2(input: List<String>) { var x = 1 val valByCycle = mutableListOf<Int>() for (line in input) { val commandLine = line.split(" ") val commandName = commandLine[0] val arg = if (commandLine.size > 1) commandLine.last().toInt() else null when (commandName) { "noop" -> { valByCycle.add(x) } "addx" -> { requireNotNull(arg) valByCycle.add(x) valByCycle.add(x) x += arg } } } val screen = mutableListOf<String>() val size = 40 * 6 screen.addAll((1..size).map { "." }) for ((cycle, xValue) in valByCycle.withIndex()) { val screenPos = cycle % size val xPos = cycle % 40 if (abs(xPos - xValue) <= 1) { screen[screenPos] = "*" } else { screen[screenPos] = "." } println("Cycle: $cycle, X=$xValue") println("-------------------------") printScreen(screen) println("-------------------------") } printScreen(screen) } val testInput = readInput("day10/day10") part1(testInput) part2(testInput) }
0
Kotlin
0
0
456bedb4d1082890d78490d3b730b2bb45913fe9
2,413
aoc-2022
Apache License 2.0
src/Day21.kt
janbina
112,736,606
false
null
package Day21 import getInput import kotlin.test.assertEquals fun main(args: Array<String>) { val input = getInput(21) .readLines() .map { it.split(" => ").map { it.split('/').map { it.toCharArray() }.toTypedArray() } } .map { Enhancements.Enhancement(it[0], it[1]) } .let { Enhancements(it) } val initial = arrayOf( ".#.".toCharArray(), "..#".toCharArray(), "###".toCharArray() ) assertEquals(167, generate(5, initial, input).countChars('#')) assertEquals(2425195, generate(18, initial, input).countChars('#')) } data class Enhancements(private val enhancements: List<Enhancement>) { data class Enhancement(val from: Array<CharArray>, val to: Array<CharArray>) { private val pixelsOn = from.countChars('#') fun matches(input: Array<CharArray>): Boolean { if (from.size != input.size) return false val size = from.size //center element stays always in place if (from.size == 3 && from[1][1] != input[1][1]) return false if (input.countChars('#') != pixelsOn) return false val flags = BooleanArray(8) { true } for (i in from.indices) { for (j in from.indices) { //direct match if (input[i][j] != from[i][j]) flags[0] = false //horizontal flip if (input[i][size-1-j] != from[i][j]) flags[1] = false //vertical flip if (input[size-1-i][j] != from[i][j]) flags[2] = false //rotated 90 if (input[j][size-1-i] != from[i][j]) flags[3] = false //rotated 180 if (input[size-1-i][size-1-j] != from[i][j]) flags[4] = false //rotated 270 if (input[size-1-j][i] != from[i][j]) flags[5] = false //rotated 90 and flipped vertically if (input[size-1-j][size-1-i] != from[i][j]) flags[6] = false //rotated 90 and flipped horizontally if (input[j][i] != from[i][j]) flags[7] = false } } return flags.any { it } } } fun enhance(input: Array<CharArray>): Array<CharArray> { return enhancements .first { it.matches(input) } .to } } fun generate(iterations: Int, initial: Array<CharArray>, enhancements: Enhancements): Array<CharArray> { var current = initial repeat(iterations) { val size = current.size val partSize = if (size % 2 == 0) 2 else 3 val parts = size / partSize val nextSize = parts * (partSize + 1) val next = Array(nextSize) { CharArray(nextSize) } for (i in 0 until parts) { for (j in 0 until parts) { val square = current.getSquare(i * partSize, j * partSize, partSize) val enhanced = enhancements.enhance(square) next.insertSquare(enhanced, i * (partSize + 1), j * (partSize + 1)) } } current = next } return current } fun Array<CharArray>.getSquare(i: Int, j: Int, size: Int): Array<CharArray> { val new = Array(size) { CharArray(size) } for (ix in i until i + size) { for (jx in j until j + size) { new[ix - i][jx - j] = this[ix][jx] } } return new } fun Array<CharArray>.insertSquare(square: Array<CharArray>, i: Int, j: Int) { for (ix in i until i + square.size) { for (jx in j until j + square.size) { this[ix][jx] = square[ix - i][jx - j] } } } fun Array<CharArray>.countChars(c: Char): Int { return this.sumBy { it.count { it == c } } }
0
Kotlin
0
0
71b34484825e1ec3f1b3174325c16fee33a13a65
3,845
advent-of-code-2017
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/MaximumBags.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2022 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode /** * 2279. Maximum Bags With Full Capacity of Rocks * @see <a href="https://leetcode.com/problems/maximum-bags-with-full-capacity-of-rocks/">Source</a> */ fun interface MaximumBags { operator fun invoke(capacity: IntArray, rocks: IntArray, additionalRocks: Int): Int } class MaximumBagsGreedy : MaximumBags { override operator fun invoke(capacity: IntArray, rocks: IntArray, additionalRocks: Int): Int { var add = additionalRocks val n: Int = rocks.size var cnt = 0 for (i in 0 until n) { rocks[i] = capacity[i] - rocks[i] } rocks.sort() var i = 0 while (i < n && rocks[i] - add <= 0) { cnt++ add -= rocks[i] i++ } return cnt } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,417
kotlab
Apache License 2.0
src/main/kotlin/com/kishor/kotlin/algo/problems/arrayandstrings/GroupAnagrams.kt
kishorsutar
276,212,164
false
null
package com.kishor.kotlin.algo.problems.arrayandstrings import java.util.* import kotlin.collections.ArrayList fun main() { // groupAnagrams() println("${groupAnagrams(arrayOf( "eat", "tea", "tan", "ate", "nat", "bat"))}") // groupAnagramsTes(arrayOf( "eat", "tea", "tan", "ate", "nat", "bat")) } /*fun groupAnagrams(strs: Array<String>): List<List<String>> { val answerList = ArrayList<ArrayList<String>>() for (i in strs.indices) { val innerList = ArrayList<String>() innerList.add(strs[i]) for (j in i until strs.size) { if (isAnagram(strs[i], strs[j])) { innerList.add(strs[j]) } } answerList.add(innerList) } return answerList }*/ fun isAnagram(str1: String, str2: String): Boolean { val intArray1 = IntArray(26) {0} for (c in str1) { intArray1[c.toInt() - 96] = 1 } for (c in str2) { intArray1[c.toInt() - 96] = 0 } for (i in intArray1) { if (i == 1) { return false } } return true } fun groupAnagrams(strs: Array<String>): List<List<String>> { val mapOfAnagrams = HashMap<String, MutableList<String>>() for (str in strs) { val ca = str.toCharArray() Arrays.sort(ca) val key = String(ca) if (!mapOfAnagrams.containsKey(key)) mapOfAnagrams[key] = ArrayList<String>() mapOfAnagrams[key]?.add(str) } return ArrayList(mapOfAnagrams.values) }
0
Kotlin
0
0
6672d7738b035202ece6f148fde05867f6d4d94c
1,505
DS_Algo_Kotlin
MIT License
kotlin/numeric/KaratsubaMultiply.kt
polydisc
281,633,906
true
{"Java": 540473, "Kotlin": 515759, "C++": 265630, "CMake": 571}
package numeric import java.util.Arrays // https://en.wikipedia.org/wiki/Karatsuba_algorithm object KaratsubaMultiply { fun karatsubaMultiply(a: IntArray, b: IntArray): IntArray { var a = a var b = b if (a.size < b.size) a = Arrays.copyOf(a, b.size) if (a.size > b.size) b = Arrays.copyOf(b, a.size) val n = a.size val res = IntArray(n + n) if (n <= 10) { for (i in 0 until n) for (j in 0 until n) res[i + j] = res[i + j] + a[i] * b[j] } else { val k = n shr 1 val a1: IntArray = Arrays.copyOfRange(a, 0, k) val a2: IntArray = Arrays.copyOfRange(a, k, n) val b1: IntArray = Arrays.copyOfRange(b, 0, k) val b2: IntArray = Arrays.copyOfRange(b, k, n) val a1b1 = karatsubaMultiply(a1, b1) val a2b2 = karatsubaMultiply(a2, b2) for (i in 0 until k) a2[i] = a2[i] + a1[i] for (i in 0 until k) b2[i] = b2[i] + b1[i] val r = karatsubaMultiply(a2, b2) for (i in a1b1.indices) r[i] = r[i] - a1b1[i] for (i in a2b2.indices) r[i] = r[i] - a2b2[i] System.arraycopy(r, 0, res, k, r.size) for (i in a1b1.indices) res[i] = res[i] + a1b1[i] for (i in a2b2.indices) res[i + n] = res[i + n] + a2b2[i] } return res } // Usage example fun main(args: Array<String?>?) { // (3*x^2+2*x+1) * (4*x+3) = 12*x^3 + 17*x^2 + 10*x + 3 System.out.println( Arrays.equals(intArrayOf(3, 10, 17, 12, 0, 0), karatsubaMultiply(intArrayOf(1, 2, 3), intArrayOf(3, 4))) ) } }
1
Java
0
0
4566f3145be72827d72cb93abca8bfd93f1c58df
1,666
codelibrary
The Unlicense
src/main/kotlin/dev/shtanko/algorithms/leetcode/ImageSmoother.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2023 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import dev.shtanko.algorithms.HALF_OF_BYTE import dev.shtanko.algorithms.OCTAL /** * 661. Image Smoother * @see <a href="https://leetcode.com/problems/image-smoother">Source</a> */ fun interface ImageSmoother { operator fun invoke(img: Array<IntArray>): Array<IntArray> } sealed interface ImageSmootherStrategy { /** * Approach 1: Create a New Smoothened Image */ data object NewSmoothenedImage : ImageSmoother, ImageSmootherStrategy { override fun invoke(img: Array<IntArray>): Array<IntArray> { val m = img.size val n = img[0].size val smoothImg = createSmoothImage(m, n) for (i in 0 until m) { for (j in 0 until n) { smoothImg[i][j] = calculateSmoothValue(img, m, n, i, j) } } return smoothImg } private fun createSmoothImage(m: Int, n: Int): Array<IntArray> { return Array(m) { IntArray(n) } } private fun calculateSmoothValue(img: Array<IntArray>, m: Int, n: Int, i: Int, j: Int): Int { var sum = 0 var count = 0 for (x in i - 1..i + 1) { for (y in j - 1..j + 1) { if (x in 0 until m && y in 0 until n) { sum += img[x][y] count += 1 } } } return sum / count } } data object ConstantSpaceSmoothenedImage : ImageSmoother, ImageSmootherStrategy { override fun invoke(img: Array<IntArray>): Array<IntArray> { val m: Int = img.size val n: Int = img[0].size val encodedImage = encodeSmoothedValues(img, m, n) val smoothedImage = extractSmoothedValues(encodedImage, m, n) return smoothedImage } private fun encodeSmoothedValues(img: Array<IntArray>, m: Int, n: Int): Array<IntArray> { val encodedImg = Array(m) { IntArray(n) } for (i in 0 until m) { for (j in 0 until n) { val neighborhoodSum = calculateNeighborhoodSum(img, m, n, i, j) val neighborhoodCount = calculateNeighborhoodCount(m, n, i, j) encodedImg[i][j] = encodePixelValue(img[i][j], neighborhoodSum, neighborhoodCount) } } return encodedImg } private fun calculateNeighborhoodSum(img: Array<IntArray>, m: Int, n: Int, i: Int, j: Int): Int { var sum = 0 for (x in i - 1..i + 1) { for (y in j - 1..j + 1) { if (x in 0 until m && y in 0 until n) { sum += img[x][y] % HALF_OF_BYTE } } } return sum } private fun calculateNeighborhoodCount(m: Int, n: Int, i: Int, j: Int): Int { var count = 0 for (x in i - 1..i + 1) { for (y in j - 1..j + 1) { if (x in 0 until m && y in 0 until n) { count++ } } } return count } private fun encodePixelValue(originalValue: Int, neighborhoodSum: Int, neighborhoodCount: Int): Int { return originalValue + (neighborhoodSum / neighborhoodCount) * HALF_OF_BYTE } private fun extractSmoothedValues(encodedImg: Array<IntArray>, m: Int, n: Int): Array<IntArray> { val smoothedImg = Array(m) { IntArray(n) } for (i in 0 until m) { for (j in 0 until n) { smoothedImg[i][j] = encodedImg[i][j] / HALF_OF_BYTE } } return smoothedImg } } data object ImageSmootherBitwise : ImageSmoother, ImageSmootherStrategy { override fun invoke(img: Array<IntArray>): Array<IntArray> { val rows = img.size val cols = img[0].size for (i in 0 until rows) { for (j in 0 until cols) { val (sum, count) = calculateNeighborSumAndCount(img, i, j, rows, cols) img[i][j] = encodeSmoothedValue(img[i][j], sum, count) } } decodeSmoothedValues(img) return img } private fun calculateNeighborSumAndCount( img: Array<IntArray>, i: Int, j: Int, rows: Int, cols: Int, ): Pair<Int, Int> { var sum = 0 var count = 0 for (x in i - 1..i + 1) { for (y in j - 1..j + 1) { if (x in 0 until rows && y in 0 until cols) { sum += img[x][y] and HALF_OF_BYTE - 1 count++ } } } return Pair(sum, count) } private fun encodeSmoothedValue(originalValue: Int, sum: Int, count: Int): Int { return originalValue or ((sum / count) shl OCTAL) } private fun decodeSmoothedValues(img: Array<IntArray>) { for (i in img.indices) { for (j in img[i].indices) { img[i][j] = img[i][j] shr OCTAL } } } } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
6,051
kotlab
Apache License 2.0
day2/src/main/kotlin/com/lillicoder/adventofcode2023/day2/Day2.kt
lillicoder
731,776,788
false
{"Kotlin": 98872}
package com.lillicoder.adventofcode2023.day2 fun main() { val day2 = Day2() val games = GameParser().parse("input.txt") println("The sum of all valid game IDs is ${day2.part1(games)}.") println("The sum of all minimum cubes powers is ${day2.part2(games)}.") } class Day2() { fun part1(games: List<Game>) = GameIdSummationCalculator().sumValidGameIds(games) fun part2(games: List<Game>) = GameMinimumCubesPowerSummationCalculator().sumMinimumCubesPowers(games) } /** * Represents a color of cube and the maximum allowed count of that color * in any given pull of a round of a game. * @param max Maximum amount of this color allowed in any given pull of cubes in a round. */ enum class Color(val max: Int) { BLUE(14), GREEN(13), RED(12), } /** * Represents a single game. * @param id Game ID. * @param rounds Game rounds. */ data class Game( val id: Int, val rounds: List<Round>, ) /** * Represents a single game round. * @param blue Blue [Pull]. * @param green Green [Pull]. * @param red Red [Pull]. */ data class Round( val blue: Pull, val green: Pull, val red: Pull, ) /** * Represents a single pull of a color of cubes in a round. * @param color [Color] of the cubes pulled. * @param count Number of cubes pulled. */ data class Pull( val color: Color, val count: Int, ) /** * Parses game records into a list of [Game]. */ class GameParser { /** * Parses the file with the given filename and returns a list of [Game]. * @param filename Name of the file to parse. * @return List of games. */ fun parse(filename: String) = parse( javaClass.classLoader.getResourceAsStream(filename)!!.reader().readLines(), ) /** * Parses the given raw game input and returns a list of [Game]. * @param raw Raw games to parse. * @return List of games. */ fun parse(raw: List<String>) = raw.map { val id = it.substringBefore(": ").substringAfter("Game ").toInt() val rounds = parseRounds(it) Game(id, rounds) } /** * Parses the list of [Round] for the given raw game input. * @param game Game to parse. * @return List of rounds. */ private fun parseRounds(game: String) = game.substringAfter(": ").split("; ").map { parseRound(it) } /** * Parses a [Round] from the given raw round input. * @param round Round to parse. * @return Round. */ private fun parseRound(round: String): Round { // Pack defaults, not all colors are guaranteed to be present in a round val pulls = round.split(", ").map { parsePull(it) }.associateBy { it.color }.withDefault { Pull(it, 0) } return Round( pulls.getValue(Color.BLUE), pulls.getValue(Color.GREEN), pulls.getValue(Color.RED), ) } /** * Parses a [Pull] from the given raw pull input. * @param pull Pull to parse. * @return Pull. */ private fun parsePull(pull: String): Pull { val pair = pull.split(" ") val count = pair[0].toInt() val color = Color.valueOf(pair[1].uppercase()) return Pull(color, count) } } /** * Calculates the minimum number of cubes of each color that would satisfy a game's * pulls, finds the power of those minimum numbers for each game, and sums all * of those powers into a single result. */ class GameMinimumCubesPowerSummationCalculator { /** * Sums all powers of required minimum cube sets for each [Game] in the given * list of games. * @param games Games to evaluate. * @return Sum of minimum cubes powers. */ fun sumMinimumCubesPowers(games: List<Game>) = games.sumOf { game -> listOf( game.rounds.maxByOrNull { it.blue.count }?.blue?.count ?: 0, game.rounds.maxByOrNull { it.green.count }?.green?.count ?: 0, game.rounds.maxByOrNull { it.red.count }?.red?.count ?: 0, ).reduce { accumulator, element -> accumulator * element } } } /** * Calculates the sum of [Game] IDs whose pulls do not exceed the allowed maximums * for a given color. */ class GameIdSummationCalculator { /** * Sums all IDs of values [Game] from the given list of games. * @param games Games to evaluate. * @return Sum of all valid game IDs. */ fun sumValidGameIds(games: List<Game>) = games.sumOf { game -> if (isValidGame(game)) game.id else 0 } /** * Determines if the given [Game] is valid for the known maximum allowed * cube per color. * @param game Game to check. * @return True if game is valid, false otherwise. */ private fun isValidGame(game: Game) = game.rounds.all { isValidRound(it) } /** * Determines if the given [Round] is valid for the known maximum allowed cubes * per color. * @param round Round to check. * @return True if the round is valid, false otherwise. */ private fun isValidRound(round: Round) = listOf(round.blue, round.green, round.red).all { isValidPull(it) } /** * Determines if the given [Pull] is valid for the known * maximum allowed cubes per color. * @param pull Pull to check. * @return True if a valid pull, false otherwise. */ private fun isValidPull(pull: Pull) = pull.count <= pull.color.max }
0
Kotlin
0
0
390f804a3da7e9d2e5747ef29299a6ad42c8d877
5,532
advent-of-code-2023
Apache License 2.0
src/Day01.kt
HylkeB
573,815,567
false
{"Kotlin": 83982}
fun main() { fun getSortedCaloriesPerElf(input: List<String>): List<Int> { return input.fold(mutableListOf(0)) { acc, cur -> if (cur.isBlank()) { acc.add(0) } else { acc[acc.lastIndex] += cur.toInt() } acc }.sortedDescending() } fun part1(input: List<String>): Int { return getSortedCaloriesPerElf(input).first() } fun part2(input: List<String>): Int { return getSortedCaloriesPerElf(input) .subList(0, 3) .sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") check(part1(testInput) == 24000) check(part2(testInput) == 45000) val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
8649209f4b1264f51b07212ef08fa8ca5c7d465b
867
advent-of-code-2022-kotlin
Apache License 2.0
src/main/kotlin/thesis/utils/unification.kt
danilkolikov
123,672,959
false
null
/** * Unification algorithm for type inference * * @author <NAME> */ package thesis.utils import thesis.preprocess.expressions.algebraic.term.AlgebraicEquation import thesis.preprocess.expressions.algebraic.term.AlgebraicTerm /** * Solves system of algebraic equations */ fun solveSystem(system: List<AlgebraicEquation>): Map<String, AlgebraicTerm> { var newSystem: List<AlgebraicEquation> = ArrayList(system) while (true) { val switched = switchVariables(newSystem) val noTrivial = removeTrivial(switched) val deconstructed = deconstructFunctions(noTrivial) val replaced = replaceOccurrences(deconstructed) if (replaced == newSystem) { break } newSystem = replaced } return newSystem .filter { it.left is AlgebraicTerm.Variable } .map { (it.left as AlgebraicTerm.Variable).name to it.right } .toMap() } private fun switchVariables(equations: List<AlgebraicEquation>) = equations.map { val (left, right) = it if (left is AlgebraicTerm.Function && right is AlgebraicTerm.Variable) { return@map AlgebraicEquation(right, left) } return@map it } private fun removeTrivial(equations: List<AlgebraicEquation>) = equations.filterNot { (left, right) -> left is AlgebraicTerm.Variable && right is AlgebraicTerm.Variable && left == right } private fun deconstructFunctions(equations: List<AlgebraicEquation>) = equations.flatMap { val (left, right) = it if (left is AlgebraicTerm.Function && right is AlgebraicTerm.Function) { if (left.name != right.name || left.arguments.size != right.arguments.size) { throw UnificationError(left, right) } return@flatMap left.arguments.zip(right.arguments) .map { (left, right) -> AlgebraicEquation(left, right) } } return@flatMap listOf(it) } private fun replaceOccurrences(equations: List<AlgebraicEquation>): List<AlgebraicEquation> { var result = equations while (true) { val wrong = result.find { e -> e.left is AlgebraicTerm.Variable && e.left != e.right && e.right.hasVariable(e.left) } if (wrong != null) { throw UnificationError(wrong.left, wrong.right) } val toReplace = result.find { e -> e.left is AlgebraicTerm.Variable && e.left != e.right && result.any { it != e && (it.left.hasVariable(e.left) || it.right.hasVariable(e.left)) } } ?: break val map = mapOf((toReplace.left as AlgebraicTerm.Variable).name to toReplace.right) result = result.map { if (it == toReplace) it else AlgebraicEquation( it.left.replace(map), it.right.replace(map) ) } } return result } class UnificationError( left: AlgebraicTerm, right: AlgebraicTerm ) : Exception("Can't unify $left and $right")
0
Kotlin
0
2
0f5ad2d9fdd1f03d3bf62255da14b05e4e0289e1
2,992
fnn
MIT License
src/main/kotlin/com/rtarita/days/Day5.kt
RaphaelTarita
724,581,070
false
{"Kotlin": 64943}
package com.rtarita.days import com.rtarita.structure.AoCDay import com.rtarita.util.day import kotlinx.datetime.LocalDate object Day5 : AoCDay { private data class MapTriple( val destStart: Long, val origStart: Long, val rangeSize: Long ) { val origRange: LongRange get() = origStart..<(origStart + rangeSize) val destRange: LongRange get() = destStart..<(destStart + rangeSize) } private class ConversionMap( private val instructions: Set<MapTriple> ) { fun origToDest(orig: Long): Long { for (instruction in instructions) { if (orig in instruction.origRange) { return orig + (instruction.destStart - instruction.origStart) } } return orig } fun destToOrig(dest: Long): Long { for (instruction in instructions) { if (dest in instruction.destRange) { return dest + (instruction.origStart - instruction.destStart) } } return dest } } override val day: LocalDate = day(5) private fun parseAlmanac(input: String): Pair<Set<Long>, List<ConversionMap>> { val entries = input.split("\n\n") val seeds = entries[0].removePrefix("seeds: ") .trim() .split(' ') .map { it.toLong() } .toSet() val maps = entries.drop(1) .map { entry -> ConversionMap( entry.lines() .drop(1) .map { val (destStart, origStart, rangeSize) = it.split(" ") MapTriple(destStart.toLong(), origStart.toLong(), rangeSize.toLong()) }.toSet() ) } return seeds to maps } override fun executePart1(input: String): Any { val (seeds, maps) = parseAlmanac(input) return seeds.minOf { seed -> maps.fold(seed) { acc, map -> map.origToDest(acc) } } } override fun executePart2(input: String): Any { val (seeds, maps) = parseAlmanac(input) val seedRanges = seeds.chunked(2) { (start, size) -> start..<(start + size) } return generateSequence(0L) { it + 1 } .first { location -> val seed = maps.foldRight(location) { map, acc -> map.destToOrig(acc) } seedRanges.any { seed in it } } } }
0
Kotlin
0
0
4691126d970ab0d5034239949bd399c8692f3bb1
2,667
AoC-2023
Apache License 2.0
src/main/kotlin/io/queue/DecodeString.kt
jffiorillo
138,075,067
false
{"Kotlin": 434399, "Java": 14529, "Shell": 465}
package io.queue import java.util.* import kotlin.math.pow class DecodeString { fun execute(input: String): String { val stack = Stack<String>() input.map { it.toString() }.map { char -> when { char == "[" -> stack.push(char) char == "]" -> pushOrAdd(stack, generateValue(stack)) "\\d".toRegex().matches(char) -> stack.push(char) else -> pushOrAdd(stack, char) } } return generateSequence { if (stack.isNotEmpty()) stack.pop() else null }.toList().let { if (it.isEmpty()) "" else it.reduce { acc, s -> s + acc } } } private fun pushOrAdd(stack: Stack<String>, newValue: String) = if (stack.isNotEmpty() && "\\w+".toRegex().matches(stack.peek())) stack.push(stack.pop() + newValue) else stack.push(newValue) private fun generateValue(stack: Stack<String>) = extraString(stack).repeat(extraNumber(stack)) private fun extraString(stack: Stack<String>) = generateSequence { if (stack.isNotEmpty() && stack.peek() != "[") stack.pop() else stack.pop().let { null } }.toList() .let { strings -> if (strings.isEmpty()) "" else strings.reduce { acc, char -> acc + char } } private fun extraNumber(stack: Stack<String>): Int = generateSequence { if (stack.isNotEmpty() && "\\d".toRegex().matches(stack.peek())) stack.pop().toString().toInt() else null } .mapIndexed { index, number -> 10.toDouble().pow(index.toDouble()).toInt() * number }.toList().let { numbersSequence -> if (numbersSequence.isEmpty()) 1 else numbersSequence.reduce { acc, new -> acc + new } } } fun main() { val decodeString = DecodeString() listOf( Pair("3[a]2[bc]", "aaabcbc"), Pair("3[a2[c]]", "accaccacc"), Pair("2[abc]3[cd]ef", "abcabccdcdcdef") ).map { (input, answer) -> val output = decodeString.execute(input) println("$input $output answer $answer is valid ${output == answer}") } }
0
Kotlin
0
0
f093c2c19cd76c85fab87605ae4a3ea157325d43
1,945
coding
MIT License
src/main/kotlin/Day7.kt
Mestru
112,782,719
false
null
import java.io.File import kotlin.math.abs data class Program(var weight: Int, var parent: String?, var children: List<String>?) val programs = HashMap<String, Program>() fun main(args: Array<String>) { // part 1 val lineRegex = "(\\w+) \\((\\d+)\\)( -> )?(.+)?".toRegex() var name: String var weight: Int var children: List<String> = ArrayList() File("input/day7.txt").forEachLine { line -> run { name = lineRegex.matchEntire(line)?.groups?.get(1)!!.value weight = lineRegex.matchEntire(line)?.groups?.get(2)!!.value.toInt() if (lineRegex.matchEntire(line)?.groups?.get(3)?.value != null) { children = lineRegex.matchEntire(line)?.groups?.get(4)?.value!!.split(", ") } children.forEach { child -> run { programs.getOrPut(child, { Program(-1, name, null) }).parent = name }} programs.getOrPut(name, { Program(weight, null, children) }).weight = weight programs.get(name)!!.children = children children = ArrayList() } } var parent = Program(0, null, null) programs.forEach { program -> run { if (program.value.parent == null) { println(program.key) parent = program.value } } } // part 2 balanceWeight(parent) } fun balanceWeight(program: Program): Int { var weight = program.weight var childWeight: Int val childrenWeight = ArrayList<Int>() if (program.children != null) { for (child in program.children!!) { childWeight = balanceWeight(programs.getOrDefault(child, Program(0, null, null))) childrenWeight.add(childWeight) weight += childWeight } } if (childrenWeight.size > 0) { val testedWeight = childrenWeight.get(0) var badWeight = -1 childrenWeight.forEach { childsWeight -> run { if (childsWeight != testedWeight) { badWeight = childsWeight } } } if (badWeight != -1 ) { println(abs(testedWeight - badWeight)) } } return weight }
0
Kotlin
0
0
2cc4211efc7fa32fb951c19d11cb4a452bfeec2c
2,119
Advent_of_Code_2017
MIT License
data_structures/y_fast_trie/Kotlin/YFastTrie.kt
ZoranPandovski
93,438,176
false
{"Jupyter Notebook": 21909905, "C++": 1692994, "Python": 1158220, "Java": 806066, "C": 560110, "JavaScript": 305918, "Go": 145277, "C#": 117882, "PHP": 85458, "Kotlin": 72238, "Rust": 53852, "Ruby": 43243, "MATLAB": 34672, "Swift": 31023, "Processing": 22089, "HTML": 18961, "Haskell": 14298, "Dart": 11842, "CSS": 10509, "Scala": 10277, "Haxe": 9750, "PureScript": 9122, "M": 9006, "Perl": 8685, "Prolog": 8165, "Shell": 7901, "Erlang": 7483, "Assembly": 7284, "R": 6832, "Lua": 6392, "LOLCODE": 6379, "VBScript": 6283, "Clojure": 5598, "Elixir": 5495, "OCaml": 3989, "Crystal": 3902, "Common Lisp": 3839, "Julia": 3567, "F#": 3376, "TypeScript": 3268, "Nim": 3201, "Brainfuck": 2466, "Visual Basic .NET": 2033, "ABAP": 1735, "Pascal": 1554, "Groovy": 976, "COBOL": 887, "Mathematica": 799, "Racket": 755, "PowerShell": 708, "Ada": 490, "CMake": 393, "Classic ASP": 339, "QMake": 199, "Makefile": 111}
/** * Y-fast trie is a data structure for storing integers from a bounded domain * It supports exact and predecessor or successor queries in time O(log log M), using O(n) space, * where n is the number of stored values and M is the maximum value in the domain. * More info about the structure and complexity here: https://en.wikipedia.org/wiki/Y-fast_trie * * The prerequisites are the XFastTrie (al-go-rithms/data_structures/x_fast_trie/Kotlin/XFastTrie.kt) and a Balanced BST. * In this implementation a Treap is used (al-go-rithms/data_structures/treap/Kotlin/persistent_treap.kt) */ class XFastMap<T>(domain: Long) { private val base = XFastTrie(domain) private val valueTable: MutableMap<Long, T> = HashMap() fun add(entry: Pair<Long, T>) { base.add(entry.first) valueTable.put(entry.first, entry.second) } fun emplace(key: Long, value: T) { valueTable[key] = value } fun successor(key: Long): Pair<Long?, T?> { val nextKey = base.successor(key) return Pair(nextKey, valueTable.get(nextKey)) } fun predecessor(key: Long): Pair<Long?, T?> { val nextKey = base.predecessor(key) return Pair(nextKey, valueTable.get(nextKey)) } fun get(key: Long) = valueTable.get(key) fun delete(key: Long) { base.delete(key) valueTable.remove(key) } } class YFastTrie(domain: Long) { class Node(val representative: Long, val bst: PersistentTreap<Long> = PersistentTreap()) private val xFast: XFastMap<Node> = XFastMap(domain) private val logM: Int = java.lang.Long.numberOfLeadingZeros(0) - java.lang.Long.numberOfLeadingZeros(domain) + 1 fun find(key: Long): Boolean { val succRepr = xFast.successor(key).second val prevRepr = xFast.predecessor(key+1).second return (succRepr?.bst?.search(key) ?: false) or (prevRepr?.bst?.search(key) ?: false) } fun successor(key: Long): Long? { var succRepr = xFast.successor(key).second if (succRepr != null && succRepr.bst.successor(key) == null) succRepr = xFast.successor(succRepr.representative).second val prevRepr = xFast.predecessor(key+1).second val succ1 = succRepr?.bst?.successor(key) val succ2 = prevRepr?.bst?.successor(key) if (succ1 == null) return succ2 if (succ2 == null) return succ1 return java.lang.Long.min(succ1, succ2) } fun predecessor(key: Long): Long? { val succRepr = xFast.successor(key).second var prevRepr = xFast.predecessor(key+1).second if (prevRepr != null && prevRepr.bst.predecessor(key) == null) prevRepr = xFast.predecessor(prevRepr.representative).second val succ1 = succRepr?.bst?.predecessor(key) val succ2 = prevRepr?.bst?.predecessor(key) if (succ1 == null) return succ2 if (succ2 == null) return succ1 return java.lang.Long.max(succ1, succ2) } fun add(key: Long) { val succRepr = xFast.successor(key).second val prevRepr = xFast.predecessor(key+1).second val succ1 = succRepr?.bst?.successor(key) val succ2 = prevRepr?.bst?.successor(key) val reprNode = when { succ1 == null -> prevRepr succ2 == null -> succRepr succ1 < succ2 -> succRepr else -> prevRepr } val tree = reprNode?.bst if (tree == null) { val addedTree = PersistentTreap<Long>() + key xFast.add(Pair(key, Node(key, addedTree))) return } val newTree = tree + key if (newTree.size > 2*logM) { val pivot = when { newTree.root!!.rightChild == null -> newTree.root.value - 1 newTree.root.leftChild == null -> newTree.root.value + 1 else -> newTree.root.value } val (leftTree, rightTree) = newTree.split(pivot) xFast.delete(reprNode.representative) val leftRepr = leftTree.root!!.value val rightRepr = rightTree.root!!.value xFast.add(Pair(leftRepr, Node(leftRepr, leftTree))) xFast.add(Pair(rightRepr, Node(rightRepr, rightTree))) } else xFast.emplace(reprNode.representative, Node(reprNode.representative, newTree)) } fun delete(key: Long): Boolean { val succRepr = xFast.successor(key).second val prevRepr = xFast.predecessor(key + 1).second val myRepr = when { succRepr?.bst?.search(key) == true -> succRepr prevRepr?.bst?.search(key) == true -> prevRepr else -> return false } val newTree = myRepr.bst - key if (newTree.size >= logM / 4) xFast.emplace(myRepr.representative, Node(myRepr.representative, newTree)) else { val toJoin = xFast.successor(myRepr.representative).second ?: xFast.predecessor(myRepr.representative).second if (toJoin == null) { xFast.emplace(myRepr.representative, Node(myRepr.representative, newTree)) return true } xFast.delete(myRepr.representative) xFast.delete(toJoin.representative) val newR = myRepr.representative xFast.add(Pair(newR, Node(newR, newTree.join(toJoin.bst, newR)))) } return true } } fun<T> List<T>.firstOrNullBinary(predicate: (T) -> Boolean): T? { var step = 1 var pos = this.size while (step < this.size) step *= 2 while (step > 0) { if (pos - step >= 0 && predicate(this[pos-step])) pos -= step step /= 2 } if (pos == this.size) return null return this[pos] } fun checkContains(trie: YFastTrie, values: List<Long>, MAX_VALUE: Long) { val sortedValues = values.sorted() val reverseSortedValues = sortedValues.reversed() for (i in 0..MAX_VALUE) { val myNext = sortedValues.firstOrNullBinary({it > i}) val actualNext = trie.successor(i) val myPrev = reverseSortedValues.firstOrNullBinary({it < i}) val actualPrev = trie.predecessor(i) if (myNext != actualNext) println("error") if (myPrev != actualPrev) println("error") } val myContent = (0..MAX_VALUE).filter { trie.find(it) }.sorted().toLongArray() if (!(myContent contentEquals values.sorted().toLongArray())) println("error") } fun main(args: Array<String>) { val MAX_VALUE = 1000005L val TO_ADD = 200000 val TO_DELETE = 50000 val trie = YFastTrie(MAX_VALUE) val values = (0..MAX_VALUE).shuffled().subList(0, TO_ADD) values.forEach { trie.add(it) } println("Check inserts") checkContains(trie, values, MAX_VALUE) val toDel = values.shuffled().subList(0, TO_DELETE).toSet() val rest = values.filter { !toDel.contains(it) } toDel.forEach { trie.delete(it) } println("Check after delete") checkContains(trie, rest, MAX_VALUE) }
62
Jupyter Notebook
1,994
1,298
62a1a543b8f3e2ca1280bf50fc8a95896ef69d63
7,046
al-go-rithms
Creative Commons Zero v1.0 Universal
kotlin/src/main/kotlin/io/github/piszmog/aoc/Day4.kt
Piszmog
433,651,411
false
null
package io.github.piszmog.aoc import java.time.Instant fun main(args: Array<String>) { val start = Instant.now() val reader = getFileReader(args[0]) var row = 0 var numLines = "" val boardLines = mutableListOf<String>() reader.lines().forEach { if (row == 0) { numLines = it } else { boardLines.add(it) } row++ } val nums = getNums(numLines) val boards = getBoards(boardLines) val part1Solution = day4Part1(nums, boards.toMutableList()) println("Part 1: $part1Solution") val part2Solution = day4Part2(nums, boards.toMutableList()) println("Part 2: $part2Solution") printElapsedTime(start) } fun getNums(input: String): List<Int> { return input.split(",").map { it.toInt() } } fun getBoards(lines: List<String>): List<Board> { val boards = mutableListOf<Board>() val input = mutableListOf<List<Int>>() lines.forEach { line -> if (line.isBlank()) { if (input.isNotEmpty()) { boards.add(Board(input.map { it -> Row(it.map { Square(false, it) }) }, false)) input.clear() } } else { input.add(line.split(" ").filter { it.isNotBlank() }.map { it.toInt() }) } } if (input.isNotEmpty()) { boards.add(Board(input.map { it -> Row(it.map { Square(false, it) }) }, false)) } return boards } fun day4Part1(callNums: List<Int>, boards: List<Board>): Int { var finalNum = 0 var unmarkedSum = 0 outer@ for (num in callNums) { finalNum = num for (board in boards) { board.markSquare(num) if (board.isWinner()) { unmarkedSum = board.getUnmarkedSum() break@outer } } } return finalNum * unmarkedSum } fun day4Part2(callNums: List<Int>, boards: List<Board>): Int { var finalNum = 0 var unmarkedSum = 0 outer@ for (num in callNums) { finalNum = num for (board in boards) { if (board.winner) { continue } board.markSquare(num) if (board.isWinner()) { board.winner = true } if (boards.all { it.winner }) { unmarkedSum = board.getUnmarkedSum() break@outer } } } return finalNum * unmarkedSum } data class Board(val rows: List<Row>, var winner: Boolean) { fun markSquare(num: Int) { for (row in rows) { for (square in row.squares) { if (square.value == num) { square.marked = true return } } } } fun getUnmarkedSum(): Int { var sum = 0 rows.forEach { row -> row.squares.filter { !it.marked }.map { it.value }.forEach { sum += it } } return sum } fun isWinner(): Boolean { for (x in rows.indices) { if (isRowWinner(x) || isColumnWinner(x)) { return true } } return false } private fun isRowWinner(row: Int) = rows[row].squares.all { it.marked } private fun isColumnWinner(col: Int) = rows.map { it.squares[col].marked }.all { it } } data class Row(val squares: List<Square>) data class Square(var marked: Boolean, val value: Int)
0
Rust
0
0
a155cb7644017863c703e97f22c8338ccb5ef544
3,397
aoc-2021
MIT License
src/Day22.kt
mathijs81
572,837,783
false
{"Kotlin": 167658, "Python": 725, "Shell": 57}
import kotlin.math.max import kotlin.math.min private const val EXPECTED_1 = 5 private const val EXPECTED_2 = 7 data class Brick(val coord: MutableList<Int>, val size: MutableList<Int>) { fun maxFall(other: Brick): Int { if (other.coord[2] > coord[2]) { return Int.MAX_VALUE } for (i in 0..1) { val a = max(coord[i], other.coord[i]) val b = min(coord[i] + size[i], other.coord[i] + other.size[i]) if (b <= a) { return Int.MAX_VALUE } } return coord[2] - (other.coord[2] + other.size[2]) } } private class Day22(isTest: Boolean) : Solver(isTest) { val bricks = readAsLines().map { it.split("~").let { val coord = it[0].splitInts().toMutableList() val endCoord = it[1].splitInts() val size = (coord zip endCoord).map { it.second - it.first + 1 } Brick(coord, size.toMutableList()) } } fun fallAll(bricks: List<Brick>) { while (true) { var change = false outer@ for (brick in bricks) { var maxFall = brick.coord[2] - 1 if (maxFall == 0) { continue } for (other in bricks) { if (brick.coord[2] > other.coord[2]) { maxFall = min(maxFall, brick.maxFall(other)) if (maxFall <= 0) { continue@outer } } } if (maxFall > 0) { //println("$brick falls by $maxFall") brick.coord[2] -= maxFall change = true } } if (!change) { break } } } fun part1(): Any { fallAll(bricks) var ans = 0 for ((index, removeBrick) in bricks.withIndex()) { //println("$index ${bricks.size}") val newList = bricks.toMutableList().apply { remove(removeBrick) } var ok = true outer@ for (brick in newList) { var maxFall = brick.coord[2] - 1 for (other in newList) { if (brick.coord[2] > other.coord[2]) { maxFall = min(maxFall, brick.maxFall(other)) if (maxFall <= 0) { continue@outer } } } if (maxFall > 0) { ok = false break } } if (ok) { ans++ } } return ans } fun part2(): Any { fallAll(bricks) val brickBlockedBy = mutableMapOf<Int, MutableList<Int>>() for (index in bricks.indices) { for (j in bricks.indices) { if (index != j && bricks[j].coord[2] > bricks[index].coord[2]) { val fall = bricks[j].maxFall(bricks[index]) if (fall == 0) { brickBlockedBy.getOrPut(j) { mutableListOf() }.add(index) } } } } var ans = 0 for (index in bricks.indices) { val removed = mutableSetOf<Int>() fun remove(i: Int) { if (i in removed) { return } removed.add(i) val candidates = brickBlockedBy.entries.filter { it.key !in removed && it.value.contains(i) }.map { it.key } for (k in candidates) { if (brickBlockedBy[k]!!.all { it in removed }) { remove(k) } } } remove(index) ans += removed.size - 1 } return ans } } fun main() { val testInstance = Day22(true) val instance = Day22(false) testInstance.part1().let { check(it == EXPECTED_1) { "part1: $it != $EXPECTED_1" } } println("part1 ANSWER: ${instance.part1()}") testInstance.part2().let { check(it == EXPECTED_2) { "part2: $it != $EXPECTED_2" } println("part2 ANSWER: ${instance.part2()}") } }
0
Kotlin
0
2
92f2e803b83c3d9303d853b6c68291ac1568a2ba
4,365
advent-of-code-2022
Apache License 2.0
day07/src/main/kotlin/Day07.kt
bzabor
160,240,195
false
null
class Day07(private val input: List<String>) { private val possibleNexts = mutableSetOf<Node>() private val path = mutableListOf<Node>() private val nodeMap = mutableMapOf<Char, Node>() fun part1(): String { buildNodeMap() possibleNexts.addAll(nodeMap.values.filter { it.required.size == 0 }) val node = getNext() if (node != null) { process(node) } return path.map { it.id }.joinToString(separator = "") } fun part2(): Int { nodeMap.clear() buildNodeMap() possibleNexts.clear() possibleNexts.addAll(nodeMap.values.filter { it.required.size == 0 }) val workingNodes = mutableListOf<Node>() var seconds = 0 while (seconds < 1000) { // if not first second, tick the clock: // - decrement working node timers // for each working node where timer is 0 // - remove it from all nodes' required sets // - remove it from the nodeMap // - remove it from working nodes if (seconds > 0) { workingNodes.forEach{ it.timer--} val completedNodes = workingNodes.filter { it.timer == 0 } workingNodes.removeAll(completedNodes) completedNodes.forEach {completedNode -> nodeMap.remove(completedNode.id) nodeMap.values.forEach { it.required.remove(completedNode) } } } var freeWorkers = 5 - nodeMap.values.filter { it.isWorking }.count() // assign each worker a next node while (possibleNexts.isNotEmpty() && freeWorkers > 0) { val node = getNext() if (node != null) { node.isWorking = true workingNodes.add(node) freeWorkers-- possibleNexts.addAll(node.next) } else { break } } print("IN SECOND $seconds ") workingNodes.forEach{ print(" [${it.id}]: ${it.timer}") } println("") if (workingNodes.size == 0) return seconds seconds++ } return 0 } private fun buildNodeMap() { for (line in input) { val (required, next) = line.split(" ").slice(listOf(1, 7)) val requiredNode = nodeMap.getOrPut(required[0]) { Node(required[0]) } val nextNode = nodeMap.getOrPut(next[0]) { Node(next[0]) } requiredNode.next.add(nextNode) nextNode.required.add(requiredNode) } } private fun getNext(): Node? { val requirementsMetNodes = possibleNexts.filter { it.required.size == 0 } if (requirementsMetNodes.size > 0) { val node = requirementsMetNodes.sortedBy { it.id }.first() possibleNexts.remove(node) return node } return null } private fun process(node: Node) { // add it to the path path.add(node) // add its nexts to possibleNexts possibleNexts.addAll(node.next) // remove it from all nodes' required sets nodeMap.values.forEach { it.required.remove(node) } // remove it from the nodeMap nodeMap.remove(node.id) // if possibleNexts exist, get next, recurse if (possibleNexts.isNotEmpty()) { val node = getNext() if (node != null) { process(node) } } } } class Node(val id: Char) { val alphabet: CharRange = 'A'..'Z' val next = mutableSetOf<Node>() val required = mutableSetOf<Node>() var isWorking = false var timer = alphabet.indexOf(id) + 1 + 60 }
0
Kotlin
0
0
14382957d43a250886e264a01dd199c5b3e60edb
3,821
AdventOfCode2018
Apache License 2.0
src/Day21p2.kt
Riaz1
577,017,303
false
{"Kotlin": 15653}
fun main() { data class LineItem( val operand1: String, val operator: String, val operand2: String, var result: Double?, var result1: Double?, var result2: Double?, var parent: String? ) fun getPathFromRoot(key: String, steps: Map<String, LineItem>): ArrayDeque<String> { var path = ArrayDeque<String>() path.addFirst(key) var item = steps[key] while(item?.parent != null) { path.addFirst(item?.parent!!) item = steps[item?.parent] } path.removeFirst() //remove root return path } //total = x operator y fun solveForXAsOperand1(total: Double?, operator: String?, y: Double?): Double? { return when (operator) { "+" -> y?.let { total?.minus(it) } "-" -> y?.let { total?.plus(it) } "*" -> y?.let { total?.div(it) } "/" -> y?.let { total?.times(it) } else -> null } } //total = y operator x fun solveForXAsOperand2(total: Double?, operator: String?, y: Double?): Double? { return when (operator) { "+" -> y?.let { total?.minus(it) } "-" -> y?.let { (total?.minus(it))?.times(-1) } "*" -> y?.let { total?.div(it) } "/" -> y?.let { it.div(total!!) } else -> null } } val fileName = "Day21_input" // "Day21_sample" val steps = readInput(fileName).associateBy( keySelector = {v -> v.substringBefore(":").trim()}, valueTransform = {v -> if (v.substringAfter(":").trim().toDoubleOrNull() != null) { LineItem( "", "", "", v.substringAfter(":").trim().toDoubleOrNull(), null, null, null) } else { LineItem( v.substringAfter(":").trim().split(" ")[0], v.substringAfter(":").trim().split(" ")[1], v.substringAfter(":").trim().split(" ")[2], null, null, null, null ) } }) var rootValue : Double? = null while (rootValue == null) { run breaking@ { steps.forEach { (key, item) -> steps[item.operand1]?.let { if (it.parent == null) { steps[item.operand1]?.parent = key } } steps[item.operand2]?.let { if (it.parent == null) { steps[item.operand2]?.parent = key } } if (key == "root" && item.result != null) { rootValue = item.result return@breaking } if (item.result == null && steps[item.operand1]?.result != null && steps[item.operand2]?.result != null) { steps[key]?.result1 = steps[item.operand1]?.result steps[key]?.result2 = steps[item.operand2]?.result steps[key]?.result = when (item.operator) { "+" -> steps[item.operand2]?.result?.let {steps[item.operand1]?.result?.plus(it) } "-" -> steps[item.operand2]?.result?.let { steps[item.operand1]?.result?.minus(it) } "*" -> steps[item.operand2]?.result?.let {steps[item.operand1]?.result?.times(it) } "/" -> steps[item.operand2]?.result?.let {steps[item.operand1]?.result?.div(it) } else -> null } } } } } rootValue.println() "%.2f".format(rootValue).println() //part 2 val target = "humn" val rootToTarget = getPathFromRoot(target, steps) var newResult: Double? var nextNode = steps["root"] newResult = if (rootToTarget.first() == nextNode?.operand1) { nextNode?.result2 } else { nextNode?.result1 } while (rootToTarget.isNotEmpty()) { val key = rootToTarget.removeFirst() if (key == target) { "%.2f".format(newResult).println() break } nextNode = steps[key] val x = rootToTarget.first() //solve for x var xIsOperand1 = false val y = if (nextNode?.operand1 == x) { xIsOperand1 = true nextNode?.result2 } else { nextNode?.result1 } //println("solve for $x where y is $y and xisoperand1: $xIsOperand1 and the total is: $newResult") newResult = if (xIsOperand1) { solveForXAsOperand1(newResult, nextNode?.operator, y) } else { solveForXAsOperand2(newResult, nextNode?.operator, y) } } }
0
Kotlin
0
0
4d742e404ece13203319e1923ffc8e1f248a8e15
5,023
aoc2022
Apache License 2.0
src/Day08.kt
kenyee
573,186,108
false
{"Kotlin": 57550}
import java.util.concurrent.atomic.AtomicInteger fun main() { // ktlint-disable filename fun sumInnerTreesInDirection( visible: Array<Array<Boolean>>, array: List<String>, dir: Direction, row: Int, col: Int ): Int { val numRows = array.size val numCols = array[0].length var curRow = row var curCol = col val lowest = -1 var tallest = lowest var numVisible = 0 while (curRow >= 0 && curRow <= (numRows - 1) && curCol >= 0 && curCol <= (numCols - 1) ) { val treeHeight = array[curRow][curCol].digitToIntOrNull()!! if (treeHeight > tallest) { tallest = treeHeight if (!visible[curRow][curCol]) { visible[curRow][curCol] = true numVisible++ } } curRow += dir.deltaY curCol += dir.deltaX } return numVisible } fun part1BruteForce(input: List<String>): Long { val grid = input.map { line -> line.map { it.digitToInt() } } val colSize = grid[0].size val rowSize = grid.size val visible = Array(rowSize) { Array(colSize) { false } } // left for (i in 0 until rowSize) { var height = -1 for (j in 0 until colSize) { if (grid[i][j] > height) { visible[i][j] = true height = grid[i][j] } } } // right for (i in 0 until rowSize) { var height = -1 for (j in colSize - 1 downTo 0) { if (grid[i][j] > height) { visible[i][j] = true height = grid[i][j] } } } // top for (j in 0 until colSize) { var height = -1 for (i in 0 until rowSize) { if (grid[i][j] > height) { visible[i][j] = true height = grid[i][j] } } } // bottom for (j in 0 until colSize) { var height = -1 for (i in rowSize - 1 downTo 0) { if (grid[i][j] > height) { visible[i][j] = true height = grid[i][j] } } } return visible.sumOf { row -> row.count { it } }.toLong() } fun part1InsideVisible(grid: List<String>): Long { val colSize = grid[0].length val rowSize = grid.size val visible = Array(rowSize) { Array(colSize) { false } } var numVisible = 0L for (j in 0 until colSize) { val column = (0 until rowSize).map { grid[it][j] } for (i in 0 until rowSize) { val curValue = grid[j][i] val left = grid[i].substring(0, j) val isLeftVisible = left.isNotEmpty() && left.all { it < curValue } val right = grid[i].substring(j + 1, colSize) val isRightVisible = right.isNotEmpty() && right.all { it < curValue } val top = column.subList(0, i) val isTopVisible = top.isNotEmpty() && top.all { it < curValue } val bottom = column.subList(i + 1, rowSize) val isBottomVisible = bottom.isNotEmpty() && bottom.all { it < curValue } val isEdge = i == 0 || j == 0 || i == rowSize - 1 || j == colSize - 1 val isVisibleInAnyDirection = isLeftVisible || isRightVisible || isTopVisible || isBottomVisible if (!visible[i][j] && (isVisibleInAnyDirection || isEdge)) { visible[i][j] = true numVisible++ } } } return numVisible } fun part1(grid: List<String>): Long { val colSize = grid[0].length val rowSize = grid.size val visible = Array(rowSize) { Array(colSize) { false } } var treesVisible = 0L for (i in 1 until colSize - 1) { treesVisible += sumInnerTreesInDirection(visible, grid, Direction.Down, 0, i) // top row } for (i in 1 until colSize - 1) { treesVisible += sumInnerTreesInDirection(visible, grid, Direction.Up, rowSize - 1, i) // bottom row } for (i in 1 until rowSize - 1) { treesVisible += sumInnerTreesInDirection(visible, grid, Direction.Right, i, 0) // left column } for (i in 1 until rowSize - 1) { treesVisible += sumInnerTreesInDirection(visible, grid, Direction.Left, i, colSize - 1) // right column } val numCorners = 4 return treesVisible + numCorners } fun part1SomeoneAtomicInt(input: List<String>): Int { val array = input.map { it.chars().toArray() }.toTypedArray() val visibility = Array(array.size) { Array(array[0].size) { false } } var count = 0 fun AtomicInteger.updateVisibility(i: Int, j: Int) { if (array[i][j] > this.get()) { if (!visibility[i][j]) { count++ visibility[i][j] = true } this.set(array[i][j]) } } for (i in array.indices) { AtomicInteger(-1).apply { array.indices.forEach { updateVisibility(i, it) } } AtomicInteger(-1).apply { array.indices.reversed().forEach { updateVisibility(i, it) } } AtomicInteger(-1).apply { array.indices.forEach { updateVisibility(it, i) } } AtomicInteger(-1).apply { array.indices.reversed().forEach { updateVisibility(it, i) } } } return count } fun treesUntilBlocked( array: List<String>, dir: Direction, row: Int, col: Int ): Int { val numRows = array.size val numCols = array[0].length var curRow = row var curCol = col var numVisible = 0 val positionHeight = array[curRow][curCol] curRow += dir.deltaY curCol += dir.deltaX while (curRow >= 0 && curRow <= (numRows - 1) && curCol >= 0 && curCol <= (numCols - 1) ) { val treeHeight = array[curRow][curCol] numVisible++ if (treeHeight >= positionHeight) { break } curRow += dir.deltaY curCol += dir.deltaX } return numVisible } fun part2(grid: List<String>): Int { val colSize = grid[0].length val rowSize = grid.size var maxCount = 0 for (i in 0 until rowSize) { for (j in 0 until colSize) { val sum = treesUntilBlocked(grid, Direction.Left, i, j) * treesUntilBlocked(grid, Direction.Right, i, j) * treesUntilBlocked(grid, Direction.Up, i, j) * treesUntilBlocked(grid, Direction.Down, i, j) maxCount = Math.max(maxCount, sum) } } return maxCount } // test if implementation meets criteria from the description, like: val testInput = readInput("Day08_test") println("Test total# of visible trees: ${part1(testInput)}") check(part1(testInput) == 21L) println("Test most scenic score: ${part2(testInput)}") check(part2(testInput) == 8) val input = readInput("Day08_input") println("Total# of visible trees: ${part1(input)}") println("Most scenic score is: ${part2(input)}") }
0
Kotlin
0
0
814f08b314ae0cbf8e5ae842a8ba82ca2171809d
7,761
KotlinAdventOfCode2022
Apache License 2.0
app/src/main/kotlin/com/resurtm/aoc2023/day04/Solution.kt
resurtm
726,078,755
false
{"Kotlin": 119665}
package com.resurtm.aoc2023.day04 import kotlin.math.pow private fun parseNums(rawNums: String): Set<Int> = rawNums.trim().split(" ").map { it.trim() }.filter { it.isNotEmpty() }.map { it.toInt() }.toSet() private fun parseLine(line: String): ParseLineResult { val parts1 = line.split(":") val parts2 = parts1[1].trim().split("|") val card = parts1[0].trim().split(" ").map { it.trim() }.filter { it.isNotEmpty() }[1].trim().toInt() val need = parseNums(parts2[0]) val hands = parseNums(parts2[1]) val size = need.intersect(hands).size val score = 2.0.pow(size - 1).toInt() return ParseLineResult(card, score = score, size = size) } fun launchDay04(testCase: String) { val rawReader = object {}.javaClass.getResourceAsStream(testCase)?.bufferedReader() val reader = rawReader ?: throw Exception("Cannot read the input") var resultPart1 = 0 val accum = mutableMapOf<Int, Int>() while (true) { val res = parseLine(reader.readLine() ?: break) val past1 = accum[res.card] accum[res.card] = if (past1 == null) 1 else past1 + 1 repeat(accum[res.card] ?: 1) { for (idx in res.card + 1..res.card + res.size) { val past2 = accum[idx] accum[idx] = if (past2 == null) 1 else past2 + 1 } } resultPart1 += res.score } println("Part 1 answer: $resultPart1") println("Part 2 answer: ${accum.values.sum()}") } private data class ParseLineResult(val card: Int, val score: Int, val size: Int)
0
Kotlin
0
0
fb8da6c246b0e2ffadb046401502f945a82cfed9
1,560
advent-of-code-2023
MIT License
11.kts
pin2t
725,922,444
false
{"Kotlin": 48856, "Go": 48364, "Shell": 54}
import java.util.* import kotlin.math.abs data class Galaxy(var col: Long, var row: Long) { fun distance(other: Galaxy): Long = abs(this.row - other.row) + abs(this.col - other.col) } val scanner = Scanner(System.`in`) val galaxies = ArrayList<Galaxy>() var rows: Long = 0 while (scanner.hasNext()) { scanner.nextLine().forEachIndexed { index, c -> if (c == '#') galaxies.add(Galaxy(index.toLong(), rows)) } rows++ } val cols: Long = galaxies.maxOf { it.col } val galaxies2 = galaxies.map { it.copy() } for (r in rows downTo 0) { if (galaxies.all { it.row != r }) { galaxies.forEach { if (it.row > r) it.row++ } galaxies2.forEach { if (it.row > r) it.row+=999999 } } } for (c in cols downTo 0) { if (galaxies.all { it.col != c }) { galaxies.forEach { if (it.col > c) it.col++ } galaxies2.forEach { if (it.col > c) it.col+=999999 } } } var sum: Long = 0; var sum2: Long = 0 for (i in 0..<(galaxies.size - 1)) { for (j in i..<galaxies.size) { sum += galaxies[i].distance(galaxies[j]) sum2 += galaxies2[i].distance(galaxies2[j]) } } println(listOf(sum, sum2))
0
Kotlin
1
0
7575ab03cdadcd581acabd0b603a6f999119bbb6
1,142
aoc2023
MIT License
src/Day03_part2.kt
yashpalrawat
573,264,560
false
{"Kotlin": 12474}
fun main() { val input = readInput("Day03") val priorities = getPriorities() val result = (input.indices step 3).sumOf { val firstElevRuksPack = input[it] val secondElevRuksPack = input[it + 1] val thirdElevRuksPack = input[it + 2] priorities[findCommanCharacter(firstElevRuksPack, secondElevRuksPack, thirdElevRuksPack)] ?: 0 } print(result) } private fun findCommanCharacter( firstElevRuksPack: String, secondElevRuksPack: String, thirdElevRuksPack: String): Char { val mapOfCharsInFirstString = firstElevRuksPack.associateWith { it to 1 } val mapOfCharsInThirdString = thirdElevRuksPack.associateWith { it to 1 } val commanChars = secondElevRuksPack .toCharArray() .filter { mapOfCharsInFirstString.containsKey(it) }.toSet() return commanChars.first { mapOfCharsInThirdString.containsKey(it) } }
0
Kotlin
0
0
78a3a817709da6689b810a244b128a46a539511a
904
code-advent-2022
Apache License 2.0
src/main/kotlin/day08/day08.kt
andrew-suprun
725,670,189
false
{"Kotlin": 18354, "Python": 17857, "Dart": 8224}
package day08 import java.io.File data class Targets(val left: String, val right: String) fun main() { run(start = { it == "AAA" }, end = { it == "ZZZ" }) run(start = { it.endsWith('A') }, end = { it.endsWith('Z') }) } fun run(start: (String) -> Boolean, end: (String) -> Boolean) { val lines = File("input.data").readLines() val turns = turnSequence(lines[0]) val instructions = parseInstructions(lines.drop(2)) var totalSteps = 1L for (startPlace in instructions.keys.filter(start)) { var place = startPlace var steps = 0L for (turn in turns) { steps++ val targets = instructions[place]!! place = if (turn == 'L') targets.left else targets.right if (end(place)) break } totalSteps = lcm(totalSteps, steps) } println(totalSteps) } fun parseInstructions(lines: List<String>): Map<String, Targets> { val result = mutableMapOf<String, Targets>() for (line in lines) { val parts = line.split(" = (", ", ", ")") result[parts[0]] = Targets(left = parts[1], right = parts[2]) } return result } fun turnSequence(turns: String) = sequence { while (true) { for (char in turns) { yield(char) } } } fun lcm(first: Long, second: Long): Long = first / gcd(first, second) * second fun gcd(first: Long, second: Long): Long { var a = first var b = second while (b > 0) { val t = b b = a % b a = t } return a } // 11911 // 10151663816849
0
Kotlin
0
0
dd5f53e74e59ab0cab71ce7c53975695518cdbde
1,575
AoC-2023
The Unlicense
src/main/kotlin/com/github/davio/aoc/general/Math.kt
Davio
317,510,947
false
{"Kotlin": 405939}
package com.github.davio.aoc.general import kotlin.math.* val Int.squared get() = this * this val Long.squared get() = this * this val Int.sqrt get() = sqrt(this.toDouble()) val Long.sqrt get() = sqrt(this.toDouble()) fun Double.roundUp() = ceil(this).toLong() fun Double.roundDown() = this.toLong() fun gcd(n1: Int, n2: Int): Int { return when { n1 == 0 -> n2 n2 == 0 -> n1 else -> { val absNumber1 = abs(n1) val absNumber2 = abs(n2) val smallerValue = min(absNumber1, absNumber2) gcd(max(absNumber1, absNumber2) % smallerValue, smallerValue) } } } fun gcd(n1: Long, n2: Long):Long { return when { n1 == 0L -> n2 n2 == 0L -> n1 else -> { val absNumber1 = abs(n1) val absNumber2 = abs(n2) val smallerValue = min(absNumber1, absNumber2) gcd(max(absNumber1, absNumber2) % smallerValue, smallerValue) } } } fun lcm(n1: Int, n2: Int): Int { return if (n1 == 0 || n2 == 0) 0 else { val gcd = gcd(n1, n2) abs(n1 * n2) / gcd } } fun lcm(n1: Long, n2: Long): Long { return if (n1 == 0L || n2 == 0L) 0L else { val gcd = gcd(n1, n2) abs(n1 * n2) / gcd } }
1
Kotlin
0
0
4fafd2b0a88f2f54aa478570301ed55f9649d8f3
1,276
advent-of-code
MIT License
src/main/kotlin/charizard/Engine.kt
mohakapt
677,036,849
false
null
package charizard /** * Calculates the final evaluation of the given board. * This is a recursive function, it calls itself to evaluate the board after each possible move. * To use it for the first time, you should call it with the default parameters. * * @param board The board to evaluate. * @param alpha The best score that the maximizing player can guarantee at that level or below. * @param beta The best score that the minimizing player can guarantee at that level or below. * @param depth The depth of the current move, used to give more weight to faster wins. * @return The best score of the board and the best move to get that score. * @see score * @see Evaluation */ fun minimax(board: Board, depth: Int = 0, alpha: Int = Int.MIN_VALUE, beta: Int = Int.MAX_VALUE): Evaluation { var alpha = alpha var beta = beta val transposition = TranspositionTable.get(board) if (transposition != null && transposition.depth <= depth) { when (transposition.type) { NodeType.EXACT -> return transposition NodeType.LOWER_BOUND -> alpha = alpha.coerceAtLeast(transposition.score) NodeType.UPPER_BOUND -> beta = beta.coerceAtMost(transposition.score) } if (alpha >= beta) { val nodeType = determineNodeType(transposition.score, alpha, beta) return Evaluation(transposition.score, nodeType, depth) } } val boardScore = board.score if (boardScore != null) { val adjustedScore = boardScore * (100 - depth) val nodeType = determineNodeType(adjustedScore, alpha, beta) return Evaluation(adjustedScore, nodeType, depth) } val maximizing = board.turn == Marker.X var bestScore = if (maximizing) Int.MIN_VALUE else Int.MAX_VALUE var bestMove = -1 val moves = board.availableMoves.shuffled().toMutableList() if (transposition?.move != null) { moves.remove(transposition.move) moves.add(0, transposition.move) } for (move in moves) { val virtualBoard = board.makeMove(move) val moveEvaluation = minimax(virtualBoard, depth + 1, alpha, beta) val moveScore = moveEvaluation.score val foundBetterMove = if (maximizing) { alpha = alpha.coerceAtLeast(moveScore) moveScore > bestScore } else { beta = beta.coerceAtMost(moveScore) moveScore < bestScore } if (foundBetterMove) { bestScore = moveScore bestMove = move } if (alpha >= beta) break } val nodeType = determineNodeType(bestScore, alpha, beta) val evaluation = Evaluation(bestScore, nodeType, depth, bestMove) TranspositionTable.put(board, evaluation) return evaluation } private fun determineNodeType(score: Int, alpha: Int, beta: Int): NodeType { return when { score <= alpha -> NodeType.UPPER_BOUND score >= beta -> NodeType.LOWER_BOUND else -> NodeType.EXACT } }
0
Kotlin
0
2
fd67f349b9bb33c15b4bdd48d9d1fef76dd35ed8
3,061
Minimax
MIT License
src/main/kotlin/solved/p581/Solution.kt
mr-nothing
469,475,608
false
{"Kotlin": 162430}
package solved.p581 class Solution { class SortingApproach { // The idea is to sort initial array and compare both arrays from the start and from the end. // The index of first element from the: // - start that is not equal is the lower bound of the subsequence // - end that if not equal is the upper bound of the subsequence fun findUnsortedSubarray(nums: IntArray): Int { val sorted = nums.sorted() var lowerBound = -1 for (i in 0..nums.lastIndex) { if (nums[i] != sorted[i]) { lowerBound = i break } } var upperBound = -1 for (i in nums.lastIndex downTo 0) { if (nums[i] != sorted[i]) { upperBound = i break } } return if (lowerBound == upperBound) 0 else upperBound - lowerBound + 1 } } class TwoPointerApproach { // The idea is to find: // - the element that should be going next to the sorted part at the start of array // - the element that should be going right before the sorted part at the end of array // Lets describe the algorithm for the first part. // 1. It is easy if min element is somewhere in the middle, we just need to sort from the very beginning. // 2. In case the second minimal element is somewhere in the middle and lower elements are sorted in the beginning of array, then we need to sort from the second element. // ... // n. In case the nth minimal element is somewhere in the middle and lower elements are sorted in the beginning of array, then we need to sort from the nth element. // // So to find this element and its index we need to go through the array and if current element is lower than maximal element met, then this can be the upper bound of the subarray we need to sort if nothing similar will be met further. // For the lower bound - if current element is greater than minimal element met, then this can be the lower bound if nothing similar will be met further. fun findUnsortedSubarray(nums: IntArray): Int { var lowerBound = -1 var upperBound = -1 var min = Int.MAX_VALUE var max = Int.MIN_VALUE for (i in 0..nums.lastIndex) { val headPointer = i val headValue = nums[headPointer] if (headValue > max) { max = headValue } else if (headValue < max) { upperBound = headPointer } val tailPointer = nums.lastIndex - i val tailValue = nums[tailPointer] if (tailValue < min) { min = tailValue } else if (tailValue > min) { lowerBound = tailPointer } } return if (upperBound == lowerBound) 0 else upperBound - lowerBound + 1 } } }
0
Kotlin
0
0
0f7418ecc8675d8361ef31cbc1ee26ea51f7708a
3,114
leetcode
Apache License 2.0
src/Day12.kt
shepard8
573,449,602
false
{"Kotlin": 73637}
fun main() { fun part1(heights: List<List<Char>>) { val chars = listOf(' ','╶','╷','┌','╴','─','┐','┬','╵','└','│','├','┘','┴','┤','┼') heights.forEachIndexed { y, line -> line.forEachIndexed { x, c -> val leftAllowed = heights[y].getOrElse(x - 1) { 'z' + 2 } <= c + 1 val rightAllowed = heights[y].getOrElse(x + 1) { 'z' + 2 } <= c + 1 val upAllowed = (heights.getOrElse(y - 1) { listOf() }).getOrElse(x) { 'z' + 2 } <= c + 1 val downAllowed = (heights.getOrElse(y + 1) { listOf() }).getOrElse(x) { 'z' + 2 } <= c + 1 if (x == 0) { println() } val char = (if (upAllowed) 8 else 0) + (if (leftAllowed) 4 else 0) + (if (downAllowed) 2 else 0) + (if (rightAllowed) 1 else 0) print(chars[char]) } } } val input = readInput("Day12") println() println(part1(input.map { it.toList() })) }
0
Kotlin
0
1
81382d722718efcffdda9b76df1a4ea4e1491b3c
1,036
aoc2022-kotlin
Apache License 2.0
solutions/aockt/y2022/Y2022D04.kt
Jadarma
624,153,848
false
{"Kotlin": 435090}
package aockt.y2022 import io.github.jadarma.aockt.core.Solution object Y2022D04 : Solution { private val inputRegex = Regex("""^(\d+)-(\d+),(\d+)-(\d+)$""") /** Parses the [input] and returns the list of elf cleanup section assignments. */ private fun parseInput(input: String): List<Pair<IntRange, IntRange>> = input .lineSequence() .map { line -> inputRegex.matchEntire(line)!!.destructured } .map { (x1, x2, y1, y2) -> x1.toInt()..x2.toInt() to y1.toInt()..y2.toInt() } .toList() /** Returns whether this [IntRange] is fully contained within the [other] or vice-versa. */ private infix fun IntRange.fullyOverlapsWith(other: IntRange): Boolean = when { isEmpty() || other.isEmpty() -> false this.first <= other.first && this.last >= other.last -> true this.first >= other.first && this.last <= other.last -> true else -> false } /** Returns whether this [IntRange] has any overlap with the [other]. */ private infix fun IntRange.overlapsWith(other: IntRange): Boolean = when { isEmpty() || other.isEmpty() -> false this.last < other.first -> false this.first > other.last -> false else -> true } override fun partOne(input: String): Any = parseInput(input).count { (x, y) -> x fullyOverlapsWith y } override fun partTwo(input: String): Any = parseInput(input).count { (x, y) -> x overlapsWith y } }
0
Kotlin
0
3
19773317d665dcb29c84e44fa1b35a6f6122a5fa
1,473
advent-of-code-kotlin-solutions
The Unlicense
src/main/kotlin/dev/shtanko/algorithms/leetcode/MaximumAverageSubarray1.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2020 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import java.lang.Double.NaN fun interface FindMaxAverage { operator fun invoke(nums: IntArray, k: Int): Double } class FindMaxAverage1 : FindMaxAverage { override operator fun invoke(nums: IntArray, k: Int): Double { if (nums.isEmpty()) return NaN val sum = IntArray(nums.size) sum[0] = nums[0] for (i in 1 until nums.size) sum[i] = sum[i - 1] + nums[i] var res = sum[k - 1] * 1.0 / k for (i in k until nums.size) { res = res.coerceAtLeast((sum[i] - sum[i - k]) * 1.0 / k) } return res } } class FindMaxAverage2 : FindMaxAverage { override operator fun invoke(nums: IntArray, k: Int): Double { var sum = 0.0 for (i in 0 until k) sum += nums[i] var res = sum for (i in k until nums.size) { sum += nums[i] - nums[i - k].toDouble() res = res.coerceAtLeast(sum) } return res / k } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,592
kotlab
Apache License 2.0
leetcode2/src/leetcode/kth-smallest-element-in-a-bst.kt
hewking
68,515,222
false
null
package leetcode import leetcode.structure.TreeNode /** * 230. 二叉搜索树中第K小的元素 * https://leetcode-cn.com/problems/kth-smallest-element-in-a-bst/ * Created by test * Date 2019/9/30 19:18 * Description * 给定一个二叉搜索树,编写一个函数 kthSmallest 来查找其中第 k 个最小的元素。 说明: 你可以假设 k 总是有效的,1 ≤ k ≤ 二叉搜索树元素个数。 示例 1: 输入: root = [3,1,4,null,2], k = 1 3 / \ 1 4 \   2 输出: 1 示例 2: 输入: root = [5,3,6,2,4,null,null,1], k = 3 5 / \ 3 6 / \ 2 4 / 1 输出: 3 进阶: 如果二叉搜索树经常被修改(插入/删除操作)并且你需要频繁地查找第 k 小的值,你将如何优化 kthSmallest 函数? 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/kth-smallest-element-in-a-bst 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 */ object KthSmallestElementInABST{ class Solution { fun kthSmallest(root: TreeNode?, k: Int): Int { travsel(root,k) return this.res } private var res:Int = 0 private var i : Int = 0 fun travsel(root: TreeNode?,k:Int) { root?:return travsel(root?.left,k) if (++i == k) { res = root?.`val` } travsel(root?.right,k) } } }
0
Kotlin
0
0
a00a7aeff74e6beb67483d9a8ece9c1deae0267d
1,448
leetcode
MIT License
src/Day11.kt
amelentev
573,120,350
false
{"Kotlin": 87839}
import kotlin.math.abs fun main() { val input = readInput("Day11") val (n, m) = input.size to input[0].length val expandY = input.map { line -> line.all { it=='.' } } val expandX = (0 until m).map { j -> input.all { it[j] == '.' } } fun countExpand(x1: Int, x2: Int, expandX: List<Boolean>): Int { if (x1 > x2) return countExpand(x2, x1, expandX) return (x1..x2).count { expandX[it] } } val galaxies = mutableListOf<Pair<Int, Int>>() for (i in 0 until n) { for (j in 0 until m) { if (input[i][j] == '#') galaxies.add(i to j) } } fun solve(expand: Long): Long { var res = 0L for ((i1, j1) in galaxies) { for ((i2, j2) in galaxies) { res += abs(i1-i2) + abs(j1-j2) res += (expand-1) * countExpand(i1, i2, expandY) res += (expand-1) * countExpand(j1, j2, expandX) } } return res/2 } println(solve(2)) println(solve(10)) println(solve(100)) println(solve(1000000)) }
0
Kotlin
0
0
a137d895472379f0f8cdea136f62c106e28747d5
1,072
advent-of-code-kotlin
Apache License 2.0
src/nativeMain/kotlin/xyz/justinhorton/aoc2022/Day08.kt
justinhorton
573,614,839
false
{"Kotlin": 39759, "Shell": 611}
package xyz.justinhorton.aoc2022 import kotlin.math.abs /** * https://adventofcode.com/2022/day/8 */ class Day08(override val input: String) : Day() { override fun part1(): String { val grid = Grid.fromChars(input) { it.digitToInt() } return grid.enumeratePoints() .count { (x, y) -> isVisible(grid, x, y) } .toString() } override fun part2(): String { val grid = Grid.fromChars(input) { it.digitToInt() } return grid.enumeratePoints() .map { (x, y) -> scenicScore(grid, x, y) } .max() .toString() } private fun isVisible(grid: Grid<Int>, x: Int, y: Int): Boolean { val thisHeight = grid[x to y] return Direction.values().any { dir -> grid.pointsInDirection(x, y, dir).all { grid[it] < thisHeight } } } private fun scenicScore(grid: Grid<Int>, x: Int, y: Int): Int { val thisHeight = grid[x to y] val visibleDistances = Direction.values().map { dir -> val coords = grid.pointsInDirection(x, y, dir) if (coords.none()) { 0 } else { val i = coords.indexOfFirst { grid[it] >= thisHeight } if (i == -1) { // can see to edge; only one of x1 - x or y1 - y is nonzero as x or y is fixed // the final pair of coordinates gives the max diff in this direction coords.last().let { (x1, y1) -> abs(x1 - x + y1 - y) } } else { i + 1 } } } return visibleDistances.fold(1) { acc, v -> acc * v } } }
0
Kotlin
0
1
bf5dd4b7df78d7357291c7ed8b90d1721de89e59
1,691
adventofcode2022
MIT License
src/main/kotlin/ru/spbstu/kparsec/examples/tip/constraint/Equalities.kt
vorpal-research
115,148,080
false
null
package ru.spbstu.kparsec.examples.tip.constraint import java.util.* sealed class Node { abstract operator fun contains(v: Node): Boolean } data class Var(val id: String = dict[currentId].also { ++currentId }) : Node() { override fun contains(v: Node): Boolean = v == this override fun toString() = id companion object { val dict = ('a'..'z').map{ it.toString() } + (0..100).map { "t" + it } var currentId = 0 } } data class Fun(val name: String, val arguments: List<Node>) : Node() { override fun contains(v: Node): Boolean = v == this || arguments.any { it.contains(v) } override fun toString() = "$name(${arguments.joinToString()})" } data class Equality(val lhv: Node, val rhv: Node) { override fun toString() = "$lhv = $rhv" } fun collectVariables(n: Node, set: MutableSet<Var>): Unit = when(n) { is Var -> set += n is Fun -> n.arguments.forEach { collectVariables(it, set) } } fun collectVariables(eq: Equality, set: MutableSet<Var>) { collectVariables(eq.lhv, set) collectVariables(eq.rhv, set) } class Solver(input: List<Equality>) { data class Exception(val eq: Equality): kotlin.Exception("Unsolvable equation: $eq") val que: Queue<Equality> = ArrayDeque(input) val subst: MutableMap<Var, Node> = mutableMapOf() val Equality.rrhv get() = subst[rhv] ?: rhv val Equality.rlhv get() = subst[lhv] ?: lhv val unsolvedVariables: MutableSet<Var> = mutableSetOf() init { input.forEach { collectVariables(it, unsolvedVariables) } } fun substitute(v: Node): Node = when { v is Var && v in subst -> substitute(subst[v]!!) else -> v } fun delete(eq: Equality): Boolean = eq.rlhv != eq.rrhv fun decompose(eq: Equality): Boolean { val lhv = eq.rlhv val rhv = eq.rrhv when { lhv is Fun && rhv is Fun -> { if(lhv.name == rhv.name && lhv.arguments.size == rhv.arguments.size) { lhv.arguments.zip(rhv.arguments) { l, r -> que.add(Equality(substitute(l), substitute(r))) } return false } else throw Exception(eq) } else -> return true } } fun swap(eq: Equality): Boolean { val lhv = eq.rlhv val rhv = eq.rrhv if(rhv is Var && lhv !is Var) { que.add(Equality(rhv, lhv)) return false } return true } fun eliminate(eq: Equality): Boolean { val lhv = eq.rlhv val rhv = eq.rrhv if(lhv is Var) { if(lhv in rhv) throw Exception(eq) unsolvedVariables -= lhv subst[lhv] = rhv return false } return true } fun solve() { while(que.isNotEmpty()) { val v = que.poll()!! when { delete(v) && decompose(v) && swap(v) && eliminate(v) -> que.add(v) } } } fun expand(witness: Var, n: Node): Node = when(n) { witness -> witness in unsolvedVariables -> n is Var -> expand(witness, substitute(n)) is Fun -> n.copy(arguments = n.arguments.map { expand(witness, it) }) } fun result(): List<Equality> { return subst.entries.map { (k, v) -> Equality(k, expand(k, v)) } } }
0
Kotlin
0
0
3238c73af7bb4269176dac57b51614b1402313e5
3,400
kparsec
MIT License
src/aoc2022/Day03.kt
NoMoor
571,730,615
false
{"Kotlin": 101800}
package aoc2022 import utils.* internal class Day03(lines: List<String>) { init { lines.forEach { println(it) } } private val lines = lines .map { val s = it.length / 2 listOf(it.toList().subList(0, s), it.toList().subList(s, it.length)) }.map { it[0].intersect(it[1]).first() }.map { score(it) } private val lines2 = lines.windowed(3, step = 3) .map { it.map { it.toMutableList() }.reduce { acc, chars -> acc.intersect(chars).toMutableList() }.first() }.map { score(it) } fun score(it: Char): Int { return if (it.isUpperCase()) it.code - 'A'.code + 27 else it.code - 'a'.code + 1 } fun part1(): Int { return lines.sum() } fun part2(): Int { return lines2.sum() } companion object { fun runDay() { val day = 3 val todayTest = Day03(readInput(day, 2022, true)) execute(todayTest::part1, "Day[Test] $day: pt 1", 157) val today = Day03(readInput(day, 2022)) execute(today::part1, "Day $day: pt 1", 7908) execute(todayTest::part2, "Day[Test] $day: pt 2", 70) execute(today::part2, "Day $day: pt 2", 2838) } } } fun main() { Day03.runDay() }
0
Kotlin
1
2
d561db73c98d2d82e7e4bc6ef35b599f98b3e333
1,198
aoc2022
Apache License 2.0