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
kotlin/src/com/daily/algothrim/leetcode/AddToArrayForm.kt
idisfkj
291,855,545
false
null
package com.daily.algothrim.leetcode import kotlin.math.pow /** * 989. 数组形式的整数加法 * * 对于非负整数 X 而言,X 的数组形式是每位数字按从左到右的顺序形成的数组。例如,如果 X = 1231,那么其数组形式为 [1,2,3,1]。 * 给定非负整数 X 的数组形式 A,返回整数 X+K 的数组形式。 * */ class AddToArrayForm { companion object { @JvmStatic fun main(args: Array<String>) { // println(AddToArrayForm().solution(intArrayOf(1, 2, 0, 0), 34)) // println(AddToArrayForm().solution(intArrayOf(9, 9, 9, 9, 9, 9, 9, 9, 9, 9), 1)) println(AddToArrayForm().solution2(intArrayOf(1, 2, 0, 0), 34)) println(AddToArrayForm().solution2(intArrayOf(9, 9, 9, 9, 9, 9, 9, 9, 9, 9), 1)) } } // 输入:A = [1,2,0,0], K = 34 // 输出:[1,2,3,4] // 解释:1200 + 34 = 1234 // 这种方式会超出int、long类型边界 fun solution(A: IntArray, K: Int): List<Int> { val result = mutableListOf<Int>() val n = A.size var i = n var num = 0 while (--i >= 0) { num += A[i].times(10f.pow(n - i - 1)).toInt() } num += K num.toString().forEach { result.add(it - '0') } return result } /** * O(max(A.size, logK)) */ fun solution2(A: IntArray, K: Int): List<Int> { val result = mutableListOf<Int>() val n = A.size var i = n var sum: Int var k = K // 从低向高位 while (--i >= 0) { // 取当前位数值 val curr = k % 10 // 求和 sum = curr + A[i] // 剩余位数数值 k /= 10 // 进位 if (sum >= 10) { sum %= 10 k++ } result.add(sum) } // k有剩余 while (k > 0) { result.add(k % 10) k /= 10 } return result.reversed() } }
0
Kotlin
9
59
9de2b21d3bcd41cd03f0f7dd19136db93824a0fa
2,098
daily_algorithm
Apache License 2.0
src/array/LeetCode347.kt
Alex-Linrk
180,918,573
false
null
package array /** * 前K个高频元素 * 给定一个非空的整数数组,返回其中出现频率前 k 高的元素。 * *示例 1: * *输入: nums = [1,1,1,2,2,3], k = 2 *输出: [1,2] *示例 2: * *输入: nums = [1], k = 1 *输出: [1] *说明: * *你可以假设给定的 k 总是合理的,且 1 ≤ k ≤ 数组中不相同的元素的个数。 *你的算法的时间复杂度必须优于 O(n log n) , n 是数组的大小。 */ class LeetCode347 { fun topKFrequent(nums: IntArray, k: Int): List<Int> { if (nums.isEmpty()) return emptyList() if (nums.size == k) return nums.toList() val map = mutableMapOf<Int, Int>() for (word in nums) { if (map.containsKey(word)) { map[word] = map[word]!! + 1 } else { map[word] = 1 } } val start = map.size / 2 val nodes = map.toList() val heaps = Array(map.size) { Node(nodes[it].first, nodes[it].second) } for (index in start downTo 0) { maxHeapify(heaps, index, heaps.lastIndex) } val list = mutableListOf<Int>() var item = 0 while (item < k) { list.add(heaps[0].value) swip(heaps, 0, heaps.lastIndex - item) item++ maxHeapify(heaps, 0, heaps.lastIndex - item) } return list } fun maxHeapify(heaps: Array<Node>, index: Int, len: Int) { val left = index * 2 val right = left + 1 var max = left if (left > len) return if (right <= len && heaps[left].count < heaps[right].count) { max = right } if (heaps[max].count > heaps[index].count) { swip(heaps, max, index) maxHeapify(heaps, max, len) } } fun swip(heaps: Array<Node>, left: Int, right: Int) { val temp = heaps[left] heaps[left] = heaps[right] heaps[right] = temp } } data class Node(val value: Int, val count: Int) fun main() { println( LeetCode347().topKFrequent(intArrayOf(1, 1, 1, 2, 2, 3), 2) ) println( LeetCode347().topKFrequent(intArrayOf(1), 1) ) }
0
Kotlin
0
0
59f4ab02819b7782a6af19bc73307b93fdc5bf37
2,235
LeetCode
Apache License 2.0
src/main/kotlin/days/Day11.kt
jgrgt
433,952,606
false
{"Kotlin": 113705}
package days class Day11 : Day(11) { override fun runPartOne(lines: List<String>): Any { val levels = parse(lines) val octopusses = Octopusses(levels) return (0..99).sumOf { octopusses.flash() } } override fun runPartTwo(lines: List<String>): Any { val levels = parse(lines) val octopusses = Octopusses(levels) var flashes = 0 var steps = 0 while(flashes != octopusses.size) { flashes = octopusses.flash() steps += 1 } return steps } fun parse(lines: List<String>): List<List<Int>> { return lines.map { line -> line.map { c -> c.digitToInt() } } } class Octopusses(l: List<List<Int>>) { val levels = l.map { it.toMutableList() }.toMutableList() val size = levels.size * levels[0].size val flashed = -1 fun flash(): Int { forEachPoint { point -> val level = getLevel(point) if (level != null) { bumpLevel(point) } } var flashes = 0 forEachPoint { p -> val level = getLevel(p) if (level == flashed) { flashes += 1 setLevel(p, 0) // reset } } return flashes } private fun bumpLevel(p: Point): List<Point> { val level = getLevel(p) ?: return emptyList() return if (level == flashed) { // Do nothing, already flashed emptyList<Point>() } else if (level < 9) { setLevel(p, level + 1) emptyList<Point>() } else if (level == 9) { setLevel(p, flashed) p.around().flatMap { bumpLevel(it) } } else { error("Invalid point value") } } private fun setLevel(p: Point, level: Int) { levels[p.x][p.y] = level } private fun getLevel(point: Point): Int? { return if (point.x < 0 || point.y < 0 || point.x >= levels.size || point.y >= levels[0].size) { null } else { levels[point.x][point.y] } } /** * yyyyyyyyyyyyyyyyyyyyy * x * x * x * x * x * x * x */ private fun forEachPoint(consumer: (Point) -> Unit) { levels.forEachIndexed { x, levelRow -> levelRow.forEachIndexed { y, _ -> consumer.invoke(Point(x, y)) } } } } data class Point(val x: Int, val y: Int) { fun around(): List<Point> { return listOf( Point(x - 1, y + 1), Point(x - 1, y), Point(x - 1, y - 1), Point(x, y + 1), Point(x, y - 1), Point(x + 1, y + 1), Point(x + 1, y), Point(x + 1, y - 1), ) } } }
0
Kotlin
0
0
6231e2092314ece3f993d5acf862965ba67db44f
3,244
aoc2021
Creative Commons Zero v1.0 Universal
src/main/kotlin/day5.kt
nerok
436,232,451
false
{"Kotlin": 32118}
import java.io.File import kotlin.math.abs fun main(args: Array<String>) { val lines = File("day5input.txt").reader() var coordinates = mutableListOf<List<Pair<Int, Int>>>() var size = 0 lines.forEachLine { fileLine -> fileLine .split("->") .map { coordinates -> coordinates .split(",") .map { coordinate -> Integer.parseInt(coordinate.filter { !it.isWhitespace() }).also { if (it > size) { size = it } } }.let { it.first() to it.last() } }.let { coordinatePair -> if (coordinatePair.first().first == coordinatePair.last().first) { val lowerEnd = minOf(coordinatePair.first().second, coordinatePair.last().second) val higherEnd = maxOf(coordinatePair.first().second, coordinatePair.last().second) return@let IntRange(lowerEnd, higherEnd).map { coordinatePair.first().first to it } } else if (coordinatePair.first().second == coordinatePair.last().second) { val lowerEnd = minOf(coordinatePair.first().first, coordinatePair.last().first) val higherEnd = maxOf(coordinatePair.first().first, coordinatePair.last().first) return@let IntRange(lowerEnd, higherEnd).map { it to coordinatePair.first().second } } else { val firstDistance = abs(coordinatePair.first().first - coordinatePair.last().first) val secondDistance = abs(coordinatePair.first().second - coordinatePair.last().second) if (firstDistance == secondDistance) { val lowerFirst = minOf(coordinatePair.first().first, coordinatePair.last().first) val higherFirst = maxOf(coordinatePair.first().first, coordinatePair.last().first) val firstRange = IntRange(lowerFirst, higherFirst).toList() val lowerSecond = minOf(coordinatePair.first().second, coordinatePair.last().second) val higherSecond = maxOf(coordinatePair.first().second, coordinatePair.last().second) val secondRange = IntRange(lowerSecond, higherSecond).toList() val reverseFirst = coordinatePair.first().first != firstRange.first() val reverseSecond = coordinatePair.first().second != secondRange.first() return@let firstRange.mapIndexed { index, i -> if (reverseFirst xor reverseSecond) { i to secondRange[secondDistance - index] } else { i to secondRange[index] } } } else { return@let emptyList() } } }.let { coordinates.add(it) } } var area = Array(size+1) { IntArray(size+1) { 0 } } coordinates.flatten().forEach { area[it.second][it.first] = area[it.second][it.first] + 1 } val hotpoints = area.map { it.filter { it > 1 } }.flatten().count().also { println(it) } }
0
Kotlin
0
0
4dee925c0f003fdeca6c6f17c9875dbc42106e1b
3,471
Advent-of-code-2021
MIT License
src/Day08.kt
6234456
572,616,769
false
{"Kotlin": 39979}
import kotlin.math.abs import kotlin.math.max fun main() { fun part1(input: List<String>): Int { val src = input.map { it.toCharArray().map { it.digitToInt() }.toIntArray() }.toTypedArray() val n = input.size // up down left right val dps: Array<Array<BooleanArray>> = Array(4){Array(n){ BooleanArray(n){true} } } // up -> down val maxArray:IntArray = IntArray(n) dps[0].indices.forEach { index -> if (index == 0){ (0 until n).forEach { maxArray[it] = src[index][it] } }else{ (0 until n).forEach { dps[0][index][it] = src[index][it] > maxArray[it] maxArray[it] = max(maxArray[it], src[index][it]) } } } // down -> up (n-1 downTo 0).forEach { index -> if (index == n-1){ (0 until n).forEach { maxArray[it] = src[index][it] } }else{ (0 until n).forEach { dps[1][index][it] = src[index][it] > maxArray[it] maxArray[it] = max(maxArray[it], src[index][it]) } } } // left -> right (0 until n).forEach { index -> if (index == 0){ (0 until n).forEach { maxArray[it] = src[it][index] } }else{ (0 until n).forEach { dps[2][it][index] = src[it][index] > maxArray[it] maxArray[it] = max(maxArray[it], src[it][index]) } } } // right-> left (n-1 downTo 0).forEach { index -> if (index == n-1){ (0 until n).forEach { maxArray[it] = src[it][index] } }else{ (0 until n).forEach { dps[3][it][index] = src[it][index] > maxArray[it] maxArray[it] = max(maxArray[it], src[it][index]) } } } var res = 0 (0 until n).forEach { i -> (0 until n).forEach { j -> if(dps[0][i][j] || dps[1][i][j] || dps[2][i][j] || dps[3][i][j]) res++ } } return res } fun part2(input: List<String>): Int { val src = input.map { it.toCharArray().map { it.digitToInt() }.toIntArray() }.toTypedArray() val n = input.size // up down left right val dps: Array<Array<IntArray>> = Array(4){Array(n){ IntArray(n){0} } } // up -> down val lastPos = Array<IntArray>(n){ IntArray(10){-1} } fun reset(){ (0 until n).forEach { i -> (0 until 9).forEach { j -> lastPos[i][j] = -1 }} } fun lastP(row: Int, col: Int, order: Int, reversed: Boolean = true):Int{ val current = src[row][col] return (current .. 9).map { if (reversed) if (lastPos[col][it] == -1) order else abs(lastPos[col][it] - row) else if (lastPos[row][it] == -1) order else abs(lastPos[row][it] - col) }.min() } dps[0].indices.forEach { index -> if (index > 0){ (0 until n).forEach { dps[0][index][it] = lastP(index, it, index) } } (0 until n).forEach { lastPos[it][src[index][it]] = index } } reset() // down -> up (n-1 downTo 0).forEach { index -> if (index < n -1){ (0 until n).forEach { dps[1][index][it] = lastP(index, it, n-1 - index) } } (0 until n).forEach { lastPos[it][src[index][it]] = index } } reset() // left -> right by col (0 until n).forEach { index -> if (index > 0){ (0 until n).forEach { dps[2][it][index] = lastP(it, index, index, false) } } (0 until n).forEach { lastPos[it][src[it][index]] = index } } reset() // right-> left (n-1 downTo 0).forEach { index -> if (index < n-1){ (0 until n).forEach { dps[3][it][index] = lastP(it, index, n-1 - index, false) } } (0 until n).forEach { lastPos[it][src[it][index]] = index } } var res = 0 var i0 = 0 var j0 = 0 (0 until n).forEach { i -> (0 until n).forEach { j -> val tmp = max(res,dps[0][i][j]* dps[1][i][j] * dps[2][i][j]*dps[3][i][j]) if (tmp > res){ i0 = i j0 = j } res = tmp } } println("i : $i0, j: $j0") return res } var input = readInput("Test08") println(part1(input)) println(part2(input)) input = readInput("Day08") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
b6d683e0900ab2136537089e2392b96905652c4e
5,518
advent-of-code-kotlin-2022
Apache License 2.0
app/src/main/kotlin/ca/warp7/rt/ext/predictor/Alliance.kt
Team865
159,395,287
false
null
package ca.warp7.rt.ext.predictor abstract class Alliance(open val teams: List<Team>) data class TeamStats(var hatch: Int, var cargo: Int) class Alliance2019(override val teams: List<Team2019>) : Alliance(teams) { private fun chooseStrat(panelL1: Double, panelL2: Double, panelL3: Double, cargoL1: Double, cargoL2: Double, cargoL3: Double, l1State: Pair<Boolean, Boolean>, l2State: Pair<Boolean, Boolean>, l3State: Pair<Boolean, Boolean>) : Pair<Int, Pair<Boolean, Boolean>> { val efficiencies: MutableList<MutableList<Double>> = mutableListOf( mutableListOf(2 / panelL1, 2 / panelL2, 2 / panelL3), mutableListOf(3 / cargoL1, 3 / cargoL2, 3 / cargoL3), mutableListOf(5 / (panelL1 + cargoL1), 5 / (panelL2 + cargoL2), 5 / (panelL3 + cargoL3)) ) listOf(l1State, l2State, l3State).forEachIndexed { i, it -> when (it) { Pair(false, false) -> { efficiencies[0][i] = 0.0 efficiencies[1][i] = 0.0 efficiencies[2][i] = 0.0 } Pair(false, true) -> { efficiencies[0][i] = 0.0 efficiencies[2][i] = 0.0 } Pair(true, false) -> { efficiencies[1][i] = 0.0 } } } val m = efficiencies.flatten().indexOf(efficiencies.flatten().max()) val strategy = Pair(m%3,(m-m%3)/3) return Pair(strategy.first, Pair(strategy.second in listOf(0,2), strategy.second in listOf(1,2))) } fun simMatch(): Pair<Double, List<TeamStats>> { var score = teams.map { team -> team.climbPoints.sample() }.sum() val stats = teams.map { TeamStats(0, 0) } val teamLocalTimes: MutableList<Double> = teams.map { Math.random() }.toMutableList() val panelPoints = 2 val cargoPoints = 3 val l = mutableListOf(Pair(12, 12), Pair(4, 4), Pair(4, 4)) teams.forEach { team -> val panel = team.autoPanel.sample().toInt() val cargo = team.autoCargo.sample().toInt() l[0] = Pair(l[0].first - panel, l[0].second) l[0] = Pair(l[0].first - cargo, l[0].second - cargo) score += panel * (panelPoints + cargoPoints) score += cargo * (cargoPoints) } var curTeam: Team2019 while (true in teamLocalTimes.map { it < 135 }) { val tIndex = teamLocalTimes.indexOf(teamLocalTimes.min()) curTeam = teams[tIndex] val availableLevels = (0..2).map { Pair(l[it].first > 0, l[it].second > 0 && (l[it].first < l[it].second)) } val choice = chooseStrat( curTeam.tele.first[0].average, curTeam.tele.first[1].average, curTeam.tele.first[2].average, curTeam.tele.second[0].average, curTeam.tele.second[1].average, curTeam.tele.second[2].average, availableLevels[0], availableLevels[1], availableLevels[2] ) when { choice.second.first -> { teamLocalTimes[tIndex] += curTeam.tele.first[choice.first].sample() if (teamLocalTimes[tIndex] <= 135) { score += panelPoints l[choice.first] = Pair(l[choice.first].first - 1, l[choice.first].second) stats[tIndex].hatch++ } } choice.second.second -> { teamLocalTimes[tIndex] += curTeam.tele.second[choice.first].sample() if (teamLocalTimes[tIndex] <= 135) { score += cargoPoints l[choice.first] = Pair(l[choice.first].first, l[choice.first].second - 1) stats[tIndex].cargo++ } } } } println("$score $stats") return Pair(score, stats) } } fun main() { val t865 = Team2019( 865, Discrete(mapOf(Pair(0.6, 2.0))), emptyDiscrete(), Gaussian(16.0, 4.0), Gaussian(16.0, 5.0), Gaussian(16.0, 5.0), Gaussian(13.0, 4.0), Gaussian(14.0, 3.0), Gaussian(14.0, 3.0), emptyDiscrete() ) val t1114 = Team2019( 1114, Discrete(mapOf(Pair(0.8, 2.0))), emptyDiscrete(), Gaussian(12.0, 3.0), Gaussian(12.0, 3.0), Gaussian(12.0, 4.0), Gaussian(13.0, 2.0), Gaussian(13.0, 2.0), Gaussian(13.0, 2.0), emptyDiscrete() ) val t4039 = Team2019( 4039, emptyDiscrete(), Discrete(mapOf(Pair(0.4, 1.0))), Gaussian(20.0, 3.0), emptyCycle(), emptyCycle(), Gaussian(20.0, 5.0), emptyCycle(), emptyCycle(), emptyDiscrete() ) val r = Alliance2019(listOf(t1114, t865, t4039)) val s: MutableList<Double> = mutableListOf() val n = 10 val stats: MutableList<List<Any>> = mutableListOf() for (i in 1..n) { val (m, stat) = r.simMatch() //println(m) s.add(m) stats.add(listOf(stat))//stat.map{listOf(it.hatch,it.Cargo)}.flatten()) } println(s.sum() / n) println(stats.forEach { match -> match.forEach { stat -> print(stat) print("\t") } println() }) }
0
Kotlin
0
2
4c97affce1eb48e14511a4b0824bb45fbb4cbcb9
5,652
Restructured-Tables
MIT License
src/main/kotlin/days/Day2.kt
andilau
544,512,578
false
{"Kotlin": 29165}
package days import days.Day2.Point.Companion.DOWN import days.Day2.Point.Companion.LEFT import days.Day2.Point.Companion.RIGHT import days.Day2.Point.Companion.UP import java.lang.IllegalArgumentException @AdventOfCodePuzzle( name = "Bathroom Security", url = "https://adventofcode.com/2016/day/2", date = Date(day = 2, year = 2016) ) class Day2(private val input: List<String>) : Puzzle { private val keypadOne = """ 123 456 789""".trimIndent().lines().let { Keypad.of(it) } private val keypadTwo = """ | 1 | 234 |56789 | ABC | D""".trimMargin().lines().let { Keypad.of(it) } override fun partOne(): String = solve(keypadOne) override fun partTwo(): String = solve(keypadTwo) private fun solve(keypad: Keypad): String { val start = keypad.find('5') return input.fold("" to start) { (code, key), line -> line.fold(key) { position, instruction -> when (instruction) { 'L' -> keypad.left(position) 'R' -> keypad.right(position) 'U' -> keypad.up(position) 'D' -> keypad.down(position) else -> throw IllegalArgumentException("Unknown instruction: $instruction") } }.let { Pair(code + it.c, it) } }.first } data class Key(val c: Char, val pos: Point) data class Point(val x: Int, val y: Int) { companion object { val LEFT = Point(-1, 0) val RIGHT = Point(1, 0) val UP = Point(0, -1) val DOWN = Point(0, 1) } } data class Keypad(val keys: List<Key>) { private val byCharacter = keys.associateBy { it.c } private val byPosition = keys.associateBy { it.pos } fun left(key: Key): Key = find(key, LEFT) fun right(key: Key): Key = find(key, RIGHT) fun up(key: Key): Key = find(key, UP) fun down(key: Key): Key = find(key, DOWN) private fun find(key: Key, delta: Point): Key { val next = Point(key.pos.x + delta.x, key.pos.y + delta.y) return byPosition[next] ?: key } fun find(char: Char): Key = byCharacter[char] ?: throw IllegalArgumentException("Char $char not found in layout") companion object { fun of(layout: List<String>): Keypad { val keys: List<Key> = layout.flatMapIndexed { y, line -> line.mapIndexedNotNull { x, char -> if (char.isWhitespace()) null else Key(char, Point(x, y)) } }.toList() return Keypad(keys) } } } }
3
Kotlin
0
0
b2a836bd3f1c5eaec32b89a6ab5fcccc91b665dc
2,708
advent-of-code-2016
Creative Commons Zero v1.0 Universal
src/Day05.kt
Aldas25
572,846,570
false
{"Kotlin": 106964}
fun main() { fun part1(input: List<String>, stacks: Array<ArrayDeque<Char>>): String { var ans = "" for (str in input) { val parts = str.split(" ") val quantity = parts[1].toInt() val from = parts[3].toInt() val to = parts[5].toInt() repeat(quantity) { stacks[to-1].addLast(stacks[from-1].removeLast()) } } for (stack in stacks) { ans += stack.last() } return ans } fun part2(input: List<String>, stacks: Array<ArrayDeque<Char>>): String { for (str in input) { val parts = str.split(" ") val quantity = parts[1].toInt() val from = parts[3].toInt() val to = parts[5].toInt() val newStack: ArrayDeque<Char> = ArrayDeque() repeat(quantity) { newStack.addLast(stacks[from-1].removeLast()) } repeat(quantity) { stacks[to-1].addLast(newStack.removeLast()) } } var ans = "" for (stack in stacks) { ans += stack.last() } return ans } fun getStacks(filename: String): Array<ArrayDeque<Char>> { return if (filename == "inputs\\day05_sample") arrayOf( ArrayDeque(listOf('Z', 'N')), ArrayDeque(listOf('M', 'C', 'D')), ArrayDeque(listOf('P')) ) else arrayOf( ArrayDeque(listOf('H', 'T', 'Z', 'D')), ArrayDeque(listOf('Q', 'R', 'W', 'T', 'G', 'C', 'S')), ArrayDeque(listOf('P', 'B', 'F', 'Q', 'N', 'R', 'C', 'H')), ArrayDeque(listOf('L', 'C', 'N', 'F', 'H', 'Z')), ArrayDeque(listOf('G', 'L', 'F', 'Q', 'S')), ArrayDeque(listOf('V', 'P', 'W', 'Z', 'B', 'R', 'C', 'S')), ArrayDeque(listOf('Z', 'F', 'J')), ArrayDeque(listOf('D', 'L', 'V', 'Z', 'R', 'H', 'Q')), ArrayDeque(listOf('B', 'H', 'G', 'N', 'F', 'Z', 'L', 'D')) ) } val filename = // "inputs\\day05_sample" "inputs\\day05" val input = readInput(filename) println("Part 1: ${part1(input, getStacks(filename))}") println("Part 2: ${part2(input, getStacks(filename))}") }
0
Kotlin
0
0
80785e323369b204c1057f49f5162b8017adb55a
2,328
Advent-of-Code-2022
Apache License 2.0
src/nativeMain/kotlin/Day2.kt
rubengees
576,436,006
false
{"Kotlin": 67428}
class Day2 : Day { private val winTable = mapOf(1 to 3, 2 to 1, 3 to 2) private fun calculateScorePart1(left: Char, right: Char): Int { val leftCode = left.code - 'A'.code + 1 val rightCode = right.code - 'X'.code + 1 return when { winTable[rightCode] == leftCode -> 6 + rightCode winTable[leftCode] == rightCode -> rightCode else -> 3 + rightCode } } override suspend fun part1(input: String): String { return input.lines() .sumOf { val chars = it.split(" ").map { part -> part.first() } calculateScorePart1(chars.first(), chars.last()) } .toString() } private val reverseWinTable = winTable.entries.associateBy({ it.value }) { it.key } private fun calculateScorePart2(left: Char, right: Char): Int { val leftCode = left.code - 'A'.code + 1 return when (right) { 'X' -> winTable.getValue(leftCode) 'Y' -> 3 + leftCode 'Z' -> 6 + reverseWinTable.getValue(leftCode) else -> error("Unknown right $right") } } override suspend fun part2(input: String): String { return input.lines() .sumOf { val chars = it.split(" ").map { part -> part.first() } calculateScorePart2(chars.first(), chars.last()) } .toString() } }
0
Kotlin
0
0
21f03a1c70d4273739d001dd5434f68e2cc2e6e6
1,452
advent-of-code-2022
MIT License
src/main/java/com/github/mmauro94/irws/Utils.kt
MMauro94
202,988,256
false
{"HTML": 765422, "Kotlin": 20314}
package com.github.mmauro94.irws /** * Computes the Jaccard distance between two generic elements [elem1] and [elem2]. * @see jaccardIndex */ inline fun <T, X> jaccardDistance(elem1: T, elem2: T, crossinline setSelector: (T) -> Set<X>): Double { return 1 - jaccardIndex(elem1, elem2, setSelector) } /** * Computes the Jaccard index (aka Jaccard similarity) between two generic elements [elem1] and [elem2]. * In order to compute the index, a [setSelector] must be provided, that will return, given an element, the reference set for that element. */ inline fun <T, X> jaccardIndex(elem1: T, elem2: T, crossinline setSelector: (T) -> Set<X>): Double { val elem1Set = setSelector(elem1) val elem2Set = setSelector(elem2) val intersection = if (elem1Set.size < elem2Set.size) { elem1Set.count { elem2Set.contains(it) } } else { elem2Set.count { elem1Set.contains(it) } } return intersection.toDouble() / (elem1Set.size + elem2Set.size - intersection) } /** * Computes the minimum value in [this] instance using the given [selector]. * It returns a [Pair] containing both the element and the minimum value computed by the selector. */ fun <T, C : Comparable<C>> Iterable<T>.minOf(selector: (T) -> C): Pair<T, C>? { var min: Pair<T, C>? = null for (elem in this) { val selected = selector(elem) if (min == null || selected < min.second) { min = Pair(elem, selected) } } return min } /** * List of supported units by the [bitsToString] function. */ private val units = listOf("bytes", "kiB", "MiB", "GiB", "TiB") /** * Converts [this] number representing a number of bits, in a human readable string, using the appropriate unit (e.g. kiB, MiB, etc.) */ fun Long.bitsToString(): String { return if (this < 8) { "$this bits" } else { var bytes = this / 8.0 val unit = units.listIterator() unit.next() while (bytes >= 1024 && unit.hasNext()) { bytes /= 1024 unit.next() } "% 7.2f %-5s".format(bytes, unit.previous()) } }
0
HTML
0
0
7582bd3e3fbca9dc8ed254c37cd36c8fb8f22105
2,118
irws-project
The Unlicense
src/Day06.kt
azat-ismagilov
573,217,326
false
{"Kotlin": 75114}
fun main() { fun String.findFirstSubstringWithDifferentChars(substringLength: Int): Int { for (index in substringLength..length) if ((index - substringLength until index) .map { this[it] } .toSet() .size == substringLength ) { return index } return length } fun part1(input: List<String>) = input.first().findFirstSubstringWithDifferentChars(4) fun part2(input: List<String>) = input.first().findFirstSubstringWithDifferentChars(14) // test if implementation meets criteria from the description, like: check(part1(listOf("bvwbjplbgvbhsrlpgdmjqwftvncz")) == 5) check(part1(listOf("nppdvjthqldpwncqszvftbrmjlhg")) == 6) check(part1(listOf("nznrnfrfntjfmvfwmzdfjlvtqnbhcprsg")) == 10) check(part1(listOf("zcfzfwzzqfrljwzlrfnpqdbhtmscgvjw")) == 11) check(part2(listOf("mjqjpqmgbljsphdztnvjfqwrcgsmlb")) == 19) check(part2(listOf("bvwbjplbgvbhsrlpgdmjqwftvncz")) == 23) check(part2(listOf("nppdvjthqldpwncqszvftbrmjlhg")) == 23) check(part2(listOf("nznrnfrfntjfmvfwmzdfjlvtqnbhcprsg")) == 29) check(part2(listOf("zcfzfwzzqfrljwzlrfnpqdbhtmscgvjw")) == 26) val input = readInput("Day06") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
abdd1b8d93b8afb3372cfed23547ec5a8b8298aa
1,331
advent-of-code-kotlin-2022
Apache License 2.0
src/Day01.kt
krisbrud
573,455,086
false
{"Kotlin": 8417}
fun main() { fun splitOnBlank(list: List<String>): List<List<Int>> { return list.fold(mutableListOf(mutableListOf<Int>())) { acc, item -> if (item.isBlank()) { acc.add(mutableListOf()) } else { acc.last().add(item.toInt()) } acc } } fun part1(input: List<String>): Int { val groups = splitOnBlank(input) val sums = groups.map { it.sum() } println(input) println(groups) println(sums) return sums.max() } fun part2(input: List<String>): Int { val groups = splitOnBlank(input) return groups.map { it.sum() }.sorted().takeLast(3).sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") check(part1(testInput) == 24000) val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
02caf3a30a292d7b8c9e2b7788df74650e54573c
969
advent-of-code-2022
Apache License 2.0
src/chapter1/problem2/solution1.kts
neelkamath
395,940,983
false
null
/* Question: Check Permutation: Given two strings, write a method to decide if one is a permutation of the other. Solution: Using a map. */ listOf("hello" to "hello", "hello" to "hleol", "hello" to "helo", "" to "bye", "b" to "by", "bye" to "eyb") .forEach { (string1, string2) -> println("$string1, $string2: ${arePermutations(string1, string2)}") } fun arePermutations(string1: String, string2: String): Boolean { val map = mutableMapOf<Char, Int>() val (longer, shorter) = if (string1.length > string2.length) listOf(string1, string2) else listOf(string2, string1) for (index in longer.indices) { map[longer[index]] = map.getOrDefault(longer[index], 0) + 1 if (index in shorter.indices) map[shorter[index]] = map.getOrDefault(shorter[index], 0) - 1 } return map.values.all { it == 0 } }
0
Kotlin
0
0
4421a061e5bf032368b3f7a4cee924e65b43f690
834
ctci-practice
MIT License
src/main/kotlin/com/ginsberg/advent2023/Day08.kt
tginsberg
723,688,654
false
{"Kotlin": 112398}
/* * Copyright (c) 2023 by <NAME> */ /** * Advent of Code 2023, Day 8 - Haunted Wasteland * Problem Description: http://adventofcode.com/2023/day/8 * Blog Post/Commentary: https://todd.ginsberg.com/post/advent-of-code/2023/day8/ */ package com.ginsberg.advent2023 class Day08(input: List<String>) { private val instructions: String = input.first() private val routeMap: Map<String, Pair<String, String>> = parseRouteMap(input) fun solvePart1(): Int = countSteps("AAA") fun solvePart2(): Long = routeMap.keys .filter { it.endsWith("A") } .map { countSteps(it).toLong() } .reduce { prev, next -> prev.lcm(next) } private fun countSteps(start: String): Int { var steps = 0 var current = start while (!current.endsWith("Z")) { current = routeMap.getValue(current).let { route -> val instruction = instructions[steps++ % instructions.length] if (instruction == 'L') route.first else route.second } } return steps } private fun parseRouteMap(input: List<String>): Map<String, Pair<String, String>> = input .drop(2) .associate { it.substring(0..2) to (it.substring(7..9) to it.substring(12..14)) } }
0
Kotlin
0
12
0d5732508025a7e340366594c879b99fe6e7cbf0
1,365
advent-2023-kotlin
Apache License 2.0
src/nativeMain/kotlin/com.qiaoyuang.algorithm/round1/Questions3.kt
qiaoyuang
100,944,213
false
{"Kotlin": 338134}
package com.qiaoyuang.algorithm.round1 import com.qiaoyuang.algorithm.round0.exchange fun test3() { val numbers0 = intArrayOf(2, 3, 1, 0, 2, 5, 3) val numbers1 = intArrayOf(2, 3, 5, 4, 3, 2, 6, 7) println("The repeat number is: ${findNumber1(numbers0)}") println("The repeat number is: ${findNumber1(numbers1)}") println("The repeat number is: ${findNumber21(numbers1)}") println("The repeat number is: ${findNumber22(numbers1)}") } /** * Questions 3-1: Find the repeat number in IntArray, the numbers between 0~n-1 */ private fun findNumber1(numbers: IntArray): Int { numbers.forEachIndexed { index, i -> if (index != i) { if (i == numbers[i]) return i else numbers.exchange(index, i) } } throw IllegalArgumentException("This IntArray doesn't have repeat number") } /** * Questions 3-2: Find the repeat number in IntArray, * the IntArray.length == n + 1, the numbers between 1~n-1, * but can't modify the IntArray. */ private fun findNumber21(numbers: IntArray): Int { val helpArray = IntArray(numbers.size) numbers.forEach { if (helpArray[it] == it) return it else helpArray[it] = it } throw IllegalArgumentException("This IntArray doesn't have repeat number") } private fun findNumber22(numbers: IntArray): Int { var start = 1 var end = numbers.lastIndex while (end >= start) { val middle = ((end - start) shr 1) + start val count = numbers countRange start..middle if (end == start) { if (count > 1) return start else break } if (count > (middle - start + 1)) end = middle else start = middle + 1 } throw IllegalArgumentException("The 'numbers' doesn't have repeat numbers") } private infix fun IntArray.countRange(range: IntRange): Int = fold(0) { acc, number -> if (number in range) acc + 1 else acc }
0
Kotlin
3
6
66d94b4a8fa307020d515d4d5d54a77c0bab6c4f
2,057
Algorithm
Apache License 2.0
src/Day04.kt
wlghdu97
573,333,153
false
{"Kotlin": 50633}
fun main() { fun String.toRange(): IntRange { val (a, b) = this.split("-") val range = a.toInt()..b.toInt() if (range.step < 0) { throw IllegalArgumentException() } return range } fun IntRange.includes(other: IntRange): Boolean { return when { (this.step != 1 || other.step != 1) -> { throw UnsupportedOperationException() } (this.first < other.first) -> { this.last >= other.last } (this.first > other.first) -> { this.last <= other.last } else -> { true } } } fun IntRange.overlap(other: IntRange): Boolean { return when { (this.step != 1 || other.step != 1) -> { throw UnsupportedOperationException() } (this.first < other.first) -> { this.last >= other.first } (this.first > other.first) -> { this.first <= other.last } else -> { true } } } fun part1(input: List<String>): Int { return input.count { val (first, second) = it.split(",") val firstRange = first.toRange() val secondRange = second.toRange() firstRange.includes(secondRange) } } fun part2(input: List<String>): Int { return input.count { val (first, second) = it.split(",") val firstRange = first.toRange() val secondRange = second.toRange() firstRange.overlap(secondRange) } } val input = readInput("Day04") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
2b95aaaa9075986fa5023d1bf0331db23cf2822b
1,810
aoc-2022
Apache License 2.0
src/Day07.kt
zirman
572,627,598
false
{"Kotlin": 89030}
import java.lang.Exception import java.util.Stack //typealias Foo = Map<String, Foo> sealed interface Filesystem { data class Directory(val nodes: MutableMap<String, Filesystem>) : Filesystem data class File(val size: Long) : Filesystem } sealed interface Size { data class Directory(override val size: Long, val nodes: Map<String, Size>) : Size data class File(override val size: Long) : Size val size: Long } fun main() { fun part1(input: List<String>): Long { val groups = input.joinToString("\n").split(Regex("""\$ """)) .map { it.split("\n").dropLast(1) } .drop(1) val root = Filesystem.Directory(mutableMapOf()) val path = Stack<Filesystem.Directory>() path.push(root) groups.forEach { group -> val (cmd) = group val cdMatches = Regex("""^cd (.+)$""").matchEntire(cmd) val lsMatches = Regex("""^ls$""").matchEntire(cmd) if (cdMatches != null) { val (dir) = cdMatches.destructured if (dir == "/") { while (path.size > 1) { path.pop() } } else if (dir == "..") { path.pop() } else if (path.peek().nodes.containsKey(dir)) { path.push(path.peek().nodes[dir] as Filesystem.Directory) } else { val directory = Filesystem.Directory(mutableMapOf()) path.peek().nodes[dir] = directory path.push(directory) } } else if (lsMatches != null) { val output = group.subList(1, group.size) output.forEach { line -> val dirRegex = Regex("""^dir (.+)$""").matchEntire(line) val fileRegex = Regex("""^(\d+) (.+)$""").matchEntire(line) if (dirRegex != null) { val (directoryName) = dirRegex.destructured if (path.peek().nodes.containsKey(directoryName).not()) { path.peek().nodes[directoryName] = Filesystem.Directory(mutableMapOf()) } } else if (fileRegex != null) { val (size, filename) = fileRegex.destructured path.peek().nodes[filename] = Filesystem.File(size.toLong()) } } } else { throw Exception() } } fun directorySizes(filesystem: Filesystem): Pair<Long, List<Pair<Long, Filesystem>>> { return when (filesystem) { is Filesystem.File -> { Pair(filesystem.size, listOf(Pair(filesystem.size, filesystem))) } is Filesystem.Directory -> { val foo = filesystem.nodes.values.map { directorySizes(it) } val size = foo.sumOf { it.first } Pair(size, listOf(Pair(size, filesystem)).plus(foo.flatMap { it.second })) } } } return directorySizes(root).second .filter { (size, filesystem) -> filesystem is Filesystem.Directory && size <= 100000L } .sumOf { (size) -> size } } fun part2(input: List<String>): Long { val groups = input.joinToString("\n").split(Regex("""\$ """)) .map { it.split("\n").takeWhile { it.isNotEmpty() } } .drop(1) val root = Filesystem.Directory(mutableMapOf()) val path = Stack<Filesystem.Directory>() path.push(root) groups.forEach { group -> val (cmd) = group val cdMatches = Regex("""^cd (.+)$""").matchEntire(cmd) val lsMatches = Regex("""^ls$""").matchEntire(cmd) if (cdMatches != null) { val (dir) = cdMatches.destructured if (dir == "/") { while (path.size > 1) { path.pop() } } else if (dir == "..") { path.pop() } else if (path.peek().nodes.containsKey(dir)) { path.push(path.peek().nodes[dir] as Filesystem.Directory) } else { val directory = Filesystem.Directory(mutableMapOf()) path.peek().nodes[dir] = directory path.push(directory) } } else if (lsMatches != null) { val output = group.subList(1, group.size) output.forEach { line -> val dirRegex = Regex("""^dir (.+)$""").matchEntire(line) val fileRegex = Regex("""^(\d+) (.+)$""").matchEntire(line) if (dirRegex != null) { val (directoryName) = dirRegex.destructured if (path.peek().nodes.containsKey(directoryName).not()) { path.peek().nodes[directoryName] = Filesystem.Directory(mutableMapOf()) } } else if (fileRegex != null) { val (size, filename) = fileRegex.destructured path.peek().nodes[filename] = Filesystem.File(size.toLong()) } } } else { throw Exception() } } fun directorySizes(filesystem: Filesystem): Size { return when (filesystem) { is Filesystem.File -> { Size.File(filesystem.size) } is Filesystem.Directory -> { val nodes = filesystem.nodes.mapValues { (_, it) -> directorySizes(it) } Size.Directory(nodes.values.sumOf { it.size }, nodes) } } } val rootSize = directorySizes(root) as Size.Directory println(rootSize) fun flattenSize(size: Size.Directory): List<Size> { return listOf(size).plus(size.nodes.values.filterIsInstance<Size.Directory>().flatMap { flattenSize(it) }) } return flattenSize(rootSize).sortedBy { it.size } .first { (70000000 - rootSize.size) + it.size >= 30000000 }.size } // test if implementation meets criteria from the description, like: val testInput = readInput("Day07_test") check(part1(testInput) == 95437L) val input = readInput("Day07") println(part1(input)) check(part2(testInput) == 24933642L) println(part2(input)) }
0
Kotlin
0
1
2ec1c664f6d6c6e3da2641ff5769faa368fafa0f
6,629
aoc2022
Apache License 2.0
common/assertion-functions/src/main/kotlin/com/testerum/common_assertion_functions/utils/SimilarStringsFinder.kt
jesus2099
405,913,304
true
{"Kotlin": 2228036, "TypeScript": 1665096, "SCSS": 1583387, "HTML": 453456, "Java": 53935, "Shell": 8666, "Gherkin": 5241, "JavaScript": 4659, "Batchfile": 3382, "Groovy": 597}
package com.testerum.common_assertion_functions.utils import org.apache.commons.lang3.StringUtils import java.util.* private val MAX_DIFFERENCE_PERCENTAGE = 50 fun didYouMean(desiredString: String, existingStrings: Iterable<String>): String { val similarStrings: List<String> = existingStrings.findSimilarStrings(desiredString) if (similarStrings.isEmpty()) { return "" } else if (similarStrings.size == 1) { return "; did you mean [${similarStrings[0]}]?" } else { return "; did you mean one of $similarStrings?" } } fun Iterable<String>.findSimilarStrings(desiredString: String): List<String> { var minDistance = Integer.MAX_VALUE var minDistanceStrings = TreeSet<String>() for (existingString in this) { val distance = calculateStringDistance(desiredString, existingString, MAX_DIFFERENCE_PERCENTAGE) if (distance == -1) { continue } if (distance == minDistance) { minDistanceStrings.add(existingString) } else if (distance < minDistance) { minDistance = distance minDistanceStrings = TreeSet<String>().apply { add(existingString) } } } return minDistanceStrings.toList() } /** * @return distance between the two strings, or -1 if the strings are unacceptably different */ private fun calculateStringDistance(source: String, target: String, minimumSimilarityPercentage: Int): Int { val maximumAllowedDistance = calculateMaximumAllowedDistance(source, target, minimumSimilarityPercentage) return StringUtils.getLevenshteinDistance( target.toLowerCase(), source.toLowerCase(), maximumAllowedDistance ) } private fun calculateMaximumAllowedDistance(source: String, target: String, minimumSimilarityPercentage: Int): Int { val lengthOfLongestString = Math.max(source.length, target.length) return lengthOfLongestString * (100 - minimumSimilarityPercentage) / 100 }
0
null
0
0
1bacdd86da1a240ad9f2932e21c69f628a1fc66c
2,207
testerum_testerum
Apache License 2.0
leetcode-75-kotlin/src/main/kotlin/DeleteTheMiddleNodeOfALinkedList.kt
Codextor
751,507,040
false
{"Kotlin": 49566}
import commonclasses.ListNode /** * You are given the head of a linked list. Delete the middle node, and return the head of the modified linked list. * * The middle node of a linked list of size n is the ⌊n / 2⌋th node from the start using 0-based indexing, * where ⌊x⌋ denotes the largest integer less than or equal to x. * * For n = 1, 2, 3, 4, and 5, the middle nodes are 0, 1, 1, 2, and 2, respectively. * * * Example 1: * * * Input: head = [1,3,4,7,1,2,6] * Output: [1,3,4,1,2,6] * Explanation: * The above figure represents the given linked list. The indices of the nodes are written below. * Since n = 7, node 3 with value 7 is the middle node, which is marked in red. * We return the new list after removing this node. * Example 2: * * * Input: head = [1,2,3,4] * Output: [1,2,4] * Explanation: * The above figure represents the given linked list. * For n = 4, node 2 with value 3 is the middle node, which is marked in red. * Example 3: * * * Input: head = [2,1] * Output: [2] * Explanation: * The above figure represents the given linked list. * For n = 2, node 1 with value 1 is the middle node, which is marked in red. * Node 0 with value 2 is the only node remaining after removing node 1. * * * Constraints: * * The number of nodes in the list is in the range [1, 10^5]. * 1 <= Node.val <= 10^5 * @see <a href="https://leetcode.com/problems/delete-the-middle-node-of-a-linked-list/">LeetCode</a> * * Example: * var li = ListNode(5) * var v = li.`val` * Definition for singly-linked list. * class ListNode(var `val`: Int) { * var next: ListNode? = null * } */ fun deleteMiddle(head: ListNode?): ListNode? { if (head?.next == null) return null var slow: ListNode? = head var fast: ListNode? = head var prev: ListNode? = null while (fast != null && fast.next != null) { prev = slow slow = slow?.next fast = fast.next?.next } prev?.next = slow?.next return head }
0
Kotlin
0
0
0511a831aeee96e1bed3b18550be87a9110c36cb
1,997
leetcode-75
Apache License 2.0
app/src/main/java/com/isaacsufyan/numerologycompose/numerology/NumerologyFinder.kt
IsaacSufyan
515,466,716
false
null
package com.isaacsufyan.numerologycompose.numerology import com.isaacsufyan.numerologycompose.numerology.big.BigDecimalMath import java.math.BigInteger import java.math.MathContext object NumerologyFinder { fun find(inputNumber: Int, selectedOptionOfPieValue: Int): Int { var n = inputNumber n++ val mathContext = MathContext(n) val bigDecimalPie = BigDecimalMath.pi(mathContext) var numberP: String if (selectedOptionOfPieValue == 0) { numberP = bigDecimalPie.toString() numberP = numberP.substring(numberP.indexOf(".")).substring(1) }else{ numberP = "1814666323" } System.out.printf("First %d Decimal Digits of Pie : %s\n", n - 1, numberP) val bigDecimalE = BigDecimalMath.e(mathContext) var numberE = bigDecimalE.toString() numberE = numberE.substring(numberE.indexOf(".")).substring(1) var lastNumber = numberE.substring(numberE.length - 1) if (lastNumber.toInt() >= 5) { lastNumber = (lastNumber.toInt() - 1).toString() numberE = numberE.substring(0, numberE.length - 1) numberE += lastNumber } System.out.printf("First %d Decimal Digits of E : %s\n", n - 1, numberE) val pie = BigInteger(numberP) val e = BigInteger(numberE) val sumOfPieAndE = pie.add(e) println("Sum Of Two Number i.e K = $sumOfPieAndE") val twoDigitPrimeCount = twoDigitPrimeNumber(sumOfPieAndE.toString()) val threeDigitPrimeCount = threeDigitPrimeNumber(sumOfPieAndE.toString()) var result = twoDigitPrimeCount * threeDigitPrimeCount println("TwoDigitPrimeNumber: $twoDigitPrimeCount") println("ThreeDigitPrimeNumber: $threeDigitPrimeCount") println("Result (TwoPrime*ThreePrime): $result") if (result > 9) { result = regularNumerologyAddition(result) println("Final Result After Regular Expression: $result") } //TODO Zero Number Have No Numerology if (result == 0) { result++ } return result } private fun twoDigitPrimeNumber(input: String): Int { val twoDigitPrimeNumberList: MutableList<String> = ArrayList() var twoDigitPrimeCount = 0 for (i in 0 until input.length - 1) { val ch = input[i] val chNext = input[i + 1] val s = ch.toString() + chNext val isPrime = isPrime(s.toInt()) if (isPrime) { twoDigitPrimeCount++ twoDigitPrimeNumberList.add(s) } } println(twoDigitPrimeNumberList) return twoDigitPrimeCount } private fun threeDigitPrimeNumber(input: String): Int { val threeDigitPrimeNumberList: MutableList<String> = ArrayList() var threeDigitPrimeCount = 0 for (i in 0 until input.length - 2) { val chFirst = input[i] val chSecond = input[i + 1] val chThird = input[i + 2] val s = chFirst.toString() + chSecond + chThird val isPrime = isPrime(s.toInt()) if (isPrime) { threeDigitPrimeCount++ threeDigitPrimeNumberList.add(s) } } println(threeDigitPrimeNumberList) return threeDigitPrimeCount } private fun isPrime(num: Int): Boolean { var flag = true for (i in 2..num / 2) { if (num % i == 0) { flag = false break } } return flag } private fun regularNumerologyAddition(num: Int): Int { var n = num var sum = 0 while (n > 0 || sum > 9) { if (n == 0) { n = sum sum = 0 } sum += n % 10 n /= 10 } return sum } }
0
Kotlin
0
2
43f74c04eec52fdf096cf9219d638f26555cc383
3,941
NumerologyTestApp
Apache License 2.0
src/week1/MaxSubArray.kt
anesabml
268,056,512
false
null
package week1 import kotlin.math.max import kotlin.system.measureNanoTime class MaxSubArray { /** Brute force (really bad) * Time complexity : O(n2) * Space complexity : O(1) */ fun maxSubArray(nums: IntArray): Int { var max = Int.MIN_VALUE for (start in nums.indices) { var currentMax = 0 for (i in start until nums.size) { currentMax += nums[i] max = max(max, currentMax) } } return max } /** The Kadane’s Algorithm * Time complexity : O(n) * Space complexity : O(1) */ fun maxSubArray2(nums: IntArray): Int { var max = nums[0] var currentMax = nums[0] for (i in 1 until nums.size) { currentMax = max(currentMax + nums[i], nums[i]) max = max(max, currentMax) } return max } /** The Kadane’s Algorithm functional solution * Time complexity : O(n) * Space complexity : O(1) */ fun maxSubArray3(nums: IntArray): Int { return nums.fold(Pair(Int.MIN_VALUE, 0)) { (max, currentMax), i -> Pair(max(max, max(currentMax + i, i)), max(currentMax + i, i)) }.first } } fun main() { val input = intArrayOf(-2, 1, -3, 4, -1, 2, 1, -5, 4) val maxSubArray = MaxSubArray() val firstSolutionTime = measureNanoTime { println(maxSubArray.maxSubArray(input)) } val secondSolutionTime = measureNanoTime { println(maxSubArray.maxSubArray2(input)) } val thirdSolutionTime = measureNanoTime { println(maxSubArray.maxSubArray3(input)) } println("First Solution execution time: $firstSolutionTime") println("Second Solution execution time: $secondSolutionTime") println("Third Solution execution time: $thirdSolutionTime") }
0
Kotlin
0
1
a7734672f5fcbdb3321e2993e64227fb49ec73e8
1,817
leetCode
Apache License 2.0
advent/src/test/kotlin/org/elwaxoro/advent/y2022/Dec16.kt
elwaxoro
328,044,882
false
{"Kotlin": 376774}
package org.elwaxoro.advent.y2022 import org.elwaxoro.advent.Node import org.elwaxoro.advent.PuzzleDayTester /** * Day 16: Proboscidea Volcanium */ class Dec16 : PuzzleDayTester(16, 2022) { override fun part1(): Any = loader().let { valves -> (1..30).fold(listOf(Path(valves["AA"]!!, 30))) { paths, _ -> paths.flatMap { path -> path.openValveAndFanOut() }.sortedByDescending { it.maxPotential() }.take(10000) // culling function }.maxOf { it.pressure }// == 1474L } override fun part2(): Any = loader().let { valves -> (1..26).fold(listOf(Path(head = valves["AA"]!!, time = 26, eleHead = valves["AA"]!!))) { paths, _ -> paths.flatMap { path -> path.openValveAndFanOut() }.sortedByDescending { it.maxPotential() }.take(20000) // uhhh apparently culling function from ^^ is too small so double it idk it works now }.maxOf { it.pressure }// == 2100L } private data class Path( val head: Node, val time: Int, val openValves: Map<Node, Int> = mapOf(), val pressure: Long = 0, val eleHead: Node? = null, ) { fun addPressure(): Path = Path(head, time - 1, openValves, pressure + openValves.map { it.key.scratch }.sum(), eleHead) fun open(openMe: Node, isEleMove: Boolean): Path { val newPressure = pressure.takeIf { isEleMove } ?: (pressure + openValves.map { it.key.scratch }.sum()) val newMap = openValves.plus(openMe to (time.takeIf { isEleMove } ?: (time - 1))) return Path(head, (time.takeIf { isEleMove } ?: (time - 1)), newMap, newPressure, eleHead) } fun move(to: Node, isEleMove: Boolean): Path { val newPressure = pressure.takeIf { isEleMove } ?: (pressure + openValves.map { it.key.scratch }.sum()) return Path(to.takeUnless { isEleMove } ?: head, (time.takeIf { isEleMove } ?: (time - 1)), openValves, newPressure, to.takeIf { isEleMove } ?: eleHead) } /** * turns out, just current pressure isn't enough for a reduction / fitness function */ fun maxPotential(): Long = openValves.map { (v, t) -> t * v.scratch }.sum().toLong() fun fanOut(fanMe: Node, isEleMove: Boolean): List<Path> = fanMe.edges.map { move(it.key, isEleMove) } fun openValveAndFanOut(): List<Path> { // first open / move the head and get all outcomes val headMoves = if (head.scratch > 0 && !openValves.containsKey(head)) { listOf(open(head, false)) } else { listOf() }.plus(fanOut(head, false)) return if (eleHead != null) { // now apply each of those new outcomes to some elephant bullshit headMoves.map { op -> if (eleHead.scratch > 0 && !op.openValves.containsKey(eleHead)) { listOf(op.open(eleHead, true)) } else { listOf() }.plus(op.fanOut(eleHead, true)) }.flatten() } else { headMoves } } } private fun loader() = mutableMapOf<String, Node>().also { nodes -> load().map { line -> line.replace("Valve ", "").replace(" has flow rate=", "=").replace(" tunnels lead to valves ", "").replace(" tunnel leads to valve ", "").let { val (v, neighbors) = it.split(";") val (valve, pressure) = v.split("=") val valveNode = nodes.getOrPut(valve) { Node(valve) } valveNode.scratch = pressure.toInt() neighbors.split(", ").map { neighborName -> val n = nodes.getOrPut(neighborName) { Node(neighborName) } valveNode.addEdge(n, 1) n.addEdge(valveNode, 1) } } } } /** * nothing was working, so this is a simulator of the sample exactly */ //@Test fun testo() = loader().let { valves -> val start = valves["AA"]!! var minutes = 0 val forcePath = listOf("DD", "open", "CC", "BB", "open", "AA", "II", "JJ", "open", "II", "AA", "DD", "EE", "FF", "GG", "HH", "open", "GG", "FF", "EE", "open", "DD", "CC", "open", "stay", "stay", "stay", "stay", "stay", "stay", "stay", "stay", "stay", "stay", "stay", "stay", "stay", "stay") var path = Path(start, minutes) while (minutes < 30) { path = when (val action = forcePath[minutes]) { "open" -> path.open(path.head, false) "stay" -> path.addPressure() else -> path.move(valves[action]!!, false) } minutes++ println("== Minute $minutes ==") println(path) println(path.maxPotential()) } } }
0
Kotlin
4
0
1718f2d675f637b97c54631cb869165167bc713c
4,936
advent-of-code
MIT License
src/main/kotlin/com/github/wakingrufus/aoc/Day4.kt
wakingrufus
159,674,364
false
null
package com.github.wakingrufus.aoc import mu.KLogging import java.time.LocalDateTime import java.time.format.DateTimeFormatter sealed class Event(val time: LocalDateTime) data class ShiftStart(val guardId: String, val timestamp: LocalDateTime) : Event(timestamp) data class SleepStart(val timestamp: LocalDateTime) : Event(timestamp) data class WakeUp(val timestamp: LocalDateTime) : Event(timestamp) data class InvalidEvent(val input: String) : Event(LocalDateTime.MIN) data class Shift( val guardId: String, val sleepMap: Map<Int, Int>) { operator fun plus(otherShift: Shift): Shift { val newMap = this.sleepMap.toMutableMap() otherShift.sleepMap.entries.forEach { newMap[it.key] = it.value + this.sleepMap.getOrDefault(it.key, 0) } return Shift(guardId = guardId, sleepMap = newMap) } } data class EventAccumulator( val currentGuard: String? = null, val sleepMap: Map<Int, Int> = mapOf(), val shifts: List<Shift> = listOf() ) class Day4 { companion object : KLogging() fun part1(input: List<String>): Int { val validEvents = parseAndOrderEvents(input) val shifts = buildShifts(validEvents) val mostSleepyGuard = mostSleepyGuard(shifts) val mostCommonMinute = mostCommonMinute(shifts.filter { it.guardId == mostSleepyGuard }) val sleepyGuardNumber = mostSleepyGuard?.toIntOrNull() ?: 0 return mostCommonMinute * sleepyGuardNumber } fun part2(input: List<String>): Int { val validEvents = parseAndOrderEvents(input) val shifts = buildShifts(validEvents) return mostCommonGuardAndMinute(shifts).let { it.first.toInt() * it.second } } fun mostCommonGuardAndMinute(shifts: List<Shift>): Pair<String, Int> { val shiftsByGuard = shifts.groupBy { it.guardId } val combinedShiftsByGuard = shiftsByGuard .mapValues { it.value.reduce(operation = { a, b -> a + b }) } val maxMinuteAndTimesByGuard = combinedShiftsByGuard .mapValues { it.value.sleepMap .maxBy { it.value } ?.let { it.key to it.value } ?: -1 to -1 } return maxMinuteAndTimesByGuard.maxBy { it.value.second }?.let { it.key to it.value.first } ?: "-1" to -1 } fun parseAndOrderEvents(input: List<String>): List<Event> { return input.map { parseEvent(it) } .filterNot { event -> (event is InvalidEvent) .also { if (event is InvalidEvent) logger.warn("invalid data: ${event.input}") } } .sortedBy { it.time } } fun buildShifts(events: List<Event>): List<Shift> { return events .plus(events[0]) .zipWithNext() .fold(EventAccumulator()) { acc, eventPair -> val firstEvent = eventPair.first val secondEvent = eventPair.second var newAcc = acc if (firstEvent is SleepStart && secondEvent is WakeUp || secondEvent is ShiftStart) { newAcc = eventPair.first.time.minute.until(eventPair.second.time.minute) .fold(acc) { a, minute -> a.copy(sleepMap = a.sleepMap + (minute to (a.sleepMap[minute] ?: 0) + 1)) } } if (secondEvent is ShiftStart) { newAcc = (acc.currentGuard?.let { acc.copy( shifts = acc.shifts + Shift(guardId = it, sleepMap = acc.sleepMap), sleepMap = mapOf() ) } ?: acc).copy(currentGuard = secondEvent.guardId) } if (firstEvent is ShiftStart && acc.currentGuard != firstEvent.guardId) { newAcc = acc.copy( currentGuard = firstEvent.guardId ) } newAcc }.shifts } fun mostSleepyGuard(shifts: List<Shift>): String? = shifts .groupBy({ s -> s.guardId }) { it.sleepMap.values.sum() }.maxBy { it.value.sum() }?.key fun mostCommonMinute(shifts: List<Shift>): Int { return shifts.reduce(operation = { a, b -> a + b }).sleepMap .maxBy { it.value }?.key ?: 0 } } val localDateFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm") fun parseEvent(input: String): Event { val tokens = input.split('[', ']') val timestamp = LocalDateTime.parse(tokens[1], localDateFormat) val actionText = tokens[2] return when { actionText.contains("Guard") -> { val guardId = actionText .substring(actionText.indexOf('#') + 1) .substringBefore(' ') ShiftStart(guardId = guardId, timestamp = timestamp) } actionText.contains("falls asleep") -> SleepStart(timestamp = timestamp) actionText.contains("wakes up") -> WakeUp(timestamp) else -> InvalidEvent(input) } }
0
Kotlin
0
0
bdf846cb0e4d53bd8beda6fdb3e07bfce59d21ea
5,491
advent-of-code-2018
MIT License
src/main/kotlin/Day01.kt
bent-lorentzen
727,619,283
false
{"Kotlin": 68153}
import java.time.LocalDateTime import java.time.ZoneOffset fun main() { fun part1(input: List<String>): Int { return input.sumOf { it.first { c -> c in ('1'..'9') }.minus('0') * 10 + it.last { c -> c in ('1'..'9') }.minus('0') } } fun part2(input: List<String>): Int { val valueMap = mapOf( "1" to 1, "2" to 2, "3" to 3, "4" to 4, "5" to 5, "6" to 6, "7" to 7, "8" to 8, "9" to 9, "one" to 1, "two" to 2, "three" to 3, "four" to 4, "five" to 5, "six" to 6, "seven" to 7, "eight" to 8, "nine" to 9 ) return input.sumOf { val first: Pair<Int, String> = it.findAnyOf(valueMap.keys) ?: error("Digit missing") val last: Pair<Int, String> = it.findLastAnyOf(valueMap.keys) ?: error("Digit missing") valueMap[first.second]!! * 10 + valueMap[last.second]!! } } val timer = LocalDateTime.now().toInstant(ZoneOffset.UTC).toEpochMilli() val result1 = part1(readLines("day01-input.txt")) "Result1: $result1".println() val result2 = part2(readLines("day01-input.txt")) "Result2: $result2".println() println("${LocalDateTime.now().toInstant(ZoneOffset.UTC).toEpochMilli() - timer} ms") }
0
Kotlin
0
0
41f376bd71a8449e05bbd5b9dd03b3019bde040b
1,450
aoc-2023-in-kotlin
Apache License 2.0
src/main/kotlin/controller/Solver.kt
mihassan
600,617,064
false
null
package controller import model.* import util.Bag import util.frequency enum class Strategy(val display: String) { AlphabeticOrder("Alphabetic order"), ShortestFirst("Shortest first"), LongestFirst("Longest first"), RandomOrder("Random order") } class Solver( private val dictionary: Dictionary, private val configuration: Configuration, private val bannedWords: Set<String>, ) { fun solve(inputLetters: String): Board? { val bagOfInputLetters = inputLetters.filter(Char::isLetter).map(Char::uppercaseChar).frequency() val dictionary = with(dictionary.prune(bagOfInputLetters, bannedWords)) { when (configuration.strategy) { Strategy.AlphabeticOrder -> sortAlphabeticOrder() Strategy.ShortestFirst -> sortShortestFirst() Strategy.LongestFirst -> sortLongestFirst() Strategy.RandomOrder -> shuffle() } } val board = Board() // Only used for debugging purpose. val words = mutableListOf<String>() val prunedDictionaryCache = mutableMapOf<Bag<Char>, Dictionary>() fun pruneDictionary(bagOfLetters: Bag<Char>): Dictionary = prunedDictionaryCache .getOrPut(bagOfLetters) { dictionary.prune(bagOfLetters, bannedWords) } inline fun allowedLetters(depth: Int, requiredLetter: Char) = when (depth) { 1 -> bagOfInputLetters else -> bagOfInputLetters - board.letters() + requiredLetter } inline fun candidates(depth: Int, requiredLetter: Char): Dictionary = pruneDictionary(allowedLetters(depth, requiredLetter)) fun solveInternal(depth: Int): Board? = if (board.allLettersUsedExactlyOnce(bagOfInputLetters)) { if (board.isValid( dictionary, bagOfInputLetters, configuration.allowTouchingWords, configuration.allowDuplicateWords ) ) { console.log("Words used: ${words.joinToString(", ")}") board.clone() } else { null } } else { board.cells.firstNotNullOfOrNull { (commonCell, requiredLetter) -> candidates(depth, requiredLetter).entries.firstNotNullOfOrNull { entry -> Direction.values().firstNotNullOfOrNull { dir -> entry.letters.withIndex().firstNotNullOfOrNull { (offset, letter) -> val startCell = commonCell.moveBy(dir, -offset) if (letter == requiredLetter && board.canPlace(entry.letters, startCell, dir)) { words.add(entry.letters) val newCells = board.place(entry.letters, startCell, dir) val result = solveInternal(depth + 1) board.clearCells(newCells) words.removeLast() result } else { null } } } } } } console.log("\n\n\nStarting a new solve\n\n\n") console.log("Candidate words size: ${dictionary.size}") console.log("Candidate words: ${dictionary.words.joinToString(", ")}") dictionary.findLeastFrequentLetter()?.let { console.log("Starting with letter: $it") board.place(it, Point(0, 0)) return solveInternal(1) } ?: return null } }
0
Kotlin
0
2
f99324e092a9eb7d9644417ac3423763059513ee
3,263
qless-solver
Apache License 2.0
src/main/kotlin/days/Day3.kt
nicopico-dev
726,255,944
false
{"Kotlin": 37616}
package days import kotlin.math.max import kotlin.math.min class Day3( inputFileNameOverride: String? = null, ) : Day(3, inputFileNameOverride) { override fun partOne(): Any { return getPartNumbers() .sum() } internal fun getPartNumbers(): List<Int> { val schematic = Schematic(inputString) return schematic .getSymbolPoints() .flatMap { point -> point.getAdjacentNumbers(schematic) } } override fun partTwo(): Any { return getGearRatios() .sumOf { it.value } } fun getGearRatios(): List<GearRatio> { val schematic = Schematic(inputString) return schematic .getSymbolPoints() .filter { point -> schematic.getCharacterAt(point) == '*' } .map { gearPoint -> gearPoint.getAdjacentNumbers(schematic) } .mapNotNull { list -> if (list.size == 2) { val first = list[0] val second = list[1] GearRatio( high = max(first, second), low = min(first, second), ) } else null } } class Schematic(private val data: String) { val width: Int = data.indexOf("\n") val height: Int = data.count { it == '\n' } @Deprecated( "User getCharacterAt(point)", replaceWith = ReplaceWith("this.getCharacterAt(Point(x, y))") ) fun getCharacterAt(x: Int, y: Int): Char { return getCharacterAt(Point(x = x, y = y)) } fun getCharacterAt(point: Point): Char { val (x, y) = point require(x in 0..<width) { "x should be in range [0, $width[ ($x)" } require(y in 0..<height) { "y should be in range [0, $height[ ($y)" } // Add 1 to width to count the `\n` character val index = (y * (width + 1)) + x return data[index] } fun getSymbolPoints(): List<Point> { val symbolRegex = Regex("[^.0-9\\s]") return symbolRegex.findAll(data.replace("\n", "")) .map { match -> val index = match.range.first Point( x = index % width, y = index / width, ) }.toList() } fun getNumberStartingPoint(point: Point): Point { require(getCharacterAt(point).isDigit()) { "Character at $point is not a digit ${getCharacterAt(point)}" } var x = point.x while (x > 0 && getCharacterAt(Point(x - 1, point.y)).isDigit()) { x -= 1 } return Point(x, point.y) } fun getWholeNumberStartingAt(point: Point): Int { require(getCharacterAt(point).isDigit()) { "Character at $point is not a digit ${getCharacterAt(point)}" } val buffer = StringBuilder() var char: Char for (x in point.x..<width) { char = getCharacterAt(Point(x, point.y)) if (!char.isDigit()) { break } buffer.append(char) } return buffer.toString().toInt() } } data class Point(val x: Int, val y: Int) { fun computeAdjacentPoints(width: Int, height: Int): List<Point> { return listOf( // Row above copy(x = x - 1, y = y - 1), copy(y = y - 1), copy(x = x + 1, y = y - 1), // Same row copy(x = x - 1), copy(x = x + 1), // Row below copy(x = x - 1, y = y + 1), copy(y = y + 1), copy(x = x + 1, y = y + 1), ).filter { // Remove all out-of-bounds points it.x in 0..<width && it.y in 0..<height } } } data class GearRatio( val high: Int, val low: Int, ) { init { high > low } val value: Int = high * low } private fun Point.getAdjacentNumbers(schematic: Schematic): List<Int> { return computeAdjacentPoints(schematic.width, schematic.height) .filter { point -> schematic.getCharacterAt(point).isDigit() } .map { point -> schematic.getNumberStartingPoint(point) } .distinct() .map { point -> schematic.getWholeNumberStartingAt(point) } } }
0
Kotlin
0
0
1a13c8bd3b837c1ce5b13f90f326f0277249d23e
4,874
aoc-2023
Creative Commons Zero v1.0 Universal
src/Day01.kt
sabercon
648,989,596
false
null
fun main() { fun findTwoWithSum(nums: Set<Int>, sum: Int): Pair<Int, Int>? { return nums.find { (sum - it) in nums } ?.let { it to (sum - it) } } fun findThreeWithSum(nums: Set<Int>, sum: Int): Triple<Int, Int, Int>? { return nums.firstNotNullOfOrNull { findTwoWithSum(nums, sum - it) ?.let { (a, b) -> Triple(a, b, it) } } } val input = readLines("Day01").map { it.toInt() }.toSet() findTwoWithSum(input, 2020)!! .let { (a, b) -> a * b }.println() findThreeWithSum(input, 2020)!! .let { (a, b, c) -> a * b * c }.println() }
0
Kotlin
0
0
81b51f3779940dde46f3811b4d8a32a5bb4534c8
637
advent-of-code-2020
MIT License
leetcode2/src/leetcode/letter-combinations-of-a-phone-number.kt
hewking
68,515,222
false
null
package leetcode /** * 17. 电话号码的字母组合 * https://leetcode-cn.com/problems/letter-combinations-of-a-phone-number/ * Created by test * Date 2019/12/14 12:21 * Description * 给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。 给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。 示例: 输入:"23" 输出:["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]. 说明: 尽管上面的答案是按字典序排列的,但是你可以任意选择答案输出的顺序。 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/letter-combinations-of-a-phone-number 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 */ object LetterCombinationsOfAPhoneNumber { class Solution { /** * 思路: * 1. 根据题设digits 取值为2-9 组合的数字字符串 * 2. 并且2-9 分别对应一组 字母数组,跟phone 键盘一致 * 3. 对输入的多组组合 比如输入23 通过步骤2 得到 两组数据 * [[a,b,c],[d,e,f]] * 4. 以上数据可以看做 a + [[d,e,f]] , b + [[d,e,f]], c + [[d,e,f]]组合 * 5。 就可以通过递归,基准情形就是 数据size == 1 */ fun letterCombinations(digits: String): List<String> { // TODO check param if (digits.isEmpty()) { return mutableListOf() } val numLists = mutableListOf<String>() for (i in digits.indices) { when(digits[i]) { '2' -> { numLists.add("abc") } '3' -> numLists.add("def") '4' -> numLists.add("ghi") '5' -> numLists.add("jkl") '6' -> numLists.add("mno") '7' -> numLists.add("pqrs") '8' -> numLists.add("tuv") '9' -> numLists.add("wxyz") } } val ans = mutableListOf<String>() combineDigits(numLists,ans,"") return ans } fun combineDigits(digits: MutableList<String> , ans: MutableList<String>,res: String) { if (digits.isEmpty()) { ans.add(res) } else { val temp = digits[0] val remain = if (digits.size == 1) mutableListOf() else digits.subList(1,digits.size) for (i in temp.indices) { combineDigits(remain,ans,res + temp[i]) } } } } @JvmStatic fun main(args: Array<String>) { Solution().letterCombinations("2,3").forEach { println(it) } } }
0
Kotlin
0
0
a00a7aeff74e6beb67483d9a8ece9c1deae0267d
2,858
leetcode
MIT License
src/day19/Day19.kt
EndzeitBegins
573,569,126
false
{"Kotlin": 111428}
package day19 import readInput import readTestInput private data class Blueprint( val id: Int, val oreRobotOreCost: Int, val clayRobotOreCost: Int, val obsidianRobotOreCost: Int, val obsidianRobotClayCost: Int, val geodeRobotOreCost: Int, val geodeRobotObsidianCost: Int, ) { val maxOreUsagePossible: Int = listOf( oreRobotOreCost, clayRobotOreCost, obsidianRobotOreCost, geodeRobotOreCost, ).max() val maxClayUsagePossible: Int = obsidianRobotClayCost val maxObsidianUsagePossible: Int = geodeRobotObsidianCost } private val blueprintRegex = """Blueprint (\d+): Each ore robot costs (\d+) ore. Each clay robot costs (\d+) ore. Each obsidian robot costs (\d+) ore and (\d+) clay. Each geode robot costs (\d+) ore and (\d+) obsidian.""".toRegex() private fun List<String>.toBlueprints(): List<Blueprint> = this.map { line -> val ( blueprintId, oreRobotOreCost, clayRobotOreCost, obsidianRobotOreCost, obsidianRobotClayCost, geodeRobotOreCost, geodeRobotObsidianCost, ) = checkNotNull(blueprintRegex.matchEntire(line)).destructured Blueprint( id = blueprintId.toInt(), oreRobotOreCost = oreRobotOreCost.toInt(), clayRobotOreCost = clayRobotOreCost.toInt(), obsidianRobotOreCost = obsidianRobotOreCost.toInt(), obsidianRobotClayCost = obsidianRobotClayCost.toInt(), geodeRobotOreCost = geodeRobotOreCost.toInt(), geodeRobotObsidianCost = geodeRobotObsidianCost.toInt(), ) } private fun Blueprint.simulateOutcomes(minutes: Int): List<EventNode> { val initialEventNode = EventNode( blueprint = this, inventory = initialInventory, robotTeam = initialRobotTeam ) var eventNodes = listOf(initialEventNode) repeat(minutes) { eventNodes = eventNodes .flatMap { eventNode -> eventNode.possibleActions() } .filterForMostSensibleActions(minutes * 125) } return eventNodes } private fun Blueprint.calculateOptimalOutcome(minutes: Int): EventNode = simulateOutcomes(minutes).maxBy { it.inventory.geodes } private fun Blueprint.calculateQualityLevel(minutes: Int) = id * calculateOptimalOutcome(minutes).inventory.geodes private data class Inventory( val ore: Int, val clay: Int, val obsidian: Int, val geodes: Int, ) private fun Inventory.withWorkFrom( robotTeam: RobotTeam, usingOre: Int = 0, usingClay: Int = 0, usingObsidian: Int = 0 ) = Inventory( ore = ore + robotTeam.oreRobots - usingOre, clay = clay + robotTeam.clayRobots - usingClay, obsidian = obsidian + robotTeam.obsidianRobots - usingObsidian, geodes = geodes + robotTeam.geodeRobots, ) private val initialInventory = Inventory( ore = 0, clay = 0, obsidian = 0, geodes = 0 ) private data class RobotTeam( val oreRobots: Int, val clayRobots: Int, val obsidianRobots: Int, val geodeRobots: Int, ) private fun RobotTeam.enlargedBy( oreRobots: Int = 0, clayRobots: Int = 0, obsidianRobots: Int = 0, geodeRobots: Int = 0 ) = RobotTeam( oreRobots = this.oreRobots + oreRobots, clayRobots = this.clayRobots + clayRobots, obsidianRobots = this.obsidianRobots + obsidianRobots, geodeRobots = this.geodeRobots + geodeRobots ) private val initialRobotTeam = RobotTeam( oreRobots = 1, clayRobots = 0, obsidianRobots = 0, geodeRobots = 0 ) private data class EventNode( val blueprint: Blueprint, val inventory: Inventory, val robotTeam: RobotTeam, ) private fun EventNode.possibleActions(): List<EventNode> { if (inventory.ore >= blueprint.geodeRobotOreCost && inventory.obsidian >= blueprint.geodeRobotObsidianCost) { return listOf( EventNode( blueprint = blueprint, inventory = inventory.withWorkFrom( robotTeam, usingOre = blueprint.geodeRobotOreCost, usingObsidian = blueprint.geodeRobotObsidianCost, ), robotTeam = robotTeam.enlargedBy(geodeRobots = 1) ) ) } val possibleActions = mutableListOf( EventNode( blueprint = blueprint, inventory = inventory.withWorkFrom(robotTeam), robotTeam = robotTeam, ) ) if (robotTeam.obsidianRobots > blueprint.maxObsidianUsagePossible) return possibleActions if (inventory.ore >= blueprint.obsidianRobotOreCost && inventory.clay >= blueprint.obsidianRobotClayCost ) { possibleActions += EventNode( blueprint = blueprint, inventory = inventory.withWorkFrom( robotTeam, usingOre = blueprint.obsidianRobotOreCost, usingClay = blueprint.obsidianRobotClayCost, ), robotTeam = robotTeam.enlargedBy(obsidianRobots = 1) ) } if (robotTeam.clayRobots > blueprint.maxClayUsagePossible) return possibleActions if (inventory.ore >= blueprint.clayRobotOreCost) { possibleActions += EventNode( blueprint = blueprint, inventory = inventory.withWorkFrom(robotTeam, usingOre = blueprint.clayRobotOreCost), robotTeam = robotTeam.enlargedBy(clayRobots = 1) ) } if (robotTeam.oreRobots > blueprint.maxOreUsagePossible) return possibleActions if (inventory.ore >= blueprint.oreRobotOreCost) { possibleActions += EventNode( blueprint = blueprint, inventory = inventory.withWorkFrom(robotTeam, usingOre = blueprint.oreRobotOreCost), robotTeam = robotTeam.enlargedBy(oreRobots = 1) ) } return possibleActions } private fun List<EventNode>.filterForMostSensibleActions(limit: Int): List<EventNode> { val blueprint = this.first().blueprint val oreWorth = 1 val oreRobotWorth = blueprint.oreRobotOreCost + 1 val clayWorth = blueprint.clayRobotOreCost val clayRobotWorth = clayWorth + 1 val obsidianWorth = blueprint.obsidianRobotOreCost * oreWorth + blueprint.obsidianRobotClayCost * clayWorth val obsidianRobotWorth = obsidianWorth + 1 val geodeWorth = blueprint.geodeRobotOreCost * oreWorth + blueprint.geodeRobotObsidianCost * obsidianWorth val geodeRobotWorth = geodeWorth + 1 fun scoreOf(eventNode: EventNode) = eventNode.inventory.ore * oreWorth + eventNode.robotTeam.oreRobots * oreRobotWorth + eventNode.inventory.clay * clayWorth + eventNode.robotTeam.clayRobots * clayRobotWorth + eventNode.inventory.obsidian * obsidianWorth + eventNode.robotTeam.obsidianRobots * obsidianRobotWorth + eventNode.inventory.geodes * geodeWorth + eventNode.robotTeam.geodeRobots * geodeRobotWorth return this .sortedByDescending { eventNode -> scoreOf(eventNode) } .take(limit) } private fun part1(input: List<String>): Int { val blueprints = input.toBlueprints() return blueprints.sumOf { blueprint -> blueprint.calculateQualityLevel(minutes = 24) } } private fun part2(input: List<String>): Int { val blueprints = input.toBlueprints().take(3) return blueprints .map { blueprint -> blueprint.calculateOptimalOutcome(minutes = 32).inventory.geodes } .reduce(Int::times) } fun main() { // test if implementation meets criteria from the description, like: val testInput = readTestInput("Day19") check(part1(testInput) == 33) check(part2(testInput) == 56 * 62) val input = readInput("Day19") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
ebebdf13cfe58ae3e01c52686f2a715ace069dab
7,786
advent-of-code-kotlin-2022
Apache License 2.0
src/me/bytebeats/algo/kt/Solution7.kt
bytebeats
251,234,289
false
null
package me.bytebeats.algo.kt import me.bytebeats.algs.ds.ListNode import me.bytebeats.algs.ds.TreeNode class Solution7 { fun verticalTraversal(root: TreeNode?): List<List<Int>> {//987 val ans = mutableMapOf<Int, MutableMap<Int, MutableList<Int>>>() if (root != null) { val queue = mutableListOf<TreeNode>() val xes = mutableListOf<Int>() val yes = mutableListOf<Int>() queue.add(root) xes.add(0) yes.add(0) var x = 0 var y = 0 var node: TreeNode? = null while (queue.isNotEmpty()) { node = queue.removeAt(0) x = xes.removeAt(0) y = yes.removeAt(0) ans.compute(x) { _, v -> if (v == null) { val map = mutableMapOf<Int, MutableList<Int>>() map.compute(y) { _, c -> if (c == null) { val list = mutableListOf<Int>() list.add(node.`val`) list } else { c.add(node.`val`) c } } map } else { v.compute(y) { _, c -> if (c == null) { val list = mutableListOf<Int>() list.add(node.`val`) list } else { c.add(node.`val`) c } } v } } if (node.left != null) { queue.add(node.left) xes.add(x - 1) yes.add(y + 1) } if (node.right != null) { queue.add(node.right) xes.add(x + 1) yes.add(y + 1) } } } return ans.entries .sortedBy { it.key }//ordered by x .map { x -> x.value .entries .sortedBy { it.key }//ordered by y .flatMap { it.value.sorted() }//ordered by value } } var btnLeafVal = 0 fun findBottomLeftValue(root: TreeNode?): Int {//513 btnLeafVal = 0 dfs(root, 0, mutableSetOf()) return btnLeafVal } private fun dfs(root: TreeNode?, level: Int, set: MutableSet<Int>) {//mid order reversal if (root == null) { return } if (!set.contains(level)) { set.add(level) btnLeafVal = root.`val` } dfs(root.left, level + 1, set) dfs(root.right, level + 1, set) } fun pathInZigZagTree(label: Int): List<Int> {//1104 val path = mutableListOf<Int>() var newLbl = label var level = (Math.log(newLbl.toDouble()) / Math.log(2.0)).toInt() while (newLbl > 1) { path.add(newLbl) newLbl = (3 * Math.pow(2.0, (--level).toDouble()) - newLbl / 2 - 1).toInt() } path.add(1) return path.reversed() } fun missingNumber(arr: IntArray): Int {//1228 var pre = 0 var post = 0 for (i in 1 until arr.size - 1) { pre = arr[i] - arr[i - 1] post = arr[i + 1] - arr[i] if (pre != post) { if (pre / post == 2) { return arr[i] - (arr[i + 1] - arr[i]) } else { return arr[i] + (arr[i] - arr[i - 1]) } } } return arr[0]//in case of [1,1,1] } fun longestSubsequence(arr: IntArray, difference: Int): Int {//1218 var ans = 0 return 0 } fun findErrorNums(nums: IntArray): IntArray {//645 val ans = IntArray(2) var xorVal = 0 for (i in nums.indices) { xorVal = xorVal xor (i + 1) xorVal = xorVal xor nums[i] } val rightMost = xorVal and (xorVal - 1).inv() var x0 = 0 var x1 = 0 for (i in nums.indices) { if ((i + 1) and rightMost != 0) { x1 = x1 xor (i + 1) } else { x0 = x0 xor (i + 1) } if (nums[i] and rightMost != 0) { x1 = x1 xor nums[i] } else { x0 = x0 xor nums[i] } } for (i in nums.indices) { if (nums[i] == x0) { ans[0] = x0 ans[1] = x1 return ans } } ans[0] = x1 ans[1] = x0 return ans } fun waysToStep(n: Int): Int {//面试题08.01 val mod = 1000000007 if (n < 2) { return 1 } else if (n < 3) { return 2 } else if (n < 4) { return 4 } else { var nn = n var f1 = 1 var f2 = 2 var f3 = 4 var tmp1 = 0 var tmp2 = 0 while (nn-- > 3) { tmp1 = f1 tmp2 = f2 f1 = f2 f2 = f3 f3 = ((f3 + tmp1) % mod + tmp2) % mod } return f3 } } fun findString(words: Array<String>, s: String): Int {//面试题10.05 var i = 0 var j = words.lastIndex var mid = 0 while (i <= j) { while (i < j && words[i].isEmpty()) { i++ } while (i < j && words[j].isEmpty()) { j-- } mid = i + (j - i) / 2 while (mid > i && words[mid].isEmpty()) { mid-- } if (words[mid] < s) { i = mid + 1 } else if (words[mid] > s) { j = mid - 1 } else { return mid } } return -1 } fun findMagicIndex(nums: IntArray): Int {//面试题08.03 var ans = -1 for (i in nums.indices) { if (i == nums[i]) { ans = i break } } return ans } var firstIdx = -1 fun findMagicIndex1(nums: IntArray): Int {//面试题08.03 firstIdx = -1 search(nums, 0, nums.lastIndex) return firstIdx } private fun search(nums: IntArray, left: Int, right: Int) { if (left > right) { return } val mid = left + (right - left) / 2 if (mid == nums[mid]) { if (firstIdx == -1) { firstIdx = mid } else if (firstIdx > mid) { firstIdx = mid } search(nums, left, mid - 1) } else { search(nums, left, mid - 1) if (firstIdx == -1 || firstIdx > mid) { search(nums, mid + 1, right) } } } fun validMountainArray(A: IntArray): Boolean {//941 if (A.size >= 3) { var hasPeak = false for (i in 1 until A.size - 1) { if (A[i - 1] < A[i] && A[i] > A[i + 1]) { if (hasPeak) { return false } hasPeak = true } else if (A[i - 1] == A[i] || A[i] == A[i + 1]) { return false } else if (A[i - 1] > A[i] && A[i] < A[i + 1]) { return false } } return hasPeak } return false } fun validMountainArray1(A: IntArray): Boolean {//941 if (A.size >= 3) { var i = 0 while (i < A.size - 1 && A[i] < A[i + 1]) { i++ } if (i == 0 || i == A.size - 1) { return false } while (i < A.size - 1 && A[i] > A[i + 1]) { i++ } return i == A.size - 1 } return false } fun longestSubarray(nums: IntArray, limit: Int): Int {//1438 var ans = 0 var i = 0 var min = nums[i] var max = nums[i] for (j in nums.indices) { min = Math.min(min, nums[j]) max = Math.max(max, nums[j]) if (max - min <= limit) { ans = Math.max(ans, j - i + 1) } else { i++ min = nums[i] max = nums[i] for (k in i + 1..j) { min = Math.min(min, nums[k]) max = Math.max(max, nums[k]) } } } return ans } fun possibleBipartition(N: Int, dislikes: Array<IntArray>): Boolean {//886 val graph = Array<MutableList<Int>>(N + 1) { mutableListOf() } for (dislike in dislikes) { graph[dislike[0]].add(dislike[1]) graph[dislike[1]].add(dislike[0]) } val color = mutableMapOf<Int, Int>() for (i in 1..N) { if (!color.containsKey(i) && !dfs(i, 0, graph, color)) { return false } } return true } private fun dfs(n: Int, c: Int, graph: Array<MutableList<Int>>, color: MutableMap<Int, Int>): Boolean { if (color.containsKey(n)) { return color[n] == c } color[n] = c for (neighbour in graph[n]) { if (!dfs(neighbour, c xor 1, graph, color)) { return false } } return true } fun floodFill(image: Array<IntArray>, sr: Int, sc: Int, newColor: Int): Array<IntArray> {//面试题08.01 if (image.isNotEmpty() && image[0].isNotEmpty()) { if (image[sr][sc] != newColor) { floodFill(image, sr, sc, newColor, image[sr][sc]) } } return image } private fun floodFill(image: Array<IntArray>, sr: Int, sc: Int, newColor: Int, color: Int) {//面试题08.01 if (sr < 0 || sc < 0 || sr >= image.size - 1 || sc >= image[0].size - 1 || image[sr][sc] != color) { return } image[sr][sc] = newColor floodFill(image, sr - 1, sc, newColor, color) floodFill(image, sr, sc - 1, newColor, color) floodFill(image, sr + 1, sc, newColor, color) floodFill(image, sr, sc + 1, newColor, color) } fun pathSum(root: TreeNode?, sum: Int): List<List<Int>> {//面试题34 val ans = mutableListOf<MutableList<Int>>() pathSum(root, sum, 0, mutableListOf(), ans) return ans } fun pathSum(root: TreeNode?, sum: Int, subSum: Int, path: MutableList<Int>, ans: MutableList<MutableList<Int>>) { if (root == null) { return } if (root.left == null && root.right == null) { if (root.`val` + subSum == sum) { val list = mutableListOf<Int>() list.addAll(path) list.add(root.`val`) ans.add(list) } } else { if (root.left != null) { val list = mutableListOf<Int>() list.addAll(path) list.add(root.`val`) pathSum(root.left, sum, root.`val` + subSum, list, ans) } if (root.right != null) { val list = mutableListOf<Int>() list.addAll(path) list.add(root.`val`) pathSum(root.right, sum, root.`val` + subSum, list, ans) } } } /** * Forsaken by me. */ fun minTime(n: Int, edges: Array<IntArray>, hasApple: List<Boolean>): Int {//1443 val graph = Array(n) { mutableListOf<Int>() } for (edge in edges) { graph[edge[0]].add(edge[1]) graph[edge[1]].add(edge[0]) } val ans = collect(n, graph, 0, hasApple, mutableSetOf()) if (ans > 0) { return (ans - 1) shr 1 } else { return 0 } } private fun collect( n: Int, graph: Array<MutableList<Int>>, i: Int, hasApple: List<Boolean>, visited: MutableSet<Int> ): Int { if (i >= n) { return 0 } var sum = 0 visited.add(i) for (nb in graph[i]) { if (!visited.contains(nb)) { sum += collect(n, graph, nb, hasApple, visited) } } if (sum > 0 || hasApple[i]) { sum += 1 } return sum } fun deleteNode(root: TreeNode?, key: Int): TreeNode? {//450 if (root != null) { if (root.`val` > key) { root.left = deleteNode(root.left, key) } else if (root.`val` < key) { root.right = deleteNode(root.right, key) } else { if (root.left == null) { return root.right } else if (root.right == null) { return root.left } else { var node = root.right while (node.left != null) { node = node.left } node.left = root.left return root.right } } } return root } fun splitBST(root: TreeNode?, V: Int): Array<TreeNode?> {//776 if (root == null) { return Array(2) { null } } else if (root.`val` <= V) { val bns = splitBST(root.right, V) root.right = bns[0] bns[0] = root return bns } else { val bns = splitBST(root.left, V) root.left = bns[1] bns[1] = root return bns } } fun partition(head: ListNode?, x: Int): ListNode? {//86 val dummyBefore = ListNode(-1) var before = dummyBefore val dummyAfter = ListNode(-1) var after = dummyAfter var p = head while (p != null) { if (p.`val` < x) { before.next = p before = before.next } else { after.next = p after = after.next } p = p.next } before.next = dummyAfter.next after.next = null return dummyBefore.next } var ptr = 0 fun decodeString(s: String): String {//394 ptr = 0 val stack = mutableListOf<String>() while (ptr < s.length) { var ch = s[ptr] if (ch.isDigit()) { stack.add(getDigits(s)) } else if (ch.isLetter() || ch == '[') { stack.add(ch.toString()) ptr++ } else { ptr++ val sub = mutableListOf<String>() while (stack.last() != "[") { sub.add(stack.last()) stack.removeAt(stack.lastIndex) } sub.reverse() stack.removeAt(stack.lastIndex) var count = stack.last().toInt() stack.removeAt(stack.lastIndex) val tmp = StringBuilder() val subStr = getString(sub) while (count-- > 0) { tmp.append(subStr) } stack.add(tmp.toString()) } } return getString(stack) } private fun getString(list: MutableList<String>): String { val str = StringBuilder() list.forEach { str.append(it) } return str.toString() } private fun getDigits(s: String): String { val digits = StringBuilder() while (s[ptr].isDigit()) { digits.append(s[ptr++]) } return digits.toString() } fun tribonacci(n: Int): Int {//1137 if (n <= 0) { return 0 } else if (n == 1) { return 1 } else if (n == 2) { return 1 } else { var t0 = 0 var t1 = 1 var t2 = 1 var nn = n var tmp1 = 0 var tmp2 = 0 while (nn-- > 2) { tmp1 = t0 tmp2 = t1 t0 = t1 t1 = t2 t2 += (tmp1 + tmp2) } return t2 } } fun minimumAbsDifference(arr: IntArray): List<List<Int>> {//1200 arr.sort() var minAbs = Int.MAX_VALUE for (i in 1 until arr.size) { minAbs = Math.min(minAbs, arr[i] - arr[i - 1]) } val ans = mutableListOf<List<Int>>() for (i in 1 until arr.size) { if (arr[i] - arr[i - 1] == minAbs) { ans.add(listOf(arr[i - 1], arr[i])) } } return ans } fun nextGreaterElement(nums1: IntArray, nums2: IntArray): IntArray {//496 for (k in nums1.indices) { val num = nums1[k] var i = 0 while (nums2[i] != num) { i++ } var idx = -1 for (j in i + 1 until nums2.size) { if (nums2[j] > num) { idx = j break } } if (idx != -1) { nums1[k] = nums2[idx] } else { nums1[k] = -1 } } return nums1 } fun nextGreaterElement1(nums1: IntArray, nums2: IntArray): IntArray {//496, monotone stack val stack = mutableListOf<Int>() val map = mutableMapOf<Int, Int>() for (i in nums2.indices) { while (stack.isNotEmpty() && nums2[i] > stack.last()) { map[stack.removeAt(stack.lastIndex)] = nums2[i] } stack.add(nums2[i]) } while (stack.isNotEmpty()) { map[stack.removeAt(stack.lastIndex)] = -1 } for (i in nums1.indices) { nums1[i] = map[nums1[i]] ?: -1 } return nums1 } fun dailyTemperatures(T: IntArray): IntArray {//739 val ans = IntArray(T.size) val stack = mutableListOf<Int>() for (i in T.lastIndex downTo 0) { while (stack.isNotEmpty() && T[i] >= T[stack.last()]) stack.removeAt(stack.lastIndex) ans[i] = if (stack.isEmpty()) 0 else stack.last() - i stack.add(i) } return ans } fun countDigitOne(n: Int): Int {//面试题43 var ans = 0 var digit = 1 var high = n / 10 var cur = n % 10 var low = 0 while (high != 0 || cur != 0) { if (cur == 0) { ans += digit * high } else if (cur == 1) { ans += (digit * high + low + 1) } else { ans += (high + 1) * digit } low += cur * digit cur = high % 10 high /= 10 digit *= 10 } return ans } fun countDigitOne1(n: Int): Int {//233 var ans = 0 if (n > 0) { var digit = 1 var high = n / 10 var cur = n % 10 var low = 0 while (high != 0 || cur != 0) { if (cur == 0) { ans += digit * high } else if (cur == 1) { ans += (digit * high + low + 1) } else { ans += (high + 1) * digit } low += cur * digit cur = high % 10 high /= 10 digit *= 10 } } return ans } fun minCostClimbingStairs(cost: IntArray): Int {//746 var dp1 = 0 var dp2 = 0 var tmp = 0 for (i in cost.lastIndex downTo 0) { tmp = Math.min(dp1, dp2) + cost[i] dp2 = dp1 dp1 = tmp } return Math.min(dp1, dp2) } fun largestRectangleArea(heights: IntArray): Int {//84 val size = heights.size val left = IntArray(size) val right = IntArray(size) val stack = mutableListOf<Int>()// store index of heights for (i in heights.indices) { while (stack.isNotEmpty() && heights[stack.last()] >= heights[i]) { stack.removeAt(stack.lastIndex) } left[i] = if (stack.isEmpty()) -1 else stack.last() stack.add(i) } stack.clear() for (i in heights.lastIndex downTo 0) { while (stack.isNotEmpty() && heights[stack.last()] >= heights[i]) { stack.removeAt(stack.lastIndex) } right[i] = if (stack.isEmpty()) size else stack.last() stack.add(i) } var ans = 0 for (i in heights.indices) { ans = Math.max(ans, (right[i] - left[i] - 1) * heights[i]) } return ans } fun maximalRectangle(matrix: Array<CharArray>): Int {//85 var ans = 0 if (matrix.isNotEmpty()) { val m = matrix.size val n = matrix[0].size val left = IntArray(n) val right = IntArray(n) { n } val height = IntArray(n) for (i in 0 until m) { var curLeft = 0 var curRight = n //update height for (j in 0 until n) { if (matrix[i][j] == '1') { height[j]++ } else { height[j] = 0 } } //update left for (j in 0 until n) { if (matrix[i][j] == '1') { left[j] = Math.max(left[j], curLeft) } else { left[j] = 0 curLeft = j + 1 } } //update right for (j in n - 1 downTo 0) { if (matrix[i][j] == '1') { right[j] = Math.min(right[j], curRight) } else { right[j] = n curRight = j } } //update area for (j in 0 until n) { ans = Math.max(ans, (right[j] - left[j]) * height[j]) } } } return ans } fun findRestaurant(list1: Array<String>, list2: Array<String>): Array<String> {//599 val intersection = list1.intersect(list2.asIterable()) val min = intersection.map { list1.indexOf(it) + list2.indexOf(it) }.minOfOrNull { it } return intersection.filter { list1.indexOf(it) + list2.indexOf(it) == min }.toTypedArray() } fun maxScore(s: String): Int {//1422 var ans = 0 var ones = 0 for (ch in s) { if (ch == '1') { ones++ } } var zeros = 0 for (i in 0 until s.lastIndex) { if (s[i] == '0') { zeros++ } else { ones-- } if (zeros + ones > ans) { ans = zeros + ones } } return ans } fun kClosest(points: Array<IntArray>, K: Int): Array<IntArray> {//973 points.sortBy { it[0] * it[0] + it[1] * it[1] } return points.take(K).toTypedArray() } fun isUnivalTree(root: TreeNode?): Boolean {//965 if (root == null) { return true } return isEqual(root.left, root.`val`) && isEqual(root.right, root.`val`) } private fun isEqual(node: TreeNode?, `val`: Int): Boolean { if (node == null) { return true } if (node.`val` != `val`) { return false } else { return isEqual(node.left, `val`) && isEqual(node.right, `val`) } } fun canBeEqual(target: IntArray, arr: IntArray): Boolean {//5408, 1460 var xorVal = 0 for (i in target.indices) {//元素各类及相应数目相同即可 xorVal = xorVal xor target[i] xorVal = xorVal xor arr[i] } return xorVal == 0 } fun hasAllCodes(s: String, k: Int): Boolean {//5409, 1461 if (s.length <= k) { return false } val visited = BooleanArray(1 shl k) { false } var cur = 0 for (i in 0 until k - 1) {//sliding window to compute digit to verify is in 0[k-2]0 ~ 1[k-2]1 cur = cur * 2 + (s[i] - '0') } for (i in k - 1 until s.length) { cur = cur * 2 + (s[i] - '0') visited[cur] = true cur = cur and (1 shl (k - 1)).dec() } for (i in visited.indices) { if (!visited[i]) { return false } } return true } fun checkIfPrerequisite(n: Int, prerequisites: Array<IntArray>, queries: Array<IntArray>): BooleanArray {//5410 val ans = BooleanArray(queries.size) { false } val arr = Array(n) { BooleanArray(n) { false } } for (pre in prerequisites) { for (i in arr.indices) { if (i == pre[0] || arr[i][pre[0]]) { arr[i][pre[1]] = true for (j in 0 until n) { if (arr[pre[1]][j]) { arr[i][j] = true } } } } } for (i in queries.indices) { ans[i] = arr[queries[i][0]][queries[i][1]] } return ans } fun maxProfit(prices: IntArray): Int {//面试题63 var max = 0 if (prices.isNotEmpty()) { var min = prices[0] for (i in prices.indices) { if (prices[i] - min > max) { max = prices[i] - min } if (prices[i] < min) { min = prices[i] } } } return max } fun maxProduct(nums: IntArray): Int {//5424, 1464 nums.sort() return (nums.last() - 1) * (nums[nums.lastIndex - 1] - 1) } /** * x 轴的最大间隔 * y 轴的最大间隔 */ fun maxArea(h: Int, w: Int, horizontalCuts: IntArray, verticalCuts: IntArray): Int {//5425, 1465 horizontalCuts.sort() verticalCuts.sort() var maxHSpan = 1L for (i in 1 until horizontalCuts.size) { maxHSpan = maxHSpan.coerceAtLeast((horizontalCuts[i] - horizontalCuts[i - 1]).toLong()) } maxHSpan = maxHSpan.coerceAtLeast(horizontalCuts[0].toLong()) maxHSpan = maxHSpan.coerceAtLeast((h - horizontalCuts.last()).toLong()) var maxVSpan = 1L for (j in 1 until verticalCuts.size) { maxVSpan = maxVSpan.coerceAtLeast((verticalCuts[j] - verticalCuts[j - 1]).toLong()) } maxVSpan = maxVSpan.coerceAtLeast((verticalCuts[0] - 0).toLong()) maxVSpan = maxVSpan.coerceAtLeast((w - verticalCuts.last()).toLong()) return (maxHSpan * maxVSpan % 1000000007).toInt() } /** * 不使用除法的除去本索引元素的数组乘积 */ fun constructArr(a: IntArray): IntArray {// 面试题66 val ans = IntArray(a.size) if (a.isNotEmpty()) { ans[0] = 1 for (i in 1 until a.size) { ans[i] = ans[i - 1] * a[i - 1] } var tmp = 1 for (i in a.size - 2 downTo 0) { tmp *= a[i + 1] ans[i] *= tmp } } return ans } /** * a: 当所有绳段长度相等时,乘积最大。 * b: 最优的绳段长度为 33 */ fun cuttingRope(n: Int): Int {//343, 面试题14-I if (n <= 3) { return n - 1 } val a = n / 3 val b = n % 3 return if (b == 0) Math.pow(3.0, a.toDouble()).toInt() else if (b == 1) (Math.pow(3.0, (a - 1).toDouble()) * 4).toInt() else (Math.pow(3.0, a.toDouble()) * 2).toInt() } /** * 动态规划解法, 拆分数组 */ fun integerBreak(n: Int): Int {//343, 面试题14-I val dp = IntArray(n + 1) dp[2] = 1 for (i in 3..n) { for (j in 1 until i) { dp[i] = Math.max(dp[i], Math.max(j * dp[i - j], j * (i - j))) } } return dp[n] } /** * 编辑距离 */ fun minDistance(word1: String, word2: String): Int {//72, edit distance val s1 = word1.length val s2 = word2.length val dp = Array(s1 + 1) { IntArray(s2 + 1) } for (i in 0..s1) { for (j in 0..s2) { if (i == 0) { dp[i][j] = j } else if (j == 0) { dp[i][j] = i } else { if (word1[i - 1] == word2[j - 1]) { dp[i][j] = dp[i - 1][j - 1] } else { dp[i][j] = 1 + Math.min(dp[i][j - 1], Math.min(dp[i - 1][j], dp[i - 1][j - 1])) } } } } return dp[s1][s2] } fun minReorder(n: Int, connections: Array<IntArray>): Int {//5426, 1466 val connIdx = Array(n) { mutableListOf<Int>() } for (i in connections.indices) { connIdx[connections[i][0]].add(i) connIdx[connections[i][1]].add(i) } val visited = BooleanArray(connections.size) { false } var ans = 0 val queue = mutableListOf<Int>() queue.add(0) var p = 0 while (queue.isNotEmpty()) { p = queue.removeAt(0) for (i in connIdx[p]) { if (visited[i]) continue visited[i] = true var a = connections[i][0] var b = connections[i][1] if (a == p) { ans++ a = b } queue.add(a) } } return ans } fun kidsWithCandies(candies: IntArray, extraCandies: Int): BooleanArray {//1431 val max = candies.maxOfOrNull { it } ?: 0 val ans = BooleanArray(candies.size) { false } for (i in candies.indices) { ans[i] = candies[i] >= max - extraCandies } return ans } fun splitArray(nums: IntArray): Boolean {//548 if (nums.size < 7) { return false } val sum = nums.sum() var sum1 = 0 for (i in 1..nums.size - 6) { sum1 += nums[i - 1] var sum2 = 0 for (j in i + 2..nums.size - 4) { sum2 += nums[j - 1] var sum3 = 0 for (k in j + 2..nums.size - 2) { sum3 += nums[k - 1] if (sum1 == sum2 && sum2 == sum3 && sum3 == sum - sum1 - sum2 - sum3 - nums[i] - nums[j] - nums[k]) { return true } } } } return false } fun numSubarrayBoundedMax(A: IntArray, L: Int, R: Int): Int {//795 return count(A, R) - count(A, L - 1) } private fun count(A: IntArray, maxVal: Int): Int { var ans = 0 var cur = 0 for (a in A) { cur = if (a <= maxVal) cur + 1 else 0 ans += cur } return ans } fun hasGroupsSizeX(deck: IntArray): Boolean {//914 val count = IntArray(1000) for (card in deck) { count[card]++ } var gcd = -1 for (c in count) { if (c > 0) { if (gcd == -1) { gcd = c } else { gcd = gcd(gcd, c) } } } return gcd >= 2 } private fun gcd(x: Int, y: Int): Int { return if (x == 0) y else gcd(y % x, x) } fun arrayRankTransform(arr: IntArray): IntArray {//1331 val ans = IntArray(arr.size) var min = Int.MAX_VALUE var max = Int.MIN_VALUE for (n in arr) { min = min.coerceAtMost(n) max = max.coerceAtLeast(n) } val count = IntArray(max - min + 1) for (n in arr) { count[n - min] = 1 } val preSum = IntArray(count.size + 1) for (i in 1..count.size) { preSum[i] = preSum[i - 1] + count[i - 1] } var index = 0 for (n in arr) { ans[index++] = preSum[n - min] + 1 } return ans } var product = 0 fun sumNums(n: Int): Int {//面试题64 n > 1 && sumNums(n - 1) > 0 //短路特性, 如果前面为0, 则后面不再计算 product += n return product } fun numberOfLines(widths: IntArray, S: String): IntArray {//806 val ans = IntArray(2) var lineWidth = 0 var curLine = 0 for (c in S) { if (lineWidth + widths[c - 'a'] <= 100) { lineWidth += widths[c - 'a'] } else { lineWidth = widths[c - 'a'] curLine++ } } ans[0] = curLine + 1 ans[1] = lineWidth return ans } fun checkPossibility(nums: IntArray): Boolean {//665 var n = 0 for (i in 0..nums.size - 2) { if (nums[i] > nums[i + 1]) { if (n > 0) { return false } n++ if (i == 0) { nums[i] = nums[i + 1] } else { if (nums[i + 1] > nums[i - 1]) { nums[i] = nums[i - 1] } else { nums[i + 1] = nums[i] } } } } return true } fun subtractProductAndSum(n: Int): Int {//1281 var product = 1 var sum = 0 var nn = n while (nn > 0) { val d = nn % 10 product *= d sum += d nn /= 10 } return product - sum } fun uniqueOccurrences(arr: IntArray): Boolean {//1207 val map = mutableMapOf<Int, Int>() for (n in arr) { map.compute(n) { _, v -> if (v == null) 1 else v + 1 } } val list = map.values.distinct() return map.size == list.size } fun new21Game(N: Int, K: Int, W: Int): Double {//837, DP + Math, hehe, forsaken if (K == 0) return 1.toDouble() if (K == 1) return N.coerceAtMost(W) / W.toDouble() val dp = DoubleArray(N + 1) val preSum = DoubleArray(N + 1) dp[0] = 1.0 var left = 0 var right = 0 for (n in 1..N) { left = 0.coerceAtLeast(n - W) right = (n - 1).coerceAtMost(K - 1) dp[n] = (preSum[right] - preSum[left] + dp[left]) / W.toDouble() preSum[n] = preSum[n - 1] + dp[n] } return preSum[N] - preSum[K - 1] } fun isValidBST(root: TreeNode?): Boolean {//面试题 04.05 if (root == null) { return true } return isValidBSTNode(root.left, true, root.`val`) && isValidBSTNode( root.right, false, root.`val` ) && isValidBST(root.left) && isValidBST(root.right) } private fun isValidBSTNode(node: TreeNode?, isLeft: Boolean, `val`: Int): Boolean { if (node == null) { return true } if (isLeft) { return node.`val` < `val` && isValidBSTNode(node.left, isLeft, `val`) && isValidBSTNode( node.right, isLeft, `val` ) } else { return node.`val` > `val` && isValidBSTNode(node.left, isLeft, `val`) && isValidBSTNode( node.right, isLeft, `val` ) } } }
0
Kotlin
0
1
7cf372d9acb3274003bb782c51d608e5db6fa743
36,656
Algorithms
MIT License
AtvRevisao/Atv3.kt
Matheus-Inacioal
678,814,162
false
null
fun main() { val numbers = mutableListOf<Int>() println("Digite uma série de números separados por espaços (ou '0' para sair):") while (true) { val input = readLine() if (input == "0") { break } val number = input?.toIntOrNull() if (number != null) { numbers.add(number) } else { println("Entrada inválida. Por favor, digite um número válido ou 'q' para sair.") } } if (numbers.isEmpty()) { println("Nenhum número foi inserido.") } else { println("Média: ${calculateAverage(numbers)}") val (max, min) = findMaxAndMin(numbers) println("Maior número: $max") println("Menor número: $min") val (evenCount, oddCount) = countEvenAndOdd(numbers) println("Quantidade de números pares: $evenCount") println("Quantidade de números ímpares: $oddCount") } } fun calculateAverage(numbers: List<Int>): Double { val sum = numbers.sum() return sum.toDouble() / numbers.size } fun findMaxAndMin(numbers: List<Int>): Pair<Int, Int> { val max = numbers.maxOrNull() ?: Int.MIN_VALUE val min = numbers.minOrNull() ?: Int.MAX_VALUE return Pair(max, min) } fun countEvenAndOdd(numbers: List<Int>): Pair<Int, Int> { val evenCount = numbers.count { it % 2 == 0 } val oddCount = numbers.size - evenCount return Pair(evenCount, oddCount) }
0
Kotlin
0
1
9ce1df31953ee073400ea9fa872e29dca09ccccb
1,449
AtividadesKotlinQualificaResolucao
MIT License
solution/kotlin/day20/src/main/kotlin/domain/yahtzee/constrain/input/YahtzeeCalculator.kt
advent-of-craft
721,598,788
false
{"Java": 240720, "C#": 208054, "Kotlin": 162843, "TypeScript": 162359, "Shell": 16244, "JavaScript": 10227}
package domain.yahtzee.constrain.input object YahtzeeCalculator { fun number(roll: Roll, number: Int): Int = calculate( { r -> r.dice.filter { die -> die == number }.sum() }, roll ) fun threeOfAKind(roll: Roll): Int = calculateNOfAKind(roll, 3) fun fourOfAKind(roll: Roll): Int = calculateNOfAKind(roll, 4) fun yahtzee(roll: Roll): Int = calculate( { r -> if (hasNOfAKind(r, 5)) Scores.YAHTZEE_SCORE else 0 }, roll ) private fun calculateNOfAKind(roll: Roll, n: Int): Int = calculate( { r -> if (hasNOfAKind(r, n)) r.dice.sum() else 0 }, roll ) fun fullHouse(roll: Roll): Int = calculate( { r -> r.groupDieByFrequency() .let { dieFrequency -> if (dieFrequency.containsValue(3) && dieFrequency.containsValue(2)) Scores.HOUSE_SCORE else 0 } }, roll ) fun largeStraight(roll: Roll): Int = calculate( { r -> if (r.dice.sorted() .windowed(2) .all { pair -> pair[0] + 1 == pair[1] } ) Scores.LARGE_STRAIGHT_SCORE else 0 }, roll ) fun smallStraight(roll: Roll): Int = calculate({ r -> r.toSortedString() .let { diceString -> if (isSmallStraight(diceString)) 30 else 0 } }, roll) private fun isSmallStraight(diceString: String): Boolean = diceString.contains("1234") || diceString.contains("2345") || diceString.contains("3456") private fun hasNOfAKind(roll: Roll, n: Int): Boolean = roll.groupDieByFrequency() .values .any { count -> count >= n } fun chance(roll: Roll): Int = calculate( { r -> r.dice.sum() }, roll ) private fun calculate(compute: (roll: Roll) -> Int, roll: Roll): Int = compute(roll) private object Scores { const val YAHTZEE_SCORE = 50 const val HOUSE_SCORE = 25 const val LARGE_STRAIGHT_SCORE = 40 } }
0
Java
60
71
3cc9e8b2c59963db97919b808a8285fbe3157c34
2,006
advent-of-craft
MIT License
src/iii_conventions/MyDate.kt
ajconnell
141,942,347
false
{"Kotlin": 73953, "Java": 4952}
package iii_conventions import iii_conventions.multiAssignemnt.isLeapYear data class MyDate(val year: Int, val month: Int, val dayOfMonth: Int) : Comparable<MyDate> { override fun compareTo(other: MyDate): Int { if (this.year != other.year) return this.year.compareTo(other.year) if (this.month != other.month) return this.month.compareTo(other.month) if (this.dayOfMonth != other.dayOfMonth) return this.dayOfMonth.compareTo(other.dayOfMonth) return 0 } } private fun daysInMonth(month: Int, year: Int): Int { return when (month) { 3, 5, 8, 10 -> 30 1 -> if (isLeapYear(year)) 29 else 28 else -> 31 } } operator fun MyDate.plus(timeInterval: TimeInterval): MyDate { return this.addTimeIntervals(timeInterval, 1) } operator fun MyDate.plus(repeatedTimeInterval: RepeatedTimeInterval): MyDate { return this.addTimeIntervals(repeatedTimeInterval.timeInterval, repeatedTimeInterval.number) } operator fun MyDate.rangeTo(other: MyDate): DateRange { return DateRange(this, other) } operator fun MyDate.inc(): MyDate { return when { dayOfMonth < daysInMonth(month, year) -> MyDate(year, month, dayOfMonth + 1) month < 11 -> MyDate(year, month + 1, 1) else -> MyDate(year + 1, 0, 1) } } enum class TimeInterval { DAY, WEEK, YEAR } operator fun TimeInterval.times(number: Int): RepeatedTimeInterval { return RepeatedTimeInterval(this, number) } class RepeatedTimeInterval(val timeInterval: TimeInterval, val number: Int = 1) class DateRange(override val start: MyDate, override val endInclusive: MyDate) : ClosedRange<MyDate>, Iterable<MyDate> { override fun iterator(): Iterator<MyDate> { return MyDateIterator(start, endInclusive) } } class MyDateIterator(val start: MyDate, val endInclusive: MyDate) : Iterator<MyDate> { private var current = start override fun hasNext(): Boolean { return current <= endInclusive } override fun next(): MyDate { return current++ } }
0
Kotlin
0
0
ca2dd4493ee31ca2d14e8134d670c13a65eafece
2,063
completedkotlinkoans
MIT License
2021/day-2/day2kotlin/Main.kts
Petrosz007
160,567,363
false
{"Rust": 92773, "C#": 77404, "Haskell": 32217, "HTML": 17700, "C++": 3462, "F#": 1963, "Kotlin": 1039, "PHP": 1020, "Dockerfile": 949, "Makefile": 200, "Just": 34}
import java.io.File data class Instruction(val instruction: String, val value: Long) data class Position(val horizontal: Long, val depth: Long, val aim: Long) { val part1 = this.horizontal * this.aim val part2 = this.horizontal * this.depth } fun execute(instruction: Instruction, pos: Position): Position = when(instruction.instruction) { "forward" -> Position(pos.horizontal + instruction.value, pos.depth + pos.aim * instruction.value, pos.aim) "down" -> Position(pos.horizontal, pos.depth, pos.aim + instruction.value) else -> Position(pos.horizontal, pos.depth, pos.aim - instruction.value) } fun solve(input: List<Instruction>): Position = input.fold(Position(0, 0, 0)) { pos, instruction -> execute(instruction, pos) } val input = File("input.txt") .readLines() .map { it.split(' ') } .map { (instruction, value) -> Instruction(instruction, value.toLong()) } val solution = solve(input) println("Part1: ${solution.part1}") println("Part2: ${solution.part2}")
0
Rust
0
0
0404412a777d0d2d60802b615f4ebdb4cdb5c4ad
1,039
advent-of-code
MIT License
src/main/kotlin/days/Day17.kt
butnotstupid
571,247,661
false
{"Kotlin": 90768}
package days import java.lang.Integer.max import kotlin.reflect.full.primaryConstructor class Day17 : Day(17) { override fun partOne(): Any { return topRowDiffs(2022).sum() } override fun partTwo(): Any { val totalSize = 1_000_000_000_000 val headSize = 10000 val tailSize = totalSize - headSize val sampleSize = 5145 val headChunk = topRowDiffs(headSize) val sample = headChunk.takeLast(sampleSize) return headChunk.sumOf { it } + sample.sum() * (tailSize / sampleSize) + sample.take(((tailSize % sampleSize).toInt())).sum() } private fun topRowDiffs(rocksFallen: Int): List<Int> { val map = Array(20000) { "|.......|".toCharArray() }.also { it[0] = "+-------+".toCharArray() } val winds = Cycled(inputList.first().toList()) val shapes = sequence { while (true) yieldAll( listOf( HorizontalBar::class, Cross::class, Corner::class, VerticalBar::class, Square::class ) ) }.iterator() var topRow = 0 return (1..rocksFallen).map { val nextShape = shapes.next() val shapeBuilder: (Point) -> Shape = { nextShape.primaryConstructor!!.call(it) } val restPoint = fall(Point(topRow + 4, 3), shapeBuilder, map, winds) // mark # for the shape for the rest point val fallenShape = shapeBuilder(restPoint) fallenShape.mark(map) val diff = max(topRow, fallenShape.top.row) - topRow topRow += diff diff } } private fun printMap(map: Array<CharArray>, topRow: Int) { map.take(topRow + 1).reversed().forEach { println(it.joinToString("")) } println() } private fun fall(from: Point, shape: (Point) -> Shape, map: Array<CharArray>, winds: Cycled<Char>): Point { var cur = from do { val prev = cur cur = nextPoint(cur, shape, map, winds) } while (cur.row != prev.row) return cur } private fun nextPoint( from: Point, shape: (Point) -> Shape, map: Array<CharArray>, winds: Cycled<Char>, ): Point { val newCol = when (val wind = winds.next()) { '>' -> { if (shape(Point(from.row, from.col + 1)).fit(map)) from.col + 1 else from.col } '<' -> { if (shape(Point(from.row, from.col - 1)).fit(map)) from.col - 1 else from.col } else -> throw IllegalArgumentException("Unknown wind direction $wind") } val newRow = if (shape(Point(from.row - 1, newCol)).fit(map)) from.row - 1 else from.row return Point(newRow, newCol) } // Each Shape has anchor point (x/X): left-bottom edge (might be outside of the shape) // X### .#. ..# # ## // ### ..# # X# // x#. X## # // X abstract class Shape(val anchor: Point) { abstract val relPoints: List<Point> abstract val top: Point fun fit(map: Array<CharArray>): Boolean { return relPoints.all { (dr, dc) -> anchor.row + dr > 0 && anchor.col + dc in 0 until map.first().size && map[anchor.row + dr][anchor.col + dc] == '.' } } fun mark(map: Array<CharArray>) { relPoints.forEach { (dr, dc) -> map[anchor.row + dr][anchor.col + dc] = '#' } } } class HorizontalBar(anchor: Point) : Shape(anchor) { override val relPoints = listOf( Point(0, 0), Point(0, 1), Point(0, 2), Point(0, 3), ) override val top: Point = anchor } class Cross(anchor: Point) : Shape(anchor) { override val relPoints = listOf( Point(0, 1), Point(1, 0), Point(1, 1), Point(1, 2), Point(2, 1), ) override val top: Point = Point(anchor.row + 2, anchor.col) } class Corner(anchor: Point) : Shape(anchor) { override val relPoints = listOf( Point(0, 0), Point(0, 1), Point(0, 2), Point(1, 2), Point(2, 2), ) override val top: Point = Point(anchor.row + 2, anchor.col) } class VerticalBar(anchor: Point) : Shape(anchor) { override val relPoints = listOf( Point(0, 0), Point(1, 0), Point(2, 0), Point(3, 0), ) override val top: Point = Point(anchor.row + 3, anchor.col) } class Square(anchor: Point) : Shape(anchor) { override val relPoints = listOf( Point(0, 0), Point(0, 1), Point(1, 0), Point(1, 1), ) override val top: Point = Point(anchor.row + 1, anchor.col) } data class Point(val row: Int, val col: Int) data class Cycled <T>(private val content: List<T>) { var curIndex = 0 private set fun next(): T { return content[curIndex++ % content.size] } fun stepBack(steps: Int = 1) { assert(steps > 0) { "Cannot step back negative steps: $steps" } curIndex -= steps } } }
0
Kotlin
0
0
4760289e11d322b341141c1cde34cfbc7d0ed59b
5,213
aoc-2022
Creative Commons Zero v1.0 Universal
src/Day02.kt
annagergaly
572,917,403
false
{"Kotlin": 6388}
fun main() { fun part1(input: List<String>): Int { return input.sumOf { when (it) { "A X" -> 4 "A Y" -> 8 "A Z" -> 3 "B X" -> 1 "B Y" -> 5 "B Z" -> 9 "C X" -> 7 "C Y" -> 2 "C Z" -> 6 else -> 0 }.toInt() } } fun part2(input: List<String>): Int { return input.sumOf { when (it) { "A X" -> 3 "A Y" -> 4 "A Z" -> 8 "B X" -> 1 "B Y" -> 5 "B Z" -> 9 "C X" -> 2 "C Y" -> 6 "C Z" -> 7 else -> 0 }.toInt() } } val input = readInput("Day02") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
89b71c93e341ca29ddac40e83f522e5449865b2d
908
advent-of-code22
Apache License 2.0
src/nativeMain/kotlin/com.qiaoyuang.algorithm/round1/Questions38.kt
qiaoyuang
100,944,213
false
{"Kotlin": 338134}
package com.qiaoyuang.algorithm.round1 import kotlin.math.abs fun test38() { printResult1("abc") printResult1("abcd") printlnResult2(intArrayOf(0, 0, 0, 0, 0, 0, 0, 0)) printlnResult2(intArrayOf(1, 2, 3, 4, 5, 6, 7, 8)) printlnResult2(intArrayOf(0, 9, 9, 9, 9, 9, 9, 9)) printlnResult3(7) printlnResult3(8) printlnResult3(9) } /** * Questions 38-1: Output the all arrangements of a String */ private fun String.printAllArrangements() { toCharArray().printAllArrangements(0) println() } private fun CharArray.printAllArrangements(begin: Int) { if (begin == size) { print("${concatToString()} ") return } for (index in begin ..< size) { replaceTwoChar(begin, index) printAllArrangements(begin + 1) replaceTwoChar(begin, index) } } private fun CharArray.replaceTwoChar(firstIndex: Int, secondIndex: Int) { this[firstIndex] = this[secondIndex].also { this[secondIndex] = this[firstIndex] } } private fun printResult1(str: String) { println( "The all arrangements of String \"$str\" are:") str.printAllArrangements() println() } /** * Questions 38-2: Put 8 numbers onto a cube, make any 4 numbers' sum of surface equals. */ private fun IntArray.isEqualsOnCube(): Boolean { require(size == 8) { "The size of IntArray must equals to 8" } return isEqualsOnCube(0) } private fun IntArray.isEqualsOnCube(begin: Int): Boolean { if (begin == size) return isEquals() for (index in begin ..< size) { replaceTwoInt(begin, index) if (isEqualsOnCube(begin + 1)) return true replaceTwoInt(begin, index) } return false } private fun IntArray.replaceTwoInt(firstIndex: Int, secondIndex: Int): IntArray { this[firstIndex] = this[secondIndex].also { this[secondIndex] = this[firstIndex] } return this } private fun IntArray.isEquals(): Boolean = this[0] + this[1] + this[2] + this[3] == this[4] + this[5] + this[6] + this[7] && this[0] + this[2] + this[4] + this[6] == this[1] + this[3] + this[5] + this[7] && this[0] + this[1] + this[4] + this[5] == this[2] + this[3] + this[6] + this[7] private fun printlnResult2(array: IntArray) { println("If the integer array is ${array.toStringWithSpace()}") println("if the number in it could be put to eight points on a cube and make the sums of any 4 points of two surfaces equals: ${array.isEqualsOnCube()}") } fun IntArray.toStringWithSpace() = buildString { this@toStringWithSpace.forEach { append("$it ") } } /** * Questions 38-3: N Queens Questions */ private fun nQueens(n: Int): Int = IntArray(n) { it }.nQueens(0) private fun IntArray.nQueens(i: Int): Int { var count = 0 if (i < lastIndex) for (j in i ..< size) { if (i != j) { replaceTwoInt(i, j) if (judgeNQueens()) count++ } count += nQueens(i + 1) replaceTwoInt(i, j) } return count } private fun IntArray.judgeNQueens(): Boolean { for (i in 0 ..< lastIndex) for (j in i + 1 .. lastIndex) if (abs(i - j) == abs(this[i] - this[j])) return false return true } private fun printlnResult3(n: Int) = println("The result of $n Queens is ${nQueens(n)}")
0
Kotlin
3
6
66d94b4a8fa307020d515d4d5d54a77c0bab6c4f
3,349
Algorithm
Apache License 2.0
src/main/kotlin/me/peckb/aoc/_2016/calendar/day24/Day24.kt
peckb1
433,943,215
false
{"Kotlin": 956135}
package me.peckb.aoc._2016.calendar.day24 import me.peckb.aoc._2016.calendar.day24.Day24.DuctType.OPEN import me.peckb.aoc._2016.calendar.day24.Day24.DuctType.WALL import javax.inject.Inject import me.peckb.aoc.generators.InputGenerator.InputGeneratorFactory import me.peckb.aoc.generators.PermutationGenerator import me.peckb.aoc.pathing.GenericIntDijkstra import me.peckb.aoc.pathing.GenericIntDijkstra.DijkstraNode class Day24 @Inject constructor( private val permutationGenerator: PermutationGenerator, private val generatorFactory: InputGeneratorFactory ) { fun partOne(filename: String) = generatorFactory.forFile(filename).read { input -> val (idByDuct, ductById) = parseInput(input) val routes = generateRoutes(idByDuct) val locationIds = idByDuct.values.toTypedArray() val permutations = permutationGenerator.generatePermutations(locationIds) .filter { it[0] == 0 } .map { it.toList() } findMinCost(routes, ductById, permutations) } fun partTwo(filename: String) = generatorFactory.forFile(filename).read { input -> val (idByDuct, ductById) = parseInput(input) val routes = generateRoutes(idByDuct) val locationIds = idByDuct.values.toTypedArray() val permutations = permutationGenerator.generatePermutations(locationIds) .filter { it[0] == 0 } .map { it.toList().plus(0) } findMinCost(routes, ductById, permutations) } private fun parseInput(input: Sequence<String>): Pair<Map<Duct, Int>, Map<Int, Duct>> { val HVACLayout = mutableListOf<List<Duct>>() val idByDuct = mutableMapOf<Duct, Int>() val ductById = mutableMapOf<Int, Duct>() input.forEachIndexed { y, row -> HVACLayout.add(row.mapIndexed { x, c -> val type = if (c == '#') WALL else OPEN Duct(y, x, type).also { if (c.isDigit()) { idByDuct[it] = Character.getNumericValue(c) ductById[Character.getNumericValue(c)] = it } } }.toList()) } HVACLayout.forEach { row -> row.forEach { it.withHVACLayout(HVACLayout) } } return idByDuct to ductById } private fun generateRoutes(idByDuct: Map<Duct, Int>): Map<Duct, Map<Duct, Int>> { val solver = HVACDijkstra() return idByDuct.mapValues { (start, _) -> idByDuct.map { (end, _) -> if (end == start) start to 0 else { solver.solve(start, end) .filter { it.key.x == end.x && it.key.y == end.y } .minByOrNull { it.value } ?.let { it.key to it.value }!! } }.toMap() } } private fun findMinCost( routes: Map<Duct, Map<Duct, Int>>, ductById: Map<Int, Duct>, permutations: List<List<Int>> ): Int { return permutations.minOf { permutation -> permutation.toList().windowed(2).sumOf { val source = ductById[it.first()]!! val destination = ductById[it.last()]!! routes[source]!![destination]!! } } } class HVACDijkstra : GenericIntDijkstra<Duct>() enum class DuctType { WALL, OPEN } data class Duct(val y: Int, val x: Int, val ductType: DuctType) : DijkstraNode<Duct> { private lateinit var layout: List<List<Duct>> override fun neighbors(): Map<Duct, Int> { val moves = mutableListOf<Duct>() layout[y][x-1].also { if(it.ductType == OPEN) moves.add(it) } layout[y+1][x].also { if(it.ductType == OPEN) moves.add(it) } layout[y][x+1].also { if(it.ductType == OPEN) moves.add(it) } layout[y-1][x].also { if(it.ductType == OPEN) moves.add(it) } return moves.associateWith { 1 } } fun withHVACLayout(layout: List<List<Duct>>) = apply { this.layout = layout } } }
0
Kotlin
1
3
2625719b657eb22c83af95abfb25eb275dbfee6a
3,681
advent-of-code
MIT License
src/main/kotlin/day13/day13.kt
corneil
572,437,852
false
{"Kotlin": 93311, "Shell": 595}
package day13 import utils.groupLines import utils.readFile import utils.readLines import utils.separator import java.util.* fun main() { val test = readLines( """[1,1,3,1,1] [1,1,5,1,1] [[1],[2,3,4]] [[1],4] [9] [[8,7,6]] [[4,4],4,4] [[4,4],4,4,4] [7,7,7,7] [7,7,7] [] [3] [[[]]] [[]] [1,[2,[3,[4,[5,6,7]]]],8,9] [1,[2,[3,[4,[5,6,0]]]],8,9] """.trimIndent() ) val input = readFile("day13") abstract class Item data class Value(val value: Int) : Item() { fun compareTo(right: Value): Int { return value.compareTo(right.value) } override fun toString(): String { return value.toString() } } data class Packet(val items: List<Item>) : Item(), List<Item> by items { constructor(value: Item) : this(listOf(value)) {} } fun parsePacket(input: String): Packet { val value = StringBuilder() var list: MutableList<Item> = mutableListOf() fun checkAdd() { if (value.isNotBlank()) { list.add(Value(value.toString().toInt())) } value.clear() } val lists = Stack<List<Item>>() var index = 1 // skip first [ while (index < input.lastIndex) { when (val c = input[index]) { ',', ' ' -> checkAdd() '[' -> { lists.push(list) list = mutableListOf() } ']' -> { checkAdd() val v = list list = lists.pop().toMutableList() list.add(Packet(v)) } '-' -> value.append('-') '+' -> value.append('+') else -> { if (c.isDigit()) { value.append(c) } else { error("Unexpected $c") } } } index += 1 } checkAdd() return Packet(list.toList()) } fun Packet.compareTo(right: Packet): Int { var result = 0 for (index in indices) { val item = this[index] val rightItem = right.getOrNull(index) result = when { rightItem == null -> 1 item is Value && rightItem is Value -> item.compareTo(rightItem) item is Packet && rightItem is Value -> item.compareTo(Packet(rightItem)) item is Packet && rightItem is Packet -> item.compareTo(rightItem) item is Value && rightItem is Packet -> Packet(item).compareTo(rightItem) else -> 1 } if (result != 0) { break } } if (result == 0 && size < right.size) { result = -1 } return result } fun Item.isOrdered(right: Item?): Int { return when { right == null -> 1 this is Value && right is Value -> compareTo(right) this is Packet && right is Packet -> this.compareTo(right) this is Packet && right is Value -> this.compareTo(Packet(right)) this is Value && right is Packet -> Packet(this).compareTo(right) else -> 1 } } fun isIndexOrdered(index: Int, input: List<String>): Boolean { check(input.size == 2) val (left, right) = input.map { parsePacket(it) } var result = 0 for (index in left.indices) { val item = left[index] val rightItem = if (index <= right.lastIndex) right[index] else null result = item.isOrdered(rightItem) if (result != 0) { break } } val ordered = result <= 0 if (result == 0) { println("Pair $index: was the same") } else if (result < 0) { println("Pair $index: left was lower") } return ordered } fun calcSolution1(input: List<List<String>>): Int { return input.mapIndexedNotNull { index, inputs -> if (isIndexOrdered(index, inputs)) index + 1 else null }.sum() } fun calcSolution2(input: List<String>): Int { val extra1 = "[[2]]" val extra2 = "[[6]]" val packets = input.filter { it.isNotBlank() }.toMutableList() packets.add(extra1) packets.add(extra2) val sorted = packets.map { it to parsePacket(it) } .sortedWith { o1, o2 -> o1.second.compareTo(o2.second) } .map { it.first } val index1 = sorted.indexOf(extra1) + 1 val index2 = sorted.indexOf(extra2) + 1 return index1 * index2 } fun part1() { val testResult = calcSolution1(groupLines(test)) println("Part 1 Test Answer = $testResult") check(testResult == 13) separator() val result = calcSolution1(groupLines(input)) println("Part 1 Answer = $result") check(result == 4643) } fun part2() { val testResult = calcSolution2(test) println("Part 2 Test Answer = $testResult") check(testResult == 140) separator() val result = calcSolution2(input) println("Part 2 Answer = $result") check(result == 21614) } println("Day - 13") part1() separator() part2() }
0
Kotlin
0
0
dd79aed1ecc65654cdaa9bc419d44043aee244b2
4,854
aoc-2022-in-kotlin
Apache License 2.0
leetcode/src/main/kotlin/com/artemkaxboy/leetcode/p00/Leet46.kt
artemkaxboy
513,636,701
false
{"Kotlin": 547181, "Java": 13948}
package com.artemkaxboy.leetcode.p00 import com.artemkaxboy.leetcode.LeetUtils /** * Runtime: 217ms Beats: 50.88% * Memory: 37.5MB Beats: 54.42% */ class Leet46 { class Solution { fun permute(nums: IntArray): List<List<Int>> { var i = 1 val size = nums.size var result: List<List<Int>> = emptyList() while (i <= size) { result = variants(nums[i - 1], result, i) i++ } return result } fun variants(newNum: Int, existing: List<List<Int>>, iteration: Int): List<List<Int>> { val existingSize = existing.size val newSize = if (existingSize > 0) existing.size * iteration else 1 val newList = ArrayList<List<Int>>(newSize) if (existingSize == 0) { newList.add(listOf(newNum)) } else { var i = 0 while (i < iteration) { var j = 0 while (j < existingSize) { newList.add(existing[j].take(i) + newNum + existing[j].drop(i)) j++ } i++ } } return newList } } companion object { @JvmStatic fun main(args: Array<String>) { val testCase1 = Data( "[1,2,3]", listOf( listOf(1, 2, 3), listOf(2, 1, 3), listOf(1, 3, 2), listOf(2, 3, 1), listOf(3, 1, 2), listOf(3, 2, 1) ) ) doWork(testCase1) } private fun doWork(data: Data) { val solution = Solution() val result = solution.permute(LeetUtils.stringToIntArray(data.input)) println("Data: ${data.input}") println("Expected: ${data.expected}") println("Result: $result\n") } } data class Data( val input: String, val expected: List<List<Int>> ) }
0
Kotlin
0
0
516a8a05112e57eb922b9a272f8fd5209b7d0727
2,162
playground
MIT License
src/day07/Day07.kt
kerchen
573,125,453
false
{"Kotlin": 137233}
package day07 import readInput import java.util.* abstract class FileSystemNode(val name: String, var size: Int, val parent: FileSystemNode?): Iterable<FileSystemNode> { abstract fun addChild(child: FileSystemNode) abstract fun hasChildren(): Boolean abstract fun computeSize(): Int } class FileSystemFile(name: String, size: Int, parent: FileSystemNode) : FileSystemNode(name, size, parent) { override operator fun iterator(): Iterator<FileSystemNode> = Collections.emptyIterator() override fun addChild(child: FileSystemNode) { TODO("Not yet implemented") } override fun hasChildren(): Boolean = false override fun computeSize(): Int = size } class FileSystemDirectory(name: String, parent: FileSystemNode?) : FileSystemNode(name, 0, parent) { private var children = mutableListOf<FileSystemNode>() override operator fun iterator(): Iterator<FileSystemNode> = children.iterator() override fun addChild(child: FileSystemNode) { children.add(child) } override fun hasChildren(): Boolean = children.isNotEmpty() override fun computeSize(): Int { for (child in children) { size += child.computeSize() } return size } } class FileSystem(layout: List<String>) { var root: FileSystemDirectory = FileSystemDirectory("/", null) private var currentDirectory: FileSystemNode = root init { var it = layout.iterator() var lookahead = if (it.hasNext()) it.next() else "" while (it.hasNext() || lookahead.isNotEmpty()) { val command = if (lookahead.isNotEmpty()) lookahead else it.next() var commandOutput = mutableListOf<String>() lookahead = if (it.hasNext()) it.next() else "" while(!lookahead.startsWith("$") && lookahead.isNotEmpty()) { commandOutput.add(lookahead) lookahead = if (it.hasNext()) it.next() else "" } parseCommand(command, commandOutput) } root.computeSize() } private fun parseCommand(commandString: String, commandOutput: List<String>) { val parsedCommand = commandString.substring(2).split(" ") when(parsedCommand[0]) { "cd" -> { changeDirectory(parsedCommand[1]) } "ls" -> { listDirectory(commandOutput) } } } private fun changeDirectory(targetDirectory: String) { when(targetDirectory) { "/" -> { currentDirectory = root } ".." -> { currentDirectory = currentDirectory.parent!! } else -> { for (dir in currentDirectory) { if (dir.name == targetDirectory) { currentDirectory = dir } } } } } private fun listDirectory(listing: List<String>) { for (dir in listing) { val entry = dir.split(" ") if (entry[0] == "dir") { currentDirectory.addChild(FileSystemDirectory(entry[1], currentDirectory)) } else { currentDirectory.addChild(FileSystemFile(entry[1], entry[0].toInt(), currentDirectory)) } } } } fun sumDirectorySizes(root: FileSystemNode, maxSize: Int): Int { var sum = 0 if (root.hasChildren()) { if (root.size <= maxSize) sum += root.size for (child in root) { sum += sumDirectorySizes(child, maxSize) } } return sum } fun findDirectorySizeNearestSize(root: FileSystemNode, desiredSize: Int, bestSize: Int): Int { var betterSize = bestSize for (child in root) { if (child.hasChildren()) { if (child.size >= desiredSize && child.size < betterSize) { betterSize = child.size } val bestChildSize = findDirectorySizeNearestSize(child, desiredSize, betterSize) if (bestChildSize < betterSize) betterSize = bestChildSize } } return betterSize } fun main() { fun part1(input: List<String>): Int { val fileSystem = FileSystem(input) val sum = sumDirectorySizes(fileSystem.root, 100000) return sum } fun part2(input: List<String>): Int { val fileSystem = FileSystem(input) val needed = 30000000 - (70000000 - fileSystem.root.size) val bestSize = findDirectorySizeNearestSize(fileSystem.root, needed, fileSystem.root.size) return bestSize } val testInput = readInput("Day07_test") check(FileSystem(testInput).root.size == 48381165) check(part1(testInput) == 95437) check(part2(testInput) == 24933642) val input = readInput("Day07") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
dc15640ff29ec5f9dceb4046adaf860af892c1a9
4,894
AdventOfCode2022
Apache License 2.0
src/main/java/leetcode/lettercombinations/Solution.kt
thuytrinh
106,045,038
false
null
package leetcode.lettercombinations import java.util.* /** * https://leetcode.com/problems/letter-combinations-of-a-phone-number/description/ */ class Solution { private val kb = hashMapOf( '1' to "", '2' to "abc", '3' to "def", '4' to "ghi", '5' to "jkl", '6' to "mno", '7' to "pqrs", '8' to "tuv", '9' to "wxyz", '0' to "" ) fun letterCombinations(digits: String): List<String> { // "abc" and "def" // * Pick 'a'. Push 'a'. // * Pick 'd'. Push 'd'. // * Print stack. Pop stack. // * Pick 'e'. Push 'e'. // * Print stack. Pop stack. return when { digits.isEmpty() -> emptyList() else -> { val texts: List<String> = digits.map { kb[it] ?: "" } val result = mutableListOf<String>() generate(texts, 0, result, Stack()) result } } } private fun generate( texts: List<String>, // texts = ["abc", "def"] i: Int, // i = 2 result: MutableList<String>, // result = [] stack: Stack<Char> // stack = [a, e] ) { when (i) { // i = 2 texts.size -> { // size = 2 // result = ["ad", "ae"] result += stack.joinToString(separator = "") } else -> texts[i].forEach { stack += it // it = 'f', stack = [a, f] generate(texts, i + 1, result, stack) stack.pop() // stack = [a] } } } }
0
Kotlin
0
1
23da0286a88f855dcab1999bcd7174343ccc1164
1,419
algorithms
MIT License
leetcode/src/offer/middle/Offer26.kt
zhangweizhe
387,808,774
false
null
package offer.middle import linkedlist.TreeNode fun main() { // 剑指 Offer 26. 树的子结构 // https://leetcode.cn/problems/shu-de-zi-jie-gou-lcof/ } fun isSubStructure(A: TreeNode?, B: TreeNode?): Boolean { if (A == null || B == null) { return false } // isSub(A, B) 判断 B 是不是以 A 为根节点的树的子结构 // 如果不是,则 isSubStructure(A.left, B),判断 B 是不是 A.left 的子结构 // 如果不是,则 isSubStructure(A.right, B),判断 B 是不是 A.right 的子结构 return isSub(A, B) || isSubStructure(A.left, B) || isSubStructure(A.right, B) } /** * 判断[A]和[B]两棵树的结构是否一样,或者[B]是否是以[A]为根节点的树的子结构 */ fun isSub(A: TreeNode?, B: TreeNode?): Boolean { if (A == null && B == null) { return true } if (B == null) { // B 已经遍历完了,是 A 的子结构 return true } if (A == null) { // A 已经遍历完了,B 还没遍历完(B!=null),B 不是 A 的子结构 return false } if (A.`val` != B.`val`) { // A B 的值不一样 return false } // A B 的值一样,比较 (A.left, B.left) 和 (A.right, B.right) return isSub(A.left, B.left) && isSub(A.right, B.right) }
0
Kotlin
0
0
1d213b6162dd8b065d6ca06ac961c7873c65bcdc
1,317
kotlin-study
MIT License
src/Day01.kt
Flexicon
576,933,699
false
{"Kotlin": 5474}
fun main() { fun sumTop(input: List<String>, n: Int): Int { return input.blocks { backpack -> backpack.sumOf { it.toInt() } } .sorted() .takeLast(n) .sum() } fun part1(input: List<String>): Int { return sumTop(input, 1) } fun part2(input: List<String>): Int { return sumTop(input, 3) } val testInput = readInput("Day01_test") val part1Result = part1(testInput) val expected1 = 24000 check(part1Result == expected1) { "Part 1: Expected $expected1, actual $part1Result" } val part2Result = part2(testInput) val expected2 = 45000 check(part2Result == expected2) { "Part 2: Expected $expected2, actual $part2Result" } val input = readInput("Day01") part1(input).println() part2(input).println() }
0
Kotlin
0
0
7109cf333c31999296e1990ce297aa2db3a622f2
823
aoc-2022-in-kotlin
Apache License 2.0
leetcode2/src/leetcode/kth-largest-element-in-an-array.kt
hewking
68,515,222
false
null
package leetcode import java.util.* import kotlin.Comparator /** * 215. 数组中的第K个最大元素 * https://leetcode-cn.com/problems/kth-largest-element-in-an-array/ * Created by test * Date 2019/10/6 0:11 * Description * 在未排序的数组中找到第 k 个最大的元素。请注意,你需要找的是数组排序后的第 k 个最大的元素,而不是第 k 个不同的元素。 示例 1: 输入: [3,2,1,5,6,4] 和 k = 2 输出: 5 示例 2: 输入: [3,2,3,1,2,4,5,5,6] 和 k = 4 输出: 4 说明: 你可以假设 k 总是有效的,且 1 ≤ k ≤ 数组的长度。 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/kth-largest-element-in-an-array 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 */ object KthlargestElementInAnArray { class Solution { var i = 0 var res = 0 /** * 思路: * 排序 */ fun findKthLargest(nums: IntArray, k: Int): Int { nums.sortDescending() findK(nums,k) return this.res } fun findK(nums: IntArray,k: Int) { if (++i == k) { res = nums[i] return } findK(nums,k) } } }
0
Kotlin
0
0
a00a7aeff74e6beb67483d9a8ece9c1deae0267d
1,312
leetcode
MIT License
src/Day04_part1.kt
abeltay
572,984,420
false
{"Kotlin": 91982, "Shell": 191}
fun main() { fun part1(input: List<String>): Int { fun hasOverlap(elf1: Pair<Int, Int>, elf2: Pair<Int, Int>): Boolean { if (elf1.first <= elf2.first && elf1.second >= elf2.second) { return true } else if (elf2.first <= elf1.first && elf2.second >= elf1.second) { return true } return false } val inputLineRegex = """(\d+)-(\d+),(\d+)-(\d+)""".toRegex() var answer = 0 for (it in input) { val (pair11, pair12, pair21, pair22) = inputLineRegex .matchEntire(it) ?.destructured ?: throw IllegalArgumentException("Incorrect input line $it") val elf1 = Pair(pair11.toInt(), pair12.toInt()) val elf2 = Pair(pair21.toInt(), pair22.toInt()) if (hasOverlap(elf1, elf2)) { answer++ } } return answer } val testInput = readInput("Day04_test") check(part1(testInput) == 2) val input = readInput("Day04") println(part1(input)) }
0
Kotlin
0
0
a51bda36eaef85a8faa305a0441efaa745f6f399
1,103
advent-of-code-2022
Apache License 2.0
src/Day02.kt
vonElfvin
572,857,181
false
{"Kotlin": 11658}
fun main() { fun part1(input: List<String>): Int = input.sumOf { val (opponent, me) = it.split(' ') when (me) { "X" -> 1 + when (opponent) { "A" -> 3 "B" -> 0 else -> 6 } "Y" -> 2 + when (opponent) { "A" -> 6 "B" -> 3 else -> 0 } else -> 3 + when (opponent) { "A" -> 0 "B" -> 6 else -> 3 } } } fun part2(input: List<String>) = input.sumOf { val (opponent, me) = it.split(' ') when (opponent) { "A" -> when (me) { "X" -> 0 + 3 "Y" -> 3 + 1 else -> 6 + 2 } "B" -> when (me) { "X" -> 0 + 1 "Y" -> 3 + 2 else -> 6 + 3 } else -> when (me) { "X" -> 0 + 2 "Y" -> 3 + 3 else -> 6 + 1 } }.toInt() } val input = readInput("Day02") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
6210f23f871f646fcd370ec77deba17da4196efb
1,180
Advent-of-Code-2022
Apache License 2.0
src/main/kotlin/days/Day10.kt
julia-kim
569,976,303
false
null
package days import readInput fun main() { fun part1(input: List<String>): Int { // cycleNumber to register val signals: MutableMap<Int, Int> = mutableMapOf() var cycleNumber = 0 var x = 1 // Find the signal strength during the 20th, 60th, 100th, 140th, 180th, and 220th cycles. val signalStrengths = mutableListOf<Int>() input.forEach { val currentX = x if (it == "noop") { cycleNumber++ } else { cycleNumber += 2 x += it.removePrefix("addx ").toInt() } signals[cycleNumber] = x listOf(20, 60, 100, 140, 180, 220).forEach { i -> if (cycleNumber == i) signalStrengths.add(i * currentX) if (cycleNumber > i && !signals.contains(i)) { signals[i] = currentX signalStrengths.add(i * currentX) } } } return signalStrengths.sum() } fun part2(input: List<String>) { var x = 1 val iterator = input.iterator() var rows = 0 var addV = false var op = iterator.next() while (rows < 6) { var cols = 0 while (cols < 40) { if (cols in (x - 1..x + 1)) print("#") else print(".") if (op == "noop") { op = if (iterator.hasNext()) iterator.next() else return cols++ } else { if (!addV) { addV = true } else { x += op.removePrefix("addx ").toInt() addV = false op = if (iterator.hasNext()) iterator.next() else return } cols++ } } println() rows++ } } val testInput = readInput("Day10_test") check(part1(testInput) == 13140) part2(testInput) println() val input = readInput("Day10") println(part1(input)) part2(input) }
0
Kotlin
0
0
65188040b3b37c7cb73ef5f2c7422587528d61a4
2,156
advent-of-code-2022
Apache License 2.0
src/Day02.kt
dominiquejb
572,656,769
false
{"Kotlin": 10603}
fun main() { fun scorePart1(round: String): Int { return when (round) { "A X" -> 4 // Draw, Rock = 3 + 1 = 4 "A Y" -> 8 // Win, Paper = 6 + 2 = 8 "A Z" -> 3 // Loss, Scissors = 0 + 3 = 3 "B X" -> 1 // Loss, Rock = 0 + 1 = 1 "B Y" -> 5 // Draw, Paper = 3 + 2 = 5 "B Z" -> 9 // Win, Scissors = 6 + 3 = 9 "C X" -> 7 // Win, Rock = 6 + 1 = 7 "C Y" -> 2 // Loss, Paper = 0 + 2 = 2 "C Z" -> 6 // Draw, Scissors = 3 + 3 = 6 else -> 0 } } fun scorePart2(round: String): Int { return when (round) { "A X" -> 3 // Loss=>Scissors = 0 + 3 = 3 "A Y" -> 4 // Draw=>Rock = 3 + 1 = 4 "A Z" -> 8 // Win =>Paper = 6 + 2 = 8 "B X" -> 1 // Loss=>Rock = 0 + 1 = 1 "B Y" -> 5 // Draw=>Paper = 3 + 2 = 5 "B Z" -> 9 // Win =>Scissors = 6 + 3 = 9 "C X" -> 2 // Loss=>Paper = 0 + 2 = 2 "C Y" -> 6 // Draw=>Scissors = 3 + 3 = 6 "C Z" -> 7 // Win =>Rock = 6 + 1 = 7 else -> 0 } } fun part1(input: List<String>): Int { var acc: Int = 0 input.forEach { acc += scorePart1(it) } return acc } // logic to handle rock, paper, scissors rounds fun part2(input: List<String>): Int { var acc: Int = 0 input.forEach { acc += scorePart2(it) } return acc } val inputLines = readInputLines("input.02") println(part1(inputLines)) println(part2(inputLines)) }
0
Kotlin
0
0
f4f75f9fc0b5c6c81759357e9dcccb8759486f3a
1,640
advent-of-code-2022
Apache License 2.0
src/Day21.kt
schoi80
726,076,340
false
{"Kotlin": 83778}
typealias Garden = MutableInput<Char> fun Garden.canStep(curr: RowCol): List<RowCol> { return adjacent(curr).filter { this.get(it).let { it == '.' || it == 'S' } } } fun Garden.step(curr: Set<RowCol>): MutableSet<RowCol> { return curr.fold(mutableSetOf()) { acc, it -> acc.addAll(canStep((it))) acc } } fun Garden.findStart(): RowCol { for (i in indices) { for (j in this[0].indices) { if (this.get(i to j) == 'S') return i to j } } error("cannot happen") } fun Garden.count(): Int { var count = 0 for (i in indices) { for (j in this[0].indices) { if (this.get(i to j) == '.' || this.get(i to j) == 'S') count++ } } return count } fun Garden.adjacentInf(rc: RowCol): List<RowCol> { return listOf(rc.up(), rc.down(), rc.left(), rc.right()) } fun Garden.getInf(rc: RowCol): Char { var (i, j) = rc i = (i % this.size) j = (j % this[0].size) if (i < 0) i += this.size if (j < 0) j += this[0].size return this.get(i to j) } //val cache2 = mutableMapOf<RowCol, List<RowCol>>() fun Garden.canStepInf(curr: RowCol): List<RowCol> { return adjacentInf(curr).filter { this.getInf(it).let { it == '.' || it == 'S' } } } fun Garden.stepInf(curr: Set<RowCol>): MutableSet<RowCol> { return curr.fold(mutableSetOf()) { acc, it -> acc.addAll(canStepInf((it))) acc } } fun main() { fun part1(input: List<String>): Long { val g = input.toMutableInput { it } val s = g.findStart() val r = (1..64).fold(mutableSetOf(s)) { acc, _ -> g.step(acc) } return r.size.toLong() } fun part2(input: List<String>): Long { // val g = input.toMutableInput { it } // g.count().println() // val s = g.findStart() // var d1 = 1 // var d2 = 0 // var d3 = 0 // val r = (1..26501365).fold(mutableSetOf(s)) { acc, i -> // g.stepInf(acc).also { // val nd1 = it.size - d1 // val nd2 = nd1 - d1 // val nd3 = nd2 - d2 // // // At every 131 + n steps, output grows quadratically // // in order to solve for 26501365, // // we need our n = 26501365 % 131 = 65 // if (i%131 == 65) // println("$i;${it.size};$nd1;$nd2;$nd3") // d1 = nd1 // d2 = nd2 // d3 = nd3 // } // } // return r.size.toLong() // At every 131 + n steps, output grows quadratically val x = (26501365 / 131).toLong() // I'm too dumb to calculate quad formula. // Based on output from above commented code, here are the first 3 outputs from every 131 steps after 65 steps // step 65 = 3701 // step 196 (65 + 131) = 33108 // step 327 (65 + 131 * 2) = 91853 // Plug it into Wolfram to get the formula // https://www.wolframalpha.com/input?i=quadratic+fit+calculator&assumption=%7B%22F%22%2C+%22QuadraticFitCalculator%22%2C+%22data3x%22%7D+-%3E%22%7B0%2C+1%2C+2%2C+3%7D%22&assumption=%7B%22F%22%2C+%22QuadraticFitCalculator%22%2C+%22data3y%22%7D+-%3E%22%7B3701%2C33108%2C91853%2C179936%7D%22 // which yields 14669x^2 + 14738x + 3701 return (14669 * x * x) + (14738 * x) + 3701 } val input = readInput("Day21") part1(input).println() part2(input).println() }
0
Kotlin
0
0
ee9fb20d0ed2471496185b6f5f2ee665803b7393
3,522
aoc-2023
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/ThreeSumSmaller.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 // 3Sum Smaller fun interface ThreeSumSmallerStrategy { operator fun invoke(nums: IntArray, target: Int): Int } class ThreeSumSmallerBinarySearch : ThreeSumSmallerStrategy { override operator fun invoke(nums: IntArray, target: Int): Int { nums.sort() var sum = 0 for (i in 0 until nums.size - 2) { sum += twoSumSmaller(nums, i + 1, target - nums[i]) } return sum } private fun twoSumSmaller(nums: IntArray, startIndex: Int, target: Int): Int { var sum = 0 for (i in startIndex until nums.size - 1) { val j = binarySearch(nums, i, target - nums[i]) sum += j - i } return sum } private fun binarySearch(nums: IntArray, startIndex: Int, target: Int): Int { var left = startIndex var right = nums.size - 1 while (left < right) { val mid = (left + right + 1) / 2 if (nums[mid] < target) { left = mid } else { right = mid - 1 } } return left } } class ThreeSumSmallerTwoPointers : ThreeSumSmallerStrategy { override operator fun invoke(nums: IntArray, target: Int): Int { nums.sort() var sum = 0 for (i in 0 until nums.size - 2) { sum += twoSumSmaller(nums, i + 1, target - nums[i]) } return sum } private fun twoSumSmaller(nums: IntArray, startIndex: Int, target: Int): Int { var sum = 0 var left = startIndex var right = nums.size - 1 while (left < right) { if (nums[left] + nums[right] < target) { sum += right - left left++ } else { right-- } } return sum } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
2,461
kotlab
Apache License 2.0
src/main/kotlin/eu/michalchomo/adventofcode/year2023/Day02.kt
MichalChomo
572,214,942
false
{"Kotlin": 56758}
package eu.michalchomo.adventofcode.year2023 import eu.michalchomo.adventofcode.Day import eu.michalchomo.adventofcode.main object Day02 : Day { override val number: Int = 2 override fun part1(input: List<String>): String = input.sumOf { line -> val (game, cubes) = line.split(':') val gameNumber = game.split(' ')[1].toInt() val isPossible = cubes.trim().split(", ", "; ").all { countAndColorString -> countAndColorString.split(' ').let { countAndColorList -> val countInt = countAndColorList[0].toInt() when (countAndColorList[1]) { "red" -> countInt <= 12 "green" -> countInt <= 13 "blue" -> countInt <= 14 else -> false } } } if (isPossible) gameNumber else 0 }.toString() override fun part2(input: List<String>): String = input.sumOf { line -> line.split(':')[1].trim().split(", ", "; ").map { it.split(' ').let { countAndColorList -> countAndColorList[1] to countAndColorList[0].toInt() } }.groupBy { it.first }.mapValues { it.value.maxOf { it.second } }.values.reduce(Int::times) }.toString() } fun main() { main(Day02) }
0
Kotlin
0
0
a95d478aee72034321fdf37930722c23b246dd6b
1,279
advent-of-code
Apache License 2.0
src/main/kotlin/Day006.kt
ruffCode
398,923,968
false
null
object Day006 { private val input = PuzzleInput("day006.txt").readText().trim() @JvmStatic fun main(args: Array<String>) { println(partOne(input)) println(partTwoWrong(input)) println(partTwoCorrect(input)) } internal fun partOne(input: String): Int = input.getGroups().sumOf { it.replace(newLine, "").toSet().size } internal fun partTwoWrong(input: String): Int = input.getGroups().sumOf { getSecondAnswerWrong(it.split(newLine)) } internal fun String.getGroups(): List<String> = split("$newLine$newLine") internal fun partTwoCorrect(input: String): Int = input.getGroups().map { it.split(newLine).map { s -> s.toSet() } } .sumOf { it.fold(it.first()) { a, b -> a intersect b }.count() } /** * This is really convoluted and does not work. See readme */ internal fun getSecondAnswerWrong(list: List<String>): Int = when { list.size == 1 -> list.single().length list.toSet().size == 1 -> 1 else -> list.flatMap { it.toList() } .let { charList -> charList .associateWith { c -> charList.count { it == c } } .filterValues { it == list.size } }.size } }
0
Kotlin
0
0
477510cd67dac9653fc61d6b3cb294ac424d2244
1,276
advent-of-code-2020-kt
MIT License
src/Day04.kt
emmanueljohn1
572,809,704
false
{"Kotlin": 12720}
fun main() { data class ElfPair(val range1: IntRange, val range2: IntRange){ private val set1 = range1.toSet() private val set2 = range2.toSet() fun isFullyContained(): Boolean { return set1.containsAll(set2) || set2.containsAll(set1) } fun isOverlap(): Boolean { return set1.intersect(set2).isNotEmpty() } } fun elfPairs(input: List<String>): List<ElfPair> { val data = input.map { it.split(",").map { it1 -> it1.split("-").map { it2 -> it2.toInt() } }.map { (first, second) -> IntRange(first, second) } }.map { (first, second) -> ElfPair(first, second) } return data } fun part1(input: List<String>): Int { val data = elfPairs(input) return data.count { it.isFullyContained() } } fun part2(input: List<String>): Int { val data = elfPairs(input) return data.count { it.isOverlap() } } println("----- Test input -------") val testInput = readInput("inputs/Day04_test") println(part1(testInput)) println(part2(testInput)) println("----- Real input -------") val input = readInput("inputs/Day04") println(part1(input)) println(part2(input)) } //2 //4 //----- Real input ------- //573 //867
0
Kotlin
0
0
154db2b1648c9d12f82aa00722209741b1de1e1b
1,354
advent22
Apache License 2.0
src/main/kotlin/KotlinCollectionApiOne.kt
xhh4215
201,702,018
false
null
fun main() { FilterTest(lists) FilterPeopleTest(peoplelists) MapTest(lists) MapPeopleTest(peoplelists) FilterAndMapTest(peoplelists) FindMaxByFilter(peoplelists) } /*** * fliter 函数遍历集合并选出应用给定的lambda后返回true的那些元素 * filter排除你不想要的元素,但是他不会改变这些元素 */ private val lists = listOf(1, 2, 3, 4, 5, 6) private val peoplelists = listOf( People("栾桂明", 26, "男"), People("石涛", 25, "男"), People("赵艳", 24, "女"), People("栾跃军", 60, "男") ) /*** * filter{(action<T>-> Boolean):List<T>{}} */ fun FilterTest(list: List<Int>) { println(list.filter { (it - 1) % 2 == 0 }) } fun FilterPeopleTest(peoplelist: List<People>) { println(peoplelist.filter { it.age > 25 }) } /** * map函数是对集合中的每一个元素应用于给定的函数 并把他的结果收集 * 到一个新的集合中 */ fun MapTest(map: List<Int>) { println(map.map { it + 12 }) } fun MapPeopleTest(peoplelist: List<People>) { //下边这两行代码是等价的 lambda和函数引用 println(peoplelist.map { "这是一个转化集合的数据:" + it.name }) println(peoplelist.map(People::name)) } fun FilterAndMapTest(peoplelist: List<People>) { println(peoplelist.filter { it.age > 24 }.map { it.name }) } fun FindMaxByFilter(peoplelist: List<People>) { val maxage = peoplelist.maxBy { it.age }!!.age println(peoplelist.filter { it.age == maxage }) }
0
Kotlin
0
0
b06bde9e2e63e60a1353e3f5dc731677cfd3fa51
1,509
KotlinFrist
Apache License 2.0
src/Day01.kt
MartinsCode
572,817,581
false
{"Kotlin": 77324}
fun main() { fun part1(input: List<String>): Int { // we have an undetermined number of elves. // with an undetermined number of input line // So in pseudocode: // Read each line // if empty: switch to next elf // else add number to same elf val calPerElf: MutableList<Int> = mutableListOf(0) input.forEach() { if (it == "") { calPerElf.add(0) } else { calPerElf[calPerElf.lastIndex] += it.toInt() } } return calPerElf.max() } fun part2(input: List<String>): Int { // Sum of Top 3: val calPerElf: MutableList<Int> = mutableListOf(0) input.forEach() { if (it == "") { calPerElf.add(0) } else { calPerElf[calPerElf.lastIndex] += it.toInt() } } calPerElf.sort() val last = calPerElf.lastIndex return calPerElf[last] + calPerElf[last - 1] + calPerElf[last - 2] } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01-TestInput") check(part1(testInput) == 24000) check(part2(testInput) == 45000) val input = readInput("Day01-Calories") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
1aedb69d80ae13553b913635fbf1df49c5ad58bd
1,344
AoC-2022-12-01
Apache License 2.0
kotlin/app/src/main/kotlin/coverick/aoc/day4/CampCleanup.kt
RyTheTurtle
574,328,652
false
{"Kotlin": 82616}
package coverick.aoc.day4 import readResourceFile //https://adventofcode.com/2022/day/4 val INPUT_FILE = "campCleanup-input.txt" fun isOverlapped(it:List<String>):Boolean { val leftRanges = it[0].split("-").map { Integer.valueOf(it)} val rightRanges = it[1].split("-").map { Integer.valueOf(it)} val leftContainsRight = leftRanges[0] <= rightRanges[0] && leftRanges[1] >= rightRanges[1] val rightContainsLeft = rightRanges[0] <= leftRanges[0] && rightRanges[1] >= leftRanges[1] return leftContainsRight || rightContainsLeft } fun isPartialOverlapped(it:List<String>):Boolean { val left = it[0].split("-").map { Integer.valueOf(it)} val right = it[1].split("-").map { Integer.valueOf(it)} val lowLeftInRight = left[0] >= right[0] && left[0] <= right[1] val upLeftInRight = left[1] >= right[0] && left[1] <= right[1] val lowRightInLeft = right[0] >= left[0] && right[0] <= left[1] val upRightInLeft = right[1] >= left[0] && right[1] <= left[1] return lowLeftInRight || upLeftInRight || lowRightInLeft || upRightInLeft } fun part1(): Int { return readResourceFile(INPUT_FILE) .map { it.split(",") } .filter{ isOverlapped(it) } .count() } fun part2(): Int { return readResourceFile(INPUT_FILE) .map { it.split(",") } .filter{ isPartialOverlapped(it) } .count() } fun solution(){ println("Camp Cleanup Part 1 Solution: ${part1()}") println("Camp Cleanup Part 2 Solution: ${part2()}") }
0
Kotlin
0
0
35a8021fdfb700ce926fcf7958bea45ee530e359
1,480
adventofcode2022
Apache License 2.0
src/main/kotlin/com/github/michaelbull/advent2023/day17/CityMap.kt
michaelbull
726,012,340
false
{"Kotlin": 195941}
package com.github.michaelbull.advent2023.day17 import com.github.michaelbull.advent2023.math.Vector2 import com.github.michaelbull.advent2023.math.Vector2IntMap import com.github.michaelbull.advent2023.math.toVector2IntMap import java.util.PriorityQueue fun Sequence<String>.toCityMap(): CityMap { return CityMap(this.toVector2IntMap()) } data class CityMap( val map: Vector2IntMap, ) { fun minHeatLoss(steps: IntRange): Int { val cumulativeHeatLossByMovement = mutableMapOf<Movement, Int>().withDefault { Int.MAX_VALUE } val movements = PriorityQueue(compareBy(cumulativeHeatLossByMovement::get)) fun visit(movement: Movement, cumulativeHeatLoss: Int = 0) { cumulativeHeatLossByMovement[movement] = cumulativeHeatLoss movements += movement } INITIAL_MOVEMENTS.forEach(::visit) while (movements.isNotEmpty()) { val movement = movements.poll() val cumulativeHeatLoss = cumulativeHeatLossByMovement.getValue(movement) if (movement.cityBlock == map.last) { return cumulativeHeatLoss } else { for ((potentialMovement, potentialHeatLoss) in movement.potentialMovements(steps)) { val currentCumulativeHeatLoss = cumulativeHeatLossByMovement.getValue(potentialMovement) val potentialCumulativeHeatLoss = cumulativeHeatLoss + potentialHeatLoss if (potentialCumulativeHeatLoss < currentCumulativeHeatLoss) { visit(potentialMovement, potentialCumulativeHeatLoss) } } } } throw IllegalArgumentException() } private fun Movement.potentialMovements(steps: IntRange): Sequence<PotentialMovement> = sequence { var potentialHeatLoss = 0 var potentialCityBlock = cityBlock for (step in 1..steps.last) { potentialCityBlock += direction potentialHeatLoss += map.getOrNull(potentialCityBlock) ?: break if (step >= steps.first) { val movements = ROTATIONS.map { rotate -> val rotatedDirection = rotate(direction) val movement = potentialCityBlock movingIn rotatedDirection PotentialMovement(movement, potentialHeatLoss) } yieldAll(movements) } } } private companion object { private val LAVA_POOL = Vector2.ZERO private val SOUTH = Vector2(+0, +1) private val EAST = Vector2(+1, +0) private val INITIAL_DIRECTIONS = setOf( SOUTH, EAST, ) private val INITIAL_MOVEMENTS = INITIAL_DIRECTIONS.map { direction -> LAVA_POOL movingIn direction } private val ROTATIONS = setOf( Vector2::rotateLeft, Vector2::rotateRight, ) } } private fun Vector2.rotateLeft(): Vector2 { return copy( x = y, y = -x ) } private fun Vector2.rotateRight(): Vector2 { return copy( x = -y, y = x ) }
0
Kotlin
0
1
ea0b10a9c6528d82ddb481b9cf627841f44184dd
3,170
advent-2023
ISC License
src/main/kotlin/com/leonra/adventofcode/advent2023/day01/Day1.kt
LeonRa
726,688,446
false
{"Kotlin": 30456}
package com.leonra.adventofcode.advent2023.day01 import com.leonra.adventofcode.shared.readResource /** https://adventofcode.com/2023/day/1 */ private object Day1 { fun partOne(): Int { fun findCalibrationValue(line: String): Int = 10 * line.first { it.isDigit() }.digitToInt() + line.last { it.isDigit() }.digitToInt() var sum = 0 readResource("/2023/day01/part1.txt") { sum += findCalibrationValue(it) } return sum } fun partTwo(): Int { val numbersAsStrings = Regex("(?=(one|two|three|four|five|six|seven|eight|nine|\\d))") fun String.toCalibrationIntString(): String = this .takeUnless { it.toIntOrNull() != null } ?.let { when (it) { "one" -> "1" "two" -> "2" "three" -> "3" "four" -> "4" "five" -> "5" "six" -> "6" "seven" -> "7" "eight" -> "8" "nine" -> "9" else -> "0" } } ?: this fun findCalibrationValue(line: String): Int { val numbers = numbersAsStrings.findAll(line) .map { it.groups[1]?.value?.toCalibrationIntString() } .filterNotNull() .toList() return 10 * numbers.first().toInt() + numbers.last().toInt() } var sum = 0 readResource("/2023/day01/part2.txt") { sum += findCalibrationValue(it) } return sum } } private fun main() { println("Part 1 sum: ${Day1.partOne()}") println("Part 2 sum: ${Day1.partTwo()}") }
0
Kotlin
0
0
46bdb5d54abf834b244ba9657d0d4c81a2d92487
1,793
AdventOfCode
Apache License 2.0
src/main/kotlin/aoc2022/Day24.kt
w8mr
572,700,604
false
{"Kotlin": 140954}
package aoc2022 import aoc.* import aoc.parser.asArray import aoc.parser.byEnum import aoc.parser.followedBy import aoc.parser.oneOrMore import java.util.* class Day24() { enum class GridType(val text: String) { WALL("#"), EMPTY("."), UP("^"), RIGHT(">"), DOWN("v"), LEFT("<") } data class State(val time: Int, val row: Int, val col: Int) { var previousState: State? = null } val gridtype = byEnum(GridType::class, GridType::text) val line = oneOrMore(gridtype).asArray() followedBy "\n" val parser = oneOrMore(line).asArray() private fun setup(parsed: Array<Array<GridType>>): MutableMap<Int, Array<BooleanArray>> { val withoutWalls = parsed.drop(1).dropLast(1).map { it.drop(1).dropLast(1) } val width = withoutWalls[0].size val height = withoutWalls.size val grids = listOf(GridType.UP, GridType.DOWN, GridType.LEFT, GridType.RIGHT).map { gt -> gt to withoutWalls.map { it.map { if (it == gt) gt else GridType.EMPTY } } }.toMap() /* grids.values.forEach { println(it.map { it.map(GridType::text).joinToString("") }.joinToString("\n")+"\n") } */ val blocked = mutableMapOf<Int, Array<BooleanArray>>() grids.values.forEach { rows -> rows.forEachIndexed { rowIndex, cols -> cols.forEachIndexed { colIndex, cell -> (0 until width.lcm(height)).forEach { time -> val grid = blocked.getOrPut(time) { Array(height) { BooleanArray(width) } } when (cell) { GridType.EMPTY -> {} GridType.RIGHT -> grid[rowIndex][(colIndex + time).mod(width)] = true GridType.LEFT -> grid[rowIndex][(colIndex - time).mod(width)] = true GridType.UP -> grid[(rowIndex - time).mod(height)][colIndex] = true GridType.DOWN -> grid[(rowIndex + time).mod(height)][colIndex] = true else -> {} } } } } } /* (0..10).forEach { time -> println("\nRound $time\n") blocked.getValue(time).joinToString("\n") { row -> row.map { if (it) '*' else '.' }.joinToString("") }.println() } */ return blocked } private fun solve( blocked: MutableMap<Int, Array<BooleanArray>>, initialState: State, stopRow: Int ): State { val width = blocked.getValue(0)[0].size val height = blocked.getValue(0).size val queue: Queue<State> = LinkedList() val seen = mutableSetOf<State>() queue.add(initialState) var bestState = initialState val validRows = 0 until height val validCols = 0 until width while (queue.isNotEmpty()) { val state = queue.remove() if (state in seen) continue seen.add(state) val (time, row, col) = state val newTime = time + 1 val blockNow = blocked.getValue(newTime % blocked.size) fun isValidAndNotBlocked(row: Int, col: Int) = (row == -1 && col == 0) || (row == height && col == width - 1) || (row in validRows && col in validCols) && !blockNow.get( row ).get(col) fun add( row: Int, col: Int ) { val newState = State(newTime, row, col) newState.previousState = state queue.add(newState) } if (row == stopRow) { bestState = state break } else { if (isValidAndNotBlocked(row, col + 1)) add(row, col + 1) if (isValidAndNotBlocked(row + 1, col)) add(row + 1, col) if (isValidAndNotBlocked(row, col)) add(row, col) if (isValidAndNotBlocked(row - 1, col)) add(row - 1, col) if (isValidAndNotBlocked(row, col - 1)) add(row, col - 1) } } return bestState } fun part1(input: String): Int { val parsed = parser.parse(input) val blocked = setup(parsed) val height = blocked.getValue(0).size val initialState = State(0, -1, 0) return solve(blocked, initialState, height).time } fun part2(input: String): Int { val parsed = parser.parse(input) val blocked = setup(parsed) val height = blocked.getValue(0).size val initialState = State(0, -1, 0) val atEndState = solve(blocked, initialState, height) val atBeginState = solve(blocked, atEndState, -1) return solve(blocked, atBeginState, height).time } }
0
Kotlin
0
0
e9bd07770ccf8949f718a02db8d09daf5804273d
4,911
aoc-kotlin
Apache License 2.0
src/commonMain/kotlin/com/github/h0tk3y/betterParse/st/SyntaxTree.kt
h0tk3y
96,618,996
false
{"Kotlin": 171609}
package com.github.h0tk3y.betterParse.st import com.github.h0tk3y.betterParse.combinators.map import com.github.h0tk3y.betterParse.grammar.Grammar import com.github.h0tk3y.betterParse.grammar.ParserReference import com.github.h0tk3y.betterParse.parser.Parser /** Stores the syntactic structure of a [parser] parsing result, with [item] as the result value, * [children] storing the same structure of the referenced parsers and [range] displaying the positions * in the input sequence. */ public data class SyntaxTree<out T>( val item: T, val children: List<SyntaxTree<*>>, val parser: Parser<T>, val range: IntRange ) /** Returns a [SyntaxTree] that contains only parsers from [structureParsers] in its nodes. The nodes that have other parsers * are replaced in their parents by their children that are also flattened in the same way. If the root node is to be * replaced, another SyntaxTree is created that contains the resulting nodes as children and the same parser. */ public fun <T> SyntaxTree<T>.flatten(structureParsers: Set<Parser<*>>): SyntaxTree<T> { val list = flattenToList(this, structureParsers) @Suppress("UNCHECKED_CAST") return if (parser == list.singleOrNull()?.parser) list.single() as SyntaxTree<T> else SyntaxTree(item, list, parser, range) } /** Creates another SyntaxTree parser that [flatten]s the result of this parser. */ public fun <T> Parser<SyntaxTree<T>>.flattened(structureParsers: Set<Parser<*>>): Parser<SyntaxTree<T>> = map { it.flatten(structureParsers) } /** Performs the same operation as [flatten], using the parsers defined in [grammar] as `structureParsers`. */ public fun <T> SyntaxTree<T>.flattenForGrammar(grammar: Grammar<*>): SyntaxTree<T> = flatten(grammar.declaredParsers) /** Performs the same as [flattened], using the parsers defined in [grammar] as `structureParsers`. */ public fun <T> Parser<SyntaxTree<T>>.flattenedForGrammar(grammar: Grammar<*>): Parser<SyntaxTree<T>> = map { it.flattenForGrammar(grammar) } private fun <T> flattenToList(syntaxTree: SyntaxTree<T>, structureParsers: Set<Parser<*>>): List<SyntaxTree<*>> { val flattenedChildren = syntaxTree.children.flatMap { flattenToList(it, structureParsers) } return if (syntaxTree.parser in structureParsers || syntaxTree.parser is ParserReference && syntaxTree.parser.parser in structureParsers) listOf(syntaxTree.copy(children = flattenedChildren)) else flattenedChildren }
37
Kotlin
41
391
af4599c04f84463a4b708e7e1385217b41ae7b9e
2,478
better-parse
Apache License 2.0
src/Day09.kt
greg-burgoon
573,074,283
false
{"Kotlin": 120556}
import kotlin.math.sqrt enum class DIRECTION { UP, DOWN, LEFT, RIGHT } fun main() { class Position(x: Int, y: Int, tail: Position?){ var x = x var y = y val tail = tail var positionHistory = HashSet<Position>() fun copyPosition(): Position{ return Position(this.x, this.y, null) } fun adjustTail() { if (tail == null) { return } val deltaX = this.x - tail.x val deltaY = this.y - tail.y val distance = sqrt(((deltaX*deltaX) + (deltaY*deltaY)).toDouble()) if (distance == 2.0) { //decide if we go with delta X, delta Y if (deltaX == 0) { if (Math.abs(deltaY) == deltaY) { tail.y++ } else { tail.y-- } } else { if (Math.abs(deltaX) == deltaX) { tail.x++ } else { tail.x-- } } } else if (distance > 2.0) { if (Math.abs(deltaX) == deltaX) { tail.x++ } else { tail.x-- } if (Math.abs(deltaY) == deltaY) { tail.y++ } else { tail.y-- } } tail.adjustTailAndHistory() } fun adjustTailAndHistory() { this.positionHistory.add(this.copyPosition()) this.adjustTail() } override fun equals(other: Any?): Boolean = other is Position && other.x == x && other.y == y override fun hashCode(): Int { return x.hashCode() + y.hashCode() } } fun part1(input: String): Int { var tail = Position(0,0, null) var head = Position(0,0, tail) input.split("\n") .map { listOf(it.split(" ")[0], it.split(" ")[1]) } .forEach { (d, s) -> val steps = s.toInt() val direction = if (d == "U") DIRECTION.UP else if (d == "D") DIRECTION.DOWN else if (d == "L") DIRECTION.LEFT else DIRECTION.RIGHT when (direction) { DIRECTION.UP -> { repeat(steps) { head.y++ head.adjustTail() } } DIRECTION.DOWN -> { repeat(steps) { head.y-- head.adjustTail() } } DIRECTION.LEFT -> { repeat(steps) { head.x-- head.adjustTail() } } DIRECTION.RIGHT -> { repeat(steps) { head.x++ head.adjustTail() } } } } return tail.positionHistory.size } fun part2(input: String): Int { var tail = Position(0,0, null) var previousTail = tail var head = previousTail repeat(9) { head = Position(0,0, previousTail) previousTail = head } input.split("\n") .map { listOf(it.split(" ")[0], it.split(" ")[1]) } .forEach { (d, s) -> val steps = s.toInt() val direction = if (d == "U") DIRECTION.UP else if (d == "D") DIRECTION.DOWN else if (d == "L") DIRECTION.LEFT else DIRECTION.RIGHT when (direction) { DIRECTION.UP -> { repeat(steps) { head.y++ head.adjustTail() } } DIRECTION.DOWN -> { repeat(steps) { head.y-- head.adjustTail() } } DIRECTION.LEFT -> { repeat(steps) { head.x-- head.adjustTail() } } DIRECTION.RIGHT -> { repeat(steps) { head.x++ head.adjustTail() } } } } return tail.positionHistory.size } // test if implementation meets criteria from the description, like: val testInput = readInput("Day09_test") val output = part1(testInput) check(output == 13) val testInputTwo = readInput("Day09_test2") val outputTwo = part2(testInputTwo) check(outputTwo == 36) val input = readInput("Day09") println(part1(input)) println(part2(input)) }
0
Kotlin
0
1
74f10b93d3bad72fa0fc276b503bfa9f01ac0e35
5,260
aoc-kotlin
Apache License 2.0
calendar/day02/Day2.kt
mpetuska
571,764,215
false
{"Kotlin": 18073}
package day02 import Day import Lines class Day2 : Day() { override fun part1(input: Lines): Any { val rules = mapOf( "A" to mapOf( "X" to 4, "Y" to 8, "Z" to 3, ), "B" to mapOf( "X" to 1, "Y" to 5, "Z" to 9, ), "C" to mapOf( "X" to 7, "Y" to 2, "Z" to 6, ), ) return input.map { it.split(" ") }.sumOf { (a, x) -> rules[a]!![x]!! } } override fun part2(input: Lines): Any { val rules = mapOf( "A" to mapOf( "A" to 4, "B" to 8, "C" to 3, ), "B" to mapOf( "A" to 1, "B" to 5, "C" to 9, ), "C" to mapOf( "A" to 7, "B" to 2, "C" to 6, ), ) val dx = mapOf( "X" to -1, "Y" to 0, "Z" to 1, ) val options = listOf("A", "B", "C") return input.map { it.split(" ") }.sumOf { (a, x) -> val i = options.indexOf(a) + dx[x]!! val n = options.size val b = options[(i % n + n) % n] rules[a]!![b]!! } } }
0
Kotlin
0
0
be876f0a565f8c14ffa8d30e4516e1f51bc3c0c5
1,095
advent-of-kotlin-2022
Apache License 2.0
aoc-2020/src/commonMain/kotlin/fr/outadoc/aoc/twentytwenty/Day20.kt
outadoc
317,517,472
false
{"Kotlin": 183714}
package fr.outadoc.aoc.twentytwenty import fr.outadoc.aoc.scaffold.Day import fr.outadoc.aoc.scaffold.readDayInput class Day20 : Day<Long> { companion object { private const val PRINT_DEBUG = false } private data class Position(val x: Int, val y: Int) private data class Tile(val id: Long, val content: List<String>) { private fun flipVertical(): Tile { return copy(content = content.reversed()) } private fun flipHorizontal(): Tile { return copy(content = content.map { line -> line.reversed() }) } private fun transpose(): Tile { return copy(content = content.mapIndexed { y, line -> line.mapIndexed { x, _ -> content[x][y] }.joinToString(separator = "") }) } val possibleVariations: List<Tile> get() = listOf( this, flipHorizontal(), flipVertical(), flipHorizontal().flipVertical(), this.transpose(), flipHorizontal().transpose(), flipVertical().transpose(), flipHorizontal().flipVertical().transpose() ) fun sharesRightBorderWith(other: Tile): Boolean { // Check if last column of this == first column of other return content .map { line -> line.last() }.toCharArray() .contentEquals( other.content.map { line -> line.first() }.toCharArray() ) } fun sharesBottomBorderWith(other: Tile): Boolean { // Check if last row of this == first row of other return content.last() == other.content.first() } } private data class Puzzle(val iteration: Int = 0, val placedTiles: Map<Position, Tile>) { val xRange: IntRange get() = placedTiles.keys.minOf { it.x }..placedTiles.keys.maxOf { it.x } val yRange: IntRange get() = placedTiles.keys.minOf { it.y }..placedTiles.keys.maxOf { it.y } val tileHeight: Int get() = placedTiles.values.first().content.size val tileWidth: Int get() = placedTiles.values.first().content.first().length val corners: List<Tile> get() = listOf( Position(xRange.first, yRange.first), Position(xRange.last, yRange.first), Position(xRange.first, yRange.last), Position(xRange.last, yRange.last) ).map { pos -> placedTiles.getValue(pos) } } private val tiles: List<Tile> = readDayInput() .split("\n\n") .map { tileSection -> val tileDescription = tileSection.lines() val id = tileDescription .first() .replace("Tile ", "") .replace(":", "") .toLong() val tileContent = tileDescription.drop(1) Tile(id = id, content = tileContent) } private val Position.surrounding: List<Position> get() = listOf( copy(x = x + 1), // right copy(x = x - 1), // left copy(y = y + 1), // up copy(y = y - 1) // down ) private val Puzzle.remainingTiles: List<Tile> get() = tiles.filterNot { tile -> tile.id in placedTiles.values.map { it.id } } private fun Puzzle.nextState(): Puzzle { val candidateTiles: List<Tile> = remainingTiles.flatMap { remainingTile -> remainingTile.possibleVariations } val candidatePositions = placedTiles.flatMap { (position, _) -> position.surrounding .filterNot { posAdjacentToPlacedTile -> // Remove positions where there already is a tile posAdjacentToPlacedTile in placedTiles.keys } } // Find all tiles next to which there's an open spot return candidatePositions.flatMap { candidatePosition -> // Try to find a tile that can fit at this position candidateTiles.filter { candidateTile -> // Find all placed tiles around this position val surroundingTiles = candidatePosition .surrounding .mapNotNull { pos -> placedTiles[pos]?.let { tile -> pos to tile } } // Check that all placed tiles around this position can fit the candidate surroundingTiles.all { existingTile -> existingTile.fits(candidatePosition to candidateTile) } }.map { variation -> // Falalalala, lala ka-ching! copy( iteration = iteration + 1, placedTiles = placedTiles + (candidatePosition to variation) ) } }.first() } private fun Pair<Position, Tile>.fits(other: Pair<Position, Tile>): Boolean { val (pos, tile) = this val (otherPos, otherTile) = other val deltaX = otherPos.x - pos.x val deltaY = otherPos.y - pos.y return when { // Other tile is right of the current one deltaX == 1 -> tile.sharesRightBorderWith(otherTile) // Other tile is left of the current one deltaX == -1 -> otherTile.sharesRightBorderWith(tile) // Other tile is on bottom of the current one deltaY == 1 -> tile.sharesBottomBorderWith(otherTile) // Other tile is on top of the current one deltaY == -1 -> otherTile.sharesBottomBorderWith(tile) else -> throw IllegalStateException("deltaX = $deltaX, deltaY = $deltaY -> invalid") } } private fun Puzzle.complete(): Puzzle { return when { remainingTiles.isEmpty() -> this else -> nextState().complete() } } private fun Tile.print() { println("tile #$id") content.forEach { line -> println(line) } println() } private fun Puzzle.print() { println("iteration #$iteration") yRange.forEach { tileY -> (0 until tileHeight).forEach { contentY -> xRange.forEach { tileX -> val tile = placedTiles[Position(tileX, tileY)] if (tile != null) { // Print tile row print(tile.content[contentY] + " ") } else { // Print empty row print(" ".repeat(tileWidth + 1)) } } println() } println() } } private val initialState: Puzzle = Puzzle( placedTiles = mapOf( Position(0, 0) to tiles.first() ) ) private fun Puzzle.trimmed(): Puzzle { return copy( placedTiles = placedTiles.map { (pos, tile) -> pos to tile.copy(content = tile.content .drop(1) .dropLast(1) .map { line -> line.drop(1).dropLast(1) } ) }.toMap() ) } private fun Puzzle.toImage(): Tile { val tileContent: List<String> = yRange.flatMap { tileY -> (0 until tileHeight).map { contentY -> xRange.joinToString(separator = "") { tileX -> val tile = placedTiles.getValue(Position(tileX, tileY)) tile.content[contentY] } } } return Tile(id = -1, content = tileContent) } private val seaMonster = " # \n" + "# ## ## ###\n" + " # # # # # # " private val seaMonsterLength = seaMonster.lines().first().length private val seaRegexes = seaMonster.lines().map { line -> Regex("^" + line.replace(' ', '.') + "$") } private fun Tile.countSeaMonsters(): Long { return content .dropLast(seaRegexes.size - 1) .mapIndexed { lineIdx, line -> // For each line in the picture // For each next line of the monster, check if it matches the corresponding regex // We've found that there might be a monster at startIdx — or at least its first line. // Find occurrences of the monster's first line! // Extract substrings that might match the monster in length (0..(line.length - seaMonsterLength)).map { startIdx -> // Extract substrings that might match the monster in length startIdx to line.substring(startIdx, startIdx + seaMonsterLength) }.filter { (_, possibleMonsterChunk) -> // Find occurrences of the monster's first line! val regex = seaRegexes.first() regex.matches(possibleMonsterChunk) }.count { (startIdx, _) -> // We've found that there might be a monster at startIdx — or at least its first line. seaRegexes.drop(1) .mapIndexed { regexIdx, regex -> regexIdx to regex } .all { (regexIdx, regex) -> // For each next line of the monster, check if it matches the corresponding regex val nextLineIdx = lineIdx + regexIdx + 1 val checkedString = content[nextLineIdx].substring(startIdx, startIdx + seaMonsterLength) regex.matches(checkedString) } } }.sum().toLong() } private fun Tile.getWaterRoughness(): Long { val seaMonsterHashes = seaMonster.count { it == '#' } val totalHashes = content .joinToString(separator = "") .count { it == '#' } return possibleVariations.sumOf { variation -> variation.countSeaMonsters().let { seaMonsterCount -> if (seaMonsterCount > 0) { totalHashes - seaMonsterHashes * seaMonsterCount } else 0 } } } override fun step1(): Long { return initialState .complete() .also { finalState -> if (PRINT_DEBUG) { finalState.print() } } .corners .also { corners -> if (PRINT_DEBUG) { println(corners) } } .fold(1) { acc, tile -> acc * tile.id } } override fun step2(): Long { return initialState .complete() .also { finalState -> if (PRINT_DEBUG) { finalState.print() } } .trimmed() .toImage() .also { bigAssTile -> if (PRINT_DEBUG) { bigAssTile.print() } }.getWaterRoughness() } override val expectedStep1: Long = 14986175499719 override val expectedStep2: Long = 2161 }
0
Kotlin
0
0
54410a19b36056a976d48dc3392a4f099def5544
11,584
adventofcode
Apache License 2.0
src/main/kotlin/g0801_0900/s0863_all_nodes_distance_k_in_binary_tree/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g0801_0900.s0863_all_nodes_distance_k_in_binary_tree // #Medium #Depth_First_Search #Breadth_First_Search #Tree #Binary_Tree // #2023_04_04_Time_147_ms_(95.83%)_Space_35.2_MB_(95.83%) import com_github_leetcode.TreeNode /* * Definition for a binary tree node. * class TreeNode(var `val`: Int = 0) { * var left: TreeNode? = null * var right: TreeNode? = null * } */ class Solution { private fun kFar(root: TreeNode?, k: Int, visited: TreeNode?, ls: MutableList<Int>) { if (root == null || k < 0 || root === visited) { return } if (k == 0) { ls.add(root.`val`) return } kFar(root.left, k - 1, visited, ls) kFar(root.right, k - 1, visited, ls) } fun distanceK(root: TreeNode?, target: TreeNode?, k: Int): List<Int> { val ls: MutableList<Int> = ArrayList() if (k == 0) { ls.add(target!!.`val`) return ls } nodeToRoot(root, target!!, k, ls) return ls } private fun nodeToRoot(root: TreeNode?, target: TreeNode, k: Int, ls: MutableList<Int>): Int { if (root == null) { return -1 } if (root.`val` == target.`val`) { kFar(root, k, null, ls) return 1 } val ld = nodeToRoot(root.left, target, k, ls) if (ld != -1) { kFar(root, k - ld, root.left, ls) return ld + 1 } val rd = nodeToRoot(root.right, target, k, ls) if (rd != -1) { kFar(root, k - rd, root.right, ls) return rd + 1 } return -1 } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,655
LeetCode-in-Kotlin
MIT License
src/Day14.kt
diego09310
576,378,549
false
{"Kotlin": 28768}
import kotlin.math.max import kotlin.math.min fun main() { data class Point(var x: Int, var y: Int) lateinit var occupied: HashMap<Int, HashSet<Int>> // For visualization lateinit var sandList: HashMap<Int, HashSet<Int>> var sandTime = false var minX = 500 var maxX = 500 fun addPoint(p: Point) { if (occupied.contains(p.y)) { occupied[p.y]!!.add(p.x) } else { occupied[p.y] = hashSetOf(p.x) } if (sandTime) { if (sandList.contains(p.y)) { sandList[p.y]!!.add(p.x) } else { sandList[p.y] = hashSetOf(p.x) } } if (p.x < minX) minX = p.x if (p.x > maxX) maxX = p.x } fun addPath(path: String) { val points = path.split(" -> ").map { val coors = it.split(",") Point(coors[0].toInt(), coors[1].toInt()) } var prev = points[0] for (i in 1 until points.size) { if (points[i].x - prev.x != 0) { val init = min(prev.x, points[i].x) val end = max(prev.x, points[i].x) val xs = (init .. end).map { it }.toCollection(HashSet()) if (occupied.contains(prev.y)) { occupied[prev.y]!!.addAll(xs) } else { occupied[prev.y] = xs } if (init < minX) minX = init if (end > maxX) maxX = end } else { val init = min(prev.y, points[i].y) val end = max(prev.y, points[i].y) for (y in init .. end) { addPoint(Point(prev.x, y)) } } prev = points[i] } } fun printCave() { val bottom = if (!sandTime) occupied.keys.max() + 2 else occupied.keys.max() + 1 for (j in 0..bottom) { // for (i in 410..580) { for (i in minX..maxX) { if (sandTime && sandList[j]?.contains(i) == true) { print('o') } else if (occupied[j]?.contains(i) == true || j == bottom) { print('#') } else if (i == 500 && j == 0) { print('x') } else { print('.') } } println() } } fun part1(input: List<String>): Int { occupied = hashMapOf() sandList = hashMapOf() sandTime = false input.forEach{ addPath(it) } printCave() sandTime = true val bottom = occupied.keys.max() var overflow = false var sand = 0 while(!overflow) { var height = 0 var x = 500 while (true) { if (height > bottom) { overflow = true break } if (occupied[height]?.contains(x) == true) { if (occupied[height]?.contains(x-1) == true) { if (occupied[height]?.contains(x + 1) == true) { addPoint(Point(x, height-1)) sand++ break } else { x++ } } else { x-- } } else { height++ } } } println("======================") printCave() println(sand) return sand } fun part2(input: List<String>): Int { occupied = hashMapOf() sandList = hashMapOf() sandTime = false input.forEach{ addPath(it) } val bottom = occupied.keys.max() + 2 printCave() sandTime = true var overflow = false var sand = 0 while(!overflow) { var height = 0 var x = 500 while (true) { if (occupied[height]?.contains(x) == true || height == bottom) { if (height == 0) { overflow = true break } if (height == bottom) { addPoint(Point(x, height-1)) sand++ break } if (occupied[height]?.contains(x-1) == true) { if (occupied[height]?.contains(x + 1) == true) { addPoint(Point(x, height-1)) sand++ break } else { x++ } } else { x-- } } else { height++ } } } println("======================") printCave() println(sand) return sand } // test if implementation meets criteria from the description, like: val testInput = readInput("../../14linput") check(part1(testInput) == 24) val input = readInput("../../14input") println(part1(input)) check(part2(testInput) == 93) println(part2(input)) }
0
Kotlin
0
0
644fee9237c01754fc1a04fef949a76b057a03fc
5,388
aoc-2022-kotlin
Apache License 2.0
src/main/kotlin/org/bradfordmiller/fuzzyrowmatcher/algos/Algo.kt
bmiller1009
267,343,413
false
null
package org.bradfordmiller.fuzzyrowmatcher.algos import org.apache.commons.text.similarity.* import org.slf4j.LoggerFactory import java.util.* /** * enumerated list of all algorithm types supported by Fuzzy Matcher * * The values are * - JaroDistance * - LevenshteinDistance * - HammingDistance * - JaccardDistance * - CosineDistance * - FuzzySimilarity */ enum class AlgoType { JaroDistance, LevenshteinDistance, HammingDistance, JaccardDistance, CosineDistance, FuzzySimilarity } /** * represents the result of an applied Fuzzy match on two strings * * @property algoType the enumerated algorithm applied to [compareRow] and [currentRow] * @property qualifies whether or not the fuzzy match meets the criteria of the [score] and threshold * @property score the score returned by the algorithm [algoType] when applied to [compareRow] and [currentRow] * @property compareRow the first string being compared * @property currentRow the second string being compared */ data class AlgoResult(val algoType: AlgoType, val qualifies: Boolean, val score: Number, val compareRow: String, val currentRow: String) { override fun toString(): String { return "The result of the algorithm ${algoType.name} had a score of $score for string {{{$compareRow}}} and {{{$currentRow}}} which resulted which had a qualification result of $qualifies" } } /** * Base definition of an algorithm with a threshold * * @param T - the type of Number being returned by the Fuzzy Matching algorithm defined in [algoType] * @property threshold - the threshold score which must be met by the application of the algorithm defined in [algoType] */ abstract class Algo<T: Number>(internal val threshold: T, val algoType: AlgoType) { companion object { val logger = LoggerFactory.getLogger(Algo::class.java) } /** * applies algorithm defined in [algoType] * * returns the score calculated by the algorithm defined in [algoType] */ abstract fun applyAlgo(compareRow: String, currentRow: String): T /** * determines whether the score returned after applying the algorithm exceeds the [incomingThreshold] * * returns a true/false based on whether the threshold is met */ abstract fun qualifyThreshold(incomingThreshold: T): Boolean } /** * calculates the Jaro string distance algorithm based on the [threshold] */ class JaroDistanceAlgo(threshold: Double): Algo<Double>(threshold, AlgoType.JaroDistance) { private val jaroWinkler by lazy {JaroWinklerDistance()} /** * applies the Jaro string distance algorithm on [compareRow] and [currentRow] * * returns the score calculated by the Jaro string distance */ override fun applyAlgo(compareRow: String, currentRow: String): Double { return (jaroWinkler.apply(compareRow, currentRow) * 100) } /** * determines whether the calculated score meets the [incomingThreshold] * * returns the determination of whether the calculation qualifies based on the score calculated and the [incomingThreshold] */ override fun qualifyThreshold(incomingThreshold: Double): Boolean { return incomingThreshold >= threshold } } /** * calculates the Levenshtein string distance algorithm based on the [threshold] */ class LevenshteinDistanceAlgo(threshold: Int): Algo<Int>(threshold, AlgoType.LevenshteinDistance) { private val levenshteinDistance by lazy {LevenshteinDistance()} /** * applies the Levenshtein string distance algorithm on [compareRow] and [currentRow] * * returns the score calculated by the Levenshtein string distance */ override fun applyAlgo(compareRow: String, currentRow: String): Int { return levenshteinDistance.apply(compareRow, currentRow) } /** * determines whether the calculated score meets the [incomingThreshold] * * returns the determination of whether the calculation qualifies based on the score calculated and the [incomingThreshold] */ override fun qualifyThreshold(incomingThreshold: Int): Boolean { return threshold >= incomingThreshold } } /** * calculates the Hamming string distance algorithm based on the [threshold] */ class HammingDistanceAlgo(threshold: Int): Algo<Int>(threshold, AlgoType.HammingDistance) { private val hammingDistance by lazy {HammingDistance()} /** * applies the Hamming string distance algorithm on [compareRow] and [currentRow] * * returns the score calculated by the Hamming string distance */ override fun applyAlgo(compareRow: String, currentRow: String): Int { val compareRowLen = compareRow.length val currentRowLen = currentRow.length if(compareRowLen == currentRowLen) { val differingLength = hammingDistance.apply(compareRow, currentRow) return compareRowLen - differingLength } else { logger.trace("Hamming Distance algorithm requires strings to be of same length.") return -1 } } /** * determines whether the calculated score meets the [incomingThreshold] * * returns the determination of whether the calculation qualifies based on the score calculated and the [incomingThreshold] */ override fun qualifyThreshold(incomingThreshold: Int): Boolean { return if(incomingThreshold == -1) { false } else { threshold <= incomingThreshold } } } /** * calculates the Hamming string distance algorithm based on the [threshold] */ class JaccardDistanceAlgo(threshold: Double): Algo<Double>(threshold, AlgoType.JaccardDistance) { private val jaccardDistance by lazy {JaccardDistance()} /** * applies the Jaccard string distance algorithm on [compareRow] and [currentRow] * * returns the score calculated by the Jaccard string distance */ override fun applyAlgo(compareRow: String, currentRow: String): Double { return jaccardDistance.apply(compareRow, currentRow) } /** * determines whether the calculated score meets the [incomingThreshold] * * returns the determination of whether the calculation qualifies based on the score calculated and the [incomingThreshold] */ override fun qualifyThreshold(incomingThreshold: Double): Boolean { return threshold >= incomingThreshold } } /** * calculates the Cosine string distance algorithm based on the [threshold] */ class CosineDistanceAlgo(threshold: Double): Algo<Double>(threshold, AlgoType.CosineDistance) { private val cosineDistance by lazy {CosineDistance()} /** * applies the Cosine string distance algorithm on [compareRow] and [currentRow] * * returns the score calculated by the Cosine string distance */ override fun applyAlgo(compareRow: String, currentRow: String): Double { return (cosineDistance.apply(compareRow, currentRow) * 100) } /** * applies the Cosine string distance algorithm on [compareRow] and [currentRow] * * returns the score calculated by the Cosine string distance */ override fun qualifyThreshold(incomingThreshold: Double): Boolean { return threshold >= incomingThreshold } } /** * calculates the Fuzzy similarity string distance algorithm based on the [threshold] */ class FuzzyScoreSimilarAlgo(threshold: Int, locale: Locale = Locale.getDefault()): Algo<Int>(threshold, AlgoType.FuzzySimilarity) { private val fuzzyScore by lazy {FuzzyScore(locale)} /** * applies the Fuzzy similarity string distance algorithm on [compareRow] and [currentRow] * * returns the score calculated by the Fuzzy similarity string distance */ override fun applyAlgo(compareRow: String, currentRow: String): Int { return fuzzyScore.fuzzyScore(compareRow, currentRow) } /** * determines whether the calculated score meets the [incomingThreshold] * * returns the determination of whether the calculation qualifies based on the score calculated and the [incomingThreshold] */ override fun qualifyThreshold(incomingThreshold: Int): Boolean { return incomingThreshold >= threshold } }
5
Kotlin
0
1
65d509f25bc18e36bd0ece53333111ca9630608e
8,295
fuzzy-row-matcher
Apache License 2.0
src/2023/Day19.kt
nagyjani
572,361,168
false
{"Kotlin": 369497}
package `2023` import java.io.File import java.lang.RuntimeException import java.math.BigInteger import java.util.* import kotlin.math.max import kotlin.math.min fun main() { Day19().solve() } class Day19 { val input1 = """ px{a<2006:qkq,m>2090:A,rfg} pv{a>1716:R,A} lnx{m>1548:A,A} rfg{s<537:gd,x>2440:R,A} qs{s>3448:A,lnx} qkq{x<1416:A,crn} crn{x>2662:A,R} in{s<1351:px,qqz} qqz{s>2770:qs,m<1801:hdj,R} gd{a>3333:R,R} hdj{m>838:A,pv} {x=787,m=2655,a=1222,s=2876} {x=1679,m=44,a=2067,s=496} {x=2036,m=264,a=79,s=2244} {x=2461,m=1339,a=466,s=291} {x=2127,m=1623,a=2188,s=1013} """.trimIndent() val input2 = """ """.trimIndent() class Gear(val x: Int, val m: Int, val a: Int, val s: Int) { operator fun get(c: String): Int = when (c) {"x" -> x; "m" -> m; "a" -> a; else -> s} fun sum(): Int = x + m + a + s } class Gpr(val lower: Int = 1, val upper: Int = 4001) class Gprs(val gprs: Map<String, Gpr> = mapOf("x" to Gpr(), "m" to Gpr(), "a" to Gpr(), "s" to Gpr())) { operator fun get(c: String): Gpr = gprs[c]!! fun splitLt(c: String, n: Int): Pair<List<Gprs>, List<Gprs>> { val g = get(c) if (g.upper <= n) { return listOf(this) to listOf() } if (g.lower >= n) { return listOf<Gprs>() to listOf(this) } val g1 = Gpr(g.lower, n) val g2 = Gpr(n, g.upper) val gprs1 = gprs.toMutableMap().also { it[c] = g1 } val gprs2 = gprs.toMutableMap().also { it[c] = g2 } return listOf(Gprs(gprs1)) to listOf(Gprs(gprs2)) } fun splitGt(c: String, n: Int): Pair<List<Gprs>, List<Gprs>> { val g = get(c) if (g.lower >= n+1) { return listOf(this) to listOf() } if (g.upper <= n+1) { return listOf<Gprs>() to listOf(this) } val g1 = Gpr(n+1, g.upper) val g2 = Gpr(g.lower, n+1) val gprs1 = gprs.toMutableMap().also { it[c] = g1 } val gprs2 = gprs.toMutableMap().also { it[c] = g2 } return listOf(Gprs(gprs1)) to listOf(Gprs(gprs2)) } fun num(): BigInteger { return gprs.values.fold(BigInteger.ONE){p, g -> p * BigInteger.valueOf(g.upper.toLong() - g.lower) } } } fun List<Gprs>.num() = sumOf { it.num() } class Workflow(val name: String, val rules: List<Rule>, val e: String) { fun apply(g: Gear): String { for (i in rules.indices) { val r = rules[i].apply(g) if (r != null) { return r } } return e } fun apply(g: Gprs): Map<String, List<Gprs>> = apply(listOf(g)) fun apply(gs: List<Gprs>): Map<String, List<Gprs>> { val result = mutableMapOf<String, List<Gprs>>() var inGs = gs for (i in rules.indices) { val (matches, nomatches) = rules[i].apply(inGs) if (matches.isNotEmpty()) { val next = rules[i].next if (result.contains(next)) { result[next] = result[next]!!.toMutableList().apply{addAll(matches)} } else { result[next] = matches } } inGs = nomatches } if (inGs.isNotEmpty()) { if (result.contains(e)) { result[e] = result[e]!!.toMutableList().apply{addAll(inGs)} } else { result[e] = inGs } } return result } } class Rule(val p: String, val r: String, val n: Int, val next: String) { fun apply(g: Gear): String? { if (r == ">" && g[p] > n || r == "<" && g[p] < n) { return next } return null } fun apply(gs: List<Gprs>): Pair<List<Gprs>, List<Gprs>> { val result = mutableListOf<Gprs>() to mutableListOf<Gprs>() gs.forEach { val (match, nomatch) = apply(it) result.first.addAll(match) result.second.addAll(nomatch) } return result } fun apply(g: Gprs): Pair<List<Gprs>, List<Gprs>> { val result = when (r) { "<" -> g.splitLt(p, n) ">" -> g.splitGt(p, n) else -> throw RuntimeException() } return result } } fun String.toRule(): Rule { val (p, r, n0, next) = Regex("([^<>])+([<>])(\\d+):(.+)").find(this)!!.destructured return Rule(p, r, n0.toInt(), next) } fun String.toWorkflow(): Workflow { val (name, rules, e) = Regex("(\\w+)\\{(.+),([^:]+)}").find(this)!!.destructured val rules1 = rules.split(",").map { it.toRule() } return Workflow(name, rules1, e) } fun String.toGear(): Gear { val (x, m, a, s) = Regex("x=(\\d+),m=(\\d+),a=(\\d+),s=(\\d+)").find(this)!!.destructured return Gear(x.toInt(), m.toInt(), a.toInt(), s.toInt()) } fun solve() { val f = File("src/2023/inputs/day19.in") val s = Scanner(f) // val s = Scanner(input1) // val s = Scanner(input2) var sum = 0 var sum1 = 0 var lineix = 0 var lines = mutableListOf<String>() var lines1 = lines var lines2 = lines while (s.hasNextLine()) { lineix++ val line = s.nextLine().trim() if (line.isEmpty() && lines.isNotEmpty()) { lines = mutableListOf<String>() continue } lines.add(line) } lines2 = lines val a = "px{a<2006:qkq,m>2090:A,rfg}".toWorkflow() val b ="{x=2461,m=1339,a=466,s=291}".toGear() val wfs = mutableMapOf<String, Workflow>() lines1.forEach { val wf = it.toWorkflow(); wfs[wf.name] = wf } val gears = lines2.map { it.toGear() } for (g in gears) { var next = "in" while (next != "A" && next != "R") { next = wfs[next]!!.apply(g) } if (next == "A") { sum += g.sum() } } val gs = mutableMapOf("in" to listOf( Gprs())) val gsA = mutableListOf<Gprs>() val gsR = mutableListOf<Gprs>() while (gs.isNotEmpty()) { val nextWfName = gs.keys.first() val wfGs = gs[nextWfName]!! gs.remove(nextWfName) val newGs0 = wfs[nextWfName]!!.apply(wfGs) val newGs1 = newGs0.toMutableMap().apply { remove("A") remove("R") } if (newGs0.contains("R")) { gsR.addAll(newGs0["R"]!!) } if (newGs0.contains("A")) { gsA.addAll(newGs0["A"]!!) } for (wfName in newGs1.keys) { if (gs.contains(wfName)) { gs[wfName] = gs[wfName]!!.toMutableList().apply{addAll(newGs1[wfName]!!)} } else { gs[wfName] = newGs1[wfName]!! } } } val suml = 0L print("$sum $sum1 ${gsA.num()}\n") } }
0
Kotlin
0
0
f0c61c787e4f0b83b69ed0cde3117aed3ae918a5
7,661
advent-of-code
Apache License 2.0
src/main/kotlin/io/github/kmakma/adventofcode/y2020/Y2020Day17.kt
kmakma
225,714,388
false
null
package io.github.kmakma.adventofcode.y2020 import io.github.kmakma.adventofcode.utils.Day fun main() { Y2020Day17().solveAndPrint() } class Y2020Day17 : Day(2020, 17, "Conway Cubes") { private lateinit var startCubes: Map<ConwayCube, Boolean> private lateinit var inputList: List<List<Char>> override fun initializeDay() { inputList = inputInCharLines() startCubes = inputList.flatMapIndexed { x, list -> list.mapIndexed { y, c -> ConwayCube(x = x, y = y, z = 0, w = 0) to (c == '#') } }.toMap() } override suspend fun solveTask1(): Any? { val cubes = computeCycles(startCubes, false) var active = 0 for (status in cubes.values) { if (status) active++ } return active } override suspend fun solveTask2(): Any? { val cubes = computeCycles(startCubes, true) var active = 0 for (status in cubes.values) { if (status) active++ } return active } private fun computeCycles(cubeMap: Map<ConwayCube, Boolean>, hyper: Boolean): Map<ConwayCube, Boolean> { var cubes = cubeMap for (i in 0..5) { val neighbourCubes = getAllNeighbours(cubes.keys, hyper) val tempCubes = mutableMapOf<ConwayCube, Boolean>() for (cube in neighbourCubes) { val isActive = cubes.getOrDefault(cube, false) val neighbours = activeNeighbours(cubes, cube, hyper) when { !isActive && neighbours == 3 -> tempCubes[cube] = true isActive && (neighbours < 2 || neighbours > 3) -> tempCubes[cube] = false else -> tempCubes[cube] = isActive } } cubes = tempCubes } return cubes } private fun getAllNeighbours(cubes: Set<ConwayCube>, hyper: Boolean = false): Set<ConwayCube> { return if (hyper) { cubes.flatMap { getBigHyperCube(it) }.toSet() } else { cubes.flatMap { getBigCube(it) }.toSet() } } private fun getBigCube(cube: ConwayCube): Set<ConwayCube> { val cubes = mutableSetOf<ConwayCube>() for (x in cube.x - 1..cube.x + 1) { for (y in cube.y - 1..cube.y + 1) { for (z in cube.z - 1..cube.z + 1) { cubes.add(ConwayCube(x, y, z, 0)) } } } return cubes } private fun getBigHyperCube(cube: ConwayCube): Set<ConwayCube> { val cubes = mutableSetOf<ConwayCube>() for (x in cube.x - 1..cube.x + 1) { for (y in cube.y - 1..cube.y + 1) { for (z in cube.z - 1..cube.z + 1) { for (w in cube.w - 1..cube.w + 1) { cubes.add(ConwayCube(x, y, z, w)) } } } } return cubes } private fun activeNeighbours(cubeMap: Map<ConwayCube, Boolean>, cube: ConwayCube, hyper: Boolean = false): Int { var neighbours = 0 val cubes = if (hyper) getBigHyperCube(cube) else getBigCube(cube) for (neighbour in cubes) { if (neighbour != cube && cubeMap.getOrDefault(neighbour, false)) neighbours++ } return neighbours } } private data class ConwayCube(val x: Int, val y: Int, val z: Int, val w: Int = 0)
0
Kotlin
0
0
7e6241173959b9d838fa00f81fdeb39fdb3ef6fe
3,434
adventofcode-kotlin
MIT License
src/main/kotlin/g2301_2400/s2392_build_a_matrix_with_conditions/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g2301_2400.s2392_build_a_matrix_with_conditions // #Hard #Array #Matrix #Graph #Topological_Sort // #2023_07_02_Time_706_ms_(100.00%)_Space_65.8_MB_(100.00%) import java.util.LinkedList import java.util.Queue class Solution { // Using topological sort to solve this problem fun buildMatrix(k: Int, rowConditions: Array<IntArray>, colConditions: Array<IntArray>): Array<IntArray> { // First, get the topo-sorted of row and col val row = toposort(k, rowConditions) val col = toposort(k, colConditions) // base case: when the length of row or col is less than k, return empty. // That is: there is a loop in established graph if (row.size < k || col.size < k) { return Array(0) { IntArray(0) } } val res = Array(k) { IntArray(k) } val map: MutableMap<Int, Int> = HashMap() for (i in 0 until k) { // we record the number corresbonding to each column: // [number, column index] map[col[i]] = i } // col: 3 2 1 // row: 1 3 2 for (i in 0 until k) { // For each row: we have number row.get(i). And we need to know // which column we need to assign, which is from map.get(row.get(i)) // known by map.get() res[i][map[row[i]]!!] = row[i] } return res } private fun toposort(k: Int, matrix: Array<IntArray>): List<Int> { // need a int[] to record the indegree of each number [1, k] val deg = IntArray(k + 1) // need a list to record the order of each number, then return this list val res: MutableList<Int> = ArrayList() // need a 2-D list to be the graph, and fill the graph val graph: MutableList<MutableList<Int>> = ArrayList() for (i in 0 until k) { graph.add(ArrayList()) } // need a queue to do the BFS val queue: Queue<Int> = LinkedList() // First, we need to establish the graph, following the given matrix for (a in matrix) { val from = a[0] val to = a[1] graph[from - 1].add(to) deg[to]++ } // Second, after building a graph, we start the bfs, // that is, traverse the node with 0 degree for (i in 1..k) { if (deg[i] == 0) { queue.offer(i) res.add(i) } } // Third, start the topo sort while (queue.isNotEmpty()) { val node = queue.poll() val list: List<Int> = graph[node - 1] for (i in list) { if (--deg[i] == 0) { queue.offer(i) res.add(i) } } } return res } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
2,821
LeetCode-in-Kotlin
MIT License
src/main/kotlin/net/wrony/aoc2023/a8/8.kt
kopernic-pl
727,133,267
false
{"Kotlin": 52043}
package net.wrony.aoc2023.a8 import kotlin.io.path.Path import kotlin.io.path.readLines fun <T> Sequence<T>.repeat() = sequence { while (true) yieldAll(this@repeat) } fun main() { Path("src/main/resources/8.txt").readLines().let { it[0].toCharArray() to it.drop(2).map { m -> m.split(" = ") .let { sl -> sl[0] to (sl[1].trim().drop(1).dropLast(1).split(", ").take(2)) } } }.let { (plan, map) -> plan.asSequence().repeat() to map.toMap() }.also { (plan, map) -> plan.foldIndexed("AAA") { idx, acc, dir -> if (acc == "ZZZ") { println(" - $dir: $acc $idx") return@also } map[acc]?.let { (left, right) -> when (dir) { 'L' -> left 'R' -> right else -> throw Exception("Unknown direction $dir") } } ?: throw Exception("Unknown key $acc") } }.also { (plan, map) -> map.keys.filter { it.endsWith("A") }.map { k -> plan.foldIndexed(k to 0) { idx, acc, dir -> if (acc.first.endsWith("Z")) { println("$acc $idx") return@map acc to idx } map[acc.first]?.let { (left, right) -> when (dir) { 'L' -> left to idx 'R' -> right to idx else -> throw Exception("Unknown direction $dir") } } ?: throw Exception("Unknown key $acc") } }.map { (_, v) -> factors(v.toLong()) }.reduce { acc, f -> acc + f }.toSet() .fold(1L) { acc, n -> acc * n }.let { println(it) } } // 7159165833283004735 - // 50530847183 - // 13289612809129 } fun factors(value: Long): List<Long> { val factors = mutableListOf<Long>() var n = value var i = 2L while (i * i <= n) { while (n % i == 0L) { factors.add(i) n /= i } i++ } if (n > 1) { factors.add(n) } return factors }
0
Kotlin
0
0
1719de979ac3e8862264ac105eb038a51aa0ddfb
2,156
aoc-2023-kotlin
MIT License
src/main/kotlin/me/peckb/aoc/_2017/calendar/day21/Day21.kt
peckb1
433,943,215
false
{"Kotlin": 956135}
package me.peckb.aoc._2017.calendar.day21 import javax.inject.Inject import me.peckb.aoc.generators.InputGenerator.InputGeneratorFactory class Day21 @Inject constructor(private val generatorFactory: InputGeneratorFactory) { fun partOne(filename: String) = generatorFactory.forFile(filename).readAs(::day21) { input -> val translations = input.flatten().groupBy { it.size } val output = expand(5, translations) output.sumOf { row -> row.count { it == '#' } } } fun partTwo(filename: String) = generatorFactory.forFile(filename).readAs(::day21) { input -> val translations = input.flatten().groupBy { it.size } val output = expand(18, translations) output.sumOf { row -> row.count { it == '#' } } } private fun expand(times: Int, translations: Map<Int, List<Translation>>): List<String> { var output = IMAGE repeat(times) { output = translations.translate(output) } return output } private fun Map<Int, List<Translation>>.translate(image: List<String>): List<String> { val size = image.size if (size == 2 || size == 3) { val source = image.joinToString("/") return this[size]!!.first { it.source == source }.destination.split("/") } val chunkSize = if (size % 2 == 0) 2 else 3 val newImages = (0 until size step chunkSize).map { yStart -> (0 until size step chunkSize).map { xStart -> val imageChunk = (yStart until (yStart + chunkSize)).map { y -> buildString { (xStart until (xStart + chunkSize)).map { x -> append(image[y][x]) } } } translate(imageChunk) } } return buildList { newImages.forEach { destinationRows -> repeat(destinationRows[0].size) { index -> add(destinationRows.joinToString("") { it[index] }) } } } } private fun day21(line: String): List<Translation> { val (originSource, destination) = line.split(" => ") val one = originSource.split("/") val two = one.rotate90() val three = two.rotate90() val four = three.rotate90() val five = one.flip() val six = two.flip() val seven = three.flip() val eight = four.flip() return listOf(one, two, three, four, five, six, seven, eight).map { it.toTranslation(one.size, destination) } } data class Translation(val size: Int, val source: String, val destination: String) private fun List<String>.rotate90(): List<String> { val parent = this return indices.map { x -> buildString { ((size - 1) downTo 0).forEach { y -> append(parent[y][x]) } } } } private fun List<String>.flip(): List<String> { return this.map { it.reversed() } } private fun List<String>.toTranslation(size: Int, destination: String): Translation { return Translation(size, this.joinToString("/"), destination) } companion object { val IMAGE = listOf( ".#.", "..#", "###" ) } }
0
Kotlin
1
3
2625719b657eb22c83af95abfb25eb275dbfee6a
2,996
advent-of-code
MIT License
src/day06/Day06.kt
martinhrvn
724,678,473
false
{"Kotlin": 27307, "Jupyter Notebook": 1336}
package day06 import readInput import readNumbers import removeLabel import removeRegex data class Race(val time: Long, val distance: Long) { fun getWays(): Int { return (0..time).count { i -> (time - i) * i > distance } } } class Day06(private val input: List<String>) { fun parseInputAsList(): List<Race> { val times = input.first().removeLabel("Time").readNumbers() val distances = input[1].removeLabel("Distance").readNumbers() return times.zip(distances) { time, distance -> Race(time, distance) } } fun parseInputAsString(): Race { val times = input.first().removeLabel("Time").removeRegex("\\s+").toLong() val distances = input[1].removeLabel("Distance").removeRegex("\\s+").toLong() return Race(times, distances) } fun part1(): Int { return parseInputAsList().fold(1) { acc, curr -> curr.getWays() * acc } } fun part2(): Int { return parseInputAsString().getWays() } } fun main() { val day06 = Day06(readInput("day06/Day06")) println(day06.part1()) println(day06.part2()) }
0
Kotlin
0
0
59119fba430700e7e2f8379a7f8ecd3d6a975ab8
1,052
advent-of-code-2023-kotlin
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/ValidParenthesesStringPath.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 /** * 2267. Check if There Is a Valid Parentheses String Path * @see <a href="https://leetcode.com/problems/check-if-there-is-a-valid-parentheses-string-path">Source</a> */ fun interface ValidParenthesesStringPath { operator fun invoke(grid: Array<CharArray>): Boolean } class ValidParenthesesStringPathDFS : ValidParenthesesStringPath { override fun invoke(grid: Array<CharArray>): Boolean { val m: Int = grid.size val n: Int = grid[0].size val dp = Array(m + 1) { Array(n + 1) { BooleanArray(ARR_SIZE) } } dp[0][0][1] = true for (i in 0 until m) for (j in 0 until n) for (k in 1..LIMIT) { dp[i][j + 1][k] = dp[i][j + 1][k] or dp[i][j][k + (if (grid[i][j] == '(') -1 else 1)] dp[i + 1][j][k] = dp[i + 1][j][k] or dp[i][j][k + (if (grid[i][j] == '(') -1 else 1)] } return dp[m][n - 1][1] } companion object { private const val LIMIT = 101 private const val ARR_SIZE = 103 } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,688
kotlab
Apache License 2.0
src/nativeMain/kotlin/com.qiaoyuang.algorithm/round1/Questions14.kt
qiaoyuang
100,944,213
false
{"Kotlin": 338134}
package com.qiaoyuang.algorithm.round1 import kotlin.math.pow fun test14() { fun printlnResult1(n: Int) = println("The rope length is $n, the max product is ${getTheMaxCutProduct1(n)}") printlnResult1(2) printlnResult1(3) printlnResult1(5) printlnResult1(8) printlnResult1(12) fun printlnResult2(n: Int) = println("The rope length is $n, the max product is ${getTheMaxCutProduct2(n)}") printlnResult2(2) printlnResult2(3) printlnResult2(5) printlnResult2(8) printlnResult2(12) } /** * Questions 14: We have a rope that length is n, cut the rope into m pieces (m > 0, n > 0). * Every pieces named such as: k[0], k[1]...k[m], please find the biggest value of the k[0] * k[1] *... * k[m]. */ // Dynamic programming private fun getTheMaxCutProduct1(n: Int): Int = when { n < 2 -> throw IllegalArgumentException("The n must bigger than 1") n == 2 -> 1 n == 3 -> 2 else -> { val products = IntArray(n + 1) { it } var max: Int for (i in 4..n) { max = 0 for (j in 1..i) { val product = products[j] * products[i - j] if (max < product) max = product products[i] = max } } max = products[n] max } } // Greedy algorithm private fun getTheMaxCutProduct2(n: Int): Int = when { n < 2 -> throw IllegalArgumentException("The n must bigger than 1") n == 2 -> 1 n == 3 -> 2 else -> { var timesOf3 = n / 3 if (n - timesOf3 * 3 == 1) timesOf3-- val timesOf2 = (n - timesOf3 * 3) shr 1 ((3.0.pow(timesOf3)) * (2.0.pow(timesOf2))).toInt() } }
0
Kotlin
3
6
66d94b4a8fa307020d515d4d5d54a77c0bab6c4f
1,712
Algorithm
Apache License 2.0
kotlin/src/com/s13g/aoc/aoc2020/Day23.kt
shaeberling
50,704,971
false
{"Kotlin": 300158, "Go": 140763, "Java": 107355, "Rust": 2314, "Starlark": 245}
package com.s13g.aoc.aoc2020 import com.s13g.aoc.Result import com.s13g.aoc.Solver import java.util.* /** * --- Day 23: Crab Cups --- * https://adventofcode.com/2020/day/23 */ class Day23 : Solver { override fun solve(lines: List<String>): Result { val cupsInput = LinkedList(lines[0].map { it.toString().toInt() }) val cupsA = playGame(cupsInput, 100, 0) val cupsB = playGame(cupsInput, 10_000_000, 1_000_000) // Part 1: List all the nodes after 1 in the circle. var currentNode = cupsA[1]!!.next() var resultA = "" while (currentNode.value != 1) { resultA += currentNode.value currentNode = currentNode.next() } // Part 2: Multiply the two values after the 1-Node. val resultB = cupsB[1]!!.next().value.toLong() * cupsB[1]!!.next().next().value.toLong() return Result(resultA, "$resultB") } private fun playGame(cupsInput: List<Int>, numRounds: Int, addAdditional: Int): Map<Int, Node> { val nodeMap = createLinkedList(cupsInput, addAdditional) val head = nodeMap[cupsInput[0]]!! val cupsMin = cupsInput.min()!! val cupsMax = nodeMap.keys.max()!! var current = head for (round in 1..numRounds) { // The three cut-outs. val a = current.next() val b = current.next().next() val c = current.next().next().next() // Cutting them out of the linked list. current.next = c.next() // Determine the destination node based on the given rules. var destinationCup: Node var dValue = current.value - 1 while (true) { if (dValue in nodeMap && dValue != a.value && dValue != b.value && dValue != c.value) { destinationCup = nodeMap[dValue]!! break } dValue-- if (dValue < cupsMin) dValue = cupsMax } // Insert the three cut out cups into the circle at the determined place. val follower = destinationCup.next destinationCup.next = a c.next = follower // Move on to the next node in the circle for the next round. current = current.next() } return nodeMap } /** Creates a singly-linked list based on the input data. */ private fun createLinkedList(cupsInput: List<Int>, listSize: Int): Map<Int, Node> { // Maps value to Node for quick access, as our linked list slow to traverse. val nodeMap = mutableMapOf<Int, Node>() val head = Node(cupsInput[0]) nodeMap[cupsInput[0]] = head var tail = head for (i in 1..cupsInput.lastIndex) { val newNode = Node(cupsInput[i], head) tail.next = newNode nodeMap[cupsInput[i]] = newNode tail = newNode } // Part 2 asks us to make the list 1 million items long. for (v in nodeMap.keys.max()!! + 1..listSize) { val newNode = Node(v, head) tail.next = newNode nodeMap[v] = newNode tail = newNode } return nodeMap } private class Node(var value: Int, var next: Node? = null) { fun next() = next!! } }
0
Kotlin
1
2
7e5806f288e87d26cd22eca44e5c695faf62a0d7
2,992
euler
Apache License 2.0
shared/src/main/kotlin/org/javacs/kt/util/StringUtils.kt
fwcd
135,159,301
false
{"Kotlin": 529657, "Python": 10015, "Java": 1400, "Dockerfile": 741}
package org.javacs.kt.util /** * Computes a string distance using a slightly modified * variant of the SIFT4 algorithm in linear time. * Note that the function is asymmetric with respect to * its two input strings and thus is not a metric in the * mathematical sense. * * Based on the JavaScript implementation from * https://siderite.dev/blog/super-fast-and-accurate-string-distance.html/ * * @param candidate The first string * @param pattern The second string * @param maxOffset The number of characters to search for matching letters */ fun stringDistance(candidate: CharSequence, pattern: CharSequence, maxOffset: Int = 4): Int = when { candidate.length == 0 -> pattern.length pattern.length == 0 -> candidate.length else -> { val candidateLength = candidate.length val patternLength = pattern.length var iCandidate = 0 var iPattern = 0 var longestCommonSubsequence = 0 var localCommonSubstring = 0 while (iCandidate < candidateLength && iPattern < patternLength) { if (candidate[iCandidate] == pattern[iPattern]) { localCommonSubstring++ } else { longestCommonSubsequence += localCommonSubstring localCommonSubstring = 0 if (iCandidate != iPattern) { // Using max to bypass the need for computer transpositions ("ab" vs "ba") val iMax = Math.max(iCandidate, iPattern) iCandidate = iMax iPattern = iMax if (iMax >= Math.min(candidateLength, patternLength)) { break } } searchWindow@ for (i in 0 until maxOffset) { when { (iCandidate + i) < candidateLength -> { if (candidate[iCandidate + i] == pattern[iPattern]) { iCandidate += i localCommonSubstring++ break@searchWindow } } (iPattern + i) < patternLength -> { if (candidate[iCandidate] == pattern[iPattern + i]) { iPattern += i localCommonSubstring++ break@searchWindow } } else -> break@searchWindow } } } iCandidate++ iPattern++ } longestCommonSubsequence += localCommonSubstring Math.max(candidateLength, patternLength) - longestCommonSubsequence } } /** Checks whether the candidate contains the pattern in order. */ fun containsCharactersInOrder(candidate: CharSequence, pattern: CharSequence, caseSensitive: Boolean): Boolean { var iCandidate = 0 var iPattern = 0 while (iCandidate < candidate.length && iPattern < pattern.length) { var patternChar = pattern[iPattern] var testChar = candidate[iCandidate] if (!caseSensitive) { patternChar = patternChar.lowercaseChar() testChar = testChar.lowercaseChar() } if (patternChar == testChar) { iPattern++ } iCandidate++ } return iPattern == pattern.length }
177
Kotlin
188
1,392
eee8afa9b6b92c4c5ae445823b3719818d595ec1
3,495
kotlin-language-server
MIT License
src/main/kotlin/ru/amai/study/coursera/kotlin/week3/taxipark/TaxiParkTask.kt
slobanov
401,728,467
true
{"Kotlin": 149929}
package ru.amai.study.coursera.kotlin.week3.taxipark /* * Task #1. Find all the drivers who performed no trips. */ fun TaxiPark.findFakeDrivers(): Set<Driver> = allDrivers - trips.map { it.driver }.toSet() private fun List<Trip>.filterByCount(minCount: Int) = flatMap { it.passengers } .groupBy { it } .filterValues { it.size >= minCount } .keys .toSet() /* * Task #2. Find all the clients who completed at least the given number of trips. */ fun TaxiPark.findFaithfulPassengers(minTrips: Int): Set<Passenger> { return if (minTrips == 0) allPassengers else trips.filterByCount(minTrips) } /* * Task #3. Find all the passengers, who were taken by a given driver more than once. */ fun TaxiPark.findFrequentPassengers(driver: Driver): Set<Passenger> = trips.filter { it.driver == driver }.filterByCount(2) /* * Task #4. Find the passengers who had a discount for majority of their trips. */ fun TaxiPark.findSmartPassengers(): Set<Passenger> { val (tripsWithDiscount, tripsWithoutDiscount) = trips.partition { (it.discount ?: 0.0) > 0 } fun List<Trip>.countWith(p: Passenger) = count { p in it.passengers } return allPassengers .filter { tripsWithDiscount.countWith(it) > tripsWithoutDiscount.countWith(it) } .toSet() } /* * Task #5. Find the most frequent trip duration among minute periods 0..9, 10..19, 20..29, and so on. * Return any period if many are the most frequent, return `null` if there're no trips. */ fun TaxiPark.findTheMostFrequentTripDurationPeriod(): IntRange? = trips.map { 10 * (it.duration / 10) } .groupingBy { it..(it+9) } .eachCount() .maxBy { it.value } ?.key /* * Task #6. * Check whether 20% of the drivers contribute 80% of the income. */ fun TaxiPark.checkParetoPrinciple(): Boolean { val driverContributions = trips .groupBy { it.driver } .map { (_, trips) -> trips.sumByDouble { it.cost } } .sortedDescending() val totalSum = trips.sumByDouble(Trip::cost) val topDriversCount = (0.2 * allDrivers.size).toInt() return totalSum > 0 && driverContributions.take(topDriversCount).sum() >= 0.8*totalSum }
1
Kotlin
4
0
ff8cafe57166b57900cbddf2a00b670e12ad1410
2,223
kotlin-for-java-dev
MIT License
kotlinLeetCode/src/main/kotlin/leetcode/editor/cn/[84]柱状图中最大的矩形.kt
maoqitian
175,940,000
false
{"Kotlin": 354268, "Java": 297740, "C++": 634}
import java.util.* //给定 n 个非负整数,用来表示柱状图中各个柱子的高度。每个柱子彼此相邻,且宽度为 1 。 // // 求在该柱状图中,能够勾勒出来的矩形的最大面积。 // // // // // // 以上是柱状图的示例,其中每个柱子的宽度为 1,给定的高度为 [2,1,5,6,2,3]。 // // // // // // 图中阴影部分为所能勾勒出的最大矩形面积,其面积为 10 个单位。 // // // // 示例: // // 输入: [2,1,5,6,2,3] //输出: 10 // Related Topics 栈 数组 // 👍 1101 👎 0 //leetcode submit region begin(Prohibit modification and deletion) class Solution { fun largestRectangleArea(heights: IntArray): Int { var len: Int = heights.size if (len == 0) { return 0 } if (len == 1) { return heights[0] } var max = 0 //新增哨兵数组 val newHeights = IntArray(len + 2) //加入原数组值 for (i in 0 until len) { newHeights[i + 1] = heights[i] } len += 2 //创建栈 val stack = LinkedList<Int>() stack.addLast(0) for (i in 1 until newHeights.size) { while (!stack.isEmpty() && newHeights[stack.last] > newHeights[i]){ val cur = stack.removeLast() max = Math.max(max,(i-stack.last-1)*newHeights[cur]) } stack.addLast(i) } return max } } //leetcode submit region end(Prohibit modification and deletion)
0
Kotlin
0
1
8a85996352a88bb9a8a6a2712dce3eac2e1c3463
1,560
MyLeetCode
Apache License 2.0
kotlin/src/main/kotlin/AoC_Day12.kt
sviams
115,921,582
false
null
object AoC_Day12 { private fun parseInput(input: List<String>) : Map<Int, List<Int>> = input.associate { value -> val split = value.split(" <-> ") split[0].toInt() to split[1].split(",").map { it.trimStart().toInt() } } private fun getGroupWithRoot(theMap: Map<Int, List<Int>>, alreadySeen: List<Int>, currentValue: Int, sofar: Int) : List<Int> = theMap[currentValue]?.fold(alreadySeen) { acc, value -> if (acc.contains(value)) acc else (acc + getGroupWithRoot(theMap,acc + value, value, sofar + 1)).distinct() } ?: alreadySeen private tailrec fun countGroups(theMap: Map<Int, List<Int>>, theCount: Int) : Int { if (!theMap.any()) return theCount val rootGroup = getGroupWithRoot(theMap, listOf(theMap.keys.first()), theMap.keys.first(), 0) return countGroups(theMap.filter { !rootGroup.contains(it.key) }, theCount + 1) } fun solvePt1(input: List<String>) : Int = getGroupWithRoot(parseInput(input), listOf(0),0, 0).size fun solvePt2(input: List<String>) : Int = countGroups(parseInput(input), 0) }
0
Kotlin
0
0
19a665bb469279b1e7138032a183937993021e36
1,100
aoc17
MIT License
Data-Structures/Graph/GraphUsingList.kt
ahampriyanshu
278,614,006
false
{"C++": 583777, "Java": 277289, "Python": 254940, "C": 223686, "C#": 127046, "JavaScript": 96050, "Ruby": 37909, "PHP": 37167, "Go": 34857, "TypeScript": 34282, "Swift": 16690, "Jupyter Notebook": 13334, "Kotlin": 9718, "Rust": 9569, "Shell": 7923, "Scala": 6275, "Haskell": 5456, "HTML": 2270, "Clojure": 348, "Makefile": 261}
import kotlin.collections.ArrayList class Node<T>(val value: T) { val neighbors = ArrayList<Node<T>>() fun addNeighbor(node: Node<T>) = neighbors.add(node) override fun toString(): String = value.toString() } class Graph<T> { private val nodes = HashSet<Node<T>>() fun addNode(value: T) { val newNode = Node(value) nodes.add(newNode) } fun getNode(reference: T): Node<T>? { return nodes.firstOrNull { it.value == reference } } fun addVertex(from: T, to: T) { getNode(to)?.let { getNode(from)?.addNeighbor(it) } } } fun <T> Graph<T>.bfs(reference: T): List<T> { getNode(reference)?.let { referenceNode -> val visited = ArrayList<Node<T>>() val queue = ArrayList<Node<T>>() queue.add(referenceNode) while (queue.isNotEmpty()) { val node = queue.removeAt(0) if (!visited.contains(node)) { visited.add(node) node.neighbors .filter { !visited.contains(it) } .forEach { queue.add(it) } } } return visited.map { it.value } } return emptyList() } fun <T> Graph<T>.dfs(reference: T): List<T> { getNode(reference)?.let { referenceNode -> val visited = ArrayList<Node<T>>() val stack = ArrayList<Node<T>>() stack.add(referenceNode) while (stack.isNotEmpty()) { val node = stack.removeAt(stack.lastIndex) if (!visited.contains(node)) { visited.add(node) node.neighbors .filter { !visited.contains(it) } .forEach { stack.add(it) } } } return visited.map { it.value } } return emptyList() } fun main() { val namesGraph = Graph<String>() namesGraph.addNode("Minato") namesGraph.addNode("Obito") namesGraph.addVertex("Minato", "Obito") namesGraph.addNode("Kakashi") namesGraph.addVertex("Minato", "Kakashi") namesGraph.addNode("Rin") namesGraph.addVertex("Minato", "Rin") namesGraph.addNode("Naruto") namesGraph.addVertex("Kakashi", "Naruto") namesGraph.addNode("Sakura") namesGraph.addVertex("Kakashi", "Sakura") namesGraph.addNode("Sasuke") namesGraph.addVertex("Kakashi", "Sasuke") print(namesGraph.bfs("Minato")) print(namesGraph.dfs("Minato")) }
0
C++
760
156
ea880b13c09df58922065ab408d23fa4d264fb7c
2,435
algo-ds-101
MIT License
src/2021/Day19.kt
nagyjani
572,361,168
false
{"Kotlin": 369497}
package `2021` import java.io.File import java.lang.Math.abs import java.util.* import kotlin.math.absoluteValue fun main() { Day19().solve() } class Day19 { companion object { val allRoll90s: List<Roll90> = allRoll90s() fun allRoll90s(): List<Roll90> { val newPosPermutations = mutableListOf<List<Int>>() for (i in 0..2) { for (j in 0..2) { for (k in 0..2) { if (i!=j && i!=k && j!=k) { newPosPermutations.add(listOf(i, j, k)) } } } } val signsPermutations = mutableListOf<List<Int>>() for (i in listOf(-1, 1)) { for (j in listOf(-1, 1)) { for (k in listOf(-1, 1)) { signsPermutations.add(listOf(i, j, k)) } } } val allRoll90s = mutableListOf<Roll90>() for (newPos in newPosPermutations) { for (signs in signsPermutations) { allRoll90s.add(Roll90(newPos, signs)) } } return allRoll90s } } class Point(val c: List<Long>) { operator fun get(i: Int): Long { return c[i] } fun asList(): List<Long> { return c } fun diff(other: Point): Point { return Point(c.zip(other.c).map { it.first - it.second }) } override operator fun equals(other: Any?): Boolean = (other is Point) && c.zip(other.c).all { it.first == it.second} override fun hashCode(): Int { return c.fold(0) {h, it -> h*1000+it.toInt()} } override fun toString(): String { return "[" + c.map { it.toString() }.joinToString (",") + "]" } operator fun unaryMinus(): Point { return Point(c.map{-it}) } } abstract class Transformation { abstract fun applyTo(p: Point): Point abstract fun inverse(): Transformation } class Move(val c: List<Long>): Transformation() { override fun applyTo(p: Point): Point { return p.asList().zip(c).map{it.first + it.second}.let{Point(it)} } override fun inverse(): Transformation { return c.map{-it}.let{Move(it)} } } class CompositeTransformation(val ts: List<Transformation>): Transformation() { override fun applyTo(p: Point): Point { return ts.fold(p){p1, it -> it.applyTo(p1)} } override fun inverse(): Transformation { return CompositeTransformation(ts.asReversed().map { it.inverse() }) } } class Roll90(val newPos: List<Int>, val signs: List<Int>): Transformation() { override fun applyTo(p: Point): Point { val c = p.asList().toMutableList() for (i in newPos.indices) { c[newPos[i]] = signs[newPos[i]] * p.asList()[i] } return Point(c) } override fun inverse(): Transformation { val newPos1 = mutableListOf(0, 0, 0) val signs1 = mutableListOf(0, 0, 0) for (i in 0..2) { newPos1[newPos[i]] = i signs1[i] = signs[newPos[i]] } return Roll90(newPos1, signs1) } } class Scanner(val name: String, val beacons: List<Point>) { override fun toString(): String { return name } val pointViews: Map<Point, List<Point>> val pointHashes: Map<Point, List<Long>> init { val pv = mutableMapOf<Point, List<Point>>() val ph = mutableMapOf<Point, List<Long>>() for (p in beacons) { pv[p] = beacons.filter { it !== p }.map{it.diff(p)} ph[p] = beacons.filter { it !== p }.map{it.diff(p).roll90Hash()} } pointViews = pv pointHashes = ph } fun overlap(other: Scanner): List<Transformation> { for (pv0 in pointViews) { val p0 = pv0.key val ps0 = pv0.value for (pv1 in other.pointViews) { val p1 = pv1.key val ps1 = pv1.value // TODO: check hashes val commonHashes = pointHashes[p0]!!.intersect(other.pointHashes[p1]!!) if (commonHashes.size < 11) { continue } for (r90 in allRoll90s) { val ps090 = ps0.map{r90.applyTo(it)} val common = ps1.intersect(ps090).size + 1 if (common > 11) { val t = CompositeTransformation(listOf(Move((-p0).asList()), r90, Move(p1.asList()))) val common1 = beacons.map { t.applyTo(it) }.intersect(other.beacons) // println("${common1.size} $common1") // TODO: more than 1 mapping // TODO: check if the rest is out of range for the other return listOf(t) } } } } return listOf() } } class ScannerBuilder { val beacons = mutableListOf<Point>() var name = "" fun add(line: String): Boolean { if (line.startsWith("---")) { name = line return true } if (line.isEmpty()) { return false } beacons.add(line.toPoint()) return true } fun build(): Scanner? { if (name == "") { return null } return Scanner(name, beacons) } } val input = """ --- scanner 0 --- 404,-588,-901 528,-643,409 -838,591,734 390,-675,-793 -537,-823,-458 -485,-357,347 -345,-311,381 -661,-816,-575 -876,649,763 -618,-824,-621 553,345,-567 474,580,667 -447,-329,318 -584,868,-557 544,-627,-890 564,392,-477 455,729,728 -892,524,684 -689,845,-530 423,-701,434 7,-33,-71 630,319,-379 443,580,662 -789,900,-551 459,-707,401 --- scanner 1 --- 686,422,578 605,423,415 515,917,-361 -336,658,858 95,138,22 -476,619,847 -340,-569,-846 567,-361,727 -460,603,-452 669,-402,600 729,430,532 -500,-761,534 -322,571,750 -466,-666,-811 -429,-592,574 -355,545,-477 703,-491,-529 -328,-685,520 413,935,-424 -391,539,-444 586,-435,557 -364,-763,-893 807,-499,-711 755,-354,-619 553,889,-390 --- scanner 2 --- 649,640,665 682,-795,504 -784,533,-524 -644,584,-595 -588,-843,648 -30,6,44 -674,560,763 500,723,-460 609,671,-379 -555,-800,653 -675,-892,-343 697,-426,-610 578,704,681 493,664,-388 -671,-858,530 -667,343,800 571,-461,-707 -138,-166,112 -889,563,-600 646,-828,498 640,759,510 -630,509,768 -681,-892,-333 673,-379,-804 -742,-814,-386 577,-820,562 --- scanner 3 --- -589,542,597 605,-692,669 -500,565,-823 -660,373,557 -458,-679,-417 -488,449,543 -626,468,-788 338,-750,-386 528,-832,-391 562,-778,733 -938,-730,414 543,643,-506 -524,371,-870 407,773,750 -104,29,83 378,-903,-323 -778,-728,485 426,699,580 -438,-605,-362 -469,-447,-387 509,732,623 647,635,-688 -868,-804,481 614,-800,639 595,780,-596 --- scanner 4 --- 727,592,562 -293,-554,779 441,611,-461 -714,465,-776 -743,427,-804 -660,-479,-426 832,-632,460 927,-485,-438 408,393,-506 466,436,-512 110,16,151 -258,-428,682 -393,719,612 -211,-452,876 808,-476,-593 -575,615,604 -485,667,467 -680,325,-822 -627,-443,-432 872,-547,-609 833,512,582 807,604,487 839,-516,451 891,-625,532 -652,-548,-490 30,-46,-14 """.trimIndent() val output = """ -892,524,684 -876,649,763 -838,591,734 -789,900,-551 -739,-1745,668 -706,-3180,-659 -697,-3072,-689 -689,845,-530 -687,-1600,576 -661,-816,-575 -654,-3158,-753 -635,-1737,486 -631,-672,1502 -624,-1620,1868 -620,-3212,371 -618,-824,-621 -612,-1695,1788 -601,-1648,-643 -584,868,-557 -537,-823,-458 -532,-1715,1894 -518,-1681,-600 -499,-1607,-770 -485,-357,347 -470,-3283,303 -456,-621,1527 -447,-329,318 -430,-3130,366 -413,-627,1469 -345,-311,381 -36,-1284,1171 -27,-1108,-65 7,-33,-71 12,-2351,-103 26,-1119,1091 346,-2985,342 366,-3059,397 377,-2827,367 390,-675,-793 396,-1931,-563 404,-588,-901 408,-1815,803 423,-701,434 432,-2009,850 443,580,662 455,729,728 456,-540,1869 459,-707,401 465,-695,1988 474,580,667 496,-1584,1900 497,-1838,-617 527,-524,1933 528,-643,409 534,-1912,768 544,-627,-890 553,345,-567 564,392,-477 568,-2007,-577 605,-1665,1952 612,-1593,1893 630,319,-379 686,-3108,-505 776,-3184,-501 846,-3110,-434 1135,-1161,1235 1243,-1093,1063 1660,-552,429 1693,-557,386 1735,-437,1738 1749,-1800,1813 1772,-405,1572 1776,-675,371 1779,-442,1789 1780,-1548,337 1786,-1538,337 1847,-1591,415 1889,-1729,1762 1994,-1805,1792""".trimIndent() fun solve() { val f = File("src/2021/inputs/day19.in") val s = Scanner(f) // val s = Scanner(input) val scanners = mutableListOf<Scanner>() while (s.hasNextLine()) { val sb = ScannerBuilder() while (s.hasNextLine() && sb.add(s.nextLine())) {} sb.build()?.let{scanners.add(it)} } val transformTo0 = mutableMapOf<Int, Transformation>(0 to Move(listOf(0, 0, 0))) val beacons = scanners[0].beacons.toMutableSet() loop@ while (transformTo0.size < scanners.size) { for (i in scanners.indices.subtract(transformTo0.keys)) { for (j in transformTo0.keys) { val t = scanners[i].overlap(scanners[j]) if (t.size > 0) { val t1 = CompositeTransformation(listOf(t[0], transformTo0[j]!!)) beacons.addAll(scanners[i].beacons.map{ // println("${it} ${t1.applyTo(it)}") t1.applyTo(it) }) transformTo0[i] = t1 println("${transformTo0.size}/${scanners.size}") continue@loop } } } } val scannerCenters = transformTo0.values.map { it.applyTo(Point(listOf(0,0,0))) } var maxDist = 0 for (i in scannerCenters) { for (j in scannerCenters) { val dist = i.diff(j).asList().fold(0){d, it -> d + abs(it.toInt())} if (dist > maxDist) { maxDist = dist } } } // val so = Scanner(output) // val outBeacons = mutableSetOf<Point>() // while (so.hasNextLine()) { // val soStr = so.nextLine() // if (soStr.isNotEmpty()) { // outBeacons.add(soStr.toPoint()) // } // } // // val bd1 = outBeacons.subtract(beacons) // val bd2 = beacons.subtract(outBeacons) println("e ${beacons.size} $maxDist") } } fun String.toPoint(): Day19.Point { return Day19.Point(split(",").map { it.toLong() }) } fun Day19.Point.canRoll90To(p: Day19.Point): Boolean { return roll90Hash() == p.roll90Hash() } fun Day19.Point.roll90Hash(): Long { return c.map { it.absoluteValue }.sorted().fold(0){acc, it -> acc * 2003 + it} } fun Day19.Point.moveTo(other: Day19.Point): Day19.Move { return Day19.Move(other.diff(this).asList()) }
0
Kotlin
0
0
f0c61c787e4f0b83b69ed0cde3117aed3ae918a5
11,558
advent-of-code
Apache License 2.0
src/chapter5/section2/TrieST.kt
w1374720640
265,536,015
false
{"Kotlin": 1373556}
package chapter5.section2 import chapter5.section1.Alphabet import edu.princeton.cs.algs4.Queue /** * 基于单词查找树的符号表 */ open class TrieST<V : Any>(protected val alphabet: Alphabet) : StringST<V> { protected inner class Node { val next = arrayOfNulls<Node>(alphabet.R()) var value: V? = null fun nextNum(): Int { var i = 0 next.forEach { if (it != null) i++ } return i } } // 根结点不可重新赋值,用于存放空字符串对应的值 protected val root = Node() protected var size = 0 override fun put(key: String, value: V) { put(root, key, value, 0) } protected open fun put(node: Node, key: String, value: V, d: Int) { if (d == key.length) { if (node.value == null) 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) } override fun get(key: String): V? { return get(root, key, 0)?.value } protected open 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) } protected open fun delete(node: Node, key: String, d: Int): Node? { if (d == key.length) { if (node.value == null) throw NoSuchElementException() node.value = null size-- return if (node.nextNum() == 0) null else node } val index = alphabet.toIndex(key[d]) val nextNode = node.next[index] ?: throw NoSuchElementException() node.next[index] = delete(nextNode, key, d + 1) return if (node.value == null && node.nextNum() == 0) null else node } override fun contains(key: String): Boolean { return get(key) != null } override fun isEmpty(): Boolean { return size == 0 } override fun size(): Int { return size } override fun keys(): Iterable<String> { val queue = Queue<String>() keys(root, queue, "") return queue } protected open 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) } protected open 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 } protected open 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) } } } fun main() { testStringST { TrieST(Alphabet.EXTENDED_ASCII) } }
0
Kotlin
1
6
879885b82ef51d58efe578c9391f04bc54c2531d
4,571
Algorithms-4th-Edition-in-Kotlin
MIT License
src/main/kotlin/g0901_1000/s0912_sort_an_array/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g0901_1000.s0912_sort_an_array // #Medium #Array #Sorting #Heap_Priority_Queue #Divide_and_Conquer #Merge_Sort #Bucket_Sort // #Counting_Sort #Radix_Sort #Udemy_Sorting_Algorithms // #2023_04_16_Time_606_ms_(98.48%)_Space_47.6_MB_(57.11%) class Solution { fun sortArray(nums: IntArray): IntArray { return mergeSort(nums, 0, nums.size - 1) } private fun mergeSort(arr: IntArray, lo: Int, hi: Int): IntArray { if (lo == hi) { val sortedArr = IntArray(1) sortedArr[0] = arr[lo] return sortedArr } val mid = (lo + hi) / 2 val leftArray = mergeSort(arr, lo, mid) val rightArray = mergeSort(arr, mid + 1, hi) return mergeSortedArray(leftArray, rightArray) } private fun mergeSortedArray(a: IntArray, b: IntArray): IntArray { val ans = IntArray(a.size + b.size) var i = 0 var j = 0 var k = 0 while (i < a.size && j < b.size) { if (a[i] < b[j]) { ans[k++] = a[i++] } else { ans[k++] = b[j++] } } while (i < a.size) { ans[k++] = a[i++] } while (j < b.size) { ans[k++] = b[j++] } return ans } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,293
LeetCode-in-Kotlin
MIT License
src/main/kotlin/d22/D22.kt
MTender
734,007,442
false
{"Kotlin": 108628}
package d22 import kotlin.math.max data class Block( val id: Int, val start: Triple<Int, Int, Int>, val end: Triple<Int, Int, Int>, val supporting: MutableSet<Int> = mutableSetOf(), val supportedBy: MutableSet<Int> = mutableSetOf() ) data class ViewInfo( val blockId: Int?, val height: Int ) fun parseBlocks(lines: List<String>): List<Block> { return lines.mapIndexed { index, line -> val startAndEndStrings = line.split("~") val start = startAndEndStrings[0].split(",").map { it.toInt() }.toTriple() val end = startAndEndStrings[1].split(",").map { it.toInt() }.toTriple() Block(index, start, end) } } fun <T> List<T>.toTriple(): Triple<T, T, T> { if (this.size != 3) throw UnsupportedOperationException("List must have exactly 3 elements") return Triple(this[0], this[1], this[2]) } fun Triple<Int, Int, Int>.subtract(other: Triple<Int, Int, Int>): Triple<Int, Int, Int> { return Triple( this.first - other.first, this.second - other.second, this.third - other.third ) } fun calculateSupports(blocks: List<Block>) { val sortedBlocks = blocks.sortedBy { it.start.third } val largestX = sortedBlocks.maxOf { max(it.start.first, it.end.first) } val largestY = sortedBlocks.maxOf { max(it.start.second, it.end.second) } val topDown = Array(largestX + 1) { Array(largestY + 1) { ViewInfo(null, 0) } } val blockMap = sortedBlocks.associateBy { it.id } for (block in sortedBlocks) { val locs = mutableListOf<Pair<Int, Int>>() val diff = block.end.subtract(block.start) if (diff.toList().any { it < 0 }) throw RuntimeException("what the hell") if (diff.first != 0) { // x-axis length for (i in 0..diff.first) { locs.add(Pair(block.start.first + i, block.start.second)) } } else if (diff.second != 0) { // y-axis length for (i in 0..diff.second) { locs.add(Pair(block.start.first, block.start.second + i)) } } else { // z-axis length or single cube locs.add(Pair(block.start.first, block.start.second)) } val belowLocs = locs.map { topDown[it.first][it.second] } val maxHeightBelow = belowLocs.maxOf { it.height } val supportedByBlockIds = belowLocs.filter { it.height == maxHeightBelow }.mapNotNull { it.blockId }.toSet() supportedByBlockIds.map { id -> blockMap[id]!! }.forEach { supportBlock -> supportBlock.supporting.add(block.id) } block.supportedBy.addAll(supportedByBlockIds) locs.forEach { loc -> topDown[loc.first][loc.second] = ViewInfo(block.id, maxHeightBelow + 1 + diff.third) } } }
0
Kotlin
0
0
a6eec4168b4a98b73d4496c9d610854a0165dbeb
2,818
aoc2023-kotlin
MIT License
atcoder/arc155/a.kt
mikhail-dvorkin
93,438,157
false
{"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408}
package atcoder.arc155 private fun solve(): Boolean { val (_, qIn) = readLongs() val s = readLn() val q = minOf(qIn % (2 * s.length) + 4 * s.length, qIn).toInt() val c = (s + " ".repeat(q)).toCharArray() val mark = BooleanArray(c.size) { false } var answer = true val queue = IntArray(c.size) for (i in c.indices) { if (mark[i]) continue if (c[i] == ' ') c[i] = 'a' var low = 0 var high = 1 queue[0] = i mark[i] = true while (low < high) { val v = queue[low++] val u = c.size - 1 - v if (c[u] == ' ') c[u] = c[v] if (c[u] != c[v]) answer = false if (!mark[u]) { queue[high++] = u mark[u] = true } val u1 = (v + c.size - s.length) % c.size val u2 = c.size - 1 - u1 val uu = (u2 + s.length) % c.size if (c[uu] == ' ') c[uu] = c[v] if (c[uu] != c[v]) answer = false if (!mark[uu]) { queue[high++] = uu mark[uu] = true } } } return answer } fun main() = repeat(readInt()) { println(solve().iif("Yes", "No")) } private fun readLn() = readLine()!! private fun readInt() = readLn().toInt() private fun readStrings() = readLn().split(" ") private fun readLongs() = readStrings().map { it.toLong() } private fun <T> Boolean.iif(onTrue: T, onFalse: T) = if (this) onTrue else onFalse
0
Java
1
9
30953122834fcaee817fe21fb108a374946f8c7c
1,258
competitions
The Unlicense
src/Day01.kt
markhor1999
574,354,173
false
{"Kotlin": 4937}
fun main() { fun List<List<Int>>.sortedNElementsSum(n: Int): Int { val values = sortedSetOf<Int>() for (element in map { it.sum() }) { values.add(element) if (values.size > n) { values.remove(values.first()) } } return values.sum() } fun part1(input: List<String>): Int { val data = input.chunkedWithPredicate( predicate = { it.isBlank() }, valueTransform = { it.toInt() } ) return data.maxOf { it.sum() } } fun part2(input: List<String>): Int { val data = input.chunkedWithPredicate( predicate = { it.isBlank() }, valueTransform = { it.toInt() } ) return data.sortedNElementsSum(3) } val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
800f218ff12908ebd885c3f475793c6be2d7fd7d
881
kotlin-advent-of-code-2022
Apache License 2.0
src/Day03.kt
buongarzoni
572,991,996
false
{"Kotlin": 26251}
fun solveDay03() { val result = readInput("Day03").mapNotNull { it.getItem() }.sum() println(result) val result2 = readInput("Day03") .chunked(3) .mapNotNull { it.getChunkPoints() } .sum() println(result2) } private fun List<String>.getChunkPoints(): Int? { for (character in component1()) { if (component2().contains(character) && component3().contains(character)) { return if (character.isLowerCase()) { character - 'a' + 1 } else { character - 'A' + 27 } } } return null } private fun String.getItem(): Int? { val part1 = substring(0, length / 2) val part2 = substring(length / 2, length) println("$part1 $part2") for (character in part1) { if (part2.contains(character)) { return if (character.isLowerCase()) { character - 'a' + 1 } else { character - 'A' + 27 } } } return null }
0
Kotlin
0
0
96aadef37d79bcd9880dbc540e36984fb0f83ce0
1,033
AoC-2022
Apache License 2.0
src/Day01.kt
atsvetkov
572,711,515
false
{"Kotlin": 10892}
import kotlin.math.max fun main() { fun part1(input: List<String>): Int { var maxCalories = 0 var currentTotal = 0 for (line in input) { if (line.isEmpty()) { maxCalories = max(maxCalories, currentTotal) currentTotal = 0 } else { currentTotal += Integer.parseInt(line) } } return maxCalories } fun part2(input: List<String>): Int { val weights = mutableListOf<Int>() var current = 0 for (line in input) { if (line.isEmpty()) { weights.add(current) current = 0 } else { current += Integer.parseInt(line) } } return weights.sorted().takeLast(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("Part 1: " + part1(input)) println("Part 2: " + part2(input)) }
0
Kotlin
0
0
01c3bb6afd658a2e30f0aee549b9a3ac4da69a91
1,126
advent-of-code-2022
Apache License 2.0
src/nativeMain/kotlin/xyz/justinhorton/aoc2022/Day07.kt
justinhorton
573,614,839
false
{"Kotlin": 39759, "Shell": 611}
package xyz.justinhorton.aoc2022 import okio.Path import okio.Path.Companion.toPath /** * https://adventofcode.com/2022/day/7 */ class Day07(override val input: String) : Day() { override fun part1(): String { val fileSystem = buildFileSystem() return fileSystem.keys .map { dir -> totalSize(dir, fileSystem) } .filter { it <= 100000 } .sum() .toString() } override fun part2(): String { val fileSystem = buildFileSystem() val spaceAvail = TOTAL_DRIVE_SPACE - totalSize("/".toPath(), fileSystem) return fileSystem.keys .map { dir -> totalSize(dir, fileSystem) } .filter { it >= FREE_SPACE_NEEDED - spaceAvail } .min() .toString() } private fun buildFileSystem(): MutableMap<Path, MutableList<FileMetadata>> { // keys are directories, values represent contained files/directories val fileMap = mutableMapOf<Path, MutableList<FileMetadata>>() val lines = input.trim().lines() var pwd: Path = "/".toPath() val firstCmd = lines[0].trim() require(firstCmd == "$ cd /") { "Unexpected first command: $firstCmd" } for (line in input.trim().lines().drop(1)) { val split = line.trim().split(" ") when (split[0]) { "$" -> { when (val cmd = split[1]) { "ls" -> continue // multi-line output follows "cd" -> { // change pwd val nextDir = split[2] pwd = if (nextDir == "..") { pwd.parent!! } else { pwd.resolve(nextDir) } } else -> throw IllegalArgumentException("Unknown command: $cmd") } } else -> { // multi-line `ls` output val lsDir = fileMap.getOrPut(pwd) { mutableListOf() } val lsSplit = line.trim().split(" ") if (lsSplit[0] == "dir") { lsDir.add(DirectoryMetadata(pwd.resolve(lsSplit[1]))) } else { lsDir.add(SimpleFileMetadata(lsSplit[1], lsSplit[0].toLong())) } } } } return fileMap } } private const val FREE_SPACE_NEEDED = 30000000L private const val TOTAL_DRIVE_SPACE = 70000000L private fun totalSize(initialDir: Path, fs: Map<Path, List<FileMetadata>>): Long { return fs.getValue(initialDir).sumOf { f -> when (f) { is SimpleFileMetadata -> f.size is DirectoryMetadata -> totalSize(f.path, fs) } } } private sealed class FileMetadata private data class SimpleFileMetadata(val name: String, val size: Long) : FileMetadata() private data class DirectoryMetadata(val path: Path) : FileMetadata()
0
Kotlin
0
1
bf5dd4b7df78d7357291c7ed8b90d1721de89e59
3,048
adventofcode2022
MIT License
src/main/kotlin/sschr15/aocsolutions/Day24.kt
sschr15
317,887,086
false
{"Kotlin": 184127, "TeX": 2614, "Python": 446}
package sschr15.aocsolutions import com.sschr15.z3kt.* import sschr15.aocsolutions.util.* /** * AOC 2023 [Day 24](https://adventofcode.com/2023/day/24) * Challenge: Killing hundreds of hailstones with one stone * ~~that's how the saying goes, right?~~ */ object Day24 : Challenge { @ReflectivelyUsed override fun solve() = challenge(2023, 24) { // test() part1 { val min = 200000000000000.0 val max = 400000000000000.0 val range = if (!_test) min..max else 7.0..27.0 val stones = inputLines.map { line -> val (pos, vel) = line.split(" @ ") val (x, y, _) = pos.split(", ").map { it.trim().toLong().toDouble() } val (dx, dy, _) = vel.split(", ").map { it.trim().toLong().toDouble() } Ray(x, y, x + dx, y + dy) } stones.combinations(2).asSequence() .map { (a, b) -> a.intersection(b) } .filter { (x) -> x.isFinite() } // x will be infinite or nan if there is no valid intersection .filter { (x, y) -> x in range && y in range } .count() } part2 { z3 { val x = int("x") val y = int("y") val z = int("z") val dx = int("dx") val dy = int("dy") val dz = int("dz") val model = solve { // three lines is technically all it takes because of how aoc gave the input for ((i, line) in inputLines.withIndex().take(3)) { val (pos, vel) = line.split(" @ ") val (xv, yv, zv) = pos.split(", ").map { it.trim().toLong() } val (dxv, dyv, dzv) = vel.split(", ").map { it.trim().toLong() } val t = int("t_$i") add(t gte 0) add(x + t * dx eq xv + t * dxv) add(y + t * dy eq yv + t * dyv) add(z + t * dz eq zv + t * dzv) } } ?: error("Failed to solve model") val xResult = model.eval(x, true).toLong() val yResult = model.eval(y, true).toLong() val zResult = model.eval(z, true).toLong() // for fun data val dxResult = model.eval(dx, true).toLong() val dyResult = model.eval(dy, true).toLong() val dzResult = model.eval(dz, true).toLong() println("$xResult, $yResult, $zResult @ $dxResult, $dyResult, $dzResult") xResult + yResult + zResult } } } @JvmStatic fun main(args: Array<String>) = println("Time: ${solve()}") }
0
Kotlin
0
0
e483b02037ae5f025fc34367cb477fabe54a6578
2,820
advent-of-code
MIT License
src/main/kotlin/g2901_3000/s2948_make_lexicographically_smallest_array_by_swapping_elements/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g2901_3000.s2948_make_lexicographically_smallest_array_by_swapping_elements // #Medium #Array #Sorting #Union_Find #2024_01_16_Time_928_ms_(94.59%)_Space_77.9_MB_(21.62%) import kotlin.math.abs class Solution { fun lexicographicallySmallestArray(nums: IntArray, limit: Int): IntArray { val n = nums.size val nodes = Array(n) { i -> Node(i, nums[i]) } nodes.sortWith { a: Node, b: Node -> Integer.signum( a.value - b.value ) } var group = 1 nodes[0].group = group for (i in 1 until n) { if (abs(nodes[i].value - nodes[i - 1].value) <= limit) { nodes[i].group = group } else { nodes[i].group = ++group } } val groupBase = IntArray(group + 1) for (i in n - 1 downTo 0) { groupBase[nodes[i].group] = i } val groupIndex = IntArray(n) for (node in nodes) { groupIndex[node.id] = node.group } val ans = IntArray(n) for (i in 0 until n) { val index = groupBase[groupIndex[i]] ans[i] = nodes[index].value groupBase[groupIndex[i]]++ } return ans } private class Node(var id: Int, var value: Int) { var group: Int = 0 } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,359
LeetCode-in-Kotlin
MIT License
src/main/kotlin/aoc2022/Day22.kt
w8mr
572,700,604
false
{"Kotlin": 140954}
package aoc2022 import aoc.parser.* class Day22() { enum class GridType(val text: String) { EMPTY(" "), OPEN("."), WALL("#") } enum class Dir { RIGHT, DOWN, LEFT, UP } operator fun Dir.minus(other: Dir) = Dir.values()[(this.ordinal - other.ordinal).mod(Dir.values().size)] sealed interface Instruction { data class Rotate(val by: Int) : Instruction data class Forward(val steps: Int) : Instruction } val gridType = byEnum(GridType::class, GridType::text) val gridLine = oneOrMore(gridType).asArray() followedBy "\n" val gridParser = oneOrMore(gridLine).asArray() followedBy "\n" val instruction = oneOf( "L" asValue Instruction.Rotate(-1), "R" asValue Instruction.Rotate(1), number() map (Instruction::Forward) ) val instructions = oneOrMore(instruction) val parser = seq(gridParser, instructions) data class State(val x: Int, val y: Int, val dir: Dir, val rot: Int) { val vdir get() = calculateChangedDir(rot) private fun calculateChangedDir(by: Int): Dir = Dir.values()[(dir.ordinal + by).mod(4)] fun changeDir(rotate: Instruction.Rotate) = copy(dir = calculateChangedDir(rotate.by)) fun step(dir: Dir) = when (dir) { Dir.RIGHT -> copy(x = x + 1) Dir.DOWN -> copy(y = y + 1) Dir.LEFT -> copy(x = x - 1) Dir.UP -> copy(y = y - 1) } } fun Array<Array<GridType>>.cell(state: State) = this.getOrElse(state.y) { arrayOf() }.getOrElse(state.x) { GridType.EMPTY } fun solve(input: String, handleEmpty: (grid: Array<Array<GridType>>, oldState: State, newState: State) -> State): Int { val (grid, instructions) = parser.parse(input) var state = State(grid[0].indexOfFirst { it != GridType.EMPTY }, 0, Dir.RIGHT, 0) fun forward( instruction: Instruction.Forward) { (1..instruction.steps).forEach { step -> var newState = state.step(state.vdir) if (grid.cell(newState) == GridType.EMPTY) { newState = handleEmpty(grid, state, newState) } when (grid.cell(newState)) { GridType.OPEN -> state = newState GridType.WALL -> return GridType.EMPTY -> {} } } } instructions.forEach { instruction -> when (instruction) { is Instruction.Rotate -> state = state.changeDir(instruction) is Instruction.Forward -> forward(instruction) } } return (state.y + 1) * 1000 + (state.x + 1) * 4 + state.vdir.ordinal } fun part1(input: String): Int { fun handleEmpty(grid: Array<Array<GridType>>, oldState: State, newState: State) = when (newState.vdir) { Dir.RIGHT -> newState.copy(x = grid[newState.y].indexOfFirst { it != GridType.EMPTY }) Dir.DOWN -> newState.copy(y = grid.indexOfFirst { it.getOrElse(newState.x) { GridType.EMPTY } != GridType.EMPTY }) Dir.LEFT -> newState.copy(x = grid[newState.y].size - 1) Dir.UP -> newState.copy(y = grid.indexOfLast { it.getOrElse(newState.x) { GridType.EMPTY } != GridType.EMPTY }) } return solve(input, ::handleEmpty) } fun part2(input: String): Int { val isTest = input.length <200 val cubeSize = if (isTest) 4 else 50 val cubeMap = if (isTest) testCubeMap() else actualCubeMap() fun getRegion(state: State): Pair<Int, Int> = (state.y / cubeSize) to (state.x / cubeSize) fun getXYInRegion(region: Pair<Int, Int>, state:State) = Pair( state.x - region.second * cubeSize, state.y - region.first * cubeSize ) fun handleEmpty(grid: Array<Array<GridType>>, oldState: State, newState: State): State { val region = getRegion(oldState) val (xInRegion, yInRegion) = getXYInRegion(region, oldState) val other = cubeMap.getValue(region).getValue(newState.vdir) val rotate = (newState.rot + other.second.ordinal + 2 - newState.vdir.ordinal).mod(Dir.values().size) val pos = when (newState.vdir) { Dir.UP -> xInRegion Dir.RIGHT -> yInRegion Dir.DOWN -> cubeSize - 1 - xInRegion Dir.LEFT -> cubeSize - 1 - yInRegion } val state = when (other.second) { Dir.UP -> newState.copy( x = (other.first.second + 1) * cubeSize - 1 - pos, y = other.first.first * cubeSize, rot = rotate ) Dir.RIGHT -> newState.copy( x = (other.first.second + 1) * cubeSize -1, y = (other.first.first + 1) * cubeSize - 1 - pos, rot = rotate ) Dir.DOWN -> newState.copy( x = other.first.second * cubeSize + pos, y = (other.first.first + 1) * cubeSize - 1, rot = rotate ) Dir.LEFT -> newState.copy( x = other.first.second * cubeSize, y = other.first.first * cubeSize + pos, rot = rotate ) } return state } return solve(input, ::handleEmpty) } private fun actualCubeMap(): Map<Pair<Int, Int>, Map<Dir, Pair<Pair<Int, Int>, Dir>>> { /* +C-++-D+ |0 ||0 | A 1|| 2F +--++G-+ +--+ |1 G B 1| +--+ +-B++--+ A2 ||2 F | 0|| 1| +--++E-+ +--+ C3 E | 0| +-D+ */ val cubeMap = mapOf( Pair(0, 1) to mapOf( Dir.LEFT to Pair(Pair(2, 0), Dir.LEFT), //A Dir.UP to Pair(Pair(3, 0), Dir.LEFT), //C ), Pair(0, 2) to mapOf( Dir.UP to Pair(Pair(3, 0), Dir.DOWN), //D Dir.RIGHT to Pair(Pair(2, 1), Dir.RIGHT), //F Dir.DOWN to Pair(Pair(1, 1), Dir.RIGHT), //G ), Pair(1, 1) to mapOf( Dir.LEFT to Pair(Pair(2, 0), Dir.UP), //B Dir.RIGHT to Pair(Pair(0, 2), Dir.DOWN), //G ), Pair(2, 0) to mapOf( Dir.LEFT to Pair(Pair(0, 1), Dir.LEFT), //A Dir.UP to Pair(Pair(1, 1), Dir.LEFT), //B ), Pair(2, 1) to mapOf( Dir.RIGHT to Pair(Pair(0, 2), Dir.RIGHT), //F Dir.DOWN to Pair(Pair(3, 0), Dir.RIGHT), //E ), Pair(3, 0) to mapOf( Dir.LEFT to Pair(Pair(0, 1), Dir.UP), //C Dir.DOWN to Pair(Pair(0, 2), Dir.UP), //D Dir.RIGHT to Pair(Pair(2, 1), Dir.DOWN), //e ), ) assert(cubeMap.all { it.value.all { inner -> cubeMap.getValue(inner.value.first).getValue(inner.value.second).first == it.key } }) return cubeMap } } private fun testCubeMap(): Map<Pair<Int, Int>, Map<Day22.Dir, Pair<Pair<Int, Int>, Day22.Dir>>> { /* +B-+ |0 C A 2| +--+ +-B++-A++--+ E1 ||1 ||1 | | 0|| 1|| 2D +-F++-G++--+ +--++D-+ G2 ||2 | | 2|| 3C +-F++-E+ */ val cubeMap = mapOf( Pair(0, 2) to mapOf( Day22.Dir.LEFT to Pair(Pair(1, 1), Day22.Dir.UP), //A Day22.Dir.UP to Pair(Pair(1, 0), Day22.Dir.UP), //B Day22.Dir.RIGHT to Pair(Pair(2, 3), Day22.Dir.RIGHT), //C ), Pair(1, 0) to mapOf( Day22.Dir.UP to Pair(Pair(0, 2), Day22.Dir.UP), //B Day22.Dir.LEFT to Pair(Pair(2, 3), Day22.Dir.DOWN), //E Day22.Dir.DOWN to Pair(Pair(2, 2), Day22.Dir.DOWN), //F ), Pair(1, 1) to mapOf( Day22.Dir.UP to Pair(Pair(0, 2), Day22.Dir.LEFT), //A Day22.Dir.DOWN to Pair(Pair(2, 2), Day22.Dir.LEFT), //G ), Pair(1, 2) to mapOf( Day22.Dir.RIGHT to Pair(Pair(2, 3), Day22.Dir.UP), //D ), Pair(2, 2) to mapOf( Day22.Dir.LEFT to Pair(Pair(1, 1), Day22.Dir.DOWN), //G Day22.Dir.DOWN to Pair(Pair(1, 0), Day22.Dir.DOWN), //F ), Pair(2, 3) to mapOf( Day22.Dir.UP to Pair(Pair(1, 2), Day22.Dir.RIGHT), //D Day22.Dir.RIGHT to Pair(Pair(0, 2), Day22.Dir.RIGHT), //C Day22.Dir.DOWN to Pair(Pair(1, 0), Day22.Dir.LEFT), //E ), ) assert(cubeMap.all { it.value.all { inner -> cubeMap.getValue(inner.value.first).getValue(inner.value.second).first == it.key } }) return cubeMap }
0
Kotlin
0
0
e9bd07770ccf8949f718a02db8d09daf5804273d
9,250
aoc-kotlin
Apache License 2.0
src/Day14.kt
ech0matrix
572,692,409
false
{"Kotlin": 116274}
fun main() { fun setupCave(input: List<String>): MutableSet<Coordinates> { val cave = mutableSetOf<Coordinates>() for(formation in input) { val parts = formation .split(" -> ") .map { it.split(',') } .map { Coordinates(it[1].toInt(), it[0].toInt()) } for(i in 0 until parts.size-1) { val first = parts[i] val second = parts[i+1] if (first.col == second.col) { // Vertical line val startRow = minOf(first.row, second.row) val endRow = maxOf(first.row, second.row) for(row in startRow .. endRow) { cave.add(Coordinates(row, first.col)) } } else if (first.row == second.row) { // Horizontal line val startCol = minOf(first.col, second.col) val endCol = maxOf(first.col, second.col) for(col in startCol .. endCol) { cave.add(Coordinates(first.row, col)) } } else { throw IllegalArgumentException("Expected lines to only be horizontal or vertical") } } } return cave } fun part1(input: List<String>): Int { val cave = setupCave(input) val sandStart = Coordinates(0, 500) var currentSand = sandStart var sandCount = 0 val bottomRow = cave.maxOf { it.row } while(currentSand.row < bottomRow) { val down = currentSand.add(Coordinates(1, 0)) val left = currentSand.add(Coordinates(1, -1)) val right = currentSand.add(Coordinates(1, 1)) if (!cave.contains(down)) { currentSand = down } else if (!cave.contains(left)) { currentSand = left } else if (!cave.contains(right)) { currentSand = right } else { // Sand can't move cave.add(currentSand) sandCount++ currentSand = sandStart } } return sandCount } fun part2(input: List<String>): Int { val cave = setupCave(input) val sandStart = Coordinates(0, 500) var currentSand = sandStart var sandCount = 0 val bottomRow = cave.maxOf { it.row } while(true) { val down = currentSand.add(Coordinates(1, 0)) val left = currentSand.add(Coordinates(1, -1)) val right = currentSand.add(Coordinates(1, 1)) if (currentSand.row == bottomRow + 1) { // Sand sitting on floor cave.add(currentSand) sandCount++ currentSand = sandStart } else if (!cave.contains(down)) { currentSand = down } else if (!cave.contains(left)) { currentSand = left } else if (!cave.contains(right)) { currentSand = right } else { // Sand can't move cave.add(currentSand) sandCount++ if (currentSand == sandStart) { // Current sand just filled the top spot. Done. break } currentSand = sandStart } } return sandCount } val testInput = readInput("Day14_test") check(part1(testInput) == 24) check(part2(testInput) == 93) val input = readInput("Day14") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
50885e12813002be09fb6186ecdaa3cc83b6a5ea
3,725
aoc2022
Apache License 2.0
advent-of-code-2022/src/main/kotlin/Day03.kt
jomartigcal
433,713,130
false
{"Kotlin": 72459}
//Day 03: Rucksack Reorganization //https://adventofcode.com/2022/day/3 import java.io.File fun main() { val rucksacks = File("src/main/resources/Day03.txt").readLines() reorganizeRucksacks(rucksacks) reorganizeRucksacksByGroup(rucksacks.chunked(3)) } private fun reorganizeRucksacks(rucksacks: List<String>) { val priorities = rucksacks.sumOf { items -> val compartment1 = items.take(items.length / 2).toSet() val compartment2 = items.drop(items.length / 2).toSet() getPriority(compartment1 intersect compartment2) } println(priorities) } fun reorganizeRucksacksByGroup(groups: List<List<String>>) { val priorities = groups.sumOf { group -> val common = group.first().toSet() intersect group[1].toSet() intersect group.last().toSet() getPriority(common) } println(priorities) } private fun getPriority(chars: Set<Char>): Int { return chars.sumOf { char -> if (char in 'a'..'z') char.code - 96 else char.code - 38 } }
0
Kotlin
0
0
6b0c4e61dc9df388383a894f5942c0b1fe41813f
1,023
advent-of-code
Apache License 2.0
src/main/kotlin/g0601_0700/s0688_knight_probability_in_chessboard/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g0601_0700.s0688_knight_probability_in_chessboard // #Medium #Dynamic_Programming #2023_02_20_Time_144_ms_(100.00%)_Space_34.9_MB_(100.00%) class Solution { private val directions = arrayOf( intArrayOf(-2, -1), intArrayOf(-2, 1), intArrayOf(-1, 2), intArrayOf(1, 2), intArrayOf(2, -1), intArrayOf(2, 1), intArrayOf(1, -2), intArrayOf(-1, -2) ) private lateinit var probabilityGiven: Array<Array<DoubleArray>> fun knightProbability(n: Int, k: Int, row: Int, column: Int): Double { probabilityGiven = Array(n) { Array(n) { DoubleArray( k + 1 ) } } return probability(row, column, k, n) } private fun probability(row: Int, column: Int, k: Int, n: Int): Double { return if (k == 0) { 1.0 } else if (probabilityGiven[row][column][k] != 0.0) { probabilityGiven[row][column][k] } else { var p = 0.0 for (dir in directions) { if (isValid(row + dir[0], column + dir[1], n)) { p += probability(row + dir[0], column + dir[1], k - 1, n) } } probabilityGiven[row][column][k] = p / 8.0 probabilityGiven[row][column][k] } } private fun isValid(row: Int, column: Int, n: Int): Boolean { return row in 0 until n && column >= 0 && column < n } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,516
LeetCode-in-Kotlin
MIT License
src/main/kotlin/Problem7.kt
jimmymorales
496,703,114
false
{"Kotlin": 67323}
import kotlin.math.floor import kotlin.math.sqrt import kotlin.system.measureNanoTime /** * 10001st prime * * By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. * * What is the 10001st prime number? * * https://projecteuler.net/problem=7 */ fun main() { println(findPrime1(6)) println(findPrime(6)) val time1 = measureNanoTime { println(findPrime1(10_001)) } val time2 = measureNanoTime { println(findPrime(10_001)) } println(time1) println(time2) } private fun findPrime1(n: Int): Long { var prime = 2L val primes = mutableListOf(prime) while (primes.size != n) { prime++ if (!primes.any { prime % it == 0L }) { primes.add(prime) } } return prime } fun findPrime(n: Int): Long { if (n == 1) return 2 var count = 1 var candidate = 1L do { candidate += 2 if (isPrime(candidate)) count++ } while (count != n) return candidate } fun isPrime(n: Long): Boolean { return when { n < 2 -> false // 1 is not prime n < 4 -> true // 2 and 3 are prime n % 2 == 0L -> false // all primes except 2 are odd n < 9 -> true // we have already excluded 4. 6 and 8 n % 3 == 0L -> false else -> { // All primes greater than 3 can be written in the form 6k+/-1. val r = floor(sqrt(n.toDouble())).toLong() for (f in 5L .. r step 6) { if (n % f == 0L) return false if (n % (f + 2) == 0L) return false } true } } }
0
Kotlin
0
0
e881cadf85377374e544af0a75cb073c6b496998
1,640
project-euler
MIT License
src/main/kotlin/aoc2022/Day19.kt
w8mr
572,700,604
false
{"Kotlin": 140954}
package aoc2022 import aoc.* import aoc.parser.* class Day19() { //Blueprint 1: Each ore robot costs 4 ore. Each clay robot costs 2 ore. Each obsidian robot costs 3 ore and 14 clay. Each geode robot costs 2 ore and 7 obsidian. enum class Material { ORE, CLAY, OBSIDIAN, GEODE } data class Cost(val amount: Int, val material: Material) data class BuildInstruction(val type: Material, val costs: Map<Material, Cost>) data class Blueprint(val index: Int, val buildInstruction: Map<Material, BuildInstruction>) data class BlueprintInt(val index: Int, val oreRobotOre: Int, val clayRobotOre: Int, val obsidianRobotOre: Int, val obsidianRobotClay: Int, val geodeRobotOre: Int, val geodeRobotObsidian: Int) fun blueprint(index: Int, buildInstruction: Map<Material, BuildInstruction>): BlueprintInt { fun amount(buildInstruction: Map<Material, BuildInstruction>, robot: Material, material: Material) = buildInstruction[robot]?.costs?.get(material)?.amount ?: 0 return BlueprintInt(index, amount(buildInstruction, Material.ORE, Material.ORE), amount(buildInstruction, Material.CLAY, Material.ORE), amount(buildInstruction, Material.OBSIDIAN, Material.ORE), amount(buildInstruction, Material.OBSIDIAN, Material.CLAY), amount(buildInstruction, Material.GEODE, Material.ORE), amount(buildInstruction, Material.GEODE, Material.OBSIDIAN) ) } val material = byEnum(Material::class) val index = "Blueprint " followedBy number() followedBy ":" val cost = seq(number(), " " followedBy material, ::Cost) val costs = cost sepBy " and " map { it.associateBy(Cost::material) } val build = seq(" Each " followedBy material, " robot costs " followedBy costs, ::BuildInstruction) followedBy "." val builds = zeroOrMore(build) map { it.associateBy(BuildInstruction::type) } val line = seq(index, builds, ::blueprint) followedBy "\n" val parser = zeroOrMore(line) fun BlueprintInt.score(timeLeft: Int): Int { val robotCosts = listOf( listOf(oreRobotOre, 0, 0, 0), listOf(clayRobotOre, 0, 0, 0), listOf(obsidianRobotOre, obsidianRobotClay, 0, 0), listOf(geodeRobotOre, 0, geodeRobotObsidian, 0)) val maxOreNeeded = maxOf(oreRobotOre, clayRobotOre, obsidianRobotOre, geodeRobotOre) val maxNeeded = listOf(maxOreNeeded, obsidianRobotClay, geodeRobotObsidian, timeLeft) fun go( timeLeft: Int, robots: List<Int>, amounts: List<Int> ): Int { if (timeLeft <= 0) { return amounts[3] } fun goGeneric(robotIdx: Int) = if ((robots[robotIdx] >= maxNeeded[robotIdx])) 0 else { val canBuild = (0..3).all { costIdx -> robotCosts[robotIdx][costIdx] == 0 || robots[costIdx] > 0 } if (!canBuild) 0 else { val timeNeeded = (0..3).maxOf { costIdx -> if (robotCosts[robotIdx][costIdx] <= 0) 0 else maxOf( 0, robotCosts[robotIdx][costIdx] - amounts[costIdx] + robots[costIdx] - 1 ) / robots[costIdx] } + 1 if (timeLeft - timeNeeded < 0) { if (robots[3] == 0) 0 else amounts[3] + timeLeft * robots[3] } else { val newRobots = robots.mapIndexed { index, count -> if (robotIdx == index) count + 1 else count} val newAmounts = amounts.mapIndexed { index, amount -> amount + timeNeeded * robots[index] - robotCosts[robotIdx][index]} go( timeLeft - timeNeeded, newRobots, newAmounts ) } } } return (0..3).maxOf(::goGeneric) } val result = go(timeLeft, listOf(1, 0, 0, 0), listOf(0, 0, 0, 0)) println("Blueprint $index: ${result}") return result } fun part1(input: String): Int { val parsed = parser.parse(input) return parsed.sumOf { it.index * it.score(24) } } fun part2(input: String): Int { val parsed = parser.parse(input) return parsed.take(3).map { it.score(32) }.product() } } /* fun BlueprintInt.score(timeLeft: Int): Int { val maxOreNeeded = maxOf(oreRobotOre, clayRobotOre, obsidianRobotOre, geodeRobotOre) fun go(timeLeft: Int, oreRobots: Int, clayRobots: Int, obsidianRobots: Int, geodeRobots: Int, oreAmount: Int, clayAmount: Int, obsidianAmount: Int, geodeAmount: Int ): Int { if (timeLeft <= 0) { return geodeAmount } fun goOre() = if (oreRobots >= maxOreNeeded) 0 else { val timeNeeded = (maxOf(0, oreRobotOre - oreAmount + oreRobots - 1) / oreRobots) + 1 if (timeLeft - timeNeeded <0) geodeAmount else go( timeLeft - timeNeeded, oreRobots + 1, clayRobots, obsidianRobots, geodeRobots, oreAmount + timeNeeded * oreRobots - oreRobotOre, clayAmount + timeNeeded * clayRobots, obsidianAmount + timeNeeded * obsidianRobots, geodeAmount + timeNeeded * geodeRobots ) } fun goClay() = if (clayRobots >= obsidianRobotClay) 0 else { val timeNeeded = (maxOf(0, clayRobotOre - oreAmount + oreRobots - 1) / oreRobots) + 1 if (timeLeft - timeNeeded <0) geodeAmount else go( timeLeft - timeNeeded, oreRobots, clayRobots + 1, obsidianRobots, geodeRobots, oreAmount + timeNeeded * oreRobots - clayRobotOre, clayAmount + timeNeeded * clayRobots, obsidianAmount + timeNeeded * obsidianRobots, geodeAmount + timeNeeded * geodeRobots ) } fun goObsidian() = if ((obsidianRobots >= geodeRobotObsidian) || (clayRobots ==0)) 0 else { val timeNeededOre = (maxOf(0, obsidianRobotOre - oreAmount + oreRobots - 1) / oreRobots) val timeNeededClay = (maxOf( 0, obsidianRobotClay - clayAmount + clayRobots - 1) / clayRobots) val timeNeeded = maxOf(timeNeededOre, timeNeededClay) + 1 if (timeLeft - timeNeeded <0) geodeAmount else go( timeLeft - timeNeeded, oreRobots, clayRobots, obsidianRobots + 1, geodeRobots, oreAmount + timeNeeded * oreRobots - obsidianRobotOre, clayAmount + timeNeeded * clayRobots - obsidianRobotClay, obsidianAmount + timeNeeded * obsidianRobots, geodeAmount + timeNeeded * geodeRobots ) } fun goGeode() = if (obsidianRobots == 0) 0 else { val timeNeededOre = (maxOf(0, geodeRobotOre - oreAmount + oreRobots - 1) / oreRobots) val timeNeededObsidian = (maxOf(0, geodeRobotObsidian - obsidianAmount + obsidianRobots - 1) / obsidianRobots) val timeNeeded = maxOf(timeNeededOre, timeNeededObsidian) + 1 if (timeLeft - timeNeeded <0) geodeAmount + geodeRobots * timeLeft else go( timeLeft - timeNeeded, oreRobots, clayRobots, obsidianRobots, geodeRobots + 1, oreAmount + timeNeeded * oreRobots - geodeRobotOre, clayAmount + timeNeeded * clayRobots, obsidianAmount + timeNeeded * obsidianRobots - geodeRobotObsidian, geodeAmount + timeNeeded * geodeRobots ) } val tries = listOf( goOre(), goClay(), goObsidian(), goGeode() ) val best = tries.max() return best } val result = go(timeLeft, 1, 0, 0, 0, 0, 0, 0, 0) println("Blueprint $index: ${result}") return result } */ /* fun BlueprintInt.scoreBreathFirst(timeLeft: Int): Int { data class State(val time: Int = 0, val robots: List<Int> = listOf(1, 0, 0, 0), val amounts: List<Int> = listOf(0, 0, 0, 0), val score: Int = 0, val oldState : State? = null) val queue: Queue<State> = LinkedList() val seen = mutableSetOf<State>() val maxNeeded = listOf(maxOf(oreRobotOre, clayRobotOre, obsidianRobotOre, geodeRobotOre), obsidianRobotClay, geodeRobotObsidian, timeLeft) val initialState = State() queue.add(initialState) var maxState = initialState val robotCosts = listOf( listOf(oreRobotOre, 0, 0, 0), listOf(clayRobotOre, 0, 0, 0), listOf(obsidianRobotOre, obsidianRobotClay, 0, 0), listOf(geodeRobotOre, 0, geodeRobotObsidian, 0)) while (queue.isNotEmpty()) { val state = queue.remove() seen.add(state) val (time, robots, amounts, score) = state (0..3).forEach { robotIdx -> if ((robots[robotIdx]<maxNeeded[robotIdx])) { val canBuild = (0..3).all { costIdx -> robotCosts[robotIdx][costIdx] == 0 || (robots[costIdx] > 0) } if (canBuild) { val timeTillBuild = (0..3).maxOf { costIdx -> if (robots[costIdx] <= 0) 0 else maxOf(0, robotCosts[robotIdx][costIdx] - amounts[costIdx] + robots[costIdx] - 1) / robots[costIdx] } + 1 val newTime = time + timeTillBuild if (newTime <= timeLeft) { val newRobots = robots.mapIndexed { index, i -> if (index == robotIdx) i + 1 else i } val newAmounts = amounts.mapIndexed { index, i -> i - robotCosts[robotIdx][index] + timeTillBuild * robots[index] } val newScore = newAmounts[3] + newRobots[3] * (timeLeft - newTime) val newState = State(newTime, newRobots, newAmounts, newScore, state) if (newState !in seen) queue.add(newState) } } } } if (score > maxState.score) { maxState = state } } println("Blueprint $index: ${maxState.score} ($maxState)") return maxState.score } */
0
Kotlin
0
0
e9bd07770ccf8949f718a02db8d09daf5804273d
11,813
aoc-kotlin
Apache License 2.0
src/main/kotlin/be/swsb/aoc2021/day7/Day7.kt
Sch3lp
433,542,959
false
{"Kotlin": 90751}
package be.swsb.aoc2021.day7 import kotlin.math.* object Day7 { fun solve1(input: List<Int>): Fuel { return findMostOptimalCost(input) } fun solve2(input: List<Int>): Fuel { return findMostOptimalCost2(input) } } fun findMostOptimalCost(positions: List<Position>): Fuel { val crabInTheMiddle: Position = positions.sorted()[positions.size / 2] return positions.fold(0) { acc, cur -> acc + cur.diff(crabInTheMiddle) } } fun calculateFuelSpent(pos1: Position, pos2: Position): Fuel { val steps = pos1.diff(pos2) fun fuelExpenditureFor(steps: Int): Fuel { return steps * (steps + 1) / 2 } return fuelExpenditureFor(steps) } fun findMostOptimalCost2(positions: List<Int>): Fuel { val average = positions.average() val probablyBestPosRoundedDown = floor(average).toInt() val probablyBestPosRoundedUp = ceil(average).toInt() val optimalFuelCostWithRoundingDown = positions.fold(0) { acc, cur -> acc + calculateFuelSpent(cur, probablyBestPosRoundedDown) } val optimalFuelCostWithRoundingUp = positions.fold(0) { acc, cur -> acc + calculateFuelSpent(cur, probablyBestPosRoundedUp) } return min(optimalFuelCostWithRoundingDown, optimalFuelCostWithRoundingUp) } fun Position.diff(other: Position): Fuel = abs(this - other) typealias Position = Int typealias Fuel = Int
0
Kotlin
0
0
7662b3861ca53214e3e3a77c1af7b7c049f81f44
1,373
Advent-of-Code-2021
MIT License
src/Day21.kt
Allagash
572,736,443
false
{"Kotlin": 101198}
import java.io.File // Advent of Code 2022, Day 21: Monkey Math class Day21(input: String) { data class Day21Exp(val name: String, var value: Long? = null, var var1: String? = null, var op:Char? = null, var var2: String? = null) companion object { private val DAY21_PATTERN_VAL = """(\w+): (\d+)""".toRegex() private val DAY21_PATTERN_EXP = """(\w+): (\w+) ([-+*/]) (\w+)""".toRegex() private const val HUMAN_ID = "humn" } private val expressions : Map<String, Day21Exp> init { expressions = input.split("\n").map { line -> if (line.contains("[-+*/]".toRegex())){ val (name, var1, op, var2) = requireNotNull(DAY21_PATTERN_EXP.matchEntire(line)) { line }.destructured Day21Exp(name, null, var1, op.first(), var2) } else { val (name, value) = requireNotNull(DAY21_PATTERN_VAL.matchEntire(line)) { line }.destructured Day21Exp(name, value.toLong()) } }.associateBy { it.name } } fun getValue(exp: Day21Exp) : Long { if (exp.value != null) return exp.value!! val val1 = getValue(expressions[exp.var1]!!) val val2 = getValue(expressions[exp.var2]!!) return when (exp.op) { '+' -> val1 + val2 '-' -> val1 - val2 '*' -> val1 * val2 '/' -> val1 / val2 else -> throw Exception("Bad op: ${exp.op}") } } private fun containsHuman(exp: Day21Exp): Boolean { if (exp.name == HUMAN_ID) return true if (exp.value != null) return false return containsHuman(expressions[exp.var1]!!) || containsHuman(expressions[exp.var2]!!) } private fun getHumanValue(exp: Day21Exp, matchVal: Long): Long { if (exp.value != null) { return if (exp.name == HUMAN_ID) matchVal else exp.value!! } val left = expressions[exp.var1]!! val right = expressions[exp.var2]!! val leftHasHuman = containsHuman(left) val rightHasHuman = containsHuman(right) check(leftHasHuman != rightHasHuman) var otherSideVal: Long val humanExp: Day21Exp if (leftHasHuman) { humanExp = left otherSideVal = getValue(right) } else { humanExp = right otherSideVal = getValue(left) } if (exp.name != "root") { if (leftHasHuman) { otherSideVal = when (exp.op) { '+' -> matchVal - otherSideVal '-' -> matchVal + otherSideVal '*' -> matchVal / otherSideVal '/' -> matchVal * otherSideVal else -> throw Exception("Bad op: ${exp.op}") } } else { otherSideVal = when (exp.op) { '+' -> matchVal - otherSideVal '-' -> otherSideVal - matchVal '*' -> matchVal / otherSideVal '/' -> otherSideVal / matchVal else -> throw Exception("Bad op: ${exp.op}") } } } return getHumanValue(humanExp, otherSideVal) } fun part1(): Long = getValue(expressions["root"]!!) fun part2(): Long = getHumanValue(expressions["root"]!!, 0) } fun main() { fun readInputAsOneLine(name: String) = File("src", "$name.txt").readText().trim() val testSolver = Day21(readInputAsOneLine("Day21_test")) check(testSolver.part1() == 152L) check(testSolver.part2() == 301L) val solver = Day21(readInputAsOneLine("Day21")) println(solver.part1()) println(solver.part2()) }
0
Kotlin
0
0
8d5fc0b93f6d600878ac0d47128140e70d7fc5d9
3,730
AdventOfCode2022
Apache License 2.0