path
stringlengths
5
169
owner
stringlengths
2
34
repo_id
int64
1.49M
755M
is_fork
bool
2 classes
languages_distribution
stringlengths
16
1.68k
content
stringlengths
446
72k
issues
float64
0
1.84k
main_language
stringclasses
37 values
forks
int64
0
5.77k
stars
int64
0
46.8k
commit_sha
stringlengths
40
40
size
int64
446
72.6k
name
stringlengths
2
64
license
stringclasses
15 values
src/main/kotlin/com/appdecay/kotlin/libenigma/utils/Alphanumeric.kt
appdecay
58,949,336
false
null
package com.appdecay.kotlin.libenigma.utils import java.util.* fun Collection<Pair<Char, Char>>.clean(): Collection<Pair<Char, Char>> = this.map { p -> if ((p.second).toInt() < (p.first).toInt()) Pair(p.second, p.first) else p }.sortedBy { it.first }.groupBy { it.first }.map { it.value.last() } fun Collection<Pair<Char, Char>>.toAlphaMap() = generateAlphaMap(this) fun generateAlphaMap(col: Collection<Pair<Char, Char>>): Map<Char, Char> = mutableMapOf<Char, Char>() .apply { col.cleanAlpha().forEach { it.toList().forEach { deleteBoth(it) } //putAll(arrayOf(it, it.reverse())) put(it.first, it.second) put(it.second, it.first) } } fun String.alphaArray(): CharArray = mutableSetOf<Char>().apply { filterUpper().forEach { add(it) } }.toCharArray() fun <K> MutableMap<K, K>.deleteBoth(element: K) { remove(element) filter { it.value == element }.keys.forEach { remove(it) } } fun <K : Comparable<K>> Map<K, K>.simplify(): List<Pair<K, K>> = mutableListOf<Pair<K, K>>().apply { for ((k, v) in this@simplify.toSortedMap()) { add(k to v) } }.filter { it.first < it.second } fun <K, V> Map<K, V>.pretty(): String = StringBuilder().apply { for ((k, v) in this@pretty) { append("$k->$v ") } }.toString() fun <T> Pair<T, T>.reverse() = second to first fun <T> Map<T, T>.valueOrSame(key: T) = get(key) ?: key fun Collection<Pair<Char, Char>>.cleanAlpha() = filter { it.toList().all { it.isAlpha() } }.map { it.first.toUpperCase() to it.second.toUpperCase() } fun String.cleanAlpha() = filter { it.isAlpha() }.toUpperCase() fun scrambled(): String = CharRange('A', 'Z').toMutableList().apply { Collections.shuffle(this) }.mergeString() fun String.generateAlphaMap(): Map<Char, Char> = upperAlphaRange.zip(cleanAlpha().toSet().plus(upperAlphaRange)).toMap() fun <K, V> Map<K, V>.forward(input: K): V? = get(input) fun <K, V> Map<K, V>.backward(output: V): K? = filter { it.value?.equals(output) ?: false }.map { it.key }.firstOrNull() fun <T> Collection<Map<T, T>>.forwardChain(input: T): T = fold(input) { acc, map -> map.forward(acc) ?: acc } fun <T> Collection<Map<T, T>>.backwardChain(input: T): T = reversed().fold(input) { acc, map -> map.backward(acc) ?: acc } fun Char.shiftAlpha(amount: Int = 1): Char = ((fromAlpha() + amount) % 26).toAlpha() fun Char.unshiftAlpha(amount: Int = 1): Char = ((fromAlpha() + 26 - amount) % 26).toAlpha() fun Char.fromAlpha(): Int = (this - 65).toInt() fun Int.toAlpha(): Char = (this + 65).toChar() inline fun <reified T> T.toLog(tag: String = "") = apply { println("$tag [${T::class}]: $this") } val upperAlphaRange = CharRange('A', 'Z') val lowerAlphaRange = CharRange('a', 'z') fun <T> Iterable<T>.mergeString(): String = joinToString(separator = "") fun Char.deviation(): Int? = if (toUpperCase() in upperAlphaRange) this - 'A' else null fun Char.isAlpha() = this in upperAlphaRange || this in lowerAlphaRange fun genString(block: StringBuilder.() -> Unit) = StringBuilder().apply(block).toString() fun String.filterUpper() = filter { it.isAlpha() }.map { it.toUpperCase() }.mergeString() fun String.alphaPad(count: Int = 3) = if (length < count) plus((1..(count - length)).map { 'A' }.joinToString(separator = "")) else take(count)
0
Kotlin
0
0
e84d487ec0b7f9c04613f09e5f336b5837372fac
3,403
kotlin-geheim
Apache License 2.0
year2023/day08/wasteland/src/main/kotlin/com/curtislb/adventofcode/year2023/day08/wasteland/WastelandNetwork.kt
curtislb
226,797,689
false
{"Kotlin": 2146738}
package com.curtislb.adventofcode.year2023.day08.wasteland import com.curtislb.adventofcode.common.io.forEachSection import java.io.File /** * A network of nodes and a list of instructions for navigating through the haunted wasteland. * * @property instructions A list of instructions that must be followed in order to move through the * wasteland. * @property nodePaths A map from each node in the network to a pair of nodes that can be reached by * following a left or right [Instruction] (respectively) from that node. * * @constructor Creates a new instance of [WastelandNetwork] with the given [instructions] and * [nodePaths]. */ class WastelandNetwork( private val instructions: List<Instruction>, private val nodePaths: Map<String, Pair<String, String>> ) { /** * All unique nodes in the network. */ val nodes: Set<String> get() = nodePaths.keys /** * Returns the number of steps needed to reach a node for which the [isGoal] function returns * `true`, starting from the given [source] node. * * @throws IllegalArgumentException If [source] is not a node in the network. * @throws IllegalStateException If there are no paths from [source] or any intermediary node. */ fun distance(source: String, isGoal: (node: String) -> Boolean): Long { require(source in nodePaths) { "Source node must be in the network: $source" } var node = source var index = 0 var stepCount = 0L while (!isGoal(node)) { // Follow the current left/right instruction val paths = nodePaths[node] ?: error("No paths from node: $node") node = when (instructions[index]) { Instruction.LEFT -> paths.first Instruction.RIGHT -> paths.second } // Advance the instruction index and step count index = (index + 1) % instructions.size stepCount++ } return stepCount } companion object { /** * A regex used to parse the available paths for each network node. */ private val PATHS_REGEX = Regex("""(\w+) = \((\w+), (\w+)\)""") /** * Returns a [WastelandNetwork] with instructions and node paths read from the given [file]. * * The [file] must have the following format, where `instructions` is an ordered sequence of * characters representing [Instruction]s, and each `node` line represents a node in the * network and the nodes that can be reached by traveling `left` or `right` from it: * * ``` * $instructions * * $node1 = ($left1, $right1) * $node2 = ($left2, $right2) * ... * $nodeN = ($leftN, $rightN) * ``` * * @throws IllegalArgumentException If [file] has the wrong format. */ fun fromFile(file: File): WastelandNetwork { val instructions = mutableListOf<Instruction>() val nodePaths = mutableMapOf<String, Pair<String, String>>() file.forEachSection { lines -> if (instructions.isEmpty()) { // Read instructions from the first line for (char in lines[0]) { instructions.add(Instruction.fromChar(char)) } } else { // Read node paths from subsequent lines for (line in lines) { val matchResult = PATHS_REGEX.matchEntire(line) require(matchResult != null) { "Malformed node paths: $line" } val (node, left, right) = matchResult.destructured nodePaths[node] = Pair(left, right) } } } return WastelandNetwork(instructions, nodePaths) } } }
0
Kotlin
1
1
6b64c9eb181fab97bc518ac78e14cd586d64499e
3,949
AdventOfCode
MIT License
lib/src/main/kotlin/utils/Vec2l.kt
madisp
434,510,913
false
{"Kotlin": 388138}
package utils import kotlin.math.abs data class Vec2l(val x: Long, val y: Long) { val adjacent get() = listOf( copy(x = x - 1), copy(x = x + 1), copy(y = y - 1), copy(y = y + 1) ) val surrounding get() = grow().filter { (x, y) -> x != this.x || y != this.y } fun grow(amount: Long = 1) = (x - amount .. x + amount).flatMap { nx -> (y - amount .. y + amount).map { ny -> Vec2l(nx, ny) } } fun rotateCw() = Vec2l(y, -x) fun rotateCcw() = Vec2l(-y, x) operator fun plus(other: Vec2l) = Vec2l(this.x + other.x, this.y + other.y) operator fun times(scalar: Long) = Vec2l(this.x * scalar, this.y * scalar) operator fun plus(scalar: Long) = Vec2l(this.x + scalar, this.y + scalar) operator fun div(scalar: Long) = Vec2l(this.x / scalar, this.y / scalar) operator fun rem(other: Vec2l) = Vec2l(this.x % other.x, this.y % other.y) fun manhattanDistanceTo(other: Vec2l): Long { return (abs(other.x - x) + abs(other.y - y)) } companion object { fun parse(str: String, delimiter: String = ","): Vec2l { return str.cut(delimiter, String::toLong, String::toLong, ::Vec2l) } val UP = Vec2l(0, -1) val DOWN = Vec2l(0, 1) val LEFT = Vec2l(-1, 0) val RIGHT = Vec2l(1, 0) } } val Collection<Vec2l>.bounds: Pair<Vec2l, Vec2l> get() { return Vec2l(minOf { it.x }, minOf { it.y }) to Vec2l(maxOf { it.x }, maxOf { it.y }) } data class SegmentL(val start: Vec2l, val end: Vec2l) { val isVertical = start.x == end.x val isHorizontal = start.y == end.y val slope: Long get() = (end.y - start.y) / (end.x - start.x) val points: List<Vec2l> get() = when { isVertical -> (minOf(start.y, end.y) .. maxOf(start.y, end.y)).map { y -> Vec2l(start.x, y) } else -> (minOf(start.x, end.x) .. maxOf(start.x, end.x)).map { x -> get(x) } } operator fun get(x: Long): Vec2l { if (isVertical) { throw IllegalStateException("Can not get point by x for a vertical line") } val dx = (x - start.x) val y = start.y + dx * slope return Vec2l(x, y) } operator fun contains(p: Vec2l): Boolean { if (p.y !in (minOf(start.y, end.y) .. maxOf(start.y, end.y))) { return false } if (p.x !in (start.x .. end.x)) { return false } // vertical line if (end.x == start.x) { return true // p.x is always start.x due to the bounds check above } else { return this[p.x] == p } } }
0
Kotlin
0
1
3f106415eeded3abd0fb60bed64fb77b4ab87d76
2,448
aoc_kotlin
MIT License
app/src/main/kotlin/advent_of_code/year_2022/day4/CampCleanup.kt
mavomo
574,441,138
false
{"Kotlin": 56468}
package advent_of_code.year_2022.day4 class CampCleanup { fun countTotalFullyOverlapingSections(puzzle: List<String>): Int { var totalOverlappingSectors = 0 puzzle.forEach { val commonSector = getCommonAssignedSections(it) if (commonSector.second) { totalOverlappingSectors++ } } return totalOverlappingSectors } fun countTotalPartiallyOverlapingSections(puzzle: List<String>): Int { var partialOverlappingSectors = 0 puzzle.forEach { val commonSector = getCommonAssignedSections2(it) if (commonSector.first.isNotEmpty()) { partialOverlappingSectors++ } } return partialOverlappingSectors } fun getCommonAssignedSections(assignment: String): Pair<Set<Int>, Boolean> { val assignmentPerGroup = assignment.split(",") val firstPairSection = assignmentPerGroup.first().split("-").map { it.toInt() } val secondPairSection = assignmentPerGroup.last().split("-").map { it.toInt() } val fullSectorForFirstGroup = (firstPairSection.first()..firstPairSection.last()).toSet() val fullSectorForTheOtherGroup = (secondPairSection.first()..secondPairSection.last()).toSet() val commonSectors = fullSectorForTheOtherGroup.intersect(fullSectorForFirstGroup) val isFullyContained = fullSectorForFirstGroup.containsAll(fullSectorForTheOtherGroup) || fullSectorForTheOtherGroup.containsAll( fullSectorForFirstGroup ) return Pair(commonSectors, isFullyContained) } private fun getCommonAssignedSections2(assignment: String): Pair<Set<Int>, Boolean> { val assignmentPerGroup = assignment.split(",") val firstPairSection = assignmentPerGroup.first().split("-").map { it.toInt() } val secondPairSection = assignmentPerGroup.last().split("-").map { it.toInt() } val fullSectorForFirstGroup = (firstPairSection.first()..firstPairSection.last()).toSet() val fullSectorForTheOtherGroup = (secondPairSection.first()..secondPairSection.last()).toSet() val commonSectors = fullSectorForTheOtherGroup.intersect(fullSectorForFirstGroup) return Pair(commonSectors, false) } }
0
Kotlin
0
0
b7fec100ea3ac63f48046852617f7f65e9136112
2,315
advent-of-code
MIT License
src/main/kotlin/year2022/day22/CubeWalker3D.kt
Ddxcv98
573,823,241
false
{"Kotlin": 154634}
package year2022.day22 import util.intSqrt import util.rotatedCounterClockwise class CubeWalker3D( private val transitions: Array<Array<Pair<Int, Int>>>, matrix: Array<Array<Char>> ) : CubeWalker<Pos3D> { private val n: Int = intSqrt(matrix.sumOf { chars -> chars.count { c -> c != ' ' } } / 6) private val faces = Array(6) { Array(4) { Array(n) { Array(n) { '\u0000' } } } } private val offsets = arrayOfNulls<Pair<Int, Int>>(6) init { var f = 0 for (i in matrix.indices step n) { for (j in matrix[i].indices step n) { if (matrix[i][j] == ' ') { continue } val face = faces[f] for (k in 0 until n) { for (l in 0 until n) { face[0][k][l] = matrix[i + k][j + l] } } face[1] = rotatedCounterClockwise(face[0]) face[2] = rotatedCounterClockwise(face[1]) face[3] = rotatedCounterClockwise(face[2]) offsets[f++] = Pair(j, i) } } } override fun walk(pos: Pos3D, steps: Int) { var f = pos.f var r = pos.r for (i in 0 until steps) { val x = (pos.x + 1).mod(n) if (x == 0) { val pair = transitions[f][r] f = pair.first r = pair.second } if (faces[f][r][pos.y][x] == '#') { break } pos.f = f pos.r = r pos.x = x } } override fun rotate(pos: Pos3D, r: Char) { when (r) { 'L' -> pos.rotateClockwise(n) 'R' -> pos.rotateCounterClockwise(n) } } override fun toPos2D(pos: Pos3D): Pos2D { val (offsetX, offsetY) = offsets[pos.f]!! return Pos2D(pos.r, pos.x + offsetX, pos.y + offsetY) } }
0
Kotlin
0
0
455bc8a69527c6c2f20362945b73bdee496ace41
1,963
advent-of-code
The Unlicense
src/questions/BinaryStringWithSubstringsRep1ToN.kt
realpacific
234,499,820
false
null
package questions import _utils.UseCommentAsDocumentation import utils.shouldBe /** * Given a binary string s and a positive integer n, return true if the binary representation of all the integers * in the range [1, n] are substrings of s, or false otherwise. * A substring is a contiguous sequence of characters within a string. * * [Source](https://leetcode.com/problems/binary-string-with-substrings-representing-1-to-n/) */ @UseCommentAsDocumentation private fun queryString(s: String, n: Int): Boolean { /** * Given n, returns r such that r < n and 2^x=r where x is +ve integer */ fun findPowerOf2LowerThanN(): Int { var multiplication = 1 while (multiplication < n) { if (multiplication * 2 >= n) { return multiplication } multiplication *= 2 } return multiplication } val lowerPowerOf2 = findPowerOf2LowerThanN() // Theorem: If we can prove that s is substring of 4~n, s will contain substring for 1~n // Similarly, if we can prove that s is substring of 16~n, s will contain substring for 1~n // Similarly, if we can prove that s is substring of 32~n, s will contain substring for 1~n // We just have to prove this for n down to lower power of 2. for (i in n downTo lowerPowerOf2) { val binaryRep = Integer.toBinaryString(i) if (!s.contains(binaryRep)) return false } return true } fun main() { queryString(s = "100101110", n = 7) shouldBe true queryString(s = "0110", n = 3) shouldBe true queryString(s = "0110", n = 4) shouldBe false }
4
Kotlin
5
93
22eef528ef1bea9b9831178b64ff2f5b1f61a51f
1,625
algorithms
MIT License
src/test/kotlin/com/xy/algorithm/Complexity.kt
monkey1992
413,857,863
false
null
package com.xy.algorithm import org.junit.Test import kotlin.math.pow import kotlin.math.sqrt /** * 算法复杂度 */ class Complexity { /** * 算法复杂度示例-O(n²) */ @Test fun complexityNSquare() { val n = 10 val array = arrayOfNulls<IntArray>(n) for (i in 0 until n) { val arrayJ = IntArray(n) array[i] = arrayJ for (j in 0 until n) { arrayJ[j] = i * j println("array[$i][$j]=${array[i]!![j]}") } } } /** * 算法复杂度示例-O(n²) */ @Test fun complexityNSquare2() { val n = 10 println("=========九九乘法口诀表=========") for (i in 1 until n) { for (j in 1 until n) { if (j > i || i == 9) { println() break } print("$j * $i = ${i * j} ") } } println("=========九九乘法口诀表=========") } /** * 算法复杂度示例-O(logn) * 数字n转换为二进制数 */ @Test fun complexityLogN() { println("=========算法复杂度示例-O(logn)=========") var n = 1000 var s = "" while (n > 0) { s = (n % 2).toString() + s n /= 2 println("n=$n") } println("s = $s") println("=========算法复杂度示例-O(logn)=========") } /** * 算法复杂度示例-O(1) * 判断数字n是否是偶数 */ @Test fun complexity1() { val n = 1024 assert(n % 2 == 0) } /** * 算法复杂度示例-O(n) * 求数字n的所有约数 */ @Test fun complexityN() { val n = 1025 val list = mutableListOf<Int>() for (i in 1..n) { if (n % i == 0) { list.add(i) } } println("list is $list") } /** * 算法复杂度示例-O(√n) * 求数字n的所有约数 */ @Test fun complexitySqrtN() { val n = 1024 val list = mutableListOf<Int>() for (i in 1..sqrt(n.toFloat()).toInt()) { if (n % i == 0) { list.add(i) list.add(n / i) } } println("list is $list") } /** * 算法复杂度示例-O(2^n) * n个位数长度的所有二进制数 */ @Test fun complexitySquareN() { fun getB(x: Int, length: Int): String { var n = x var s = "" if (n > 0) { while (n > 0) { s = (n % 2).toString() + s n /= 2 } } else { s = 0.toString() } val sLength = s.length val lengthDiff = length - sLength if (lengthDiff > 0) { for (i in 0 until lengthDiff) { s = "0$s" } } return s } val n = 3 val list = mutableListOf<String>() for (i in 0 until 2.toDouble().pow(n.toDouble()).toInt()) { list.add(getB(i, 3)) } println("list is $list") } /** * 算法复杂度示例-O(n!) * 求元素个数为n的数组的所有排列 */ @Test fun complexitySquareNFactorial() { val array = arrayOf(8, 6, 12, 969, 67, 39) val size = array.size data class Node( val loopLayerIndex: Int, val arrayItem: Int ) for (i in 0..size) { for (j in 0..size) { if (j == i) { continue } for (k in 0..size) { if (k == i || k == j) { continue } for (l in 0..size) { if (l == i || l == j || l == k) { continue } } } } } val nodeArrays = emptyArray<Array<Node>>() val nodeArray = Array(size) { Node(-1, -1) } fun getFactorial(loopLayerIndex: Int) { for (i in 0..size) { nodeArray[i] = Node(loopLayerIndex, array[i]) } } getFactorial(0) } }
0
Kotlin
0
0
5d955911ecba67d7f38d87692505d77e7e894929
4,450
XyAlgorithm
Apache License 2.0
src/main/kotlin/days/Day12.kt
hughjdavey
317,575,435
false
null
package days import Coord2 import Direction class Day12 : Day(12) { private val instructions = inputList.map { Instruction(it.first(), it.drop(1).toInt()) } // 1007 override fun partOne(): Any { return Ship(false).followInstructions(instructions).position.manhattan() } // 41212 override fun partTwo(): Any { return Ship(true).followInstructions(instructions).position.manhattan() } class Ship(private val usesWaypoint: Boolean) { private var direction = Direction.EAST private var waypoint = Coord2(10, 1) var position = Coord2(0, 0) fun followInstructions(instructions: List<Instruction>): Ship { return instructions.fold(this) { ship, ins -> ship.respond(ins) } } fun respond(instruction: Instruction): Ship { when (instruction.action) { 'N', 'E', 'S', 'W' -> setPos(instruction) 'L', 'R' -> setDirection(instruction) 'F' -> move(instruction.value) else -> throw IllegalArgumentException() } return this } private fun setPos(instruction: Instruction) { val func = when (instruction.action) { 'N' -> { c: Coord2 -> c.plusY(instruction.value) } 'E' -> { c: Coord2 -> c.plusX(instruction.value) } 'S' -> { c: Coord2 -> c.minusY(instruction.value) } 'W' -> { c: Coord2 -> c.minusX(instruction.value) } else -> throw IllegalArgumentException() } if (usesWaypoint) waypoint = func(waypoint) else position = func(position) } private fun setDirection(instruction: Instruction) { if (usesWaypoint) { waypoint = if (instruction.action == 'L') waypoint.rotate(position, -instruction.value) else waypoint.rotate(position, instruction.value) } else { direction = if (instruction.action == 'L') direction.rotate(-instruction.value) else direction.rotate(instruction.value) } } private fun move(units: Int) { if (usesWaypoint) { val diff = waypoint.diff(position) position = position.plusX(diff.x * units).plusY(diff.y * units) waypoint = Coord2(position.x + diff.x, position.y + diff.y) } else { setPos(Instruction(direction.name.first(), units)) } } } data class Instruction(val action: Char, val value: Int) }
0
Kotlin
0
1
63c677854083fcce2d7cb30ed012d6acf38f3169
2,596
aoc-2020
Creative Commons Zero v1.0 Universal
src/Main.kt
mhdanas97
157,410,315
false
null
import java.util.* import kotlin.Comparator fun main(args: Array<String>) { val operatorComparator: Comparator<Operator> = kotlin.Comparator { o1: Operator, o2: Operator -> (if (o1.visited) o1.cost else o1.cost + o1.andNodes.sumBy { it.heuristic }) -(if (o2.visited) o2.cost else o2.cost + o2.andNodes.sumBy { it.heuristic }) } val p0 = Node("P0", 0, false, PriorityQueue(operatorComparator), 0) val p1 = Node("P1", 0, true, PriorityQueue(operatorComparator), null) val p2 = Node("P2", 50, false, PriorityQueue(operatorComparator), null) val p3 = Node("P3", 28, false, PriorityQueue(operatorComparator), null) val p4 = Node("P4", 40, false, PriorityQueue(operatorComparator), null) val p5 = Node("P5", 0, true, PriorityQueue(operatorComparator), null) val p6 = Node("P6", 0, true, PriorityQueue(operatorComparator), null) val p7 = Node("P7", 30, false, PriorityQueue(operatorComparator), null) val p8 = Node("P8", 22, false, PriorityQueue(operatorComparator), null) val p9 = Node("P9", 20, false, PriorityQueue(operatorComparator), null) val p10 = Node("P10", 30, false, PriorityQueue(operatorComparator), null) val p11 = Node("P11", 15, false, PriorityQueue(operatorComparator), null) val p12 = Node("P12", 15, false, PriorityQueue(operatorComparator), null) val p13 = Node("P13", 0, true, PriorityQueue(operatorComparator), null) val p14 = Node("P14", 0, true, PriorityQueue(operatorComparator), null) val p15 = Node("P15", 0, true, PriorityQueue(operatorComparator), null) p0.operators.add( Operator("P1P2", 5 + p1.heuristic + p2.heuristic, p0, arrayListOf(p1, p2), false) ) p0.operators.add( Operator("P3", 19 + p3.heuristic, p0, arrayListOf(p3), false) ) p0.operators.add( Operator("P4P5", 8 + p4.heuristic + p5.heuristic, p0, arrayListOf(p4, p5), false) ) p2.operators.add( Operator("P15P10", 5 + p15.heuristic + p10.heuristic, p2, arrayListOf(p15, p10), false) ) p3.operators.add( Operator("P6P7", 20 + p6.heuristic + p7.heuristic, p3, arrayListOf(p6, p7), false) ) p3.operators.add( Operator("P8P9", 10 + p8.heuristic + p9.heuristic, p3, arrayListOf(p8, p9), false) ) p4.operators.add( Operator("P10", 10 + p10.heuristic, p4, arrayListOf(p10), false) ) p4.operators.add( Operator("P11P12", 20 + p11.heuristic + p12.heuristic, p4, arrayListOf(p11, p12), false) ) p10.operators.add( Operator("P13P14P6", 45 + p13.heuristic + p14.heuristic + p6.heuristic , p10, arrayListOf(p13, p14, p6), false) ) println(p0.solve(null)) }
0
Kotlin
0
0
2de961e04e1c247a1f549099af3b218d6c5ddeb1
2,722
AOStar
The Unlicense
src/main/kotlin/dev/shtanko/algorithms/leetcode/TargetSum.kt
ashtanko
515,874,521
false
{"Kotlin": 235302, "Shell": 755, "Makefile": 591}
/* * MIT License * Copyright (c) 2022 <NAME> * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package dev.shtanko.algorithms.leetcode import kotlin.math.abs /** * 494. Target Sum * @link https://leetcode.com/problems/target-sum/ */ fun interface TargetSum { operator fun invoke(nums: IntArray, target: Int): Int } /** * Approach 1: Brute Force * Time complexity: O(2^n) * Space complexity: O(n) */ class TargetSumBruteForce : TargetSum { private var count = 0 override fun invoke( nums: IntArray, target: Int, ): Int { calculate(nums, 0, 0, target) return count } private fun calculate( nums: IntArray, i: Int, sum: Int, target: Int, ) { if (i == nums.size) { if (sum == target) { count++ } } else { calculate(nums, i + 1, sum + nums[i], target) calculate(nums, i + 1, sum - nums[i], target) } } } /** * Approach 2: Recursion with Memoization * Time complexity: O(t⋅n) * Space complexity: O(t⋅n) */ val targetSumMemoization = TargetSum { nums: IntArray, target: Int -> var total = 0 fun calculate( nums: IntArray, i: Int, sum: Int, target: Int, memo: Array<IntArray>, ): Int { return if (i == nums.size) { if (sum == target) { 1 } else { 0 } } else { if (memo[i][sum + total] != Int.MIN_VALUE) { return memo[i][sum + total] } val add = calculate(nums, i + 1, sum + nums[i], target, memo) val subtract = calculate(nums, i + 1, sum - nums[i], target, memo) memo[i][sum + total] = add + subtract memo[i][sum + total] } } total = nums.sum() val memo = Array(nums.size) { IntArray(2 * total + 1) { Int.MIN_VALUE } } return@TargetSum calculate(nums, 0, 0, target, memo) } /** * Approach 3: 2D Dynamic Programming * Time complexity: O(t⋅n) * Space complexity: O(t⋅n) */ internal val twoDSolution = TargetSum { nums: IntArray, target: Int -> val total: Int = nums.sum() val dp = Array(nums.size) { IntArray(2 * total + 1) } dp[0][nums[0] + total] = 1 dp[0][-nums[0] + total] += 1 for (i in 1 until nums.size) { for (sum in -total..total) { if (dp[i - 1][sum + total] > 0) { dp[i][sum + nums[i] + total] += dp[i - 1][sum + total] dp[i][sum - nums[i] + total] += dp[i - 1][sum + total] } } } if (abs(target) > total) 0 else dp[nums.size - 1][target + total] } /** * Approach 4: 1D Dynamic Programming * Time complexity: O(t⋅n) * Space complexity: O(t) */ internal val oneDSolution = TargetSum { nums: IntArray, target: Int -> val total: Int = nums.sum() var dp = IntArray(2 * total + 1) dp[nums[0] + total] = 1 dp[-nums[0] + total] += 1 for (i in 1 until nums.size) { val next = IntArray(2 * total + 1) for (sum in -total..total) { if (dp[sum + total] > 0) { next[sum + nums[i] + total] += dp[sum + total] next[sum - nums[i] + total] += dp[sum + total] } } dp = next } if (abs(target) > total) 0 else dp[target + total] }
2
Kotlin
1
9
6a2d7ed76e2d88a3446f6558109809c318780e2c
4,439
the-algorithms
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/HammingWeight.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2023 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode /** * 191. Number of 1 Bits * @see <a href="https://leetcode.com/problems/number-of-1-bits">Source</a> */ fun interface HammingWeight { operator fun invoke(n: Int): Int } class HammingWeightSolution : HammingWeight { override fun invoke(n: Int): Int { var count = 0 var num = n for (i in 0 until Int.SIZE_BITS) { if (num and 1 == 1) { count++ } num = num shr 1 } return count } } class HammingWeightStd : HammingWeight { override fun invoke(n: Int) = Integer.bitCount(n) } class HammingWeightXor : HammingWeight { override fun invoke(n: Int): Int { var count = 0 var num = n while (num != 0) { num = num xor (num and -num) count++ } return count } } class HammingWeightAnd : HammingWeight { companion object { private const val BITS = 32 } override fun invoke(n: Int): Int { var input = n var res = 0 for (i in 0..<BITS) { res += input and 1 input = input shr 1 } return res } } class HammingWeightUnsignedShiftRight : HammingWeight { override fun invoke(n: Int): Int { var mutableN = n var ones = 0 while (mutableN != 0) { if (mutableN.and(1) == 1) { ones++ } mutableN = mutableN.ushr(1) } return ones } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
2,126
kotlab
Apache License 2.0
src/main/kotlin/g1301_1400/s1307_verbal_arithmetic_puzzle/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g1301_1400.s1307_verbal_arithmetic_puzzle // #Hard #Array #String #Math #Backtracking // #2023_06_05_Time_164_ms_(100.00%)_Space_37.8_MB_(100.00%) class Solution { private lateinit var map: IntArray private lateinit var grid: Array<CharArray> private var solved = false private lateinit var usedDigit: BooleanArray private lateinit var mustNotBeZero: BooleanArray private var cols = 0 private var resultRow = 0 fun isSolvable(words: Array<String>, result: String): Boolean { solved = false val rows = words.size + 1 cols = result.length grid = Array(rows) { CharArray(cols) } mustNotBeZero = BooleanArray(26) usedDigit = BooleanArray(10) resultRow = rows - 1 map = IntArray(26) map.fill(-1) var maxLength = 0 for (i in words.indices) { var j = words[i].length if (j > maxLength) { maxLength = j } if (j > 1) { mustNotBeZero[words[i][0].code - 'A'.code] = true } if (j > cols) { return false } for (c in words[i].toCharArray()) { grid[i][--j] = c } } if (maxLength + 1 < cols) { return false } var j = cols if (j > 1) { mustNotBeZero[result[0].code - 'A'.code] = true } for (c in result.toCharArray()) { grid[resultRow][--j] = c } backtrack(0, 0, 0) return solved } private fun canPlace(ci: Int, d: Int): Boolean { return !usedDigit[d] && map[ci] == -1 || map[ci] == d } private fun placeNum(ci: Int, d: Int) { usedDigit[d] = true map[ci] = d } private fun removeNum(ci: Int, d: Int) { usedDigit[d] = false map[ci] = -1 } private fun placeNextNum(r: Int, c: Int, sum: Int) { if (r == resultRow && c == cols - 1) { solved = sum == 0 } else { if (r == resultRow) { backtrack(0, c + 1, sum) } else { backtrack(r + 1, c, sum) } } } private fun backtrack(r: Int, c: Int, sum: Int) { val unused = '\u0000' if (grid[r][c] == unused) { placeNextNum(r, c, sum) } else { val ci = grid[r][c].code - 'A'.code if (r == resultRow) { val d = sum % 10 if (map[ci] == -1) { if (canPlace(ci, d)) { placeNum(ci, d) placeNextNum(r, c, sum / 10) if (solved) { return } removeNum(ci, d) } } else { if (map[ci] == d) { placeNextNum(r, c, sum / 10) } } } else { if (map[ci] == -1) { val startIndex = if (mustNotBeZero[ci]) 1 else 0 for (d in startIndex..9) { if (canPlace(ci, d)) { placeNum(ci, d) placeNextNum(r, c, sum + d) if (solved) { return } removeNum(ci, d) } } } else { placeNextNum(r, c, sum + map[ci]) } } } } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
3,666
LeetCode-in-Kotlin
MIT License
src/main/java/org/chalup/parser/Parser.kt
chalup
226,190,276
false
null
package org.chalup.parser import org.chalup.parser.Json.JsonBool import org.chalup.parser.Json.JsonInt import org.chalup.parser.Json.JsonNull import org.chalup.parser.LeBoolean.LeFalse import org.chalup.parser.LeBoolean.LeOr import org.chalup.parser.LeBoolean.LeTrue import org.chalup.parser.LoopStep.Done import org.chalup.parser.LoopStep.Loop import org.chalup.parser.ParserStep.Bad import org.chalup.parser.ParserStep.Good import org.chalup.parser.Problem.Custom import org.chalup.parser.Problem.ExpectedKeyword import org.chalup.parser.Problem.ExpectedSymbol import org.chalup.parser.Problem.ExpectingFloat import org.chalup.parser.Problem.ExpectingInt import org.chalup.parser.Problem.UnexpectedChar import org.chalup.parser.Result.Error import org.chalup.parser.Result.Ok import org.chalup.parser.TrailingSeparatorTreatment.FORBIDDEN import org.chalup.parser.TrailingSeparatorTreatment.MANDATORY import org.chalup.parser.TrailingSeparatorTreatment.OPTIONAL sealed class Result<out ErrorT, out OkT> { data class Error<T>(val error: T) : Result<T, Nothing>() data class Ok<T>(val value: T) : Result<Nothing, T>() } data class State(val src: String, val offset: Int, val indent: Int, val row: Int, val col: Int) sealed class ParserStep<out T> { data class Good<T>(val progress: Boolean, val value: T, val state: State) : ParserStep<T>() data class Bad(val progress: Boolean, val problems: List<DeadEnd>) : ParserStep<Nothing>() } sealed class Problem { data class ExpectedSymbol(val str: String) : Problem() data class ExpectedKeyword(val str: String) : Problem() object ExpectingInt : Problem() object ExpectingFloat : Problem() object UnexpectedChar : Problem() data class Custom(val message: String) : Problem() } data class Token(val str: String, val problem: Problem, val delimiterPredicate: (Char) -> Boolean) data class DeadEnd(val row: Int, val col: Int, val problem: Problem) { constructor(state: State, problem: Problem) : this(state.row, state.col, problem) } class Parser<T>(val parse: (State) -> ParserStep<T>) { fun run(input: String): Result<List<DeadEnd>, T> = when (val step = parse(State(src = input, offset = 0, indent = 1, row = 1, col = 1))) { is Good -> Ok(step.value) is Bad -> Error(step.problems) } } fun isSubstring(str: String, offset: Int, row: Int, col: Int, bigString: String): Triple<Int, Int, Int> { var newOffset = offset var newRow = row var newCol = col var isGood = offset + str.length <= bigString.length var i = 0 while (isGood && i < str.length) { val isNewline = bigString[newOffset] == '\n' isGood = str[i++] == bigString[newOffset++] if (isNewline) { newRow++; newCol = 1 } else { newCol++ } } return Triple(if (isGood) newOffset else -1, newRow, newCol) } val int: Parser<Int> = number(NumberContext( int = Ok { n: Int -> n }, float = Error(ExpectingInt), invalid = ExpectingInt, expecting = ExpectingInt )) val float: Parser<Float> = number(NumberContext( int = Ok { n: Int -> n.toFloat() }, float = Ok { n: Float -> n }, invalid = ExpectingFloat, expecting = ExpectingFloat )) data class NumberContext<out T>(val int: Result<Problem, (Int) -> T>, val float: Result<Problem, (Float) -> T>, val invalid: Problem, val expecting: Problem) fun <T> number(context: NumberContext<T>): Parser<T> = Parser { s -> val (intOffset, n) = consumeBase(10, s.offset, s.src) finalizeFloat(context, intOffset, n, s) } fun consumeBase(base: Int, offset: Int, string: String): Pair<Int, Int> { var total = 0 var newOffset = offset while (newOffset < string.length) { val digit = string[newOffset] - '0' if (digit < 0 || digit >= base) break total = base * total + digit newOffset++ } return newOffset to total } fun <T> finalizeFloat(context: NumberContext<T>, intOffset: Int, n: Int, s: State): ParserStep<T> { val floatOffset = consumeDotAndExp(intOffset, s.src) return when { floatOffset < 0 -> Bad(progress = true, problems = listOf(DeadEnd(row = s.row, col = s.col - (floatOffset + s.offset), problem = context.invalid))) s.offset == floatOffset -> Bad(progress = false, problems = fromState(s, context.expecting)) intOffset == floatOffset -> finalizeInt(context.invalid, context.int, s.offset, intOffset, n, s) else -> when (context.float) { is Error -> Bad(progress = true, problems = listOf(DeadEnd(s, context.invalid))) // shouldn't we take the problem from the handler? is Ok -> s.src.substring(s.offset, floatOffset).toFloatOrNull() ?.let { Good(progress = true, value = context.float.value(it), state = s.bumpOffset(floatOffset)) } ?: Bad(progress = true, problems = fromState(s, context.invalid)) } } } fun <T> finalizeInt(invalid: Problem, handler: Result<Problem, (Int) -> T>, startOffset: Int, endOffset: Int, n: Int, s: State): ParserStep<T> = when (handler) { is Error -> Bad(progress = true, problems = fromState(s, handler.error)) is Ok -> if (startOffset == endOffset) Bad(progress = s.offset < startOffset, problems = fromState(s, invalid)) else Good(progress = true, value = handler.value(n), state = s.bumpOffset(endOffset)) } private fun State.bumpOffset(newOffset: Int) = copy( offset = newOffset, col = col + (newOffset - offset) ) fun fromState(s: State, x: Problem) = listOf(DeadEnd(s, x)) fun consumeDotAndExp(offset: Int, src: String): Int = if (src.at(offset) == '.') consumeExp(chompBase10(offset + 1, src), src) else consumeExp(offset, src) fun chompBase10(offset: Int, src: String): Int { var newOffset = offset while (newOffset < src.length) { val char = src[newOffset] if (char < '0' || char > '9') break newOffset++ } return newOffset } fun consumeExp(offset: Int, src: String): Int { if (src.at(offset) == 'e' || src.at(offset) == 'E') { val eOffset = offset + 1 val expOffset = if (src[eOffset] == '+' || src[eOffset] == '-') eOffset + 1 else eOffset val newOffset = chompBase10(expOffset, src) if (expOffset == newOffset) { return -newOffset } else { return newOffset } } else { return offset } } // Elm version uses under the hood some Javascript method which returns 'NaN' when reaching // outside of the valid offset range. I'm duplicating this logic here to keep the reset of // the code the same. fun String.at(offset: Int) = if (offset >= length) null else get(offset) fun symbol(str: String): Parser<Unit> = token(Token(str, ExpectedSymbol(str), delimiterPredicate = { false })) fun keyword(str: String): Parser<Unit> = token(Token(str, ExpectedKeyword(str), delimiterPredicate = { it.isLetterOrDigit() || it == '_' })) fun token(token: Token) = Parser { s -> val (newOffset, newRow, newCol) = isSubstring(token.str, s.offset, s.row, s.col, s.src) if (newOffset == -1 || isSubChar(token.delimiterPredicate, newOffset, s.src) >= 0) Bad(progress = false, problems = fromState(s, token.problem)) else Good(progress = token.str.isNotEmpty(), value = Unit, state = s.copy(offset = newOffset, row = newRow, col = newCol)) } val spaces: Parser<Unit> = chompWhile { it.isWhitespace() } fun chompWhile(predicate: (Char) -> Boolean): Parser<Unit> = Parser { state -> tailrec fun helper(offset: Int, row: Int, col: Int): ParserStep<Unit> = when (val newOffset = isSubChar(predicate, offset, state.src)) { -1 -> Good(progress = state.offset < offset, value = Unit, state = state.copy(offset = offset, row = row, col = col)) -2 -> helper(offset + 1, row + 1, 1) else -> helper(newOffset, row, col + 1) } helper(state.offset, state.row, state.col) } fun chompIf(predicate: (Char) -> Boolean): Parser<Unit> = Parser { s -> when (val newOffset = isSubChar(predicate, s.offset, s.src)) { -1 -> Bad(progress = false, problems = fromState(s, UnexpectedChar)) -2 -> Good(progress = true, value = Unit, state = s.copy(offset = s.offset + 1, row = s.row + 1, col = 1)) else -> Good(progress = true, value = Unit, state = s.copy(offset = newOffset, col = s.col + 1)) } } fun isSubChar(predicate: (Char) -> Boolean, offset: Int, string: String): Int = when { string.length <= offset -> -1 predicate(string[offset]) -> if (string[offset] == '\n') -2 else offset + 1 else -> -1 } fun <T> succeed(v: T): Parser<T> = Parser { state -> Good(progress = false, value = v, state = state) } fun problem(message: String): Parser<Nothing> = Parser { s -> Bad(progress = false, problems = fromState(s, Custom(message))) } fun <T> oneOf(parsers: List<Parser<out T>>): Parser<T> = Parser { s -> tailrec fun helper(problems: List<DeadEnd>, parsers: List<Parser<out T>>): ParserStep<T> = if (parsers.isEmpty()) Bad(progress = false, problems = problems) else when (val step = parsers.first().parse(s)) { is Good -> step is Bad -> if (step.progress) step else helper(problems + step.problems, parsers.drop(1)) } helper(problems = emptyList(), parsers = parsers) } fun <T> oneOf(vararg parsers: Parser<out T>): Parser<T> = oneOf(parsers.asList()) fun <T> parser(block: (self: Parser<T>) -> Parser<T>): Parser<T> { var stubParser: Parser<T> = Parser { throw IllegalStateException("Using stubbed parser!") } val selfParser: Parser<T> = Parser { s -> stubParser.parse(s) } return block(selfParser).also { stubParser = it } } fun <T, R> map(func: (T) -> R, parser: Parser<T>): Parser<R> = Parser { s -> when (val step = parser.parse(s)) { is Good -> Good(progress = step.progress, value = func(step.value), state = step.state) is Bad -> step } } infix fun <T, R> Parser<T>.mapTo(func: (T) -> R): Parser<R> = map(func, this) fun <T1, T2, R> map2(func: (T1, T2) -> R, parserA: Parser<T1>, parserB: Parser<T2>): Parser<R> = Parser { s -> when (val stepA = parserA.parse(s)) { is Bad -> stepA is Good -> when (val stepB = parserB.parse(stepA.state)) { is Bad -> Bad(progress = stepA.progress || stepB.progress, problems = stepB.problems) is Good -> Good(progress = stepA.progress || stepB.progress, value = func(stepA.value, stepB.value), state = stepB.state) } } } fun getChompedString(parser: Parser<*>): Parser<String> = Parser { s -> when (val step = parser.parse(s)) { is Bad -> step is Good -> Good(progress = step.progress, value = s.src.substring(s.offset, step.state.offset), state = step.state) } } infix fun <T, R> Parser<T>.andThen(func: (T) -> Parser<out R>): Parser<R> = Parser { s -> when (val stepA = parse(s)) { is Bad -> stepA is Good -> when (val stepB = func(stepA.value).parse(stepA.state)) { is Bad -> Bad(progress = stepA.progress || stepB.progress, problems = stepB.problems) is Good -> Good(progress = stepA.progress || stepB.progress, value = stepB.value, state = stepB.state) } } } infix fun <T, R> Parser<(T) -> R>.keep(keepParser: Parser<T>): Parser<R> = map2( func = { f, arg -> f(arg) }, parserA = this, parserB = keepParser ) infix fun <T1, T2, R> Parser<(T1, T2) -> R>.keep2(keepParser: Parser<T1>): Parser<(T2) -> R> = map2( func = { f, a1 -> { a2: T2 -> f(a1, a2) } }, parserA = this, parserB = keepParser ) infix fun <KeepT, SkipT> Parser<KeepT>.skip(skip: Parser<SkipT>): Parser<KeepT> = map2( func = { a: KeepT, _: SkipT -> a }, parserA = this, parserB = skip ) sealed class LoopStep<out S, out T> { data class Loop<S>(val state: S) : LoopStep<S, Nothing>() data class Done<T>(val result: T) : LoopStep<Nothing, T>() } fun <S, T> loop(loopState: S, callback: (S) -> Parser<LoopStep<S, T>>): Parser<T> = Parser { s -> tailrec fun helper(progress: Boolean, loopState: S, parserState: State): ParserStep<T> = when (val step = callback(loopState).parse(parserState)) { is Good -> when (val nextLoopStep = step.value) { is Loop -> helper(progress = progress || step.progress, loopState = nextLoopStep.state, parserState = step.state) is Done -> Good(progress = progress || step.progress, value = nextLoopStep.result, state = step.state) } is Bad -> Bad(progress = progress || step.progress, problems = step.problems) } helper(false, loopState, s) } enum class TrailingSeparatorTreatment { FORBIDDEN, OPTIONAL, MANDATORY } // TODO mark internal? infix fun <SkipT, KeepT> Parser<SkipT>.skipThen(keep: Parser<KeepT>): Parser<KeepT> = map2( func = { _: SkipT, b: KeepT -> b }, parserA = this, parserB = keep ) fun <T> sequence(start: String, separator: String, end: String, trailingSeparatorTreatment: TrailingSeparatorTreatment, itemParser: Parser<T>, spacesParser: Parser<Unit> = spaces): Parser<List<T>> { return symbol(start) skipThen spacesParser skipThen sequenceEnd(endParser = symbol(end), spacesParser = spacesParser, separatorParser = symbol(separator), trailingSeparatorTreatment = trailingSeparatorTreatment, itemParser = itemParser) } fun <T> sequenceEnd(endParser: Parser<Unit>, spacesParser: Parser<Unit>, itemParser: Parser<T>, separatorParser: Parser<Unit>, trailingSeparatorTreatment: TrailingSeparatorTreatment): Parser<List<T>> { val chompRest: (T) -> Parser<List<T>> = { item: T -> when (trailingSeparatorTreatment) { FORBIDDEN -> loop(listOf(item), { s -> sequenceEndForbidden(endParser, spacesParser, itemParser, separatorParser, s) }) OPTIONAL -> loop(listOf(item), { s -> sequenceEndOptional(endParser, spacesParser, itemParser, separatorParser, s) }) MANDATORY -> (spacesParser skipThen separatorParser skipThen spacesParser skipThen loop(listOf(item), { s -> sequenceEndMandatory(spacesParser, itemParser, separatorParser, s)})) skip endParser } } return oneOf( itemParser andThen chompRest, endParser mapTo { emptyList<T>() } ) } fun <T> sequenceEndForbidden(endParser: Parser<Unit>, spacesParser: Parser<Unit>, itemParser: Parser<T>, separatorParser: Parser<Unit>, items: List<T>): Parser<LoopStep<List<T>, List<T>>> = spacesParser skipThen oneOf(separatorParser skipThen spacesParser skipThen (itemParser mapTo { item -> Loop(items + item) }), endParser mapTo { Done(items) }) fun <T> sequenceEndOptional(endParser: Parser<Unit>, spacesParser: Parser<Unit>, itemParser: Parser<T>, separatorParser: Parser<Unit>, items: List<T>): Parser<LoopStep<List<T>, List<T>>> { val parseEnd = endParser mapTo { Done(items) } return spacesParser skipThen oneOf(separatorParser skipThen spacesParser skipThen oneOf(itemParser mapTo { item -> Loop(items + item) }, parseEnd), parseEnd) } fun <T> sequenceEndMandatory(spacesParser: Parser<Unit>, itemParser: Parser<T>, separatorParser: Parser<Unit>, items: List<T>): Parser<LoopStep<List<T>, List<T>>> { return oneOf( itemParser skip spacesParser skip separatorParser skip spacesParser mapTo { item -> Loop(items + item) }, succeed(Unit) mapTo { Done(items) } ) } enum class Suite(val symbol: Char) { CLUBS('c'), HEARTS('h'), DIAMONDS('d'), SPADES('s') } enum class Rank(val symbol: Char) { TWO('2'), THREE('3'), FOUR('4'), FIVE('5'), SIX('6'), SEVEN('7'), EIGHT('8'), NINE('9'), TEN('T'), JACK('J'), QUEEN('Q'), KING('K'), ACE('A') } data class Card(val rank: Rank, val suite: Suite) { override fun toString(): String = "${rank.symbol}${suite.symbol}" } data class Point(val x: Int, val y: Int) sealed class Json { data class JsonInt(val int: Int) : Json() data class JsonBool(val boolean: Boolean) : Json() object JsonNull : Json() { override fun toString() = "null" } } sealed class LeBoolean { object LeTrue : LeBoolean() { override fun toString() = "true" } object LeFalse : LeBoolean() { override fun toString() = "false" } data class LeOr(val lhs: LeBoolean, val rhs: LeBoolean) : LeBoolean() { override fun toString() = "($lhs || $rhs)" } } fun main() { val leBooleanParser: Parser<LeBoolean> = parser { leBoolean -> oneOf( succeed(LeTrue) skip keyword("true"), succeed(LeFalse) skip keyword("false"), (succeed { l: LeBoolean, r: LeBoolean -> LeOr(l, r) } skip symbol("(") skip spaces keep2 leBoolean skip spaces skip symbol("||") skip spaces keep leBoolean skip spaces skip symbol(")") ) ) } val jsonParser: Parser<Json> = oneOf( int mapTo { JsonInt(it) }, keyword("true") mapTo { JsonBool(true) }, keyword("false") mapTo { JsonBool(false) }, keyword("null") mapTo { JsonNull } ) val parser: Parser<Point> = ( succeed { x: Int, y: Int -> Point(x, y) } skip symbol("(") skip spaces keep2 int skip spaces skip symbol(",") skip spaces keep int skip spaces skip symbol(")") ) val phpParser = getChompedString( succeed(Unit) skip chompIf { it == '$' } skip chompIf { it.isLetter() || it == '_' } skip chompWhile { it.isLetterOrDigit() || it == '_' } ) val zipCodeParser = getChompedString(chompWhile { it.isDigit() }) .andThen { code -> if (code.length == 5) succeed(code) else problem("a U.S. zip code has exactly 5 digits, but I found '$code'") } val letKeywordParser = keyword("let") val suiteParser = oneOf(Suite.values().map { suite -> symbol("${suite.symbol}") mapTo { suite } }) val rankParser = oneOf(Rank.values().map { rank -> symbol("${rank.symbol}") mapTo { rank } }) val cardParser = ( succeed { rank: Rank, suite: Suite -> Card(rank, suite) } keep2 rankParser keep suiteParser ) val handsParser = sequence( start = "[", end = "]", separator = ",", trailingSeparatorTreatment = MANDATORY, itemParser = cardParser ) println(parser.run("(10,20)")) println(int.run("123")) println(float.run("123")) println(float.run("123.123")) println(jsonParser.run("10")) println(jsonParser.run("null")) println(leBooleanParser.run("(true || (true || false))")) println(letKeywordParser.run("let")) println(letKeywordParser.run("letters")) println(phpParser.run("\$txt")) println(phpParser.run("\$x")) println(zipCodeParser.run("12345")) println(zipCodeParser.run("test")) println(zipCodeParser.run("123456789")) println(cardParser.run("Kh")) println(cardParser.run("Qs")) println(cardParser.run("*K")) println(cardParser.run("KK")) println(handsParser.run("[Kh, Qs]")) println(handsParser.run("[Kh, Qs,]")) }
0
Kotlin
0
0
ab208872827fa9de3f4f734c93a4ba37ccae7936
22,081
elmish-kt-parser
Apache License 2.0
pulsar-skeleton/src/test/kotlin/ai/platon/pulsar/crawl/common/TestPrefixStringMatcher.kt
platonai
124,882,400
false
null
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 ai.platon.pulsar.crawl.common import ai.platon.pulsar.common.PrefixStringMatcher import org.junit.Assert import org.junit.Test /** * Unit tests for PrefixStringMatcher. */ class TestPrefixStringMatcher { private fun makeRandString(minLen: Int, maxLen: Int): String { val len = minLen + (Math.random() * (maxLen - minLen)).toInt() val chars = CharArray(len) for (pos in 0 until len) { chars[pos] = alphabet[(Math.random() * alphabet.size).toInt()] } return String(chars) } @Test fun testPrefixMatcher() { var numMatches = 0 var numInputsTested = 0 for (round in 0 until NUM_TEST_ROUNDS) { // build list of prefixes val numPrefixes = (Math.random() * MAX_TEST_PREFIXES).toInt() val prefixes = arrayOfNulls<String>(numPrefixes) for (i in 0 until numPrefixes) { prefixes[i] = makeRandString(0, MAX_PREFIX_LEN) } val prematcher = PrefixStringMatcher(prefixes) // test random strings for prefix matches for (i in 0 until NUM_TEST_INPUTS_PER_ROUND) { val input = makeRandString(0, MAX_INPUT_LEN) var matches = false var longestMatch = -1 var shortestMatch = -1 for (j in prefixes.indices) { if (prefixes[j]!!.length > 0 && input.startsWith(prefixes[j]!!)) { matches = true val matchSize = prefixes[j]!!.length if (matchSize > longestMatch) longestMatch = matchSize if (matchSize < shortestMatch || shortestMatch == -1) shortestMatch = matchSize } } if (matches) numMatches++ numInputsTested++ Assert.assertTrue("'" + input + "' should " + (if (matches) "" else "not ") + "match!", matches == prematcher.matches(input)) if (matches) { Assert.assertTrue(shortestMatch == prematcher.shortestMatch(input).length) Assert.assertTrue(input.substring(0, shortestMatch) == prematcher.shortestMatch(input)) Assert.assertTrue(longestMatch == prematcher.longestMatch(input).length) Assert.assertTrue(input.substring(0, longestMatch) == prematcher.longestMatch(input)) } } } println("got " + numMatches + " matches out of " + numInputsTested + " tests") } companion object { private const val NUM_TEST_ROUNDS = 20 private const val MAX_TEST_PREFIXES = 100 private const val MAX_PREFIX_LEN = 10 private const val NUM_TEST_INPUTS_PER_ROUND = 100 private const val MAX_INPUT_LEN = 20 private val alphabet = charArrayOf('a', 'b', 'c', 'd') } }
1
HTML
32
110
f93bccf5075009dc7766442d3a23b5268c721f54
3,806
pulsar
GNU Affero General Public License v3.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/ReverseParentheses.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2023 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import dev.shtanko.datastructures.Stack import java.util.Deque import java.util.LinkedList import java.util.Queue /** * 1190. Reverse Substrings Between Each Pair of Parentheses * @see <a href="https://leetcode.com/problems/reverse-substrings-between-each-pair-of-parentheses/">Source</a> */ fun interface ReverseParentheses { operator fun invoke(s: String): String } class ReverseParenthesesBF : ReverseParentheses { override operator fun invoke(s: String): String { val st: Stack<Char> = Stack() for (c in s.toCharArray()) { if (c == ')') { val p: Queue<Char> = LinkedList() while (st.isNotEmpty() && st.peek() != '(') p.add(st.poll()) if (st.isNotEmpty()) st.poll() while (p.isNotEmpty()) st.push(p.remove()) } else { st.push(c) } } val sb = StringBuilder() while (st.isNotEmpty()) sb.append(st.poll()) return sb.reverse().toString() } } class ReverseParenthesesSort : ReverseParentheses { override operator fun invoke(s: String): String { val dq: Deque<StringBuilder> = LinkedList() dq.push(java.lang.StringBuilder()) // In case the first char is NOT '(', need an empty StringBuilder. for (c in s.toCharArray()) { when (c) { '(' -> { // need a new StringBuilder to save substring in brackets pair dq.offer(java.lang.StringBuilder()) } ')' -> { // found a matched brackets pair and reverse the substring between them. val end = dq.pollLast() dq.peekLast().append(end.reverse()) } else -> { // append the char to the last StringBuilder. dq.peekLast().append(c) } } } return dq.pollLast().toString() } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
2,581
kotlab
Apache License 2.0
src/main/kotlin/problems/MaxProdSubArray.kt
amartya-maveriq
510,824,460
false
{"Kotlin": 42296}
package problems import java.lang.Integer.max /** * Leetcode : Medium * https://leetcode.com/problems/maximum-product-subarray/ * Given an integer array nums, find a contiguous non-empty subarray within the array that has the largest product, and return the product. The test cases are generated so that the answer will fit in a 32-bit integer. A subarray is a contiguous subsequence of the array. Example 1: Input: nums = [2,3,-2,4] Output: 6 Explanation: [2,3] has the largest product 6. Example 2: Input: nums = [-2,0,-1] Output: 0 Explanation: The result cannot be 2, because [-2,-1] is not a subarray. */ class MaxProdSubArray( private val nums: IntArray ) { fun maxProduct(): Int { var res = maxOfArray(nums) var curMax = 1 var curMin = 1 for (num in nums) { val temp = curMax curMax = maxOf(curMax * num, curMin * num, num) curMin = minOf(temp * num, curMin * num, num) res = max(curMax, res) } return res } private fun maxOfArray(nums: IntArray): Int { var temp: Int = Int.MIN_VALUE nums.forEach { if (it > temp) { temp = it } } return temp } }
0
Kotlin
0
0
2f12e7d7510516de9fbab866a59f7d00e603188b
1,255
data-structures
MIT License
src/main/kotlin/com/ginsberg/advent2017/Day21.kt
tginsberg
112,672,087
false
null
/* * Copyright (c) 2017 by <NAME> */ package com.ginsberg.advent2017 import com.ginsberg.advent2017.grid.FractalGrid import com.ginsberg.advent2017.grid.join /** * AoC 2017, Day 21 * * Problem Description: http://adventofcode.com/2017/day/21 * Blog Post/Commentary: https://todd.ginsberg.com/post/advent-of-code/2017/day21/ */ class Day21(input: List<String>) { private val rowSplit = " => ".toRegex() private val transforms: Map<FractalGrid, FractalGrid> = parseInput(input) private val startGrid = FractalGrid(".#./..#/###") fun solve(iterations: Int): Int { var grid = startGrid repeat(iterations) { val splits = grid.split() val next = splits.map { transforms.getValue(it) } grid = next.join() } return grid.toString().count { it == '#' } } private fun parseInputRow(input: String): Pair<FractalGrid, FractalGrid> = input.split(rowSplit) .map { FractalGrid(it) } .let { it.first() to it.last() } private fun parseInput(input: List<String>): Map<FractalGrid, FractalGrid> = input.map { parseInputRow(it) }.flatMap { pair -> pair.first.combinations().map { combo -> combo to pair.second } }.toMap() }
0
Kotlin
0
15
a57219e75ff9412292319b71827b35023f709036
1,311
advent-2017-kotlin
MIT License
src/Day14.kt
acrab
573,191,416
false
{"Kotlin": 52968}
import com.google.common.truth.Truth.assertThat import java.lang.Integer.max import java.lang.Integer.min enum class GridSpace { Rock, Air, Sand } fun rangeBetween(start: Int, end: Int) = min(start, end)..max(start, end) fun main() { fun List<MutableList<GridSpace>>.printMap(width: Int) { println(joinToString("\n") { row -> row.takeLast(width).joinToString("") { when (it) { GridSpace.Rock -> "#" GridSpace.Air -> " " GridSpace.Sand -> "o" } } }) } fun MutableList<MutableList<GridSpace>>.fillLine(startX: Int, startY: Int, endX: Int, endY: Int) { while (size <= max(startY, endY)) { add(mutableListOf()) } for (y in rangeBetween(startY, endY)) { val row = this[y] while (row.size <= max(startX, endX)) { row.add(GridSpace.Air) } for (x in rangeBetween(startX, endX)) { row[x] = GridSpace.Rock } } } /** * Produces a grid indexed &#91;y&#93;&#91;x&#93; */ fun parseGrid(input: List<String>): MutableList<MutableList<GridSpace>> { val output = mutableListOf<MutableList<GridSpace>>() input.forEach { shape -> shape.split(" -> ") .windowed(2) .forEach { line -> val (startX, startY) = line[0].split(",").map { it.toInt() } val (endX, endY) = line[1].split(",").map { it.toInt() } output.fillLine(startX, startY, endX, endY) } } val maxLength = output.maxOf { it.size } output.forEach { while (it.size < maxLength) { it.add(GridSpace.Air) } } return output } fun MutableList<GridSpace>.addSandGrain(position: Int) { while (size < position) { add(GridSpace.Air) } set(position, GridSpace.Sand) } fun part1(input: List<String>): Int { val map = parseGrid(input) map.printMap(200) var sandGrainsAdded = 0 val path = mutableListOf(0 to 500) while (true) { val (currentY, currentX) = path.last() val nextRowCoordinate = currentY + 1 //If a sand grain goes below this point, it has fallen off the map, and we can end if (nextRowCoordinate == map.size) { break } val nextRow = map[nextRowCoordinate] //try to fall down if (currentX > nextRow.size || nextRow[currentX] == GridSpace.Air) { path.add(nextRowCoordinate to currentX) continue } //try to fall left if (currentX - 1 > nextRow.size || nextRow[currentX - 1] == GridSpace.Air) { path.add(nextRowCoordinate to currentX - 1) continue } //try to fall right if (currentX + 1 > nextRow.size || nextRow[currentX + 1] == GridSpace.Air) { path.add(nextRowCoordinate to currentX + 1) continue } //can't fall in any direction, then place a grain, and start next grain from the row above sandGrainsAdded++ path.removeLast() map[currentY].addSandGrain(currentX) } return sandGrainsAdded } fun part2(input: List<String>): Int { val map = parseGrid(input) val mapWidth = map[0].size map.add(MutableList(mapWidth) { GridSpace.Air }) val extraSpace = MutableList(100) { GridSpace.Air } map.forEach { it.addAll(extraSpace) } map.printMap(200) var sandGrainsAdded = 0 val path = mutableListOf(0 to 500) while (path.any()) { if (sandGrainsAdded > 0 && sandGrainsAdded % 5_000 == 0) { println("Added $sandGrainsAdded") map.printMap(200) } val (currentY, currentX) = path.last() val nextRowCoordinate = currentY + 1 if (nextRowCoordinate >= map.size) { //we've reached the floor, place a grain and continue sandGrainsAdded++ path.removeLast() map[currentY].addSandGrain(currentX) continue } val nextRow = map[nextRowCoordinate] //try to fall down if (currentX >= nextRow.size || nextRow[currentX] == GridSpace.Air) { path.add(nextRowCoordinate to currentX) continue } //try to fall left if (currentX - 1 >= nextRow.size || nextRow[currentX - 1] == GridSpace.Air) { path.add(nextRowCoordinate to currentX - 1) continue } //try to fall right if (currentX + 1 >= nextRow.size || nextRow[currentX + 1] == GridSpace.Air) { path.add(nextRowCoordinate to currentX + 1) continue } //can't fall in any direction, then place a grain, and start next grain from the row above sandGrainsAdded++ path.removeLast() map[currentY].addSandGrain(currentX) } return sandGrainsAdded } val testInput = readInput("Day14_test") assertThat(part1(testInput)).isEqualTo(24) val input = readInput("Day14") println(part1(input)) assertThat(part2(testInput)).isEqualTo(93) println(part2(input)) }
0
Kotlin
0
0
0be1409ceea72963f596e702327c5a875aca305c
5,652
aoc-2022
Apache License 2.0
src/org/aoc2021/Day10.kt
jsgroth
439,763,933
false
{"Kotlin": 86732}
package org.aoc2021 import java.nio.file.Files import java.nio.file.Path object Day10 { private val values = mapOf( ')' to 3, ']' to 57, '}' to 1197, '>' to 25137, ) private fun solvePart1(lines: List<String>): Int { return lines.sumOf { line -> doLine(line) } } private fun solvePart2(lines: List<String>): Long { val scores = lines.filter { doLine(it) == 0 } .map { line -> solveIncompleteLine(line) } .sorted() return scores[scores.size / 2] } private fun doLine(line: String): Int { val chars = mutableListOf<Char>() for (c in line) { if (c in setOf('(', '[', '{', '<')) { chars.add(c) } else if (chars.isEmpty()) { return values[c]!! } else { if ( (c == ')' && chars.last() != '(') || (c == ']' && chars.last() != '[') || (c == '}' && chars.last() != '{') || (c == '>' && chars.last() != '<') ) { return values[c]!! } chars.removeLast() } } return 0 } private fun solveIncompleteLine(line: String): Long { val chars = mutableListOf<Char>() for (c in line) { if (c in setOf('(', '[', '{', '<')) { chars.add(c) } else { chars.removeLast() } } return chars.reversed().fold(0L) { p, c -> 5 * p + when (c) { '(' -> 1 '[' -> 2 '{' -> 3 '<' -> 4 else -> throw IllegalArgumentException("$c") } } } @JvmStatic fun main(args: Array<String>) { val lines = Files.readAllLines(Path.of("input10.txt"), Charsets.UTF_8) val solution1 = solvePart1(lines) println(solution1) val solution2 = solvePart2(lines) println(solution2) } }
0
Kotlin
0
0
ba81fadf2a8106fae3e16ed825cc25bbb7a95409
2,137
advent-of-code-2021
The Unlicense
src/main/kotlin/year2022/day22/Problem.kt
Ddxcv98
573,823,241
false
{"Kotlin": 154634}
package year2022.day22 import IProblem import java.io.BufferedReader class Problem(transitions: Array<Array<Pair<Int, Int>>>) : IProblem { private val matrix: Array<Array<Char>> private val moves = mutableListOf<(Pair<Int, Char>)>() private val cw2D: CubeWalker2D private val cw3D: CubeWalker3D init { javaClass .getResourceAsStream("/2022/22.txt")!! .bufferedReader() .use { matrix = parseMap(it) parseMoves(it.readLine()) } cw2D = CubeWalker2D(matrix) cw3D = CubeWalker3D(transitions, matrix) } private fun parseMap(br: BufferedReader): Array<Array<Char>> { val lines = mutableListOf<CharArray>() var width = 0 while (true) { val line = br.readLine() if (line.isEmpty()) { break } val chars = line.toCharArray() if (chars.size > width) { width = chars.size } lines.add(chars) } return Array(lines.size) { i -> Array(width) { j -> if (j < lines[i].size) { lines[i][j] } else { ' ' } } } } private fun parseMoves(s: String) { var n = 0 for (char in s.toCharArray()) { n = if (char.isDigit()) { n * 10 + char.digitToInt() } else { moves.add(Pair(n, char)) 0 } } moves.add(Pair(n, 'X')) } private fun <P : Pos2D> dance(cw: CubeWalker<P>, pos: P): Int { for ((n, r) in moves) { cw.walk(pos, n) cw.rotate(pos, r) } val facing = pos.r while (pos.r != 0) { cw.rotate(pos, 'L') } val pos2D = cw.toPos2D(pos) return 1000 * (pos2D.y + 1) + 4 * (pos2D.x + 1) + facing } override fun part1(): Int { val pos = Pos2D(0, matrix[0].indexOfFirst { it == '.' }, 0) return dance(cw2D, pos) } override fun part2(): Int { val pos = Pos3D(0, 0, 0, 0) return dance(cw3D, pos) } }
0
Kotlin
0
0
455bc8a69527c6c2f20362945b73bdee496ace41
2,263
advent-of-code
The Unlicense
src/Day06.kt
kerchen
573,125,453
false
{"Kotlin": 137233}
import java.util.* import kotlin.collections.ArrayDeque fun main() { fun findUniqueWindow(input: String, windowSize: Int): Int { var window: ArrayDeque<Char> = ArrayDeque(windowSize) var index = 0 for (c in input) { index += 1 window.addFirst(c) if (window.size > windowSize) { window.removeLast() if (window.toSet().size == windowSize) { return index } } } return index } fun part1(input: List<String>): List<Int> { var firstMarkers = mutableListOf<Int>() for (dataStream in input) { firstMarkers.add(findUniqueWindow(dataStream, 4)) } return firstMarkers } fun part2(input: List<String>): List<Int> { var firstMarkers = mutableListOf<Int>() for (dataStream in input) { firstMarkers.add(findUniqueWindow(dataStream, 14)) } return firstMarkers } val testInput = readInput("Day06_test") check(part1(testInput) == listOf(7, 5, 6, 10, 11)) check(part2(testInput) == listOf(19, 23, 23, 29, 26)) val input = readInput("Day06") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
dc15640ff29ec5f9dceb4046adaf860af892c1a9
1,266
AdventOfCode2022
Apache License 2.0
src/main/kotlin/exercises/findpivotindex/FindPivotIndex.kt
amykv
538,632,477
false
{"Kotlin": 169929}
package exercises.findpivotindex /* Given an array of integers nums, calculate the pivot index of this array. The pivot index is the index where the sum of all the numbers strictly to the left of the index is equal to the sum of all the numbers strictly to the index's right. If the index is on the left edge of the array, then the left sum is 0 because there are no elements to the left. This also applies to the right edge of the array. Return the leftmost pivot index. If no such index exists, return -1. Example 1: Input: nums = [1,7,3,6,5,6] Output: 3 Explanation: The pivot index is 3. Left sum = nums[0] + nums[1] + nums[2] = 1 + 7 + 3 = 11 Right sum = nums[4] + nums[5] = 5 + 6 = 11 Example 2: Input: nums = [1,2,3] Output: -1 Explanation: There is no index that satisfies the conditions in the problem statement. */ fun main() { val solution = Solution() val myNums = intArrayOf(1, 7, 3, 6, 5, 6) println(solution.pivotIndex(myNums)) } //724 class Solution { fun pivotIndex(nums: IntArray): Int { var leftSum = 0 var rightSum = nums.sum() for (i in nums.indices) { rightSum -= nums[i] if (leftSum == rightSum) { return i } leftSum += nums[i] } return -1 } }
0
Kotlin
0
2
93365cddc95a2f5c8f2c136e5c18b438b38d915f
1,302
dsa-kotlin
MIT License
src/main/kotlin/g0501_0600/s0572_subtree_of_another_tree/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g0501_0600.s0572_subtree_of_another_tree // #Easy #Depth_First_Search #Tree #Binary_Tree #Hash_Function #String_Matching // #Algorithm_II_Day_7_Breadth_First_Search_Depth_First_Search // #2023_01_23_Time_214_ms_(92.39%)_Space_38.4_MB_(45.65%) import com_github_leetcode.TreeNode /* * Example: * var ti = TreeNode(5) * var v = ti.`val` * Definition for a binary tree node. * class TreeNode(var `val`: Int) { * var left: TreeNode? = null * var right: TreeNode? = null * } */ class Solution { private fun isSubtreeFound(root: TreeNode?, subRoot: TreeNode?): Boolean { if (root == null && subRoot == null) { return true } if (root == null || subRoot == null) { return false } return if (root.`val` == subRoot.`val`) { isSubtreeFound(root.left, subRoot.left) && isSubtree(root.right, subRoot.right) } else { false } } fun isSubtree(root: TreeNode?, subRoot: TreeNode?): Boolean { if (root == null && subRoot == null) { return true } return if (root == null || subRoot == null) { false } else isSubtreeFound(root, subRoot) || isSubtree(root.left, subRoot) || isSubtree(root.right, subRoot) } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,317
LeetCode-in-Kotlin
MIT License
src/main/kotlin/biz/koziolek/adventofcode/coords2d.kt
pkoziol
434,913,366
false
{"Kotlin": 715025, "Shell": 1892}
package biz.koziolek.adventofcode import kotlin.math.abs import kotlin.math.pow import kotlin.math.sqrt enum class Direction(val char: Char) { NORTH('^'), SOUTH('v'), WEST('<'), EAST('>'), } data class Coord(val x: Int, val y: Int) { operator fun plus(other: Coord) = Coord(x + other.x, y + other.y) operator fun minus(other: Coord) = Coord(x - other.x, y - other.y) operator fun unaryMinus() = Coord(-x, -y) override fun toString() = "$x,$y" fun toLong() = LongCoord(x, y) fun distanceTo(other: Coord) = sqrt( (x - other.x).toDouble().pow(2) + (y - other.y).toDouble().pow(2) ) infix fun manhattanDistanceTo(other: Coord): Int = abs(x - other.x) + abs(y - other.y) fun getAdjacentCoords(includeDiagonal: Boolean = false): Set<Coord> = if (includeDiagonal) { setOf( this + Coord(-1, 0), this + Coord(0, -1), this + Coord(1, 0), this + Coord(0, 1), this + Coord(-1, -1), this + Coord(1, -1), this + Coord(-1, 1), this + Coord(1, 1), ) } else { setOf( this + Coord(-1, 0), this + Coord(0, -1), this + Coord(1, 0), this + Coord(0, 1), ) } fun move(direction: Direction, count: Int = 1): Coord = when (direction) { Direction.NORTH -> copy(y = y - count) Direction.SOUTH -> copy(y = y + count) Direction.WEST -> copy(x = x - count) Direction.EAST -> copy(x = x + count) } fun walk(direction: Direction, distance: Int, includeCurrent: Boolean) = when (direction) { Direction.NORTH -> walkNorthTo(y - distance, includeCurrent) Direction.SOUTH -> walkSouthTo(y + distance, includeCurrent) Direction.WEST -> walkWestTo(x - distance, includeCurrent) Direction.EAST -> walkEastTo(x + distance, includeCurrent) } fun walkNorthTo(dstY: Int, includeCurrent: Boolean) = sequence { val startY = if (includeCurrent) y else y - 1 for (y in startY downTo dstY) { yield(Coord(x, y)) } } fun walkWestTo(dstX: Int, includeCurrent: Boolean) = sequence { val startX = if (includeCurrent) x else x - 1 for (x in startX downTo dstX) { yield(Coord(x, y)) } } fun walkSouthTo(dstY: Int, includeCurrent: Boolean) = sequence { val startY = if (includeCurrent) y else y + 1 for (y in startY..dstY) { yield(Coord(x, y)) } } fun walkEastTo(dstX: Int, includeCurrent: Boolean) = sequence { val startX = if (includeCurrent) x else x + 1 for (x in startX..dstX) { yield(Coord(x, y)) } } companion object { val yComparator: Comparator<Coord> = Comparator.comparing { it.y } val xComparator: Comparator<Coord> = Comparator.comparing { it.x } fun fromString(str: String): Coord = str.split(',') .map { it.trim().toInt() } .let { Coord(x = it[0], y = it[1]) } } } fun Iterable<String>.parse2DMap(): Sequence<Pair<Coord, Char>> = parse2DMap { it } fun <T> Iterable<String>.parse2DMap(valueMapper: (Char) -> T?): Sequence<Pair<Coord, T>> = sequence { forEachIndexed { y, line -> line.forEachIndexed { x, char -> val value = valueMapper(char) if (value != null) { yield(Coord(x, y) to value) } } } } fun IntProgression.zipAsCoord(ys: IntProgression) = zip(ys) { x, y -> Coord(x, y) } fun <T> Map<Coord, T>.getWidth() = getHorizontalRange().count() fun <T> Map<Coord, T>.getHeight() = getVerticalRange().count() fun <T> Map<Coord, T>.getHorizontalRange() = keys.minAndMaxOrNull { it.x }?.let { it.first..it.second } ?: IntRange.EMPTY fun <T> Map<Coord, T>.getVerticalRange() = keys.minAndMaxOrNull { it.y }?.let { it.first..it.second } ?: IntRange.EMPTY fun Iterable<Coord>.sortByYX() = sortedWith( Coord.yComparator.thenComparing(Coord.xComparator) ) /** * Walk north -> south, west -> east. * * |---> 1 * |---> 2 * |---> 3 * V */ fun <T> Map<Coord, T>.walkSouth() = sequence { val xRange = getHorizontalRange() val yRange = getVerticalRange() for (y in yRange) { for (x in xRange) { yield(Coord(x, y)) } } } /** * Walk west -> east, south -> north. * * 1 2 3 * ^ ^ ^ * | | | * | | | * -----> */ fun <T> Map<Coord, T>.walkEast() = sequence { val xRange = getHorizontalRange() val yRange = getVerticalRange() for (x in xRange) { for (y in yRange.reversed()) { yield(Coord(x, y)) } } } /** * Walk south -> north -> south, east -> west. * * ^ * 3 <---| * 2 <---| * 1 <---| */ fun <T> Map<Coord, T>.walkNorth() = sequence { val xRange = getHorizontalRange() val yRange = getVerticalRange() for (y in yRange.reversed()) { for (x in xRange.reversed()) { yield(Coord(x, y)) } } } /** * Walk east -> west, north -> south. * * <----- * | | | * | | | * V V V * 3 2 1 */ fun <T> Map<Coord, T>.walkWest() = sequence { val xRange = getHorizontalRange() val yRange = getVerticalRange() for (x in xRange.reversed()) { for (y in yRange) { yield(Coord(x, y)) } } } fun Map<Coord, Char>.to2DString(default: Char): String = to2DString { _, c -> c ?: default } fun <T> Map<Coord, T>.to2DString(formatter: (Coord, T?) -> Char): String = to2DStringOfStrings { coord, t -> formatter(coord, t).toString() } fun <T> Map<Coord, T>.to2DStringOfStrings(formatter: (Coord, T?) -> String): String = buildString { val (minX, maxX) = keys.minAndMaxOrNull { it.x }!! val (minY, maxY) = keys.minAndMaxOrNull { it.y }!! for (y in minY..maxY) { for (x in minX..maxX) { val coord = Coord(x, y) val value = get(coord) append(formatter(coord, value)) } if (y != maxY) { append('\n') } } } fun <T> Map<Coord, T>.to2DRainbowString(formatter: (Coord, T?) -> Pair<String, Float?>): String = to2DStringOfStrings { coord, value -> val (str, colorPercentage) = formatter(coord, value) if (colorPercentage != null) { AsciiColor.rainbow(colorPercentage, str) } else { str } } fun <T> Map<Coord, T>.getAdjacentCoords(coord: Coord, includeDiagonal: Boolean): Set<Coord> = keys.getAdjacentCoords(coord, includeDiagonal) fun Iterable<Coord>.getAdjacentCoords(coord: Coord, includeDiagonal: Boolean): Set<Coord> { return sequence { yield(Coord(-1, 0)) yield(Coord(0, -1)) yield(Coord(1, 0)) yield(Coord(0, 1)) if (includeDiagonal) { yield(Coord(-1, -1)) yield(Coord(1, -1)) yield(Coord(-1, 1)) yield(Coord(1, 1)) } } .map { coord + it } .filter { contains(it) } .toSet() } fun Map<Coord, Int>.toGraph(includeDiagonal: Boolean): Graph<CoordNode, UniDirectionalGraphEdge<CoordNode>> = buildGraph { this@toGraph.forEach { (coord, value) -> val node2 = coord.toGraphNode() getAdjacentCoords(coord, includeDiagonal) .forEach { adjCoord -> add(UniDirectionalGraphEdge( node1 = adjCoord.toGraphNode(), node2 = node2, weight = value, )) } } } fun Map<Coord, Int>.toBiDirectionalGraph(includeDiagonal: Boolean): Graph<CoordNode, BiDirectionalGraphEdge<CoordNode>> = buildGraph { this@toBiDirectionalGraph.forEach { (coord, value) -> val node2 = coord.toGraphNode() getAdjacentCoords(coord, includeDiagonal) .forEach { adjCoord -> add(BiDirectionalGraphEdge( node1 = adjCoord.toGraphNode(), node2 = node2, weight = value, )) } } } fun Coord.toGraphNode() = CoordNode(this) data class CoordNode(val coord: Coord) : GraphNode { override val id = "x${coord.x}_y${coord.y}" override fun toGraphvizString(exactXYPosition: Boolean, xyPositionScale: Float): String { val props = mutableListOf<String>() if (exactXYPosition) props.add("pos=\"${coord.x * xyPositionScale},${coord.y * xyPositionScale}!\"") val propsStr = when { props.isNotEmpty() -> " [" + props.joinToString(",") + "]" else -> "" } return "$id$propsStr" } }
0
Kotlin
0
0
1b1c6971bf45b89fd76bbcc503444d0d86617e95
9,140
advent-of-code
MIT License
src/Day03.kt
ezeferex
575,216,631
false
{"Kotlin": 6838}
object Constants { const val UPPER_CASE_PRIORITY = 38 const val LOWER_CASE_PRIORITY = 96 } fun Char.getPriority() = code - if (isLowerCase()) Constants.LOWER_CASE_PRIORITY else Constants.UPPER_CASE_PRIORITY fun main() { fun part1() = "Part 1: " + readInput("03").split("\n") .sumOf { val pockets = it.splitInTwo() var itemType = ' ' for (item in pockets.first.iterator()) { if (item in pockets.second) { itemType = item break } } itemType.getPriority() } fun part2() = "Part 2: " + readInput("03").split("\n") .windowed(3, 3) .sumOf { var items = it[0].toSet() it.forEach { bag -> items = items.intersect(bag.toSet()) } items.first().getPriority() } println(part1()) println(part2()) }
0
Kotlin
0
0
f06f8441ad0d7d4efb9ae449c9f7848a50f3f57c
934
advent-of-code-2022
Apache License 2.0
src/test/kotlin/ch/ranil/aoc/aoc2022/Day19.kt
stravag
572,872,641
false
{"Kotlin": 234222}
package ch.ranil.aoc.aoc2022 import ch.ranil.aoc.AbstractDay import org.junit.jupiter.api.Test import java.time.Duration import kotlin.test.Ignore import kotlin.test.assertEquals import kotlin.test.fail class Day19 : AbstractDay() { @Test fun part1Test() { assertEquals(33, compute1(testInput)) } @Test fun part1Puzzle() { assertEquals(1150, compute1(puzzleInput)) } @Test @Ignore fun part2Test() { assertEquals(56 * 62, compute2(testInput)) } @Test @Ignore fun part2Puzzle() { assertEquals(0, compute2(puzzleInput)) } private fun compute1(input: List<String>): Int { val results = input .map { Blueprint.parse(it) } .map { blueprint -> blueprint.number to maxGeodes(blueprint, 24) } return results.sumOf { (number, geodes) -> number * geodes } } private fun compute2(input: List<String>): Int { val results = input .map { Blueprint.parse(it) } .take(3) .map { blueprint -> maxGeodes(blueprint, 32) } return results.reduce { acc, i -> acc * i } } private fun maxGeodes(blueprint: Blueprint, minutes: Int): Int { println("Starting $blueprint") val startTime = System.currentTimeMillis() var max = 0 var iteration = 0L val statesCache = HashSet<State>() val states = mutableListOf( State( robots = Robots(oreRobots = 1), resources = Resources(), remainingMinutes = minutes, ) ) while (states.isNotEmpty()) { iteration++ val state = states.removeLast() if (state.robots.clayRobots == 0 || state.robots.obsidianRobots == 0) { val minutesUntilObsidianRobot = blueprint.minutesUntilProduced(Action.BUILD_OBSIDIAN_ROBOT, state) val minutesUntilGeodeRobot = blueprint.minutesUntilProduced(Action.BUILD_GEODE_ROBOT, state) if (minutesUntilObsidianRobot + minutesUntilGeodeRobot >= state.remainingMinutes) { // abort not enough time left to build any geode robots continue } if (maxProduction(state.remainingMinutes - minutesUntilObsidianRobot - minutesUntilGeodeRobot) <= max) { // even best case not better continue } } else if (state.robots.geodeRobots == 0) { val minutesUntilGeodeRobot = blueprint.minutesUntilProduced(Action.BUILD_GEODE_ROBOT, state) if (maxProduction(state.remainingMinutes - minutesUntilGeodeRobot) <= max) { continue } } if (statesCache.contains(state)) { continue } statesCache.add(state) val nextStates = state.nextPossibleStates(blueprint) nextStates.forEach { nextState -> if (nextState.remainingMinutes == 0) { if (nextState.resources.geode > max) { max = nextState.resources.geode val duration = Duration.ofMillis(System.currentTimeMillis() - startTime) println("$max - iteration $iteration, $duration") } } else { states.add(nextState) } } } val duration = Duration.ofMillis(System.currentTimeMillis() - startTime) println("Took $iteration iterations, $duration") return max } private fun maxProduction(minutes: Int): Int { return (0 until minutes).sum() } private data class Blueprint( val number: Int, private val requiredResourcesForAction: Map<Action, Resources>, ) { fun requiredResources(action: Action): Resources { return requiredResourcesForAction[action] ?: Resources() } fun maxRequiredResources(type: (Resources) -> Int): Int { return requiredResourcesForAction.values.maxOfOrNull(type) ?: 0 } fun minutesUntilProduced(action: Action, state: State): Int { val required = requiredResources(action) return when (action) { Action.NOOP -> 0 Action.BUILD_ORE_ROBOT -> minutesUntilProduced( count = required.ore, startingCount = state.resources.ore, startingRobots = state.robots.oreRobots ) Action.BUILD_CLAY_ROBOT -> minutesUntilProduced( count = required.ore, startingCount = state.resources.ore, startingRobots = state.robots.oreRobots ) // only clay of interest Action.BUILD_OBSIDIAN_ROBOT -> minutesUntilProduced( count = required.clay, startingCount = state.resources.clay, startingRobots = state.robots.clayRobots, ) // only obsidian of interest Action.BUILD_GEODE_ROBOT -> minutesUntilProduced( required.obsidian, state.resources.obsidian, state.robots.obsidianRobots ) } } private fun minutesUntilProduced(count: Int, startingCount: Int, startingRobots: Int): Int { var minutes = 0 var robots = startingRobots var sum = startingCount while (true) { sum += robots if (sum >= count) { return minutes } robots++ minutes++ } } companion object { fun parse(line: String): Blueprint { val (namePart, rulesPart) = line.split(":") val number = namePart.split(" ").last().toInt() val rulesParts = rulesPart.split(".").map { it.split(" ").mapNotNull { num -> num.toIntOrNull() } } val oreRobotRequires = Resources( ore = rulesParts[0][0] ) val clayRobotRequires = Resources( ore = rulesParts[1][0] ) val obsidianRobotRequires = Resources( ore = rulesParts[2][0], clay = rulesParts[2][1], ) val geodeRobotRequires = Resources( ore = rulesParts[3][0], obsidian = rulesParts[3][1], ) return Blueprint( number = number, requiredResourcesForAction = mapOf( Action.BUILD_ORE_ROBOT to oreRobotRequires, Action.BUILD_CLAY_ROBOT to clayRobotRequires, Action.BUILD_OBSIDIAN_ROBOT to obsidianRobotRequires, Action.BUILD_GEODE_ROBOT to geodeRobotRequires, ) ) } } } private enum class Action { NOOP, BUILD_ORE_ROBOT, BUILD_CLAY_ROBOT, BUILD_OBSIDIAN_ROBOT, BUILD_GEODE_ROBOT, } private data class State( val robots: Robots, val resources: Resources, val remainingMinutes: Int, ) { fun next(action: Action, blueprint: Blueprint): State { val requiredResources = blueprint.requiredResources(action) val resourcesAfterActionAndGathering = resources - requiredResources + robots return State( robots = robots.build(action), resources = resourcesAfterActionAndGathering, remainingMinutes = remainingMinutes - 1 ) } fun nextPossibleStates(blueprint: Blueprint): List<State> { val nextPossibleActions = nextPossibleActions(blueprint) return nextPossibleActions.map { action -> next(action, blueprint) } } private fun nextPossibleActions(blueprint: Blueprint): List<Action> { if (can(Action.BUILD_GEODE_ROBOT, blueprint)) { return listOf(Action.BUILD_GEODE_ROBOT) } val actions = ArrayList<Action>(4) if (can(Action.BUILD_OBSIDIAN_ROBOT, blueprint)) { val maxObsidianConsumption = blueprint.maxRequiredResources { it.obsidian } * remainingMinutes val obsidianProductionCapacity = resources.obsidian + (robots.obsidianRobots * remainingMinutes) if (maxObsidianConsumption > obsidianProductionCapacity) { actions.add(Action.BUILD_OBSIDIAN_ROBOT) } } if (can(Action.BUILD_CLAY_ROBOT, blueprint)) { val maxClayConsumption = blueprint.maxRequiredResources { it.clay } * remainingMinutes val clayProductionCapacity = resources.clay + (robots.clayRobots * remainingMinutes) if (maxClayConsumption > clayProductionCapacity) { actions.add(Action.BUILD_CLAY_ROBOT) } } if (can(Action.BUILD_ORE_ROBOT, blueprint)) { val maxOreConsumption = blueprint.maxRequiredResources { it.ore } * remainingMinutes val oreProductionCapacity = resources.ore + (robots.oreRobots * remainingMinutes) if (maxOreConsumption > oreProductionCapacity) { actions.add(Action.BUILD_ORE_ROBOT) } } actions.add(Action.NOOP); return actions } private fun can(action: Action, blueprint: Blueprint): Boolean { val requiredResources = blueprint.requiredResources(action) return resources.ore >= requiredResources.ore && resources.clay >= requiredResources.clay && resources.obsidian >= requiredResources.obsidian && resources.geode >= requiredResources.geode } } private data class Resources( val ore: Int = 0, val clay: Int = 0, val obsidian: Int = 0, val geode: Int = 0, ) { operator fun minus(other: Resources): Resources { return Resources( ore = ore - other.ore, clay = clay - other.clay, obsidian = obsidian - other.obsidian, geode = geode - other.geode, ) } operator fun plus(other: Resources): Resources { return Resources( ore = ore + other.ore, clay = clay + other.clay, obsidian = obsidian + other.obsidian, geode = geode + other.geode, ) } operator fun plus(other: Robots): Resources { return Resources( ore = ore + other.oreRobots, clay = clay + other.clayRobots, obsidian = obsidian + other.obsidianRobots, geode = geode + other.geodeRobots, ) } } private data class Robots( val oreRobots: Int = 0, val clayRobots: Int = 0, val obsidianRobots: Int = 0, val geodeRobots: Int = 0, ) { fun build(action: Action): Robots { return when (action) { Action.NOOP -> copy() Action.BUILD_ORE_ROBOT -> copy(oreRobots = oreRobots + 1) Action.BUILD_CLAY_ROBOT -> copy(clayRobots = clayRobots + 1) Action.BUILD_OBSIDIAN_ROBOT -> copy(obsidianRobots = obsidianRobots + 1) Action.BUILD_GEODE_ROBOT -> copy(geodeRobots = geodeRobots + 1) } } } }
0
Kotlin
1
0
dbd25877071cbb015f8da161afb30cf1968249a8
11,766
aoc
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/NumberOfUniqueGoodSubsequences.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 /** * 1987. Number of Unique Good Subsequences * @see <a href="https://leetcode.com/problems/number-of-unique-good-subsequences/">Source</a> */ fun numberOfUniqueGoodSubsequences(binary: String): Int { val mod = E + 7 var ends0 = 0 var ends1 = 0 var has0 = 0 for (i in binary.indices) { if (binary[i] == '1') { ends1 = (ends0 + ends1 + 1) % mod } else { ends0 = (ends0 + ends1) % mod has0 = 1 } } return (ends0 + ends1 + has0) % mod } private const val E = 1e9.toInt()
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,203
kotlab
Apache License 2.0
src/main/kotlin/aoc01/solution.kt
dnene
317,653,484
false
null
package aoc01 import java.io.File fun <T> List<T>.combinations(r: Int, start: Int = 0): List<List<T>> = if (r <= size - start) { (start..size-start-r).flatMap { combinations(r-1, start+1) } } else listOf<List<T>>() fun <T> List<T>.combinationsOfTwo(): List<Pair<T, T>> = (0..size - 2).flatMap { outer -> (outer + 1 until size).map { inner -> this[outer] to this[inner] } } fun <T> List<T>.combinationsOfThree(): List<Triple<T, T, T>> = (0..size - 3).flatMap { outer -> (outer + 1..size - 2).flatMap { middle -> (middle + 1 until size).map { inner -> Triple(this[outer], this[middle], this[inner]) } } } fun main(args: Array<String>) { File("data/inputs/aoc01.txt") .readLines() .map { it.toInt() } .run { combinations(2) .filter { it[0] + it[1] == 2020 } .map { println(it); println(it[0] * it[1]) } combinations(3) .filter { it[0] + it[1] + it[2] == 2020 } .forEach { println(it); println(it[0] * it[1] * it[2]) } } }
0
Kotlin
0
0
db0a2f8b484575fc3f02dc9617a433b1d3e900f1
1,184
aoc2020
MIT License
kotlin/src/main/kotlin/dev/mikeburgess/euler/problems/Problem033.kt
mddburgess
261,028,925
false
null
package dev.mikeburgess.euler.problems import dev.mikeburgess.euler.common.gcd /** * Problem 33 * * The fraction 49/98 is a curious fraction, as an inexperienced mathematician in attempting to * simplify it may incorrectly believe that 49/98 = 4/8, which is correct, is obtained by * cancelling the 9s. * * We shall consider fractions like, 30/50 = 3/5, to be trivial examples. * * There are exactly four non-trivial examples of this type of fraction, less than one in value, * and containing two digits in the numerator and denominator. * * If the product of these four fractions is given in its lowest common terms, find the value of * the denominator. */ class Problem033 : Problem { override fun solve(): Long { var numProduct = 1L var denProduct = 1L for (i in 1..9) { for (den in 1..9) { for (num in 1 until den) { if (den * (10 * num + i) == num * (10 * i + den)) { numProduct *= num denProduct *= den } } } } return denProduct / gcd(numProduct, denProduct) } }
0
Kotlin
0
0
86518be1ac8bde25afcaf82ba5984b81589b7bc9
1,178
project-euler
MIT License
src/main/kotlin/com/zachjones/languageclassifier/core/Adaboost.kt
zachtjones
184,465,284
false
{"Kotlin": 73431}
package com.zachjones.languageclassifier.core import com.zachjones.languageclassifier.attribute.Attribute import com.zachjones.languageclassifier.entities.InputRow import com.zachjones.languageclassifier.entities.LanguageDecision import com.zachjones.languageclassifier.entities.MultiLanguageDecision import com.zachjones.languageclassifier.entities.WeightedList import com.zachjones.languageclassifier.model.types.Language import java.util.stream.Collectors class Adaboost private constructor(input: WeightedList<InputRow>) : Decider { /** weighted inputs and hypotheses used in learning. * These weights change as we go through. */ private var inputs: WeightedList<InputRow> /** This one is the weights according to the correct % of each hypothesis. * We need to keep this not normalized and then do the normalization at the end of each iteration. */ private val hypotheses = WeightedList<Decider>() /** This list will always be a normalized list of the individual stumps. */ private var normalizedHypotheses: WeightedList<Decider>? = null /** Private constructor to create an Adaboost ensemble */ init { this.inputs = input } /** Represents the ensemble's decision on the input row. */ override fun decide(row: InputRow): LanguageDecision { // map the first language to -1, and the second language to 1 val weights = WeightedList<LanguageDecision>() for (i in 0 until normalizedHypotheses!!.size()) { // iterate through the hypotheses, weighting their predictions val weight = normalizedHypotheses!!.getWeight(i) weights.addWeight(weight, normalizedHypotheses!!.getItem(i).decide(row)) } weights.normalize() val mapWeights = mutableMapOf<Language, Double>() Language.values().forEach { mapWeights[it] = 0.0 } weights.stream().forEach {(decisionConfidence, languageDecision) -> languageDecision.confidences().forEach { (language, languageConfidence) -> mapWeights[language] = mapWeights[language]!! + (languageConfidence * decisionConfidence) } } return MultiLanguageDecision(weights = mapWeights) } override fun representation(numSpaces: Int): String { val rep = "Adaboost on the following " + hypotheses.size() + " decision stumps:\n" val each = normalizedHypotheses!!.stream() .map { i: Pair<Double, Decider> -> """ Weight: ${i.first}, stump: ${i.second.representation(0)} """.trimIndent() } .collect(Collectors.joining("\n\n")) return """ $rep $each """.trimIndent() } companion object { /** Learns using the Adaboost technique on decision stumps. * This learns a binary classifier between the two languages. * @param inputs The inputs to decide on. Should initially be unweighted. * @param ensembleSize The number of stumps to create. * @param attributes The set of potential attributes to use. * @param languageOne The first language of the inputs * @param languageTwo The second language of the inputs */ fun learn( inputs: WeightedList<InputRow>, ensembleSize: Int, attributes: Set<Attribute>, languageOne: Language, languageTwo: Language ): Decider { val result = Adaboost(inputs) val totalSize = inputs.size() for (i in 0 until ensembleSize) { val newHypothesis = DecisionTree.learn(result.inputs, 1, attributes, totalSize, languageOne, languageTwo) var error = 0.0 for (j in 0 until inputs.size()) { val row = inputs[j] // weight, example if (newHypothesis.decide(row.second).mostConfidentLanguage() != row.second.language) { error += row.first } } // special case: we learn it 100%, should just add it with normal weight if (error == 0.0) { result.hypotheses.addWeight(1.0, newHypothesis) result.normalizedHypotheses = result.hypotheses.normalize() break } // reduce the weights of the ones we got right val reductionRate = error / (1 - error) for (j in 0 until result.inputs.size()) { val row = result.inputs[j] if (newHypothesis.decide(row.second).mostConfidentLanguage() == row.second.language) { result.inputs.setWeight(j, result.inputs.getWeight(j) * reductionRate) } } // normalize weights result.inputs = result.inputs.normalize() // calculate the weight for this hypothesis and add it result.hypotheses.addWeight(DecisionTree.log2((1 - error) / error), newHypothesis) result.normalizedHypotheses = result.hypotheses.normalize() } return result } } }
0
Kotlin
0
1
dfe8710fcf8daa1bc57ad90f7fa3c07a228b819f
5,246
Multi-Language-Classifier
Apache License 2.0
src/commonMain/kotlin/ai/hypergraph/kaliningraph/parsing/BarHillel.kt
breandan
245,074,037
false
{"Kotlin": 1482924, "Haskell": 744, "OCaml": 200}
package ai.hypergraph.kaliningraph.parsing import ai.hypergraph.kaliningraph.automata.* import ai.hypergraph.kaliningraph.types.* import ai.hypergraph.kaliningraph.types.times import kotlin.time.TimeSource /** * Specialized Bar-Hillel construction for Levenshtein automata. See also * [FSA.intersect] for the generic Bar-Hillel version with arbitrary FSA. */ infix fun FSA.intersectLevFSA(cfg: CFG) = cfg.intersectLevFSA(this) infix fun CFG.intersectLevFSA(fsa: FSA): CFG = intersectLevFSAP(fsa) // subgrammar(fsa.alphabet) // .also { it.forEach { println("${it.LHS} -> ${it.RHS.joinToString(" ")}") } } fun CFG.makeLevGrammar(source: List<Σᐩ>, distance: Int) = intersectLevFSA(makeLevFSA(source, distance)) fun CFG.barHillelRepair(prompt: List<Σᐩ>, distance: Int) = makeLevGrammar(prompt, distance).enumSeq(List(prompt.size + distance) { "_" }) // http://www.cs.umd.edu/~gasarch/BLOGPAPERS/cfg.pdf#page=2 // https://browse.arxiv.org/pdf/2209.06809.pdf#page=5 private infix fun CFG.intersectLevFSAP(fsa: FSA): CFG { var clock = TimeSource.Monotonic.markNow() val lengthBoundsCache = lengthBounds val nts = mutableSetOf("START") fun Σᐩ.isSyntheticNT() = first() == '[' && last() == ']' && count { it == '~' } == 2 fun List<Production>.filterRHSInNTS() = asSequence().filter { (_, rhs) -> rhs.all { !it.isSyntheticNT() || it in nts } } val initFinal = (fsa.init * fsa.final).map { (q, r) -> "START" to listOf("[$q~START~$r]") } .filterRHSInNTS() val transits = fsa.Q.map { (q, a, r) -> "[$q~$a~$r]".also { nts.add(it) } to listOf(a) } .filterRHSInNTS() // For every production A → σ in P, for every (p, σ, q) ∈ Q × Σ × Q // such that δ(p, σ) = q we have the production [p, A, q] → σ in P′. val unitProds = unitProdRules(fsa) .onEach { (a, _) -> nts.add(a) }.filterRHSInNTS() // For each production A → BC in P, for every p, q, r ∈ Q, // we have the production [p,A,r] → [p,B,q] [q,C,r] in P′. val validTriples = fsa.stateCoords.let { it * it * it }.filter { it.isValidStateTriple() }.toList() val binaryProds = nonterminalProductions.map { // if (i % 100 == 0) println("Finished ${i}/${nonterminalProductions.size} productions") val (A, B, C) = it.π1 to it.π2[0] to it.π2[1] validTriples // CFG ∩ FSA - in general we are not allowed to do this, but it works // because we assume a Levenshtein FSA, which is monotone and acyclic. .filter { it.isCompatibleWith(A to B to C, fsa, lengthBoundsCache) } .map { (a, b, c) -> val (p, q, r) = a.π1 to b.π1 to c.π1 "[$p~$A~$r]".also { nts.add(it) } to listOf("[$p~$B~$q]", "[$q~$C~$r]") }.toList() }.flatten().filterRHSInNTS() println("Constructing ∩-grammar took: ${clock.elapsedNow()}") clock = TimeSource.Monotonic.markNow() return (initFinal + transits + binaryProds + unitProds).toSet().postProcess() .also { println("Bar-Hillel construction took ${clock.elapsedNow()}") } } // For every production A → σ in P, for every (p, σ, q) ∈ Q × Σ × Q // such that δ(p, σ) = q we have the production [p, A, q] → σ in P′. fun CFG.unitProdRules(fsa: FSA): List<Pair<String, List<Σᐩ>>> = (unitProductions * fsa.nominalize().flattenedTriples) .filter { (_, σ, arc) -> (arc.π2)(σ) } .map { (A, σ, arc) -> "[${arc.π1}~$A~${arc.π3}]" to listOf(σ) } fun CFG.postProcess() = this.also { println("∩-grammar has ${it.size} total productions") } .dropVestigialProductions() .normalForm .noEpsilonOrNonterminalStubs .also { println("∩-grammar has ${it.size} useful productions") } .freeze() // .also { println(it.pretty) } // .also { println(it.size) } // Recursively removes all productions from a synthetic CFG containing a // dangling nonterminal, i.e., a nonterminal that does not produce any terminals // // This works but is the most inefficient part of the current implementation... // // TODO: Maybe instead of creating an enormous CFG and then removing productions // we can just create a CFG that only contains the productions we need, by // starting from the terminals and working our way up to START? // Consider: // ∩-grammar has 96634 total productions // Removed 81177 vestigial productions. // Removed 15035 vestigial productions. // Removed 331 vestigial productions. // Removed 57 vestigial productions. // Removed 7 vestigial productions. // Removed 0 vestigial productions. // Disabling nonterminal stubs! // ∩-grammar has 56 useful productions <- Why can't we just create this CFG?! fun CFG.dropVestigialProductions( criteria: (Σᐩ) -> Boolean = { it.first() == '[' && it.last() == ']' && it.count { it == '~' } == 2 } ): CFG { val nts: Set<Σᐩ> = map { it.LHS }.toSet() // val reachable = reachableSymbols() // val rw = toMutableSet() // .apply { removeAll { prod -> prod.RHS.any { criteria(it) && it !in nts } } } // .also { println("Removed ${size - it.size} invalid productions") } // .freeze().removeUselessSymbols() val rw = asSequence().filter { prod -> prod.RHS.all { !criteria(it) || it in nts } }.toSet() .also { println("Removed ${size - it.size} invalid productions") } .freeze().removeUselessSymbols() println("Removed ${size - rw.size} vestigial productions, resulting in ${rw.size} productions.") return if (rw.size == size) rw else rw.dropVestigialProductions(criteria) } // Generic Bar-Hillel construction for arbitrary CFL ∩ REG language infix fun FSA.intersect(cfg: CFG) = cfg.freeze().intersect(this) infix fun CFG.intersect(fsa: FSA): CFG { val clock = TimeSource.Monotonic.markNow() val initFinal = (fsa.init * fsa.final).map { (q, r) -> "START" to listOf("[$q~START~$r]") } val transits = fsa.Q.map { (q, a, r) -> "[$q~$a~$r]" to listOf(a) } // For every production A → σ in P, for every (p, σ, q) ∈ Q × Σ × Q // such that δ(p, σ) = q we have the production [p, A, q] → σ in P′. val unitProds = unitProdRules(fsa) // For each production A → BC in P, for every p, q, r ∈ Q, // we have the production [p,A,r] → [p,B,q] [q,C,r] in P′. val binaryProds = nonterminalProductions.mapIndexed { i, it -> val triples = fsa.states * fsa.states * fsa.states val (A, B, C) = it.π1 to it.π2[0] to it.π2[1] triples.map { (p, q, r) -> "[$p~$A~$r]" to listOf("[$p~$B~$q]", "[$q~$C~$r]") } }.flatten() return (initFinal + transits + binaryProds + unitProds).toSet().postProcess() .also { println("Postprocessing took ${clock.elapsedNow()}") } } // Tracks the number of tokens a given nonterminal can represent // e.g., a NT with a bound of 1..3 can parse { s: Σ^[1, 3] } val CFG.lengthBounds: Map<Σᐩ, IntRange> by cache { // val clock = TimeSource.Monotonic.markNow() val epsFree = noEpsilonOrNonterminalStubs.freeze() val tpl = List(20) { "_" } val map = epsFree.nonterminals.associateWith { -1..-1 }.toMutableMap() epsFree.initPForestMat(tpl).seekFixpoint().diagonals.mapIndexed { idx, sets -> sets.flatMap { it.map { it.key } }.forEach { nt -> map[nt]?.let { (if (it.first < 0) (idx + 1) else it.first)..(idx + 1) }?.let { map[nt] = it } } } // println("Computed NT length bounds in ${clock.elapsedNow()}") map } fun Π3A<STC>.isValidStateTriple(): Boolean { fun Pair<Int, Int>.dominates(other: Pair<Int, Int>) = first <= other.first && second <= other.second return first.coords().dominates(second.coords()) && second.coords().dominates(third.coords()) } fun Π3A<STC>.isCompatibleWith(nts: Triple<Σᐩ, Σᐩ, Σᐩ>, fsa: FSA, lengthBounds: Map<Σᐩ, IntRange>): Boolean { fun lengthBounds(nt: Σᐩ, fudge: Int = 20): IntRange = (lengthBounds[nt] ?: -1..-1) // Okay if we overapproximate the length bounds a bit .let { (it.first - fudge)..(it.last + fudge) } fun manhattanDistance(first: Pair<Int, Int>, second: Pair<Int, Int>): Int = second.second - first.second + second.first - first.first // Range of the shortest path to the longest path, i.e., Manhattan distance fun SPLP(a: STC, b: STC) = (fsa.APSP[a.π1 to b.π1] ?: Int.MAX_VALUE).. manhattanDistance(a.coords(), b.coords()) fun IntRange.overlaps(other: IntRange) = (other.first in first..last) || (other.last in first..last) // "[$p,$A,$r] -> [$p,$B,$q] [$q,$C,$r]" fun isCompatible() = lengthBounds(nts.first).overlaps(SPLP(first, third)) && lengthBounds(nts.second).overlaps(SPLP(first, second)) && lengthBounds(nts.third).overlaps(SPLP(second, third)) return isCompatible() }
0
Kotlin
8
100
c755dc4858ed2c202c71e12b083ab0518d113714
8,732
galoisenne
Apache License 2.0
src/main/kotlin/com/kishor/kotlin/algo/algorithms/graph/MinKnightMoves.kt
kishorsutar
276,212,164
false
null
package com.kishor.kotlin.algo.algorithms.graph import java.util.HashSet import java.util.LinkedList import java.util.Queue import java.util.Deque import java.util.HashMap internal class MinKnightMoves { fun minKnightMoves(x: Int, y: Int): Int { var x = x var y = y x = Math.abs(x) y = Math.abs(y) if (x == 0 && y == 0) return 0 val queue: Queue<Pair<Int, Int>> = LinkedList() val set: MutableSet<Pair<Int, Int>> = HashSet() queue.add(Pair(0, 0)) set.add(queue.peek()) val dirs = arrayOf( intArrayOf(2, 1), intArrayOf(-2, 1), intArrayOf(2, -1), intArrayOf(-2, -1), intArrayOf(1, 2), intArrayOf(-1, 2), intArrayOf(1, -2), intArrayOf(-1, -2) ) var level = 0 while (!queue.isEmpty()) { val size = queue.size for (i in 0 until size) { val parent = queue.poll() for (dir in dirs) { val x0: Int = Math.abs(parent.first + dir[0]) val y0: Int = Math.abs(parent.second + dir[1]) if (x0 == x && y0 == y) return level + 1 val child = Pair(x0, y0) if (!set.contains(child)) { set.add(child) queue.add(child) } } } level++ } return level } fun minKnightMovesUsingArray(x: Int, y: Int): Int { // the offsets in the eight directions val offsets = arrayOf( intArrayOf(1, 2), intArrayOf(2, 1), intArrayOf(2, -1), intArrayOf(1, -2), intArrayOf(-1, -2), intArrayOf(-2, -1), intArrayOf(-2, 1), intArrayOf(-1, 2) ) // - Rather than using the inefficient HashSet, we use the bitmap // otherwise we would run out of time for the test cases. // - We create a bitmap that is sufficient to cover all the possible // inputs, according to the description of the problem. val visited = Array(605) { BooleanArray(605) } val queue: Deque<IntArray> = LinkedList() queue.addLast(intArrayOf(0, 0)) var steps = 0 while (queue.size > 0) { val currLevelSize = queue.size // iterate through the current level for (i in 0 until currLevelSize) { val curr = queue.removeFirst() if (curr[0] == x && curr[1] == y) { return steps } for (offset in offsets) { val next = intArrayOf(curr[0] + offset[0], curr[1] + offset[1]) // align the coordinate to the bitmap if (!visited[next[0] + 302][next[1] + 302]) { visited[next[0] + 302][next[1] + 302] = true queue.addLast(next) } } } steps++ } // move on to the next level return steps } // DFS private val memo: MutableMap<String, Int?> = HashMap() private fun dfs(x: Int, y: Int): Int { val key = "$x,$y" if (memo.containsKey(key)) { return memo[key]!! } return if (x + y == 0) { 0 } else if (x + y == 2) { 2 } else { val ret = Math.min( dfs(Math.abs(x - 1), Math.abs(y - 2)), dfs(Math.abs(x - 2), Math.abs(y - 1)) ) + 1 memo[key] = ret ret } } fun minKnightMovesDfs(x: Int, y: Int): Int { return dfs(Math.abs(x), Math.abs(y)) } }
0
Kotlin
0
0
6672d7738b035202ece6f148fde05867f6d4d94c
3,848
DS_Algo_Kotlin
MIT License
lib/src/main/kotlin/aoc/day10/Day10.kt
Denaun
636,769,784
false
null
package aoc.day10 fun part1(input: String): Int = execute(parse(input)) .withIndex() .drop(20) .windowed(1, 40) .sumOf { (x) -> x.value * x.index } fun part2(input: String): String = execute(parse(input)).draw() fun execute(instructions: List<Instruction>): Sequence<Int> = sequence { var x = 1 yield(x) for (instruction in instructions) { repeat(instruction.cycles) { yield(x) } if (instruction is AddX) { x += instruction.v } } yield(x) } fun Sequence<Int>.draw(): String { val litPixels = List(6) { MutableList(40) { false } } for ((cycle, offset) in drop(1).withIndex()) { val column = cycle % 40 val row = (cycle / 40) % 6 if (offset - 1 <= column && column <= offset + 1) { litPixels[row][column] = true } } return litPixels.joinToString("\n") { it.joinToString("") { isLit -> if (isLit) { "#" } else { "." } } } }
0
Kotlin
0
0
560f6e33f8ca46e631879297fadc0bc884ac5620
1,064
aoc-2022
Apache License 2.0
kotlin/0673-number-of-longest-increasing-subsequence.kt
neetcode-gh
331,360,188
false
{"JavaScript": 473974, "Kotlin": 418778, "Java": 372274, "C++": 353616, "C": 254169, "Python": 207536, "C#": 188620, "Rust": 155910, "TypeScript": 144641, "Go": 131749, "Swift": 111061, "Ruby": 44099, "Scala": 26287, "Dart": 9750}
/* * DFS + memoization solution */ class Solution { fun findNumberOfLIS(nums: IntArray): Int { val memo = HashMap<Int, Pair<Int, Int>>() var lisLen = 0 var lisCount = 0 fun dfs(i: Int): Pair<Int, Int> { if (i in memo) return memo[i]!! var maxLen = 1 var maxCount = 1 for (j in i+1 until nums.size) { if (nums[i] < nums[j]) { val (curLen, curCount) = dfs(j) if (curLen + 1 > maxLen) { maxLen = curLen + 1 maxCount = curCount } else if (curLen + 1 == maxLen) { maxCount += curCount } } } if (maxLen > lisLen) { lisLen = maxLen lisCount = maxCount } else if (maxLen == lisLen) { lisCount += maxCount } memo[i] = (maxLen to maxCount) return memo[i]!! } for (i in nums.indices) dfs(i) return lisCount } } /* * DP solution */ class Solution { fun findNumberOfLIS(nums: IntArray): Int { val lis = IntArray(nums.size) {1} val count = IntArray(nums.size) var lisLen = 0 var lisCount = 0 for (i in nums.size-1 downTo 0) { var maxLen = 1 var maxCount = 1 for (j in i+1 until nums.size) { if (nums[i] < nums[j]) { val curLen = lis[j] val curCount = count[j] if (curLen + 1 > maxLen) { maxLen = curLen + 1 maxCount = curCount } else if (curLen + 1 == maxLen) { maxCount += curCount } } } if (maxLen > lisLen) { lisLen = maxLen lisCount = maxCount } else if (maxLen == lisLen) { lisCount += maxCount } lis[i] = maxLen count[i] = maxCount } return lisCount } }
337
JavaScript
2,004
4,367
0cf38f0d05cd76f9e96f08da22e063353af86224
2,244
leetcode
MIT License
day17/Kotlin/day17.kt
Ad0lphus
353,610,043
false
{"C++": 195638, "Python": 139359, "Kotlin": 80248}
import java.io.* fun print_day_17() { val yellow = "\u001B[33m" val reset = "\u001b[0m" val green = "\u001B[32m" println(yellow + "-".repeat(25) + "Advent of Code - Day 17" + "-".repeat(25) + reset) println(green) val process = Runtime.getRuntime().exec("figlet Trick Shot -c -f small") val reader = BufferedReader(InputStreamReader(process.inputStream)) reader.forEachLine { println(it) } println(reset) println(yellow + "-".repeat(33) + "Output" + "-".repeat(33) + reset + "\n") } fun main() { print_day_17() println("Puzzle 1: ${Day17().part_1()}") println("Puzzle 2: ${Day17().part_2()}") println("\n" + "\u001B[33m" + "=".repeat(72) + "\u001b[0m" + "\n") } class Day17 { data class BoundingBox(val xRange: IntRange, val yRange: IntRange) private val target = File("../Input/day17.txt").readLines().first().drop(13) .split(", ").map { it.drop(2).split("..").let { (a, b) -> a.toInt()..b.toInt() }} .let { BoundingBox(it[0], it[1]) } fun part_1() = (1..400).flatMap { x -> (1..400).map { y -> checkStep(x, y, target) } }.fold(0) { max, step -> if (step.first) maxOf(max, step.second) else max } fun part_2() = (1..400).flatMap { x -> (-400..400).map { y -> checkStep(x, y, target).first } }.count { it } data class Coord(var x:Int, var y:Int) data class Velocity(var x:Int, var y:Int) private fun checkStep(xVelocity: Int, yVelocity: Int, target: BoundingBox): Pair<Boolean, Int> { val p = Coord(0, 0) val v = Velocity(xVelocity, yVelocity) var maxHeight = 0 var hitTarget = false while (p.x <= target.xRange.last && p.y >= target.yRange.first) { p.x += v.x p.y += v.y maxHeight = maxOf(p.y, maxHeight) if (p.x in target.xRange && p.y in target.yRange) { hitTarget = true break } if (v.x > 0) v.x-- v.y-- } return Pair(hitTarget, maxHeight) } }
0
C++
0
0
02f219ea278d85c7799d739294c664aa5a47719a
2,039
AOC2021
Apache License 2.0
src/main/kotlin/tr/emreone/adventofcode/days/Day5.kt
EmRe-One
434,793,519
false
{"Kotlin": 44202}
package tr.emreone.adventofcode.days object Day5 { fun part1(input: List<String>): Int { return input.count { line -> val condition1 = line.count { arrayOf('a', 'e', 'i', 'o', 'u').contains(it) } >= 3 val condition2 = line.windowed(2).count { it[0] == it[1] } > 0 val condition3 = line.windowed(2).count { arrayOf("ab", "cd", "pq", "xy").contains(it) } > 0 condition1 && condition2 && !condition3 } } fun part2(input: List<String>): Int { return input.count { line -> val condition1 = line.windowed(2).count { val regex = """($it)([a-zA-Z]*)($it)""".toRegex() val match = regex.find(line) match != null } > 0 val condition2 = line.windowed(3).count { it[0] == it[2] } > 0 condition1 && condition2 } } }
0
Kotlin
0
0
57f6dea222f4f3e97b697b3b0c7af58f01fc4f53
1,014
advent-of-code-2015
Apache License 2.0
src/main/kotlin/year2023/day14/Problem.kt
Ddxcv98
573,823,241
false
{"Kotlin": 154634}
package year2023.day14 import IProblem class Problem : IProblem { private val lines = javaClass .getResourceAsStream("/2023/14.txt")!! .bufferedReader() .lines() .toList() private fun north(matrix: Array<CharArray>) { for (j in matrix[0].indices) { var idx = 0 for (i in matrix.indices) { when (matrix[i][j]) { '#' -> idx = i + 1 'O' -> { matrix[i][j] = '.' matrix[idx++][j] = 'O' } } } } } private fun west(matrix: Array<CharArray>) { for (i in matrix.indices) { var idx = 0 for (j in matrix[0].indices) { when (matrix[i][j]) { '#' -> idx = j + 1 'O' -> { matrix[i][j] = '.' matrix[i][idx++] = 'O' } } } } } private fun south(matrix: Array<CharArray>) { for (j in matrix[0].indices) { var idx = matrix.size - 1 for (i in matrix.indices.reversed()) { when (matrix[i][j]) { '#' -> idx = i - 1 'O' -> { matrix[i][j] = '.' matrix[idx--][j] = 'O' } } } } } private fun east(matrix: Array<CharArray>) { for (i in matrix.indices) { var idx = matrix.size - 1 for (j in matrix[0].indices.reversed()) { when (matrix[i][j]) { '#' -> idx = j - 1 'O' -> { matrix[i][j] = '.' matrix[i][idx--] = 'O' } } } } } private fun weight(matrix: Array<CharArray>): Int { var w = 0 for (i in matrix.indices) { w += matrix[i].count { it == 'O' } * (matrix.size - i) } return w } override fun part1(): Int { val matrix = Array(lines.size) { i -> lines[i].toCharArray() } north(matrix) return weight(matrix) } override fun part2(): Int { val matrix = Array(lines.size) { i -> lines[i].toCharArray() } val snapshots = mutableMapOf<String, Int>() val weights = mutableListOf<Int>() var j = 0 while (true) { val key = matrix.joinToString("") { it.joinToString("") } val i = snapshots[key] if (i != null) { return weights[(1_000_000_000 - i) % (j - i) + i] } snapshots[key] = j++ weights.add(weight(matrix)) north(matrix) west(matrix) south(matrix) east(matrix) } } }
0
Kotlin
0
0
455bc8a69527c6c2f20362945b73bdee496ace41
2,968
advent-of-code
The Unlicense
src/main/kotlin/algorithms/NumberGuessingGame.kt
AgentKnopf
240,955,745
false
null
package algorithms /** * I pick a number from 1 to n. You have to guess which number I picked. Every time you guess wrong, I'll tell you whether the number is higher or lower. * You call a pre-defined API guess(int num) which returns 3 possible results (-1, 1, or 0): */ internal data class NumberGuessingGame(val luckyNumber: Int) { /** * @return 0 if the given number is equal to [luckyNumber]; -1 if [luckyNumber] is lower than the given number; * 1 if [luckyNumber] is higher than the given number. */ private fun guess(guessedNumber: Int): Int { return when { guessedNumber == luckyNumber -> 0 guessedNumber > luckyNumber -> -1 else -> 1 } } /** * Guesses the lucky number using binary search and the given maximum number. The limit for guessing is 1 to [maxNumber] (inclusive). * @return the guessed number. */ fun guessNumber(maxNumber: Int): Int { //Binary search approach var right = maxNumber var left = 1 var pivot: Int while (left <= right) { pivot = left + (right - left) / 2 val guessResult = guess(pivot) when (guessResult) { 0 -> //We're done return pivot -1 -> //The target number is lower than the current pivot right = pivot 1 -> //The target number is higher than the current pivot left = pivot + 1 } } //This constitutes an error return -1 } }
0
Kotlin
1
0
5367ce67e54633e53b2b951c2534bf7b2315c2d8
1,595
technical-interview
MIT License
kotlin/src/com/daily/algothrim/leetcode/MoveZeroes.kt
idisfkj
291,855,545
false
null
package com.daily.algothrim.leetcode /** * 283. 移动零 * * 给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。 * * 示例: * * 输入: [0,1,0,3,12] * 输出: [1,3,12,0,0] * 说明: * * 必须在原数组上操作,不能拷贝额外的数组。 * 尽量减少操作次数。 * */ class MoveZeroes { companion object { @JvmStatic fun main(args: Array<String>) { val nums = intArrayOf(0, 1, 0, 3, 12) MoveZeroes().solution(nums).apply { nums.forEach { println(it) } } println() val nums2 = intArrayOf(0, 0, 1) MoveZeroes().solution2(nums2).apply { nums2.forEach { println(it) } } } } // [0,1,0,3,12] [1, 0, 0, 3, 12] // [1,3,12,0,0] // [0,0,1] fun solution(nums: IntArray) { var i = 0 while (i < nums.size) { var k = 0 while (k < nums.size - i - 1) { if (nums[k] == 0) { val temp = nums[k + 1] nums[k + 1] = nums[k] nums[k] = temp } k++ } i++ } } fun solution2(nums: IntArray) { var right = 0 var left = 0 val n = nums.size while (right < n) { if (nums[right] != 0) { val temp = nums[right] nums[right] = nums[left] nums[left] = temp left++ } right++ } } }
0
Kotlin
9
59
9de2b21d3bcd41cd03f0f7dd19136db93824a0fa
1,720
daily_algorithm
Apache License 2.0
src/main/kotlin/co/csadev/hannukah5783/Day01.kt
gtcompscientist
577,439,489
false
{"Kotlin": 252918}
/** * Copyright (c) 2022 by <NAME> * Advent of Code 2022, Day 20 * Problem Description: http://adventofcode.com/2021/day/20 */ package co.csadev.hannukah5783 import co.csadev.adventOfCode.BaseDay import co.csadev.adventOfCode.Resources import co.csadev.hannukah5783.Day01.PhoneChars.Companion.toDigit class Day01(override val input: List<String> = Resources.resourceAsList("83noahs-customers.jsonl")) : BaseDay<List<String>, String, Int> { override fun solvePart1(): String { return customers.map { c -> c.lastName() to c }.filter { (lastName, _) -> lastName.length == 10 }.first { (lastName, c) -> val asPhone = lastName.asPhone val strippedPhone = c.phone.replace("-", "") asPhone == strippedPhone }.second.phone } private enum class PhoneChars(val chars: List<Char>, val digit: String) { P1(emptyList(), "1"), P2("ABC".toList(), "2"), P3("DEF".toList(), "3"), P4("GHI".toList(), "4"), P5("JKL".toList(), "5"), P6("MNO".toList(), "6"), P7("PQRS".toList(), "7"), P8("TUV".toList(), "8"), P9("WXYZ".toList(), "9"); companion object { private val vals = values() fun Char.toDigit() = vals.first { this in it.chars }.digit } } private val String.asPhone: String get() = uppercase().map { it.toDigit() }.joinToString("") override fun solvePart2() = 0 }
0
Kotlin
0
1
43cbaac4e8b0a53e8aaae0f67dfc4395080e1383
1,510
advent-of-kotlin
Apache License 2.0
src/main/kotlin/endredeak/aoc2022/Day13.kt
edeak
571,891,076
false
{"Kotlin": 44975}
package endredeak.aoc2022 import com.google.gson.Gson fun main() { solve("Distress Signal") { fun String.toList(): List<*> = Gson().fromJson(this, List::class.java) fun List<*>.compareTo(other: List<*>): Int { if (this.isEmpty() && other.isNotEmpty()) return -1 else if (this.isNotEmpty() && other.isEmpty()) return 1 else if (this.isEmpty()) return 0 val l = this[0] val r = other[0] val result = if (l is Double && r is Double) l.toInt() - r.toInt() else if (l is Double && r is List<*>) listOf(l).compareTo(r) else if (l is List<*> && r is Double) l.compareTo(listOf(r)) else (l as List<*>).compareTo(r as List<*>) return if (result == 0) this.drop(1).compareTo(other.drop(1)) else result } val input = lines part1(5252) { input.chunked(3) { (l, r) -> l.toList().compareTo(r.toList())} .withIndex() .filter { it.value <= 0 } .sumOf { it.index+1 } } part2(20592) { val dividers = listOf("[[2]]", "[[6]]") input.plus(dividers) .filter { it.isNotEmpty() } .map { it.toList() } .sortedWith(List<*>::compareTo) .mapIndexedNotNull { i, l -> if (l in dividers.map { it.toList() }) i + 1 else null } .let { (i1, i2) -> i1 * i2 } } } }
0
Kotlin
0
0
e0b95e35c98b15d2b479b28f8548d8c8ac457e3a
1,523
AdventOfCode2022
Do What The F*ck You Want To Public License
src/main/kotlin/day25.kt
gautemo
572,204,209
false
{"Kotlin": 78294}
import shared.getText import kotlin.math.pow fun main() { val input = getText("day25.txt") println(day25A(input)) } fun day25A(input: String): String { val decimalSum = input.lines().map { line -> line.snafuToLong() }.reduce { acc, number -> acc + number } var fiveNumeral = decimalSum.toString(5) var result = "" while (fiveNumeral.isNotEmpty()) { val last = fiveNumeral.last() fiveNumeral = fiveNumeral.take(fiveNumeral.length-1) when(last) { '4' -> { result = "-$result" fiveNumeral = fiveNumeral.incrementFiveNumeral() } '3' -> { result = "=$result" fiveNumeral = fiveNumeral.incrementFiveNumeral() } else -> { result = "$last$result" } } } return result } private fun String.snafuToLong(): Long { return mapIndexed { i, c -> val multiply = 5.0.pow(length-1-i).toLong() when(c) { '-' -> -1 '=' -> -2 else -> c.digitToInt().toLong() } * multiply }.reduce { acc, number -> acc + number } } private fun String.incrementFiveNumeral(): String { if(isEmpty()) return "1" if(last().digitToInt() < 4) { return "${take(length-1)}${last().digitToInt() + 1}" } return "${take(length-1).incrementFiveNumeral()}0" }
0
Kotlin
0
0
bce9feec3923a1bac1843a6e34598c7b81679726
1,430
AdventOfCode2022
MIT License
aoc-2017/src/main/kotlin/nl/jstege/adventofcode/aoc2017/days/Day16.kt
JStege1206
92,714,900
false
null
package nl.jstege.adventofcode.aoc2017.days import nl.jstege.adventofcode.aoccommon.days.Day import nl.jstege.adventofcode.aoccommon.utils.extensions.head import nl.jstege.adventofcode.aoccommon.utils.extensions.swap /** * * @author <NAME> */ class Day16 : Day(title = "Permutation Promenade") { private companion object Configuration { private const val SECOND_ITERATIONS = 1_000_000_000 } override fun first(input: Sequence<String>): Any { return input.head .split(",") .map(Instruction.Parser::parse) .fold(('a'..'p').toMutableList()) { programs, instr -> instr(programs) } .joinToString("") } override fun second(input: Sequence<String>): Any { return input.head .split(",") .map(Instruction.Parser::parse) .let { instructions -> var programs = ('a'..'p').toMutableList() val history = mutableMapOf<List<Char>, Int>() var i = 0 while (i < SECOND_ITERATIONS && programs !in history) { history[programs.toList()] = i programs = instructions.fold(programs) { ps, instr -> instr(ps) } i++ } history.entries.find { (_, v) -> v == SECOND_ITERATIONS % i }?.key ?: programs } .joinToString("") } private sealed class Instruction { companion object Parser { fun parse(instr: String): Instruction = when (instr.first()) { 's' -> Spin(instr.drop(1).toInt()) 'x' -> instr.drop(1).split("/").let { (a, b) -> Exchange(a.toInt(), b.toInt()) } 'p' -> instr.drop(1).split("/").let { (a, b) -> Partner(a.first(), b.first()) } else -> throw IllegalArgumentException("Invalid input") } } abstract operator fun invoke(programs: MutableList<Char>): MutableList<Char> class Spin(val n: Int) : Instruction() { override fun invoke(programs: MutableList<Char>) = (programs.subList(programs.size - n, programs.size) + programs.subList(0, programs.size - n)).toMutableList() } class Exchange(val a: Int, val b: Int) : Instruction() { override fun invoke(programs: MutableList<Char>) = programs .also { it.swap(a, b) } } class Partner(val a: Char, val b: Char) : Instruction() { override fun invoke(programs: MutableList<Char>) = programs .also { it.swap(programs.indexOf(a), programs.indexOf(b)) } } } }
0
Kotlin
0
0
d48f7f98c4c5c59e2a2dfff42a68ac2a78b1e025
2,686
AdventOfCode
MIT License
src/main/kotlin/g2201_2300/s2258_escape_the_spreading_fire/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g2201_2300.s2258_escape_the_spreading_fire // #Hard #Array #Breadth_First_Search #Binary_Search #Matrix // #2023_06_28_Time_304_ms_(100.00%)_Space_38.5_MB_(100.00%) @Suppress("NAME_SHADOWING") class Solution { private fun setFire(grid: Array<IntArray>, dir: Array<IntArray>): Array<IntArray> { val n = grid.size val m = grid[0].size val bfs = ArrayDeque<Int>() val fire = Array(n) { IntArray(m) } for (i in 0 until n) { for (j in 0 until m) { fire[i][j] = Int.MAX_VALUE if (grid[i][j] == 1) { fire[i][j] = 0 bfs.add(i * m + j) } if (grid[i][j] == 2) { fire[i][j] = 0 } } } while (bfs.isNotEmpty()) { val rm = bfs.removeFirst() val x = rm / m val y = rm % m for (d in 0..3) { val nx = x + dir[d][0] val ny = y + dir[d][1] if (nx >= 0 && ny >= 0 && nx < n && ny < m && fire[nx][ny] == Int.MAX_VALUE) { fire[nx][ny] = fire[x][y] + 1 bfs.add(nx * m + ny) } } } return fire } private fun isPoss(fire: Array<IntArray>, dir: Array<IntArray>, time: Int): Boolean { var time = time if (time >= fire[0][0]) { return false } val n = fire.size val m = fire[0].size val bfs = ArrayDeque<Int>() bfs.add(0) val isVis = Array(n) { BooleanArray(m) } isVis[0][0] = true while (bfs.isNotEmpty()) { var size = bfs.size while (size-- > 0) { val rm = bfs.removeFirst() val x = rm / m val y = rm % m if (x == n - 1 && y == m - 1) { return true } for (d in 0..3) { val nx = x + dir[d][0] val ny = y + dir[d][1] if (nx >= 0 && ny >= 0 && nx < n && ny < m && !isVis[nx][ny]) { if (nx == n - 1 && ny == m - 1) { if (time + 1 <= fire[nx][ny]) { isVis[nx][ny] = true bfs.add(nx * m + ny) } } else { if (time + 1 < fire[nx][ny]) { isVis[nx][ny] = true bfs.add(nx * m + ny) } } } } } time++ } return false } fun maximumMinutes(grid: Array<IntArray>): Int { val dir = arrayOf(intArrayOf(0, 1), intArrayOf(1, 0), intArrayOf(-1, 0), intArrayOf(0, -1)) val fire = setFire(grid, dir) var lo = 0 var hi = 1e9.toInt() while (lo <= hi) { val mid = (hi - lo shr 1) + lo if (isPoss(fire, dir, mid)) { lo = mid + 1 } else { hi = mid - 1 } } return hi } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
3,265
LeetCode-in-Kotlin
MIT License
src/org/aoc2021/Day3.kt
jsgroth
439,763,933
false
{"Kotlin": 86732}
package org.aoc2021 import java.nio.file.Files import java.nio.file.Path object Day3 { private fun solvePart1(filename: String): Int { val lines = Files.readAllLines(Path.of(filename), Charsets.UTF_8) val numBits = lines[0].length val oneCounts = Array(numBits) { 0 } lines.forEach { line -> line.forEachIndexed { i, bit -> if (bit == '1') { oneCounts[i]++ } } } val majorityLine = if (lines.size % 2 == 0) { lines.size / 2 } else { lines.size / 2 + 1 } val gammaString = oneCounts.map { if (it >= majorityLine) '1' else '0' } .joinToString(separator = "") val epsilonString = gammaString.map { if (it == '1') '0' else '1' } .joinToString(separator = "") return gammaString.toInt(2) * epsilonString.toInt(2) } private fun solvePart2(filename: String): Int { val lines = Files.readAllLines(Path.of(filename), Charsets.UTF_8) val oxygenRating = findRating(lines, false) val co2Rating = findRating(lines, true) return oxygenRating * co2Rating } private tailrec fun findRating(lines: List<String>, invert: Boolean, i: Int = 0): Int { if (lines.size == 1) { return lines[0].toInt(2) } val (leadingOnes, leadingZeroes) = lines.partition { it[i] == '1' } val mostCommonBit = if (leadingOnes.size >= leadingZeroes.size) '1' else '0' val remainingLines = lines.filter { line -> val matches = (line[i] == mostCommonBit) if (invert) !matches else matches } return findRating(remainingLines, invert, i + 1) } @JvmStatic fun main(args: Array<String>) { val filename = "input3.txt" val solution1 = solvePart1(filename) println(solution1) val solution2 = solvePart2(filename) println(solution2) } }
0
Kotlin
0
0
ba81fadf2a8106fae3e16ed825cc25bbb7a95409
2,008
advent-of-code-2021
The Unlicense
src/main/kotlin/github/walkmansit/aoc2020/Day08.kt
walkmansit
317,479,715
false
null
package github.walkmansit.aoc2020 class Day08(val input: List<String>) : DayAoc<Int, Int> { private class SequenceOfAction(val lines: List<String>) { sealed class Action { abstract fun apply(acc: Int, position: Int): Pair<Int, Int> abstract fun hasAlternative(): Boolean abstract fun toAlternative(): Action class NopAction(val value: Int) : Action() { override fun apply(acc: Int, position: Int) = acc to position + 1 override fun hasAlternative() = true override fun toAlternative() = JmpAction(value) } class AccAction(val value: Int) : Action() { override fun apply(acc: Int, position: Int) = acc + value to position + 1 override fun hasAlternative() = false override fun toAlternative() = this } class JmpAction(val value: Int) : Action() { override fun apply(acc: Int, position: Int) = acc to position + value override fun hasAlternative() = true override fun toAlternative() = NopAction(value) } companion object { fun fromString(value: String): Action { val parts = value.split(' ') return when (parts[0]) { "nop" -> NopAction(parts[1].toInt()) "acc" -> AccAction(parts[1].toInt()) "jmp" -> JmpAction(parts[1].toInt()) else -> throw IllegalArgumentException() } } } } fun findAccBeforeLoop(): Int { val linesVisited = lines.map { Action.fromString(it) to false }.toMutableList() var accumulated = 0 var idx = 0 do { // apply current line action val (a, i) = linesVisited[idx].first.apply(accumulated, idx) // update prev line to visited linesVisited[idx] = linesVisited[idx].first to true // set prev to current accumulated = a idx = i } while (!linesVisited[idx].second) return accumulated } fun findTerminateResult(): Int { val initialList = lines.map { Action.fromString(it) to false }.toMutableList() var list = lines.map { Action.fromString(it) to false }.toMutableList() for (i in getAlternativeActionsIds(initialList)) { // change action in list to alt list[i] = list[i].first.toAlternative() to false val (fine, acc) = simulate(list) if (fine) return acc else { // set list to initial list[i] = list[i].first.toAlternative() to false list = list.map { it.first to false }.toMutableList() } } return 0 } fun simulate(actionsVisited: MutableList<Pair<Action, Boolean>>): Pair<Boolean, Int> { var accumulated = 0 var idx = 0 do { // apply current line action val (a, i) = actionsVisited[idx].first.apply(accumulated, idx) // update prev line to visited actionsVisited[idx] = actionsVisited[idx].first to true // set prev to current accumulated = a idx = i if (idx == actionsVisited.size) return true to accumulated if (actionsVisited[idx].second) return false to 0 if (idx < 0) return false to 0 } while (idx != actionsVisited.size) return true to accumulated } fun getAlternativeActionsIds(actions: List<Pair<Action, Boolean>>) = sequence { for ((i, v) in actions.withIndex()) { if (v.first.hasAlternative()) yield(i) } } } override fun getResultPartOne(): Int { return SequenceOfAction(input).findAccBeforeLoop() } override fun getResultPartTwo(): Int { return SequenceOfAction(input).findTerminateResult() } }
0
Kotlin
0
0
9c005ac4513119ebb6527c01b8f56ec8fd01c9ae
4,390
AdventOfCode2020
MIT License
src/Day01.kt
devLeitner
572,272,654
false
{"Kotlin": 6301}
fun main() { fun part1(input: List<String>): Int { return input.size } fun part2(input: List<String>): Int { return input.size } val elves = arrayListOf<Elf>() val input = readInput("resources/day1source") var elf: Elf = Elf(0) input.forEach{ if(it.isBlank()){ elves.add(elf) elf = Elf(0) }else{ elf.calories += it.toInt(); } } val maxElf = elves.maxBy { it.calories } elves.sortBy { it.calories } val maxElves = elves.subList(elves.size-3, elves.size) val result = maxElves.map { it.calories }.sum() print("\n$maxElf") print("\nTop 3 elves, sum of calories: $result") } internal data class Elf(var calories: Int)
0
Kotlin
0
0
72b9d184fc58f790b393260fc6b1a0ed24028059
772
AOC_2022
Apache License 2.0
src/main/kotlin/utils/Model.kt
Kebaan
573,069,009
false
null
package utils import kotlin.math.abs import kotlin.math.max sealed interface GameResult { object Win : GameResult object Lose : GameResult object Draw : GameResult } data class Point(val x: Int, val y: Int) { operator fun plus(other: Point) = Point(x + other.x, y + other.y) operator fun minus(other: Point) = Point(x - other.x, y - other.y) fun move(direction: Direction) = this + direction.delta fun normalized() = Point(if (x != 0) x / abs(x) else 0, if (y != 0) y / abs(y) else 0) fun manhattanDistance(other: Point): Int { val deltaX = abs(x - other.x) val deltaY = abs(y - other.y) return deltaX + deltaY } fun manhattanLength(): Int = abs(x) + abs(y) fun chebyshevDistance(other: Point): Int { val deltaX = abs(x - other.x) val deltaY = abs(y - other.y) return max(deltaX, deltaY) } fun chebyshevLength(): Int = max(abs(x), abs(y)) } enum class Direction(val delta: Point) { NORTH(Point(0, 1)), NORTH_EAST(Point(1, 1)), EAST(Point(1, 0)), SOUTH(Point(0, -1)), SOUTH_EAST(Point(1, -1)), SOUTH_WEST(Point(-1, -1)), WEST(Point(-1, 0)), NORTH_WEST(Point(-1, 1)); companion object { fun from(delta: Point): Direction = values().find { it.delta == delta } ?: error("unknown delta $delta") fun from(input: String): Direction = when (input) { "U", "N" -> NORTH "NE" -> NORTH_EAST "R", "E" -> EAST "SE" -> SOUTH_EAST "D", "S" -> SOUTH "SW" -> SOUTH_WEST "L", "W" -> WEST "NW" -> NORTH_WEST else -> throw Exception("unknown direction $input") } } }
0
Kotlin
0
0
ef8bba36fedbcc93698f3335fbb5a69074b40da2
1,738
Advent-of-Code-2022
Apache License 2.0
app/src/main/java/com/themobilecoder/adventofcode/day7/DaySevenUtils.kt
themobilecoder
726,690,255
false
{"Kotlin": 323477}
package com.themobilecoder.adventofcode.day7 import com.themobilecoder.adventofcode.splitByNewLine fun String.convertToHandBids(): List<HandBid> { return splitByNewLine().map { val line = it.split(" ") val hand = line[0] val bid = line[1].toInt() HandBid( hand = hand, bid = bid, handType = hand.getHandType() ) } } fun String.convertToHandBidsWithWildCard(): List<HandBid> { return splitByNewLine().map { val line = it.split(" ") val hand = line[0] val bid = line[1].toInt() HandBid( hand = hand, bid = bid, handType = hand.getHandTypeWithWildCard() ) } } fun String.getHandType(): HandBid.HandType { val mapOfValues = mutableMapOf<Char, Int>() this.forEach { if (mapOfValues.contains(it)) { mapOfValues[it] = (mapOfValues[it] ?: 0) + 1 } else { mapOfValues[it] = 1 } } val values = mapOfValues.values return if (values.contains(5)) { HandBid.HandType.FIVE_OF_A_KIND } else if (values.contains(4)) { HandBid.HandType.FOUR_OF_A_KIND } else if (values.contains(3) && values.contains(2)) { HandBid.HandType.FULL_HOUSE } else if (values.contains(3)) { HandBid.HandType.THREE_OF_A_KIND } else if (values.filter { it == 2 }.size == 2) { HandBid.HandType.TWO_PAIR } else if (values.contains(2)) { HandBid.HandType.PAIR } else { HandBid.HandType.HIGH } } fun String.getHandTypeWithWildCard(): HandBid.HandType { val mapOfValues = mutableMapOf<Char, Int>() this.forEach { if (mapOfValues.contains(it)) { mapOfValues[it] = (mapOfValues[it] ?: 0) + 1 } else { mapOfValues[it] = 1 } } if (mapOfValues.contains('J') && mapOfValues['J'] != 5) { val cardWithMaxValue = mapOfValues.filter { it.key != 'J' }.maxBy { it.value } mapOfValues[cardWithMaxValue.key] = (mapOfValues[cardWithMaxValue.key] ?: 0) + (mapOfValues['J'] ?: 0) mapOfValues['J'] = 0 } val values = mapOfValues.values return if (values.contains(5)) { HandBid.HandType.FIVE_OF_A_KIND } else if (values.contains(4)) { HandBid.HandType.FOUR_OF_A_KIND } else if (values.contains(3) && values.contains(2)) { HandBid.HandType.FULL_HOUSE } else if (values.contains(3)) { HandBid.HandType.THREE_OF_A_KIND } else if (values.filter { it == 2 }.size == 2) { HandBid.HandType.TWO_PAIR } else if (values.contains(2)) { HandBid.HandType.PAIR } else { HandBid.HandType.HIGH } } fun compareCard(c: Char, c2: Char): Int { return c.getCardFromChar().value - c2.getCardFromChar().value } fun compareCardWithWildCard(c: Char, c2: Char): Int { return c.getCardWithWildCardFromChar().value - c2.getCardWithWildCardFromChar().value }
0
Kotlin
0
0
b7770e1f912f52d7a6b0d13871f934096cf8e1aa
2,992
Advent-of-Code-2023
MIT License
src/main/kotlin/g1801_1900/s1862_sum_of_floored_pairs/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g1801_1900.s1862_sum_of_floored_pairs // #Hard #Array #Math #Binary_Search #Prefix_Sum // #2023_06_22_Time_710_ms_(100.00%)_Space_54.1_MB_(100.00%) class Solution { fun sumOfFlooredPairs(nums: IntArray): Int { val mod: Long = 1000000007 nums.sort() val max = nums[nums.size - 1] val counts = IntArray(max + 1) val qnts = LongArray(max + 1) for (k in nums) { counts[k]++ } for (i in 1 until max + 1) { if (counts[i] == 0) { continue } var j = i while (j <= max) { qnts[j] += counts[i].toLong() j = j + i } } for (i in 1 until max + 1) { qnts[i] = (qnts[i] + qnts[i - 1]) % mod } var sum: Long = 0 for (k in nums) { sum = (sum + qnts[k]) % mod } return sum.toInt() } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
949
LeetCode-in-Kotlin
MIT License
bench/algorithm/pidigits/1n.kt
yonillasky
509,064,681
true
{"C#": 202607, "Rust": 189880, "Common Lisp": 142537, "C": 54246, "Java": 48247, "Go": 47792, "Python": 43609, "Zig": 43144, "Kotlin": 42064, "Julia": 36071, "Dart": 35399, "TypeScript": 35277, "Crystal": 33440, "C++": 33006, "OCaml": 31954, "Chapel": 30434, "JavaScript": 26877, "Nim": 26351, "Vue": 24386, "V": 22794, "Swift": 20938, "Racket": 20474, "Fortran": 19285, "Ruby": 18011, "D": 12226, "Haxe": 8855, "Lua": 8168, "Elixir": 6620, "Perl": 5588, "Shell": 5493, "Raku": 4441, "Haskell": 2823, "Hack": 821, "SCSS": 503, "HTML": 53}
/* The Computer Language Benchmarks Game https://salsa.debian.org/benchmarksgame-team/benchmarksgame/ Based on Java version (1) by <NAME> Contributed by <NAME> Modified by hanabi1224 */ import com.ionspin.kotlin.bignum.integer.* fun main(args: Array<String>) { val L = 10 var n = args[0].toInt() var j = 0 val digits = PiDigitSpigot() while (n > 0) { if (n >= L) { for (i in 0..L - 1) print(digits.next()) j += L } else { for (i in 0..n - 1) print(digits.next()) for (i in n..L - 1) print(" ") j += n } print("\t:") println(j) n -= L } } internal class PiDigitSpigot { var z: Transformation var x: Transformation var inverse: Transformation init { z = Transformation(1, 0, 0, 1) x = Transformation(0, 0, 0, 0) inverse = Transformation(0, 0, 0, 0) } operator fun next(): Int { val y = digit() if (isSafe(y)) { z = produce(y) return y } else { z = consume(x.next()) return next() } } fun digit(): Int { return z.extract(3) } fun isSafe(digit: Int): Boolean { return digit == z.extract(4) } fun produce(i: Int): Transformation { return inverse.qrst(10, -10 * i, 0, 1).compose(z) } fun consume(a: Transformation): Transformation { return z.compose(a) } } internal class Transformation { var q: BigInteger var r: BigInteger var s: BigInteger var t: BigInteger var k: Int = 0 constructor(q: Int, r: Int, s: Int, t: Int) { this.q = q.toBigInteger() this.r = r.toBigInteger() this.s = s.toBigInteger() this.t = t.toBigInteger() k = 0 } constructor(q: BigInteger, r: BigInteger, s: BigInteger, t: BigInteger) { this.q = q this.r = r this.s = s this.t = t k = 0 } operator fun next(): Transformation { k++ q = k.toBigInteger() r = (4 * k + 2).toBigInteger() s = 0.toBigInteger() t = (2 * k + 1).toBigInteger() return this } fun extract(j: Int): Int { val bigj = j.toBigInteger() val numerator = q.multiply(bigj).add(r) val denominator = s.multiply(bigj).add(t) return numerator.divide(denominator).intValue() } fun qrst(q: Int, r: Int, s: Int, t: Int): Transformation { this.q = q.toBigInteger() this.r = r.toBigInteger() this.s = s.toBigInteger() this.t = t.toBigInteger() k = 0 return this } fun compose(a: Transformation): Transformation { return Transformation( q.multiply(a.q), q.multiply(a.r).add(r.multiply(a.t)), s.multiply(a.q).add(t.multiply(a.s)), s.multiply(a.r).add(t.multiply(a.t)) ) } }
0
C#
0
0
f72b031708c92f9814b8427b0dd08cb058aa6234
2,978
Programming-Language-Benchmarks-bp
MIT License
src/main/kotlin/moe/kadosawa/aoc/day3/Main.kt
httpolar
435,526,631
false
null
package moe.kadosawa.aoc.day3 import moe.kadosawa.aoc.Solution import moe.kadosawa.aoc.input class Main : Solution { private val input = input("input3.txt")!!.readLines() private val normalInput = MutableList(input.first().length) { MutableList<Char?>(input.size) { null } } init { input.forEachIndexed { i, row -> for (j in row.indices) { normalInput[j][i] = input[i][j] } } } override fun part1() { var gammaRate = "" var epsilonRate = "" normalInput.forEach { bits -> var zeros = 0 var ones = 0 bits.forEach { bit -> if (bit == '0') { zeros++ } if (bit == '1') { ones++ } } if (zeros > ones) { gammaRate += "0" epsilonRate += "1" } else { gammaRate += "1" epsilonRate += "0" } } println("Part 1: ${gammaRate.toInt(2) * epsilonRate.toInt(2)}") } override fun part2() { var oxygenRating = input("input3.txt")!!.readLines() oxygenBruteforce@ for (i in 0 until oxygenRating.first().length) { var zeros = 0 var ones = 0 oxygenRating.forEach { line -> if (line[i] == '0') { zeros++ } else if (line[i] == '1') { ones++ } } val mostCommon = if (ones >= zeros) { '1' } else { '0' } if (oxygenRating.size == 1) { break@oxygenBruteforce } oxygenRating = oxygenRating.filter { it[i] == mostCommon } } var scrubberRating = input("input3.txt")!!.readLines() scrubberBruteforce@ for (i in 0 until scrubberRating.first().length) { var zeros = 0 var ones = 0 scrubberRating.forEach {line -> if (line[i] == '0') { zeros++ } else if (line[i] == '1') { ones++ } } val leastCommon = if (zeros <= ones) { '0' } else { '1' } if (scrubberRating.size == 1) { break@scrubberBruteforce } scrubberRating = scrubberRating.filter { it[i] == leastCommon } } println("Part 2: ${oxygenRating.first().toUInt(2) * scrubberRating.first().toUInt(2)}") } override fun run() { part1() part2() } }
0
Kotlin
0
1
540ced34eb89a7bf5bb5535c7507e51eaac3f72e
2,753
Advent-of-Code
The Unlicense
src/questions/AddBinary.kt
realpacific
234,499,820
false
null
package questions import _utils.UseCommentAsDocumentation import utils.shouldBe /** * Given two binary strings a and b, return their sum as a binary string. * [Source](https://leetcode.com/problems/add-binary/) */ @UseCommentAsDocumentation private fun addBinary(a: String, b: String): String { val size = maxOf(a.length, b.length) val a_ = a.padStart(size, '0') val b_ = b.padStart(size, '0') val result = CharArray(size) { ' ' } var carry = 0 for (i in (size - 1) downTo 0) { val top = Character.getNumericValue(a_[i]) // GOTCHA: Use Character#getNumericalValue val bottom = Character.getNumericValue(b_[i]) var sum: Int val isAllOne = top == bottom && top == 1 if (isAllOne) { // 1 + 1 if (carry == 0) { // 1 + 1 + 0 sum = 0 carry = 1 } else { // 1 + 1 + 1 sum = 1 carry = 1 } } else { val isAllZero = top == bottom && top == 0 if (isAllZero) { // 0 + 0 sum = carry carry = 0 } else { // 1 + 0 if (carry == 1) { // 1 + 0 + 1 sum = 0 carry = 1 } else { // 1 + 0 + 0 carry = 0 sum = 1 } } } result[i] = if (sum == 0) '0' else '1' } val value = result.joinToString("") return if (carry == 1) "1$value" else value // consider remaining carry } fun main() { addBinary(a = "1", b = "111") shouldBe "1000" addBinary(a = "11", b = "1") shouldBe "100" addBinary(a = "1010", b = "1011") shouldBe "10101" }
4
Kotlin
5
93
22eef528ef1bea9b9831178b64ff2f5b1f61a51f
1,726
algorithms
MIT License
year2018/src/main/kotlin/net/olegg/aoc/year2018/day13/Day13.kt
0legg
110,665,187
false
{"Kotlin": 511989}
package net.olegg.aoc.year2018.day13 import net.olegg.aoc.someday.SomeDay import net.olegg.aoc.utils.Directions import net.olegg.aoc.utils.Directions.Companion.CCW import net.olegg.aoc.utils.Directions.Companion.CW import net.olegg.aoc.utils.Directions.D import net.olegg.aoc.utils.Directions.L import net.olegg.aoc.utils.Directions.R import net.olegg.aoc.utils.Directions.U import net.olegg.aoc.utils.Vector2D import net.olegg.aoc.utils.get import net.olegg.aoc.year2018.DayOf2018 /** * See [Year 2018, Day 13](https://adventofcode.com/2018/day/13) */ object Day13 : DayOf2018(13) { private val TURNS_SLASH = mapOf( U to R, R to U, D to L, L to D, ) private val TURNS_BACKSLASH = mapOf( U to L, L to U, D to R, R to D, ) override fun first(): Any? { val input = matrix val tracks = input .map { line -> line.map { char -> when (char) { '^', 'v' -> '|' '<', '>' -> '-' else -> char } } } val trains = input .flatMapIndexed { y, line -> line.mapIndexedNotNull { x, c -> val pos = Vector2D(x, y) when (c) { '^' -> Triple(pos, U, 0) 'v' -> Triple(pos, D, 0) '<' -> Triple(pos, L, 0) '>' -> Triple(pos, R, 0) else -> null } } } .sortedWith(compareBy({ it.first.y }, { it.first.x })) (0..1_000_000).fold(trains) { state, _ -> val coords = state.map { it.first }.toMutableSet() val newState = state .map { (pos, dir, turn) -> val (newDir, newTurn) = when (tracks[pos]) { '\\' -> TURNS_BACKSLASH[dir] to turn '/' -> TURNS_SLASH[dir] to turn '+' -> when (turn % 3) { 0 -> CCW[dir] to turn + 1 1 -> dir to turn + 1 2 -> CW[dir] to turn + 1 else -> dir to turn } else -> dir to turn } val newPos = pos + newDir!!.step coords -= pos if (newPos in coords) { return "${newPos.x},${newPos.y}" } coords += newPos Triple(newPos, newDir, newTurn) } return@fold newState.sortedWith(compareBy({ it.first.y }, { it.first.x })) } return null } override fun second(): Any? { val input = matrix val tracks = input .map { line -> line.map { char -> when (char) { '^', 'v' -> '|' '<', '>' -> '-' else -> char } } } val trains = input .flatMapIndexed { y, line -> line.mapIndexedNotNull { x, c -> val pos = Vector2D(x, y) when (c) { '^' -> Triple(pos, U, 0) 'v' -> Triple(pos, D, 0) '<' -> Triple(pos, L, 0) '>' -> Triple(pos, R, 0) else -> null } } } .sortedWith(compareBy({ it.first.y }, { it.first.x })) (0..1_000_000).fold(trains) { state, _ -> val newState = mutableListOf<Triple<Vector2D, Directions, Int>>() val removed = mutableSetOf<Int>() state .forEachIndexed { index, (pos, dir, turn) -> if (index !in removed) { val (newDir, newTurn) = when (tracks[pos]) { '\\' -> TURNS_BACKSLASH[dir] to turn '/' -> TURNS_SLASH[dir] to turn '+' -> when (turn % 3) { 0 -> CCW[dir] to turn + 1 1 -> dir to turn + 1 2 -> CW[dir] to turn + 1 else -> dir to turn } else -> dir to turn } when (val newPos = pos + newDir!!.step) { in state.map { it.first }.subList(index + 1, state.size) -> { removed += state.indexOfFirst { it.first == newPos } } in newState.map { it.first } -> { newState.removeIf { it.first == newPos } } else -> { newState.add(Triple(newPos, newDir, newTurn)) } } } } if (newState.size == 1) { val newTrain = newState.first().first return "${newTrain.x},${newTrain.y}" } return@fold newState.sortedWith(compareBy({ it.first.y }, { it.first.x })) } return null } } fun main() = SomeDay.mainify(Day13)
0
Kotlin
1
7
e4a356079eb3a7f616f4c710fe1dfe781fc78b1a
4,464
adventofcode
MIT License
advent-of-code-2021/src/code/day12/Main.kt
Conor-Moran
288,265,415
false
{"Kotlin": 53347, "Java": 14161, "JavaScript": 10111, "Python": 6625, "HTML": 733}
package code.day12 import code.common.isLowercase import java.io.File fun main() { doIt("Day 12 Part 1: Test Input", "src/code/day12/test.input", part1) doIt("Day 12 Part 1: Real Input", "src/code/day12/part1.input", part1) doIt("Day 12 Part 2: Test Input", "src/code/day12/test.input", part2); doIt("Day 12 Part 2: Real Input", "src/code/day12/part1.input", part2); } fun doIt(msg: String, input: String, calc: (nums: List<String>) -> Int) { val lines = arrayListOf<String>() File(input).forEachLine { lines.add(it) } println(String.format("%s: Ans: %d", msg , calc(lines))) } val part1: (List<String>) -> Int = { lines -> val map = parse(lines).map val paths = mutableListOf(mutableListOf("start")) buildPaths(paths, map); dump(paths) paths.size } val part2: (List<String>) -> Int = { lines -> val map = parse(lines).map val paths = mutableListOf(mutableListOf("start")) buildPaths2(paths, map); dump(paths) paths.size } private fun dump(paths: MutableList<MutableList<String>>) { return for (path in paths) { println(path.joinToString(", ")) } } fun buildPaths(paths: MutableList<MutableList<String>>, map: Map<String, List<String>>) { val allPaths = mutableListOf<MutableList<String>>() allPaths.addAll(paths) paths.removeAll() { true } var allDone = true for (path in allPaths) { val lastFragment = path.last() if (lastFragment == "end") { paths.add(path) continue } allDone = false; val dests = map.getOrDefault(lastFragment, emptyList()) for (dest in dests) { if (!dest.isLowercase() || !path.contains(dest)) { addPath(path, dest, paths) } } } if (!allDone) buildPaths(paths, map) } fun buildPaths2(paths: MutableList<MutableList<String>>, map: Map<String, List<String>>) { val allPaths = mutableListOf<MutableList<String>>() allPaths.addAll(paths) paths.removeAll() { true } var allDone = true for (path in allPaths) { val lastFragment = path.last() val canDupeSmall = !hasDupeSmall(path) if (lastFragment == "end") { paths.add(path) continue } allDone = false; val dests = map.getOrDefault(lastFragment, emptyList()) for (dest in dests) { if (!dest.isLowercase()) { addPath(path, dest, paths) } else { if (dest == "start") continue if (path.contains(dest)) { if (canDupeSmall) { addPath(path, dest, paths) } } else { addPath(path, dest, paths) } } } } if (!allDone) buildPaths2(paths, map) } private fun addPath( pathBase: MutableList<String>, dest: String, paths: MutableList<MutableList<String>> ) { val newPath = mutableListOf<String>() newPath.addAll(pathBase) newPath.add(dest) paths.add(newPath) } fun hasDupeSmall(path: List<String>): Boolean { val uniqSmall = mutableSetOf<String>() path.filter { it.isLowercase() }.forEach { if (uniqSmall.contains(it)) return true uniqSmall.add(it) } return false } val parse: (List<String>) -> Input = { lines -> val parsed = mutableMapOf<String, MutableList<String>>() lines.forEach() { val tokens = it.split("-") parsed.getOrPut(tokens[0]) { mutableListOf<String>() }.add(tokens[1]) parsed.getOrPut(tokens[1]) { mutableListOf<String>() }.add(tokens[0]) } Input(parsed) } class Input(val map: Map<String, List<String>>)
0
Kotlin
0
0
ec8bcc6257a171afb2ff3a732704b3e7768483be
3,743
misc-dev
MIT License
src/main/kotlin/Intersection.kt
ishmeister
195,967,617
false
null
package com.kotrt import java.util.* import kotlin.math.pow import kotlin.math.sqrt data class Intersection(val t: Double, val shape: Shape) : Comparable<Intersection> { override fun compareTo(other: Intersection) = when { t < other.t -> -1 t > other.t -> 1 else -> 0 } private fun findRefractiveIndexes(xs: List<Intersection>): Pair<Double, Double> { val containers = ArrayList<Shape>() var n1 = 1.0 var n2 = 1.0 xs.forEach { i -> if (i == this) { n1 = if (containers.isEmpty()) 1.0 else containers.last().material.refractiveIndex } val shapeIndex = containers.indexOf(i.shape) if (shapeIndex >= 0) containers.removeAt(shapeIndex) else containers.add(i.shape) if (i == this) { n2 = if (containers.isEmpty()) 1.0 else containers.last().material.refractiveIndex return@forEach } } return Pair(n1, n2) } fun prepareComputations(ray: Ray, xs: List<Intersection> = listOf(this)): HitComputations { val (n1, n2) = findRefractiveIndexes(xs) val point = ray.position(t) val eyeVec = -ray.direction val normalVec = shape.normalAt(point) val inside = normalVec.dot(eyeVec) < 0.0 val computedNormalVec = if (inside) -normalVec else normalVec // push point slightly in direction of normal to prevent self-shadowing val overPoint = point + computedNormalVec * EPSILON // push point slightly below the surface for refractions val underPoint = point - computedNormalVec * EPSILON val reflectVec = ray.direction.reflect(computedNormalVec) return HitComputations( t = t, shape = shape, point = point, overPoint = overPoint, eyeVec = eyeVec, normalVec = computedNormalVec, inside = inside, reflectVec = reflectVec, n1 = n1, n2 = n2, underPoint = underPoint ) } } data class HitComputations( val t: Double, val shape: Shape, val point: Tuple, val overPoint: Tuple, val eyeVec: Tuple, val normalVec: Tuple, val inside: Boolean, val reflectVec: Tuple, val n1: Double, val n2: Double, val underPoint: Tuple ) fun findHit(intersections: List<Intersection>): Intersection? = when { intersections.isEmpty() -> null else -> intersections.sorted().firstOrNull { it.t >= 0.0 } } fun calculateReflectance(comps: HitComputations): Double { // Schlick approximation of Fresnel effect var cos = comps.eyeVec.dot(comps.normalVec) if (comps.n1 > comps.n2) { val n = comps.n1 / comps.n2 val sin2t = n * n * (1.0 - cos * cos) if (sin2t > 1.0) return 1.0 cos = sqrt(1.0 - sin2t) } val r0 = ((comps.n1 - comps.n2) / (comps.n1 + comps.n2)).pow(2) return r0 + (1.0 - r0) * (1.0 - cos).pow(5) }
0
Kotlin
0
0
e6fdc23aad7fce73712030864c438a51961fab3e
3,192
raytracer-kotlin
MIT License
src/Day01.kt
annagergaly
572,917,403
false
{"Kotlin": 6388}
fun main() { fun part1(input: List<String>): Int { val sums = mutableListOf<Int>() var sum = 0 for (line in input) { if (line.isBlank()) { sums.add(sum) sum = 0 } else { sum += line.toInt() } } return sums.max() } fun part2(input: List<String>): Int { val sums = mutableListOf<Int>() var sum = 0 for (line in input) { if (line.isBlank()) { sums.add(sum) sum = 0 } else { sum += line.toInt() } } return sums.sortedDescending().take(3).sum() } val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
89b71c93e341ca29ddac40e83f522e5449865b2d
797
advent-of-code22
Apache License 2.0
src/main/kotlin/org/sjoblomj/adventofcode/day4/Shift.kt
sjoblomj
161,537,410
false
null
package org.sjoblomj.adventofcode.day4 import java.time.LocalDate private val idRegex = ".* Guard #(?<num>[0-9]+) begins shift".toRegex() private val fallAsleepRegex = "\\[.* 00:(?<num>[0-9]{2})] falls asleep".toRegex() private val wakeUpRegex = "\\[.* 00:(?<num>[0-9]{2})] wakes up".toRegex() private val dateOfLastLine = "\\[(?<num>[0-9-]+) [0-9]{2}:[0-9]{2}] .*".toRegex() data class Shift(val id: Int, val minuteWhenFallingAsleep: List<Int>, val minuteWhenAwoken: List<Int>, val date: LocalDate) internal fun parseIndata(indata: List<String>): List<Shift> { val data = indata.sorted() val shiftList = mutableListOf<Shift>() var i = 0 while (i < data.size) { val id = getNumberFromLine(data, i++, idRegex) val sleepTimes = mutableListOf<Int>() val awakeTimes = mutableListOf<Int>() i = parseSleepAndAwakeTimes(data, i, sleepTimes, awakeTimes) val date = getDateFromLine(data, i - 1, dateOfLastLine) shiftList.add(Shift(id, sleepTimes, awakeTimes, date)) } return shiftList } private fun parseSleepAndAwakeTimes(data: List<String>, index: Int, sleepTimes: MutableList<Int>, awakeTimes: MutableList<Int>): Int { var i = index while (i < data.size && !data[i].contains(idRegex)) { val sleepTime = getNumberFromLine(data, i++, fallAsleepRegex) val awakeTime = getNumberFromLine(data, i++, wakeUpRegex) assertLegalValues(i, sleepTime, sleepTimes, awakeTime, awakeTimes) sleepTimes.add(sleepTime) awakeTimes.add(awakeTime) } return i } private fun assertLegalValues(index: Int, sleepTime: Int, sleepTimes: MutableList<Int>, awakeTime: Int, awakeTimes: MutableList<Int>) { if (sleepTimes.isNotEmpty()) { if (sleepTimes.last() >= awakeTime) throw IllegalAccessException("Around index $index of sorted data: Time for falling asleep was after waking up") if (awakeTimes.last() >= sleepTime) throw IllegalAccessException("Around index $index of sorted data: Time for awakening was after falling asleep") } } private fun getNumberFromLine(data: List<String>, index: Int, regex: Regex): Int { val res = getStringFromLine(data, index, regex) return res.toInt() } private fun getDateFromLine(data: List<String>, index: Int, regex: Regex): LocalDate { val res = getStringFromLine(data, index, regex) return LocalDate.parse(res) } private fun getStringFromLine(data: List<String>, index: Int, regex: Regex): String { if (index >= data.size) throw IllegalAccessException("At index $index of sorted data: Expected to be able to match '$regex', but found no more indata") if (!data[index].contains(regex)) throw IllegalAccessException("At index $index of sorted data: Expected line to match '$regex', but was '${data[index]}'") return regex.matchEntire(data[index])?.groups?.get("num")?.value ?: throw IllegalAccessException("At index $index of sorted data: Unable to extract requested group") }
0
Kotlin
0
0
80db7e7029dace244a05f7e6327accb212d369cc
2,924
adventofcode2018
MIT License
src/main/kotlin/com/hj/leetcode/kotlin/problem645/Solution.kt
hj-core
534,054,064
false
{"Kotlin": 619841}
package com.hj.leetcode.kotlin.problem645 /** * LeetCode page: [645. Set Mismatch](https://leetcode.com/problems/set-mismatch/); */ class Solution { /* Complexity: * Time O(N) and Space O(1) where N is the size of nums; */ fun findErrorNums(nums: IntArray): IntArray { val (a, b) = errorsUnordered(nums) return if (a in nums) intArrayOf(a, b) else intArrayOf(b, a) } private fun errorsUnordered(nums: IntArray): Pair<Int, Int> { val xorOfErrors = xorOfErrors(nums) val bitMask = xorOfErrors.rightmostBit() val xorMasked = { acc: Int, i: Int -> if (i and bitMask == 0) acc xor i else acc } val aError = (nums.fold(0, xorMasked) xor (1..nums.size).fold(0, xorMasked)) return Pair(aError, aError xor xorOfErrors) } private fun xorOfErrors(nums: IntArray): Int { val xorOperation = { a: Int, b: Int -> a xor b } return (nums.reduce(xorOperation) xor (1..nums.size).reduce(xorOperation)) } private fun Int.rightmostBit() = this - (this and (this - 1)) }
1
Kotlin
0
1
14c033f2bf43d1c4148633a222c133d76986029c
1,120
hj-leetcode-kotlin
Apache License 2.0
src/iii_conventions/MyDate.kt
shivan42
58,006,522
false
null
package iii_conventions import java.time.temporal.TemporalAmount data class MyDate(val year: Int, val month: Int, val dayOfMonth: Int) : Comparable<MyDate> { override fun compareTo(other: MyDate) = when { year != other.year -> year - other.year month != other.month -> month - other.month else -> dayOfMonth - other.dayOfMonth } infix operator fun plus(timeInterval: TimeInterval): MyDate { return parseTimeInterval(timeInterval) } infix operator fun plus(timeIntervalTimes: TimeIntervalTimes): MyDate { return parseTimeInterval(timeIntervalTimes.timeInterval, timeIntervalTimes.amount) } private fun parseTimeInterval(timeInterval: TimeInterval, i: Int = 1): MyDate { return when (timeInterval) { TimeInterval.YEAR -> this.addTimeIntervals(TimeInterval.YEAR, i) TimeInterval.WEEK -> this.addTimeIntervals(TimeInterval.WEEK, i) else -> this.addTimeIntervals(TimeInterval.DAY, i) } } } operator fun MyDate.rangeTo(other: MyDate): DateRange = DateRange(this, other) enum class TimeInterval { DAY, WEEK, YEAR; infix operator fun times(i: Int): TimeIntervalTimes = TimeIntervalTimes(this, i) } class TimeIntervalTimes(val timeInterval: TimeInterval, val amount: Int) class DateRange(val start: MyDate, val endInclusive: MyDate) : Iterable<MyDate> { override fun iterator(): Iterator<MyDate> = DateIterator(this) infix operator fun contains(date: MyDate): Boolean { return date >= start && date <= endInclusive } } class DateIterator(val dateRange: DateRange) : Iterator<MyDate> { var current: MyDate = dateRange.start override fun next(): MyDate { val result = current current = current.nextDay() return result } override fun hasNext(): Boolean = current <= dateRange.endInclusive }
0
Kotlin
1
1
f833f96bad3fba07f74e29ea0ed85f7d53fbf7eb
1,891
kotlin-koans-solution
MIT License
app/src/main/kotlin/io/github/andrewfitzy/day01/Task01.kt
andrewfitzy
747,793,365
false
{"Kotlin": 60159, "Shell": 1211}
package io.github.andrewfitzy.day01 import io.github.andrewfitzy.util.Point class Task01(puzzleInput: List<String>) { private val input: List<String> = puzzleInput private val rotationMapping: Map<Pair<String, String>, String> = mapOf( Pair("N", "R") to "E", Pair("N", "L") to "W", Pair("E", "R") to "S", Pair("E", "L") to "N", Pair("S", "R") to "W", Pair("S", "L") to "E", Pair("W", "R") to "N", Pair("W", "L") to "S", ) fun solve(): Int { var heading = "N" val start = Point(0, 0) var end = Point(0, 0) val moves = input.first().split(", ") for (move: String in moves) { val direction: String = move.substring(0, 1) val distance: Int = move.substring(1).trim().toInt() heading = rotationMapping[Pair(heading, direction)]!! end = move(end, heading, distance) } return start.getManhattanDistance(end) } private fun move( end: Point, heading: String, distance: Int, ): Point { return when (heading) { "N" -> Point(end.x, end.y + distance) "E" -> Point(end.x + distance, end.y) "S" -> Point(end.x, end.y - distance) else -> Point(end.x - distance, end.y) // assume W } } }
0
Kotlin
0
0
15ac072a14b83666da095b9ed66da2fd912f5e65
1,409
2016-advent-of-code
Creative Commons Zero v1.0 Universal
src/main/java/me/olegthelilfix/leetcoding/old/LongestPalindrome.kt
olegthelilfix
300,408,727
false
null
package me.olegthelilfix.leetcoding.old //Given a string s, return the longest palindromic substring in s. fun isPalindrome(s: String): Boolean { if (s.isEmpty()) { return false } for (i in 0 .. s.length/2) { if(s[i] != s[s.length-i-1]) { return false } } return true } fun longestPalindrome(s: String): String { if (s.length == 1) { return s } if (isPalindrome(s)) { return s } var longest = s[0].toString() for (i in 0 until s.length - 1) { s.slice(0..10) var substring: String = s[i].toString() for (j in i + 1 until s.length) { substring += s[j] if (isPalindrome(substring) && substring.length > longest.length) { longest = substring } } } return longest } fun main() { // isPalindrome("abcba") var t = System.currentTimeMillis() longestPalindrome("<KEY>") var t2 = System.currentTimeMillis() print(t2-t) }
0
Kotlin
0
0
bf17d2f6915b7a491d93f57f8e7461adda7029c0
1,999
MyKata
MIT License
src/main/kotlin/kt/kotlinalgs/app/kickstart/RecordBreaker.ws.kts
sjaindl
384,471,324
false
null
/* https://codingcompetitions.withgoogle.com/kickstart/round/00000000008f49d7/0000000000bcf2ed Isyana is given the number of visitors at her local theme park on N consecutive days. The number of visitors on the i-th day is Vi. A day is record breaking if it satisfies both of the following conditions: Either it is the first day, or the number of visitors on the day is strictly larger than the number of visitors on each of the previous days. Either it is the last day, or the number of visitors on the day is strictly larger than the number of visitors on the following day. Note that the very first day could be a record breaking day! Please help Isyana find out the number of record breaking days. Input The first line of the input gives the number of test cases, T. T test cases follow. Each test case begins with a line containing the integer N. The second line contains N integers. The i-th integer is Vi and represents the number of visitors on the i-th day. Output For each test case, output one line containing Case #x: y, where x is the test case number (starting from 1) and y is the number of record breaking days. Limits Time limit: 20 seconds. Memory limit: 1 GB. 1≤T≤100. 0≤Vi≤2×105, for all i. Test Set 1 1≤N≤1000. Test Set 2 1≤N≤2×105, for at most 10 test cases. For the remaining cases, 1≤N≤1000. Sample Sample Input save_alt content_copy 4 8 1 2 0 7 2 0 2 0 6 4 8 15 16 23 42 9 3 1 4 1 5 9 2 6 5 6 9 9 9 9 9 9 Sample Output save_alt content_copy Case #1: 2 Case #2: 1 Case #3: 3 Case #4: 0 In Sample Case #1, the underlined numbers in the following represent the record breaking days: 12––07––2020. In Sample Case #2, only the last day is a record breaking day: 4815162342–––. In Sample Case #3, the first, the third, and the sixth days are record breaking days: 3––14––159––265. In Sample Case #4, there is no record breaking day: 999999. */ var line = 0 var args: Array<String?> = arrayOf() fun readLine(): String? { val result = args[line] line++ return result } fun main(mainArgs: Array<String?>) { args = mainArgs // Read number of testcases from standard input. val testCases = readLine()?.toInt() ?: 0 for (testCase in 1 until testCases + 1) { // O(N) runtime, O(1) space solution per testcase val numVisitors = readLine()?.toInt() val days = readLine()?.split(" ")?.map { it.toInt() } var recordBreakingDays = 0 var max = 0 days?.forEachIndexed { index, visitors -> // Condition 1: first day or larger then all following days if (index != 0 && visitors <= max) { return@forEachIndexed } max = visitors // Condition 2: last day or larger than next day if (index != days.size - 1 && days[index + 1] >= visitors) { return@forEachIndexed } recordBreakingDays++ } println("Case #$testCase: $recordBreakingDays") } } main(arrayOf("1", "8", "1 2 0 7 2 0 2 0"))
0
Java
0
0
e7ae2fcd1ce8dffabecfedb893cb04ccd9bf8ba0
3,077
KotlinAlgs
MIT License
src/day14/Code.kt
ldickmanns
572,675,185
false
{"Kotlin": 48227}
package day14 import day09.Coordinates import readInput // x -> distance to right // y -> distance down // Sand falls (at each step) // - down, if not possible // - down-left, if not possible // - down-right, if not possible // - comes to a rest typealias RockStroke = List<Coordinates> val startingPoint = Coordinates(x = 500, y = 0) operator fun Array<BooleanArray>.get(coordinates: Coordinates) = this[coordinates.y][coordinates.x] operator fun Array<BooleanArray>.set(coordinates: Coordinates, boolean: Boolean) { this[coordinates.y][coordinates.x] = boolean } val Coordinates.down: Coordinates get() = copy(y = y + 1) val Coordinates.downLeft: Coordinates get() = copy(x = x - 1, y = y + 1) val Coordinates.downRight: Coordinates get() = copy(x = x + 1, y = y + 1) private infix fun Coordinates.inside(grid: Array<BooleanArray>) = x >= 0 && x < grid.first().size && y >= 0 && y < grid.size private infix fun Coordinates.outside(grid: Array<BooleanArray>) = !inside(grid) fun main() { val input = readInput("day14/input") // val input = readInput("day14/input_test") // println(part1(input)) println(part2(input)) } fun part1(input: List<String>): Int { val rockStrokes = parseInput(input) val boundingBox = getBoundingBox(rockStrokes) val occupationGrid = getOccupationGrid(rockStrokes, boundingBox) return computeRestingUnits(boundingBox, occupationGrid) } private fun parseInput(input: List<String>): List<RockStroke> = input.map { line -> val coordinatesStrings = line.split(" -> ") coordinatesStrings.map { coordinatesString -> val coordinates = coordinatesString.split(",").map { it.toInt() } Coordinates(coordinates.first(), coordinates.last()) } } private fun getBoundingBox( rockStrokes: List<RockStroke>, maxYOffset: Int = 0, xPadding: Int = 0, ): Pair<Coordinates, Coordinates> { var minCoordinates = startingPoint var maxCoordinates = startingPoint rockStrokes.forEach { rockStroke: RockStroke -> rockStroke.forEach { coordinates: Coordinates -> if (coordinates.x > maxCoordinates.x) maxCoordinates = maxCoordinates.copy(x = coordinates.x) if (coordinates.x < minCoordinates.x) minCoordinates = minCoordinates.copy(x = coordinates.x) if (coordinates.y > maxCoordinates.y) maxCoordinates = maxCoordinates.copy(y = coordinates.y) if (coordinates.y < minCoordinates.y) minCoordinates = minCoordinates.copy(y = coordinates.y) } } minCoordinates = minCoordinates.copy(x = minCoordinates.x - xPadding) maxCoordinates = maxCoordinates.copy(x = maxCoordinates.x + xPadding, y = maxCoordinates.y + maxYOffset) return Pair(minCoordinates, maxCoordinates) } private fun getOccupationGrid( rockStrokes: List<RockStroke>, boundingBox: Pair<Coordinates, Coordinates> ): Array<BooleanArray> { val (minCoordinates, maxCoordinates) = boundingBox val deltaCoordinates = maxCoordinates - minCoordinates val occupationGrid = Array(deltaCoordinates.y + 1) { BooleanArray(deltaCoordinates.x + 1) } rockStrokes.forEach { rockStroke: RockStroke -> rockStroke.windowed(2) { val lineStart = it.first() val lineEnd = it.last() val xRange = if (lineStart.x <= lineEnd.x) lineStart.x..lineEnd.x else lineEnd.x..lineStart.x val yRange = if (lineStart.y <= lineEnd.y) lineStart.y..lineEnd.y else lineEnd.y..lineStart.y xRange.forEach { x -> yRange.forEach { y -> val normalizedX = x - minCoordinates.x val normalizedY = y - minCoordinates.y occupationGrid[normalizedY][normalizedX] = true } } } } return occupationGrid } private fun computeRestingUnits( boundingBox: Pair<Coordinates, Coordinates>, occupationGrid: Array<BooleanArray> ): Int { var sandPosition = startingPoint - boundingBox.first var restingUnits = 0 while (true) { when { sandPosition.down outside occupationGrid -> break !occupationGrid[sandPosition.down] -> sandPosition = sandPosition.down sandPosition.downLeft outside occupationGrid -> break !occupationGrid[sandPosition.downLeft] -> sandPosition = sandPosition.downLeft sandPosition.downRight outside occupationGrid -> break !occupationGrid[sandPosition.downRight] -> sandPosition = sandPosition.downRight else -> { if (occupationGrid[sandPosition]) break occupationGrid[sandPosition] = true ++restingUnits sandPosition = startingPoint - boundingBox.first } } } occupationGrid.forEach { row -> row.forEach { print(if (it) '#' else '.') } println() } println("-".repeat(25)) return restingUnits } fun part2(input: List<String>): Int { val rockStrokes = parseInput(input) val boundingBox = getBoundingBox(rockStrokes, maxYOffset = 2, xPadding = 200) val occupationGrid = getOccupationGrid(rockStrokes, boundingBox) occupationGrid.last().indices.forEach { occupationGrid.last()[it] = true } return computeRestingUnits(boundingBox, occupationGrid) }
0
Kotlin
0
0
2654ca36ee6e5442a4235868db8174a2b0ac2523
5,359
aoc-kotlin-2022
Apache License 2.0
src/main/java/com/booknara/problem/search/binary/MaximumAverageSubarrayIIKt.kt
booknara
226,968,158
false
{"Java": 1128390, "Kotlin": 177761}
package com.booknara.problem.search.binary /** * 644. Maximum Average Subarray II (Hard) * https://leetcode.com/problems/maximum-average-subarray-ii/ */ class MaximumAverageSubarrayIIKt { // T:O(n*log((max - min) / 0.00001), S:O(n) fun findMaxAverage(nums: IntArray, k: Int): Double { var l = -10001.0 var r = 10001.0 while (l + 0.00001 < r) { val mid = l + (r - l) / 2.0 if (canFindLargerAverage(nums, mid, k)) { l = mid } else { r = mid } } return l } fun canFindLargerAverage(nums: IntArray, mid: Double, k: Int): Boolean { val size = nums.size var prev = 0.0 var cur = 0.0 // equal to k for (i in 0 until k) { cur += nums[i] - mid } if (cur >= 0) return true for (i in k until size) { cur += nums[i] - mid prev += nums[i - k] - mid if (prev < 0.0) { cur -= prev prev = 0.0 } if (cur >= 0.0) return true } return false } }
0
Java
1
1
04dcf500ee9789cf10c488a25647f25359b37a53
997
playground
MIT License
src/main/kotlin/com/hj/leetcode/kotlin/problem452/Solution.kt
hj-core
534,054,064
false
{"Kotlin": 619841}
package com.hj.leetcode.kotlin.problem452 /** * LeetCode page: [452. Minimum Number of Arrows to Burst Balloons](https://leetcode.com/problems/minimum-number-of-arrows-to-burst-balloons/); */ class Solution { /* Complexity: * Time O(NLogN) and Space O(N) where N is the size of points; */ fun findMinArrowShots(points: Array<IntArray>): Int { if (points.isEmpty()) return 0 val sortedPoints = sortedPointsByEnd(points) var minShots = 1 var currShotPosition = sortedPoints[0][1] for ((start, end) in sortedPoints) { if (start > currShotPosition) { minShots++ currShotPosition = end } } return minShots } private fun sortedPointsByEnd(points: Array<IntArray>): List<IntArray> { return points.sortedBy { it[1] } } }
1
Kotlin
0
1
14c033f2bf43d1c4148633a222c133d76986029c
867
hj-leetcode-kotlin
Apache License 2.0
src/main/kotlin/me/peckb/aoc/_2021/calendar/day15/Day15.kt
peckb1
433,943,215
false
{"Kotlin": 956135}
package me.peckb.aoc._2021.calendar.day15 import me.peckb.aoc.generators.InputGenerator.InputGeneratorFactory import java.util.PriorityQueue import javax.inject.Inject import kotlin.Float.Companion.POSITIVE_INFINITY class Day15 @Inject constructor(private val generatorFactory: InputGeneratorFactory) { fun smallPath(fileName: String) = generatorFactory.forFile(fileName).read { input -> val graph = input.map { row -> row.map(Character::getNumericValue).map { risk -> Vertex(risk.toLong()) } }.toList() setupEdges(graph) dijkstra(graph) } fun largePath(fileName: String) = generatorFactory.forFile(fileName).read { input -> val growthSize = 5 val data = input.toList() val maxY = data.size * growthSize val maxX = data[data.size - 1].length * growthSize val defaultVertex = Vertex(-1) val graph = MutableList(maxY) { MutableList(maxX) { defaultVertex } } (0 until growthSize).forEach { yLoop -> (0 until growthSize).forEach { xLoop -> data.forEachIndexed { y, row -> row.forEachIndexed { x, riskChar -> val realY = (yLoop * data.size) + y val realX = (xLoop * row.length) + x var r = Character.getNumericValue(riskChar) + yLoop + xLoop while (r > 9) { r -= 9 } graph[realY][realX] = Vertex(r.toLong()) } } } } setupEdges(graph) dijkstra(graph) } private fun setupEdges(graph: List<List<Vertex>>) { graph.forEachIndexed { y, vertexRow -> vertexRow.forEachIndexed { x, vertex -> graph[y].getOrNull(x + 1)?.let { left -> left.addNeighbor(vertex) vertex.addNeighbor(left) } graph.getOrNull(y + 1)?.get(x)?.let { down -> down.addNeighbor(vertex) vertex.addNeighbor(down) } } } } private fun dijkstra(graph: List<List<Vertex>>): Long? { val source = graph[0][0] val maxY = graph.size - 1 val maxX = graph[maxY].size - 1 val destination = graph[maxY][maxX] val distances = mutableMapOf(source to 0f).withDefault { POSITIVE_INFINITY } val previous = mutableMapOf<Vertex, Vertex>() val queue = PriorityQueue(compareBy<Vertex> { distances.getValue(it) }).apply { add(source) } while (queue.isNotEmpty()) { val closestNode = queue.remove() closestNode.neighbors.forEach { neighbor -> val alt = distances.getValue(closestNode) + neighbor.risk if (alt < distances.getValue(neighbor)) { distances[neighbor] = alt previous[neighbor] = closestNode queue.add(neighbor) } } } return distances[destination]?.toLong() } class Vertex(val risk: Long, val neighbors: MutableList<Vertex> = mutableListOf()) { fun addNeighbor(vertex: Vertex) { neighbors.add(vertex) } } }
0
Kotlin
1
3
2625719b657eb22c83af95abfb25eb275dbfee6a
2,894
advent-of-code
MIT License
src/aoc2022/Day17_2_.kt
RobertMaged
573,140,924
false
{"Kotlin": 225650}
package aoc2022 import utils.Vertex import utils.checkEquals import utils.sendAnswer /* #### the - shape falls first, sixth, 11th, 16th, etc. .#. ### .#. ..# ..# ### # # # # ## ## */ private const val ROCK = 1 private const val AIR = 0 private const val REST = -1 private const val LEFT = -1 private const val RIGHT = 1 fun main() { fun createShape(type: Int, maxY: Int,pos: Int, lastY: (Int) -> Unit): List<List<Vertex>> { var starty = maxY val list = listOf(when(type) { 0 -> (2..5).map { Vertex(x = it + pos, y = starty++) } else-> emptyList() } ) lastY(starty) return list } /** * The tall, vertical chamber is exactly seven units wide. * Each rock appears so that its left edge is two units away from the left wall and * its bottom edge is three units above the highest rock in the room * (or the floor, if there isn't one). */ /* fall first , push second */ fun part1(input: String): Int { var x = 0 val dir = { if(input[x++ % input.length] == '<') -1 else 1 } var readyY = 1 var type = -1 val base = ArrayDeque(listOf((0..6).map { Vertex(x = it, y = 0) })) val lineShape = createShape(++type % 4, readyY, dir()+dir()+dir()+dir()) { newY: Int -> readyY = newY} //if intersect go tp next shape if(base.last().zip(lineShape.first()).any { it.first.x == it.second.x}) lineShape.forEach(base::addLast) return 0 } fun part2(input: String): Int { return 0 } // parts execution val testInput = readInputAsText("Day17_test") val input = readInputAsText("Day17") part1(testInput).checkEquals(3068) part1(input) .sendAnswer(part = 1, day = "17", year = 2022) part2(testInput).checkEquals(TODO()) part2(input) .sendAnswer(part = 2, day = "17", year = 2022) }
0
Kotlin
0
0
e2e012d6760a37cb90d2435e8059789941e038a5
1,989
Kotlin-AOC-2023
Apache License 2.0
The_Skyline_Problem.kt
xiekch
166,329,519
false
{"C++": 165148, "Java": 103273, "Kotlin": 97031, "Go": 40017, "Python": 22302, "TypeScript": 17514, "Swift": 6748, "Rust": 6579, "JavaScript": 4244, "Makefile": 349}
import java.util.* import kotlin.collections.ArrayList //https://leetcode.com/problems/the-skyline-problem/discuss/61193/Short-Java-solution class Solution { fun getSkyline(buildings: Array<IntArray>): List<List<Int>> { val res = ArrayList<ArrayList<Int>>() val height = ArrayList<ArrayList<Int>>() for (building in buildings) { height.add(arrayListOf(building[0], building[2])) height.add(arrayListOf(building[1], -building[2])) } height.sortWith(Comparator { a, b -> if (a[0] == b[0]) a[1] - b[1] else a[0] - b[0] }) // println(height) val pq = PriorityQueue<Int>(Comparator { a, b -> b - a }) pq.offer(0) var prevHeight = 0 for (point in height) { // println(point) if (point[1] > 0) { pq.offer(point[1]) } else { pq.remove(-point[1]) } if (!pq.isEmpty() && pq.peek() != prevHeight) { res.add(arrayListOf(point[0], pq.peek())) // println(res) prevHeight = pq.peek() } } return res } } fun main(args: Array<String>) { val solution = Solution() val testset = arrayOf( arrayOf( intArrayOf(2, 9, 10), intArrayOf(3, 7, 15), intArrayOf(5, 12, 12), intArrayOf(15, 20, 10), intArrayOf(19, 24, 8) ), arrayOf( intArrayOf(0, 2, 3), intArrayOf(2, 5, 3) ) ) for (buildings in testset) println(solution.getSkyline(buildings)) }
0
C++
0
0
eb5b6814e8ba0847f0b36aec9ab63bcf1bbbc134
1,636
leetcode
MIT License
day12/Part1.kt
anthaas
317,622,929
false
null
import java.io.File import kotlin.math.abs fun main(args: Array<String>) { val input = File("input.txt").readLines().map { Pair(it[0], it.substring(1).toInt()) } var faceOfTheShip = 'E' var northDistanceFromStart = 0 var eastDistanceFromStart = 0 for (entry in input) { val (instruction, value) = entry when (instruction) { 'N' -> northDistanceFromStart += value 'S' -> northDistanceFromStart -= value 'E' -> eastDistanceFromStart += value 'W' -> eastDistanceFromStart -= value 'L', 'R' -> faceOfTheShip = turnShip(faceOfTheShip, instruction, value / 90) 'F' -> { when (faceOfTheShip) { 'N' -> northDistanceFromStart += value 'S' -> northDistanceFromStart -= value 'E' -> eastDistanceFromStart += value 'W' -> eastDistanceFromStart -= value } } else -> error("unknown instruction") } } println(abs(northDistanceFromStart) + abs(eastDistanceFromStart)) } private fun turnShip(orientation: Char, direction: Char, numberOfSteps: Int): Char { if (numberOfSteps == 0) { return orientation } when (direction) { 'L' -> { when (orientation) { 'N' -> return turnShip('W', direction, numberOfSteps - 1) 'S' -> return turnShip('E', direction, numberOfSteps - 1) 'E' -> return turnShip('N', direction, numberOfSteps - 1) 'W' -> return turnShip('S', direction, numberOfSteps - 1) } } 'R' -> { when (orientation) { 'N' -> return turnShip('E', direction, numberOfSteps - 1) 'S' -> return turnShip('W', direction, numberOfSteps - 1) 'E' -> return turnShip('S', direction, numberOfSteps - 1) 'W' -> return turnShip('N', direction, numberOfSteps - 1) } } } error("direction mismatch") }
0
Kotlin
0
0
aba452e0f6dd207e34d17b29e2c91ee21c1f3e41
2,074
Advent-of-Code-2020
MIT License
src/main/kotlin/com/frankandrobot/rapier/nlp/RuleMetric.kt
frankandrobot
62,833,944
false
null
/* * Copyright 2016 <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 com.frankandrobot.rapier.nlp import com.frankandrobot.rapier.meta.Examples import com.frankandrobot.rapier.meta.RapierParams import com.frankandrobot.rapier.meta.SlotFiller import com.frankandrobot.rapier.parse.getMatchedFillers import com.frankandrobot.rapier.rule.IRule import org.funktionale.memoization.memoize internal fun log2(a : Double) = Math.log(a) / Math.log(2.0) /** * If a rule covers less than this number of positive matches, then this rule evaluates * to infinity. * * Don't ask me where "1.442695" comes from...that was in the original source code and * not mentioned in the research paper. */ internal fun metric(p : Int, n : Int, ruleSize : Double, minPosMatches: Int) : Double = if (p < minPosMatches) Double.POSITIVE_INFINITY else -1.442695*log2((p+1.0)/(p+n+2.0)) + ruleSize / (p.toDouble()) data class MetricResults(val positives : List<SlotFiller>, val negatives : List<SlotFiller>) /** * Go through each Example Document and try to find a Rule match. If a match is * found in an Example, it is a "positive match" when the filler match is in the * Example FilledTemplate. Otherwise, it is a "negative match" if the filler match is * not in the FilledTemplate. (In this case, it is considered to be an "accidental" * match and therefore, a negative match). * * Note that the check to tell if a filler occurs in an Example tests only the * word property, not the tag or semantic class. * */ fun IRule.metricResults(examples : Examples) : MetricResults = _metricResults(this, examples) private val _metricResults = { rule : IRule, examples : Examples -> val results = rule.getMatchedFillers(examples) MetricResults(positives = results.positives, negatives = results.negatives) }.memoize() fun IRule.metric(params : RapierParams, examples: Examples) : Double { val result = this.metricResults(examples) return metric( p = result.positives.size, n = result.negatives.size, ruleSize = this.ruleSize(params.ruleSizeWeight), minPosMatches = params.metricMinPositiveMatches ) }
1
Kotlin
1
1
ddbc0dab60ca595e63a701e2f8cd6694ff009adc
2,745
rapier
Apache License 2.0
dsalgo/src/commonTest/kotlin/com/nalin/datastructurealgorithm/problem/FB_problem_test.kt
nalinchhajer1
534,780,196
false
{"Kotlin": 86359, "Ruby": 1605}
package com.nalin.datastructurealgorithm.problem import com.nalin.datastructurealgorithm.ds.toArray import com.nalin.datastructurealgorithm.problems.* import kotlin.test.Test import kotlin.test.assertEquals class FB_problem_test { @Test fun check_findMinimum_shiftedSortedArray() { assertEquals(findMinimum_shiftedSortedArray(arrayOf<Int>()), -1) assertEquals(findMinimum_shiftedSortedArray(arrayOf<Int>(3)), 0) assertEquals(findMinimum_shiftedSortedArray(arrayOf<Int>(3, 5, 9, 10)), 0) assertEquals(findMinimum_shiftedSortedArray(arrayOf<Int>(10, 9, 3, 5)), 2) assertEquals(findMinimum_shiftedSortedArray(arrayOf<Int>(4, 1, 3)), 1) assertEquals(findMinimum_shiftedSortedArray(arrayOf<Int>(4, 5, 6, 7, 8, 10, 9, 3)), 7) } @Test fun check_insertCircularLinkedList() { val root = insertCircularLinkedList(null, 10) assertEquals(root.toArray(), listOf(10)) insertCircularLinkedList(root, 14) assertEquals(root.toArray(), listOf(10, 14)) insertCircularLinkedList(root, 6) assertEquals(root.toArray(), listOf(10, 14, 6)) insertCircularLinkedList(root, 11) insertCircularLinkedList(root, 9) insertCircularLinkedList(root, 5) insertCircularLinkedList(root, 7) assertEquals(root.toArray(), listOf(10, 11, 14, 5, 6, 7, 9)) insertCircularLinkedList(root, 14) insertCircularLinkedList(root, 13) insertCircularLinkedList(root, 12) insertCircularLinkedList(root, 11) insertCircularLinkedList(root, 10) insertCircularLinkedList(root, 9) insertCircularLinkedList(root, 8) insertCircularLinkedList(root, 7) insertCircularLinkedList(root, 6) insertCircularLinkedList(root, 5) assertEquals( root.toArray(), listOf(10, 10, 11, 11, 12, 13, 14, 14, 5, 5, 6, 6, 7, 7, 8, 9, 9) ) } @Test fun testMergeSortedArray() { assertEquals( mergeSortedArray( arrayOf(null, null, null), arrayOf(1, 2, 3) ).joinToString { it.toString() }, arrayOf<Int?>(1, 2, 3).joinToString { it.toString() }) assertEquals( mergeSortedArray( arrayOf(1, 2, 3, null, null, null), arrayOf(1, 2, 3) ).joinToString { it.toString() }, arrayOf<Int?>(1, 1, 2, 2, 3, 3).joinToString { it.toString() }) assertEquals( mergeSortedArray( arrayOf(1, 2, 3), arrayOf() ).joinToString { it.toString() }, arrayOf<Int?>(1, 2, 3).joinToString { it.toString() }) assertEquals( mergeSortedArray( arrayOf(10, 11, 12, null, null, null), arrayOf(1, 2, 3) ).joinToString { it.toString() }, arrayOf<Int?>(1, 2, 3, 10, 11, 12).joinToString { it.toString() }) assertEquals( mergeSortedArray( arrayOf(1, 2, 3, null, null, null), arrayOf(10, 11, 12) ).joinToString { it.toString() }, arrayOf<Int?>(1, 2, 3, 10, 11, 12).joinToString { it.toString() }) } @Test fun testMergeDuplicateChar() { assertEquals(mergeDuplicateChar("abccbc"), "ac") assertEquals(mergeDuplicateChar(""), "") assertEquals(mergeDuplicateChar("ab"), "ab") assertEquals(mergeDuplicateChar("abccba"), "") } @Test fun testFindPalindomeWithErrorProbabaility1() { assertEquals(findPalindomeWithErrorProbabaility1("tacocats"), true) assertEquals(findPalindomeWithErrorProbabaility1("racercar"), true) assertEquals(findPalindomeWithErrorProbabaility1("kbayak"), true) assertEquals(findPalindomeWithErrorProbabaility1("acbccba"), true) assertEquals(findPalindomeWithErrorProbabaility1("abcd"), false) assertEquals(findPalindomeWithErrorProbabaility1("btnnure"), false) } @Test fun testsumOfConsecutiveElement() { assertEquals(sumOfConsecutiveElement(listOf(1, 3, 1, 4, 23), 8), true) assertEquals(sumOfConsecutiveElement(listOf(1, 3, 1, 4, 23), 7), false) // assertEquals(sumOfConsecutiveElement(listOf(1, 3, 1, 4, 6), 7), false) } }
0
Kotlin
0
0
eca60301dab981d0139788f61149d091c2c557fd
4,323
kotlin-ds-algo
MIT License
src/day12/Point.kt
g0dzill3r
576,012,003
false
{"Kotlin": 172121}
package day12 data class Point (val x: Int = 0, val y: Int = 0) { fun distance (other: Point): Int = Math.abs (x - other.x) + Math.abs (y - other.y) fun move (direction: Direction) = Point (x + direction.dx, y + direction.dy) fun delta (other: Point): Pair<Int, Int> = Pair (other.x - x, other.y - y) fun direction (other: Point): Direction { val (dx, dy) = delta (other) return Direction.values ().first { it.dx == dx && it.dy == dy } } override fun toString() = "($x, $y)" } enum class Direction (val dx: Int, val dy: Int) { UP (0, -1), DOWN (0, 1), LEFT (-1, 0), RIGHT (1, 0); val pair: Pair<Int, Int> = Pair (dx, dy) } fun main (args: Array<String>) { val a = Point () val b = a.move (Direction.UP) val c = a.move (Direction.DOWN) val d = a.move (Direction.LEFT) val e = a.move (Direction.RIGHT) println ("a") listOf (a, b, c, d, e).forEach { println ("distance from $a to $it is ${a.distance (it)}") if (a.distance (it) == 1) { println (" - ${a.direction(it)}") } } println ("b") listOf (a, b, c, d, e).forEach { println ("distance from $b to $it is ${b.distance (it)}") if (b.distance (it) == 1) { println (" - ${b.direction(it)}") } } return } // EOF
0
Kotlin
0
0
6ec11a5120e4eb180ab6aff3463a2563400cc0c3
1,347
advent_of_code_2022
Apache License 2.0
src/main/kotlin/ctci/chapterfour/MinimalTree.kt
amykv
538,632,477
false
{"Kotlin": 169929}
package ctci.chapterfour // 4.2 - page 109 // Given a sorted (increasing order) array with unique integer elements, write an algorithm in Kotlin to create a binary // search tree with minimal height. fun main() { val arr = intArrayOf(1, 2, 3, 4, 5, 6, 7, 8, 9) val root = createMinimalBST(arr, 0, arr.size - 1) inOrderTraversal(root) } //This function uses a recursive approach to traverse the tree in-order, first traversing the left subtree, then // visiting the current node, and finally traversing the right subtree. fun inOrderTraversal(root: TreeNode?) { if (root == null) return inOrderTraversal(root.left) println(root.value) inOrderTraversal(root.right) } //One way to create a binary search tree with minimal height from a sorted array is to use a technique called // "divide and conquer". The idea is to divide the array in half, take the middle element as the root of the tree, // and recursively build the left and right subtrees using the elements to the left and right of the middle // element respectively. //This function takes an array of integers, and the start and end indices of the subarray to be used as input. It // calculates the middle index of the subarray, creates a new TreeNode with the value at that index, and recursively // calls itself to build the left and right subtrees of the node, passing the appropriate subarrays as input. class TreeNode(val value: Int, var left: TreeNode? = null, var right: TreeNode? = null) fun createMinimalBST(arr: IntArray, start: Int, end: Int): TreeNode? { if (start > end) return null val mid = (start + end) / 2 val node = TreeNode(arr[mid]) node.left = createMinimalBST(arr, start, mid - 1) node.right = createMinimalBST(arr, mid + 1, end) return node } //The time complexity of this algorithm is O(n), where n is the number of elements in the array, as it visits each // element of the array once. The space complexity is O(n) as well, as it recursively calls itself for each element // in the array.
0
Kotlin
0
2
93365cddc95a2f5c8f2c136e5c18b438b38d915f
2,032
dsa-kotlin
MIT License
src/main/kotlin/com/hopkins/aoc/day16/main.kt
edenrox
726,934,488
false
{"Kotlin": 88215}
package com.hopkins.aoc.day16 import java.io.File import java.lang.IllegalStateException const val debug = false const val part = 2 // A history of the Beam's we've seen in the past. We use this to avoid following // cycles val history = mutableSetOf<Beam>() /** Advent of Code 2023: Day 16 */ fun main() { // Read the file input val lines: List<String> = File("input/input16.txt").readLines() val numLines = lines.size if (debug) { println("Num lines: $numLines") } // Step 1: read the details of the map val map: Map<Point, Char> = lines.flatMapIndexed { y, line -> line.mapIndexedNotNull { x, c -> if (c == '.') { null } else { Point(x, y) to c } } }.toMap() val mapWidth = lines[0].length val mapHeight = lines.size if (debug) { // Output the map (ensure we read it right) println("Map") println("===") for (y in 0 until mapWidth) { for (x in 0 until mapHeight) { val c = map.getOrDefault(Point(x, y), '.') print(c) } println() } } // Step 2: Calculate the list of start Beams // In part 1, there is a single start, in Part 2 there are many starts. val startList: List<Beam> = if (part == 1) { listOf(Beam(Point(0, 0), directionRight)) } else { (0 until mapWidth).flatMap { listOf( Beam(Point(it, 0), directionDown), Beam(Point(it, mapHeight-1), directionUp)) } + (0 until mapHeight).flatMap { listOf( Beam(Point(0, it), directionRight), Beam(Point(mapWidth - 1, it), directionLeft)) } } // Step 3: val maxEnergy = startList.maxOf { start -> history.clear() // Iterative BFS traversal of the map val current = mutableListOf(start) while (current.isNotEmpty()) { val beam = current.removeFirst() history.add(beam) val next = beam.nextBeams(map) .filterNot { history.contains(it) } .filterNot { isOutsideBounds(it.position, mapWidth, mapHeight) } current.addAll(next) } // Calculate the set of energized tiles val energized = history.map { it.position }.toSet() if (debug) { // Output the energized map println("Energized") println("=========") for (y in 0 until mapWidth) { for (x in 0 until mapHeight) { val c = if (energized.contains(Point(x, y))) '#' else '.' print(c) } println() } } energized.size } print("Max Energy: $maxEnergy") // Part 1: 6514 // Part 2: 8089 } /** Returns `true` if the specified position is outside the bounds of the map. */ fun isOutsideBounds(position: Point, width: Int, height: Int) = position.x < 0 || position.y < 0 || position.x >= width || position.y >= height data class Beam(val position: Point, val direction: Point) { /** * Returns a [List] of [Beam]s created by adding the specified * directions to the current position. */ private fun newBeams(vararg directions: Point): List<Beam> { return directions.map { Beam(position.add(it), it) } } /** Returns the next [Beam]s when we advance this [Beam]. */ fun nextBeams(map: Map<Point, Char>): List<Beam> { val tile: Char = map.getOrDefault(position, '.') return when (tile) { '.' -> newBeams(direction) '|' -> if (direction in verticalDirections) { newBeams(direction) } else { newBeams(directionUp, directionDown) } '-' -> if (direction in verticalDirections) { newBeams(directionLeft, directionRight) } else { newBeams(direction) } '\\', '/' -> newBeams(getNextDirection(tile)) else -> throw IllegalStateException("Unexpected tile: $tile at $position") } } /** Returns the next direction when a beam hits a corner tile. */ private fun getNextDirection(cornerTile: Char): Point { require(cornerTile in "\\/") return when (direction) { directionUp -> if (cornerTile == '/') directionRight else directionLeft directionDown -> if (cornerTile == '/') directionLeft else directionRight directionLeft -> if (cornerTile == '/') directionDown else directionUp directionRight -> if (cornerTile == '/') directionUp else directionDown else -> throw IllegalStateException("Unexpected direction: $direction") } } } // Some known direction vectors val directionUp = Point(0, -1) val directionLeft = Point(-1, 0) val directionRight = Point(1, 0) val directionDown = Point(0 , 1) val verticalDirections = setOf(directionUp, directionDown) /** Represents a point in 2 dimensions. */ data class Point(val x: Int, val y: Int) { fun add(dx: Int, dy: Int): Point = Point(x + dx, y + dy) fun add(other: Point) = add(other.x, other.y) }
0
Kotlin
0
0
45dce3d76bf3bf140d7336c4767e74971e827c35
5,545
aoc2023
MIT License
src/main/kotlin/g2101_2200/s2172_maximum_and_sum_of_array/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g2101_2200.s2172_maximum_and_sum_of_array // #Hard #Array #Dynamic_Programming #Bit_Manipulation #Bitmask // #2023_06_26_Time_165_ms_(100.00%)_Space_34.8_MB_(100.00%) class Solution { fun maximumANDSum(nums: IntArray, numSlots: Int): Int { val mask = Math.pow(3.0, numSlots.toDouble()).toInt() - 1 val memo = IntArray(mask + 1) return dp(nums.size - 1, mask, numSlots, memo, nums) } private fun dp(i: Int, mask: Int, numSlots: Int, memo: IntArray, ints: IntArray): Int { if (memo[mask] > 0) { return memo[mask] } if (i < 0) { return 0 } var slot = 1 var bit = 1 while (slot <= numSlots) { if (mask / bit % 3 > 0) { memo[mask] = Math.max( memo[mask], (ints[i] and slot) + dp(i - 1, mask - bit, numSlots, memo, ints) ) } ++slot bit *= 3 } return memo[mask] } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,026
LeetCode-in-Kotlin
MIT License
03-DataClassAndCollection/08-CollectionOperations.kt
ivantendou
739,307,014
false
{"Kotlin": 43124}
// 08 - Collections Operations // filter() and filterNot() val numberList = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) val evenList = numberList.filter { it % 2 == 0 } // evenList: [2, 4, 6, 8, 10] val numberList = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) val notEvenList = numberList.filterNot { it % 2 == 0 } // notEvenList: [1, 3, 5, 7, 9] // map() val numberList = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) val multipliedBy5 = numberList.map { it * 5 } // multipliedBy5: [5, 10, 15, 20, 25, 30, 35, 40, 45, 50] // count() val numberList = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) print(numberList.count()) // Output: 10 val numberList = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) print(numberList.count { it % 3 == 0 }) // <- notice this lambda // Output: 3 // find(), firstOrNull(), and lastOrNull() val numberList = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) val firstOddNumber = numberList.find { it % 2 == 1 } val firstOrNullNumber = numberList.firstOrNull { it % 2 == 3 } // firstOddNumber: 1 // firstOrNullNumber: null // first() and last() val numberList = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) val moreThan10 = numberList.first { it > 1 } print(moreThan10) // Output: 2 // sum() val numberList = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) val total = numberList.sum() // total: 55 println(total) // sorted() val kotlinChar = listOf('k', 'o', 't', 'l', 'i', 'n') val ascendingSort = kotlinChar.sorted() // ascending by default println(ascendingSort) // ascendingSort: [i, k, l, n, o, t] val kotlinChar = listOf('k', 'o', 't', 'l', 'i', 'n') val descendingSort = kotlinChar.sortedDescending() // descending println(descendingSort) // descendingSort: [t, o, n, l, k, i]
0
Kotlin
0
0
3e189aab80fe598223fa17c41f23ac79948f8fe9
1,656
Kotlin-Dicoding
MIT License
colleges/fsu/src/main/kotlin/io/github/opletter/courseevals/fsu/DataProcessing.kt
opLetter
597,896,755
false
{"Kotlin": 390300}
package io.github.opletter.courseevals.fsu import io.github.opletter.courseevals.common.* import io.github.opletter.courseevals.common.data.* import java.nio.file.Path val campusMap = mapOf( "Tallahassee Main Campus" to "Main", "Florida State University" to "Main", "Sarasota Campus" to "Main", "Panama City Campus" to "Pnm", "International Campuses" to "Intl", "Main" to "Tallahassee Main Campus", "Pnm" to "Panama City Campus", "Intl" to "International Campuses", ) // CoursePrefixes.txt comes from https://registrar.fsu.edu/bulletin/undergraduate/information/course_prefix/ fun getDeptNames(): Map<String, String> { return readResource("CoursePrefixes.txt") .split("<tr class=\"TableAllLeft\">") .drop(2) .associate { row -> row .split("<span class=\"pTables9pt\">") .drop(1) .map { it.substringBefore("</span>") } .take(2) .let { it[0] to it[1] } } + ("IFS" to "Independent Florida State") } fun organizeReports(reportsDir: Path, outputDir: Path): SchoolDeptsMap<List<Report>> { val list = readResource("Areas.txt").lines().map { AreaEntry.fromString(it) } val uniqueCodes = list.groupBy({ it.code }, { it.code }).filter { it.value.size == 1 }.keys val nodes = buildTree(list) val childParentMap = buildChildParentMap(nodes, uniqueCodes) return CourseSearchKeys .flatMap { reportsDir.resolve("${it.take(3)}/${it.drop(3)}.json").decodeJson<List<Report>>() } .groupBy { report -> val newArea = report.area .replace("HSFCS-", "HSFCS - ") .replace("ASCOP-", "ASCOP - ") .replace("HSRMP -", "ETRMP - ") .replace(" ", " ") .filter { it != ',' } .let { childParentMap[it] ?: childParentMap[it.substringBefore(" -")] ?: it } campusMap[newArea] ?: error("Unknown area: $newArea") }.mapValues { (_, keys) -> keys .distinctBy { it.ids } .groupBy { it.courseCode.take(3) } }.writeToFiles(outputDir) .also { val schoolsData = it.entries.associate { (key, value) -> key to School( code = key, name = campusMap[key] ?: error("No name for $key"), depts = value.keys.sorted().toSet(), campuses = setOf(Campus.valueOf(key.uppercase())), level = LevelOfStudy.U, ) } outputDir.resolve("schools.json").writeAsJson(schoolsData) } } fun getStatsByProf( reportsDir: Path, includeQuestions: List<Int> = QuestionsLimited.indices - setOf(0, 3, 4, 11), ): SchoolDeptsMap<Map<String, InstructorStats>> { return getCompleteSchoolDeptsMap<List<Report>>(reportsDir).mapEachDept { _, _, reports -> val allNames = reports.map { it.htmlInstructor.uppercase() }.toSet() - "" val nameMappings = allNames.sorted().flatMap { name -> val (last, first) = name.split(", ") val lastParts = last.split(" ", "-") val matching = allNames.filter { otherName -> val (otherLast, otherFirst) = otherName.split(", ") val otherLastParts = otherLast.split(" ", "-") (first.startsWith(otherFirst) || otherFirst.startsWith(first)) && (otherLastParts.any { it in lastParts } || lastParts.any { it in otherLastParts }) } val chosen = matching.maxByOrNull { it.length } ?: return@flatMap emptyList() matching.map { it to chosen } }.toMap() reports .filter { it.htmlInstructor.uppercase().isNotBlank() } .groupBy { nameMappings[it.htmlInstructor.uppercase()] ?: error("${it.htmlInstructor.uppercase()}\n${nameMappings}") }.mapValues { (_, reports) -> val filteredReports = reports .filter { report -> includeQuestions.all { it in report.ratings } }.takeIf { it.isNotEmpty() } ?: return@mapValues null InstructorStats( lastSem = reports.maxOf { val term = it.term.split(" ").reversed().joinToString(" ") Semester.Triple.valueOf(term).numValue }, overallStats = filteredReports.getTotalRatings(includeQuestions), courseStats = filteredReports.flatMap { report -> "[A-Z]{3}\\d{4}[A-Z]?".toRegex().findAll(report.courseCode) .map { it.value.drop(3) } .toSet() .associateWith { report } .entries }.groupBy({ it.key }, { it.value }) .mapValues { (_, reports) -> reports.getTotalRatings(includeQuestions) } ) }.filterValues { it != null }.mapValues { it.value!! } } } // returns list of (# of 1s, # of 2s, ... # of 5s) for each question // note that entries must have scores.size>=100 - maybe throw error? // ***IMPORTANT NOTE*** By default, don't give ratings for question index 7 - as it's mostly irrelevant fun List<Report>.getTotalRatings(includeQuestions: List<Int>): Ratings { return mapNotNull { report -> includeQuestions.map { report.ratings.getValue(it) } }.combine().map { it.reversed() } // reversed so that rankings go from 0-5 } fun createAllInstructors(statsByProfDir: Path): Map<String, List<Instructor>> { return getCompleteSchoolDeptsMap<Map<String, InstructorStats>>(statsByProfDir).mapValues { (_, deptMap) -> deptMap.flatMap { (dept, entries) -> entries.map { (name, stats) -> Instructor(name, dept, stats.lastSem) } }.sortedBy { it.name } } }
0
Kotlin
0
3
44077ad89388cead3944975e975840580d2c9d0b
6,044
course-evals
MIT License
src/main/kotlin/nl/tulipsolutions/mnemonic/wordlist/WordListMaps.kt
TulipSolutions
279,126,945
false
null
// Copyright 2020 Tulip Solutions B.V. // // 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 nl.tulipsolutions.mnemonic.wordlist import java.text.Normalizer enum class Languages { Czech, English, French, Italian, Japanese, Korean, SimplifiedChinese, Spanish, TraditionalChinese } val languageListMap = mapOf<Languages, Array<String>>( Languages.Czech to czechWordList, Languages.English to englishWordList, Languages.French to frenchWordList, Languages.Italian to italianWordList, Languages.Japanese to japaneseWordList, Languages.Korean to koreanWordList, Languages.SimplifiedChinese to simplifiedChineseWordList, Languages.Spanish to spanishWordList, Languages.TraditionalChinese to traditionalChineseWordList ) val checkedLanguageListMap = mapOf<Languages, Array<String>>( Languages.Czech to checkedCzechWordList, Languages.English to checkedEnglishWordList, Languages.French to checkedFrenchWordList, Languages.Italian to checkedItalianWordList, Languages.Japanese to checkedJapaneseWordList, Languages.Korean to checkedKoreanWordList, Languages.SimplifiedChinese to checkedSimplifiedChineseWordList, Languages.Spanish to checkedSpanishWordList, Languages.TraditionalChinese to checkedTraditionalChineseWordList ) val languageWordListMap = Languages.values().map { Pair(it, languageListMap[it]?.toWordListHashMap()) }.toMap() fun Array<String>.toWordListHashMap(): Map<String, Int> { if (this.size != 2048) { throw IncorrectWordListSize(this.size) } return this.mapIndexed { index: Int, s: String -> s.normalize() to index s to index }.toList().toMap() } fun List<Int>.mapValuesToMnemonicWords(language: Languages): List<String> = this.map { // The wordlist can contain native characters, // but they must be encoded in UTF-8 using Normalization Form Compatibility Decomposition (NFKD). languageListMap[language]?.get(it)!!.normalize() } fun String.normalize(): String = Normalizer.normalize(this, Normalizer.Form.NFKD)
1
Kotlin
0
0
1a78849d243d2e2834eb2c80276863ed5746f6c8
2,574
bitcoin-tools
Apache License 2.0
cpg-core/src/main/java/de/fraunhofer/aisec/cpg/helpers/Benchmark.kt
yogical
425,824,120
true
{"Java": 1228692, "Kotlin": 897750, "LLVM": 170600, "Go": 83086, "Python": 53525, "C++": 43784, "C": 30139, "TypeScript": 4873, "JavaScript": 527, "CMake": 204}
/* * Copyright (c) 2019, Fraunhofer AISEC. All rights reserved. * * 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 de.fraunhofer.aisec.cpg.helpers import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper import de.fraunhofer.aisec.cpg.TranslationConfiguration import java.io.File import java.nio.file.Path import java.time.Duration import java.time.Instant import java.util.* import kotlin.IllegalArgumentException import org.slf4j.LoggerFactory class BenchmarkResults(val entries: List<List<Any>>) { val json: String get() { val mapper = jacksonObjectMapper() return mapper.writeValueAsString(entries.associate { it[0] to it[1] }) } /** Pretty-prints benchmark results for easy copying to GitHub issues. */ fun print() { println("# Benchmark run ${UUID.randomUUID()}") printMarkdown(entries, listOf("Metric", "Value")) } } /** Interface definition to hold different statistics about the translation process. */ interface StatisticsHolder { val translatedFiles: List<String> val benchmarks: List<Benchmark> val config: TranslationConfiguration fun addBenchmark(b: Benchmark) val benchmarkResults: BenchmarkResults get() { return BenchmarkResults( listOf( listOf("Translation config", config), listOf("Number of files translated", translatedFiles.size), listOf( "Translated file(s)", translatedFiles.map { relativeOrAbsolute(Path.of(it), config.topLevel) } ), *benchmarks .map { listOf("${it.caller}: ${it.message}", "${it.duration} ms") } .toTypedArray() ) ) } } /** * Prints a table of values and headers in markdown format. Table columns are automatically adjusted * to the longest column. */ fun printMarkdown(table: List<List<Any>>, headers: List<String>) { val lengths = IntArray(headers.size) // first, we need to calculate the longest column per line for (row in table) { for (i in row.indices) { val value = row[i].toString() if (value.length > lengths[i]) { lengths[i] = value.length } } } // table header val dash = lengths.joinToString(" | ", "| ", " |") { ("-".repeat(it)) } var i = 0 val header = headers.joinToString(" | ", "| ", " |") { it.padEnd(lengths[i++]) } println() println(header) println(dash) for (row in table) { var rowIndex = 0 // TODO: Add pretty printing for objects (e.g. List, Map) val line = row.joinToString(" | ", "| ", " |") { it.toString().padEnd(lengths[rowIndex++]) } println(line) } println() } /** * This function will shorten / relativize the [path], if it is relative to [topLevel]. Otherwise, * the full path will be returned. */ fun relativeOrAbsolute(path: Path, topLevel: File?): Path { return if (topLevel != null) { try { topLevel.toPath().toAbsolutePath().relativize(path) } catch (ex: IllegalArgumentException) { path } } else { path } } open class Benchmark @JvmOverloads constructor( c: Class<*>, val message: String, private var debug: Boolean = false, private var holder: StatisticsHolder? = null ) { val caller: String private val start: Instant var duration: Long private set fun stop(): Long { duration = Duration.between(start, Instant.now()).toMillis() val msg = "$caller: $message done in $duration ms" if (debug) { log.debug(msg) } else { log.info(msg) } // update our holder, if we have any holder?.addBenchmark(this) return duration } companion object { private val log = LoggerFactory.getLogger(Benchmark::class.java) } init { this.duration = -1 caller = c.simpleName start = Instant.now() val msg = "$caller: $message" if (debug) { log.debug(msg) } else { log.info(msg) } } }
0
Java
0
0
c4d136eef727cd4d1cf1e3691e83aa7b4623f6a8
5,239
cpg
Apache License 2.0
src/main/kotlin/09.kts
reitzig
318,492,753
false
null
import _09.Result.* import java.io.File sealed class Result { data class Wrong(val firstBadNumber: Long) : Result() object Okay : Result() } fun canSum(summands: List<Long>, number: Long): Boolean { for (i in summands.indices) { for (j in summands.indices) { if (i == j) continue if (summands[i] + summands[j] == number) { return true } } } return false } fun checkSequence(numbers: List<Long>, preambleLength: Int): Result { var minAllowedIndex = 0 for (number in numbers.drop(preambleLength)) { val allowedSummands = numbers.slice(minAllowedIndex until minAllowedIndex + preambleLength) if (!canSum(allowedSummands, number)) { return Wrong(number) } minAllowedIndex += 1 } return Okay } fun findSublistWithSum(numbers: List<Long>, sum: Long): List<Long> { for (i in numbers.indices) { for (j in i + 1..numbers.lastIndex) { val sub = numbers.subList(i, j + 1) when (sub.sum()) { in 0 until sum -> continue sum -> return sub else -> break } } } throw IllegalArgumentException("no such subsequence") } //val preambleLength = 5 // example val preambleLength = 25 // input val numbers = File(args[0]).readLines().map { it.toLong() } // Part 1: when (val result = checkSequence(numbers, preambleLength)) { is Okay -> println("okay") is Wrong -> { println(result) // Part 2 findSublistWithSum(numbers, result.firstBadNumber).let { assert(it.isNotEmpty()) println(it.minOrNull()!! + it.maxOrNull()!!) } } }
0
Kotlin
0
0
f17184fe55dfe06ac8897c2ecfe329a1efbf6a09
1,737
advent-of-code-2020
The Unlicense
compiler/testData/codegen/box/closures/closureCapturingGenericParam.kt
JetBrains
3,432,266
false
{"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80}
interface IntConvertible { fun toInt(): Int } fun <FooTP> foo(init: Int, v: FooTP, l: Int.(FooTP) -> Int) = init.l(v) fun <BarTP : IntConvertible> computeSum(array: Array<BarTP>) = foo(0, array) { var res = this for (element in it) res += element.toInt() res } class N(val v: Int) : IntConvertible { override fun toInt() = v } interface Grouping<GroupingInputTP, out GroupingOutputTP> { fun keyOf(element: GroupingInputTP): GroupingOutputTP } fun <GroupingByTP> groupingBy(keySelector: (Char) -> GroupingByTP): Grouping<Char, GroupingByTP> { fun <T> foo(p0: T, p1: GroupingByTP) {} foo(0, keySelector('a')) class A<T>(p0: T, p1: GroupingByTP) {} A(0, keySelector('a')) return object : Grouping<Char, GroupingByTP> { override fun keyOf(element: Char): GroupingByTP = keySelector(element) } } class Delft<DelftTP> { fun getComparator(other: DelftTP) = { this == other } } fun box(): String { if (computeSum(arrayOf(N(2), N(14))) != 16) return "Fail1" if (groupingBy { it }.keyOf('A') != 'A') return "Fail2" return "OK" }
166
Kotlin
5,771
46,772
bef0946ab7e5acd5b24b971eca532c43c8eba750
1,104
kotlin
Apache License 2.0
src/main/kotlin/com/github/solairerove/algs4/leprosorium/linked_list/InsertIntoASortedCircularLinkedList.kt
solairerove
282,922,172
false
{"Kotlin": 251919}
package com.github.solairerove.algs4.leprosorium.linked_list /** * Given a Circular Linked List node, which is sorted in non-descending order, * write a function to insert a value insertVal into the list such that it remains a sorted circular list. * The given node can be a reference to any single node in the list * and may not necessarily be the smallest value in the circular list. * * If there are multiple suitable places for insertion, you may choose any place to insert the new value. * After the insertion, the circular list should remain sorted. * * If the list is empty (i.e., the given node is null), * you should create a new single circular list and return the reference to that single node. * Otherwise, you should return the originally given node. * * Input: head = [3 -> 4 -> 1], insertVal = 2 * 1 -> | * 4 <- 3 * Output: [3 -> 4 -> 1 -> 2] * * Explanation: In the figure above, there is a sorted circular list of three elements. * You are given a reference to the node with value 3, and we need to insert 2 into the list. * The new node should be inserted between node 1 and node 3. * After the insertion, the list should look like this, and we should still return node 3. */ // O(n) time | O(1) space fun insert(head: ListNode?, insertVal: Int): ListNode { val newNode = ListNode(insertVal) if (head == null) { newNode.next = newNode return newNode } if (head.next == head) { newNode.next = head head.next = newNode return head } var curr: ListNode? = head while (curr != null && curr.next != head) { if (curr.value <= curr.next!!.value) { if (insertVal >= curr.value && insertVal <= curr.next!!.value) break } else { if (insertVal >= curr.value || insertVal <= curr.next!!.value) break } curr = curr.next } val next = curr?.next curr?.next = newNode newNode.next = next return head }
1
Kotlin
0
3
64c1acb0c0d54b031e4b2e539b3bc70710137578
1,977
algs4-leprosorium
MIT License
src/main/kotlin/d12/d12.kt
LaurentJeanpierre1
573,454,829
false
{"Kotlin": 118105}
package d12 import readInput import java.util.PriorityQueue data class Pos(val x: Int, val y: Int) { var prev: Pos? = null var length: Int = -1 constructor(x: Int, y: Int, prev: Pos?, length: Int) : this(x,y){ this.prev = prev this.length = length } } fun part1(input: List<String>): Int { var target : Pos? = null var start : Pos? = null val ite = input.listIterator() val elev = Array<CharArray>(input.size) { var line = ite.next() var idx = line.indexOf('E') if (idx>-1) { line = line.replace('E', 'z') target = Pos(idx, it) } idx = line.indexOf('S') if (idx>-1) { line = line.replace('S', 'a') start = Pos(idx, it, null, 0) } line.toCharArray() } assert(start != null) assert(target != null) val queue = PriorityQueue<Pos>() {p1, p2 -> p1.length.compareTo(p2.length)} queue.add(start) val visited = mutableSetOf<Pos>() while (queue.isNotEmpty()) { val place = queue.poll() if (place in visited) continue if (place == target) return place.length visited.add(place) val (x,y) = place val limit = elev[y][x] + 1 if (x>0 && elev[y][x-1]<= limit) { val next = Pos(x-1, y, place, place.length+1) if (next !in visited) queue.add(next) } if (x<elev[0].size-1 && elev[y][x+1]<= limit) { val next = Pos(x+1, y, place, place.length+1) if (next !in visited) queue.add(next) } if (y>0 && elev[y-1][x]<= limit) { val next = Pos(x, y-1, place, place.length+1) if (next !in visited) queue.add(next) } if (y<elev.size-1 && elev[y+1][x]<= limit) { val next = Pos(x, y+1, place, place.length+1) if (next !in visited) queue.add(next) } } return 0 } fun part2(input: List<String>): Int { val queue = PriorityQueue<Pos>() {p1, p2 -> p1.length.compareTo(p2.length)} var target : Pos? = null val ite = input.listIterator() val elev = Array<CharArray>(input.size) { var line = ite.next() var idx = line.indexOf('E') if (idx>-1) { line = line.replace('E', 'z') target = Pos(idx, it) } idx = line.indexOf('S') if (idx>-1) { line = line.replace('S', 'a') } line.toCharArray() } assert(target != null) for ((y,line) in elev.withIndex()) { for ((x,col) in line.withIndex()) { if (col == 'a') queue.add(Pos(x,y,null,0)) } } val visited = mutableSetOf<Pos>() while (queue.isNotEmpty()) { val place = queue.poll() if (place in visited) continue if (place == target) return place.length visited.add(place) val (x,y) = place val limit = elev[y][x] + 1 if (x>0 && elev[y][x-1]<= limit) { val next = Pos(x-1, y, place, place.length+1) if (next !in visited) queue.add(next) } if (x<elev[0].size-1 && elev[y][x+1]<= limit) { val next = Pos(x+1, y, place, place.length+1) if (next !in visited) queue.add(next) } if (y>0 && elev[y-1][x]<= limit) { val next = Pos(x, y-1, place, place.length+1) if (next !in visited) queue.add(next) } if (y<elev.size-1 && elev[y+1][x]<= limit) { val next = Pos(x, y+1, place, place.length+1) if (next !in visited) queue.add(next) } } return 0 } fun main() { //val input = readInput("d12/test") val input = readInput("d12/input1") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
5cf6b2142df6082ddd7d94f2dbde037f1fe0508f
3,799
aoc2022
Creative Commons Zero v1.0 Universal
hoon/HoonAlgorithm/src/main/kotlin/boj/week02/recursive_function/FibonacciSequence5.kt
boris920308
618,428,844
false
{"Kotlin": 137657, "Swift": 35553, "Java": 1947, "Rich Text Format": 407}
package boj.week02.recursive_function import java.util.* /** * * no.10870 * https://www.acmicpc.net/problem/10870 * * 피보나치 수는 0과 1로 시작한다. 0번째 피보나치 수는 0이고, 1번째 피보나치 수는 1이다. 그 다음 2번째 부터는 바로 앞 두 피보나치 수의 합이 된다. * 이를 식으로 써보면 Fn = Fn-1 + Fn-2 (n ≥ 2)가 된다. * n=17일때 까지 피보나치 수를 써보면 다음과 같다. * 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597 * n이 주어졌을 때, n번째 피보나치 수를 구하는 프로그램을 작성하시오. * * 입력 * 첫째 줄에 n이 주어진다. n은 20보다 작거나 같은 자연수 또는 0이다. * * 출력 * 첫째 줄에 n번째 피보나치 수를 출력한다. */ fun main() { val inputValue = Scanner(System.`in`) println("${fibonacci(inputValue.nextInt())}") } fun fibonacci(n: Int): Int { if (n <= 1) { return n } return fibonacci(n - 1) + fibonacci(n - 2) }
1
Kotlin
1
2
88814681f7ded76e8aa0fa7b85fe472769e760b4
1,042
HoOne
Apache License 2.0
src/test/kotlin/com/igorwojda/integer/digitfrequency/Solution.kt
igorwojda
159,511,104
false
{"Kotlin": 254856}
package com.igorwojda.integer.digitfrequency // Time complexity: O(n) // Generate digit frequency map for each integer and compare them private object Solution1 { private fun equalDigitFrequency(i1: Int, i2: Int): Boolean { val i1Str = i1.toString() val i2Str = i2.toString() if (i1Str.length != i2Str.length) { return false } val frequencyCounter1 = i1Str.groupingBy { it }.eachCount() val frequencyCounter2 = i2Str.groupingBy { it }.eachCount() return frequencyCounter1 == frequencyCounter2 } } // Time complexity: O(n^2) // Loop through each character of first integer and look for this character in another integer. If character if found // remove it from second integer to make sure that character frequency match. private object Solution2 { private fun equalDigitFrequency(i1: Int, i2: Int): Boolean { val i1Str = i1.toString().toList() val i2Str = i2.toString().toMutableList() if (i1Str.size != i2Str.size) { return false } i1Str.forEach { // under the hood 'indexOf' iterates through entire list (it's like nested loop) val index = i2Str.indexOf(it) if (index == -1) { return false } i2Str.removeAt(index) } return true } }
9
Kotlin
225
895
b09b738846e9f30ad2e9716e4e1401e2724aeaec
1,370
kotlin-coding-challenges
MIT License
gcj/y2022/round2/a.kt
mikhail-dvorkin
93,438,157
false
{"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408}
package gcj.y2022.round2 private fun solve(): String { val (n, k) = readInts() var x = 1 var w = n - 1 val ans = mutableListOf<String>() var toCut = n * n - 1 - k var where = 1 while (w > 0) { val y = x + 4 * w repeat(4) { i -> val from = x + i * w + 1 val to = y + i * (w - 2) val cut = to - from - 1 if (cut in 1..toCut && from >= where) { ans.add("$from $to") toCut -= cut where = to } } w -= 2 x = y } if (toCut != 0) return "IMPOSSIBLE" return "" + ans.size + "\n" + ans.joinToString("\n") } fun main() = repeat(readInt()) { println("Case #${it + 1}: ${solve()}") } private fun readLn() = readLine()!! private fun readInt() = readLn().toInt() private fun readStrings() = readLn().split(" ") private fun readInts() = readStrings().map { it.toInt() }
0
Java
1
9
30953122834fcaee817fe21fb108a374946f8c7c
804
competitions
The Unlicense
app/src/test/java/com/terencepeh/leetcodepractice/GroupAnagrams.kt
tieren1
560,012,707
false
{"Kotlin": 26346}
package com.terencepeh.leetcodepractice // O(NKlogK) // O(NK) fun groupAnagrams(strs: Array<String>): List<List<String>> { if (strs.isEmpty()) { return emptyList() } val hashMap = hashMapOf<String, MutableList<String>>() for (s in strs) { val ca = s.toCharArray() ca.sort() val key = String(ca) if (!hashMap.containsKey(key)) { hashMap[key] = arrayListOf() } hashMap[key]!!.add(s) } return ArrayList(hashMap.values) } fun matchAnagrams(strs: Array<String>, originalWord: String): List<String> { if (originalWord.isBlank()) { return emptyList() } val input = originalWord.toCharArray() input.sort() val inputKey = String(input) val hashMap = hashMapOf<String, MutableList<String>>() for (s in strs) { val ca = s.toCharArray() ca.sort() val key = String(ca) if (!hashMap.containsKey(key)) { hashMap[key] = arrayListOf() } hashMap[key]!!.add(s) } return hashMap[inputKey] ?: emptyList() } fun main() { val strs = arrayOf("eat", "tea", "tan", "ate", "nat", "bat") println("groupAnagrams result: ${groupAnagrams(strs)}") println("matchAnagrams result: ${matchAnagrams(strs, "ant")}") }
0
Kotlin
0
0
427fa2855c01fbc1e85a840d0be381cbb4eec858
1,302
LeetCodePractice
MIT License
kotlin/src/katas/kotlin/leetcode/longest_substring/LongestSubstring.kt
dkandalov
2,517,870
false
{"Roff": 9263219, "JavaScript": 1513061, "Kotlin": 836347, "Scala": 475843, "Java": 475579, "Groovy": 414833, "Haskell": 148306, "HTML": 112989, "Ruby": 87169, "Python": 35433, "Rust": 32693, "C": 31069, "Clojure": 23648, "Lua": 19599, "C#": 12576, "q": 11524, "Scheme": 10734, "CSS": 8639, "R": 7235, "Racket": 6875, "C++": 5059, "Swift": 4500, "Elixir": 2877, "SuperCollider": 2822, "CMake": 1967, "Idris": 1741, "CoffeeScript": 1510, "Factor": 1428, "Makefile": 1379, "Gherkin": 221}
package katas.kotlin.leetcode.longest_substring import datsok.shouldEqual import org.junit.Test /** * https://leetcode.com/problems/longest-substring-without-repeating-characters/ */ class LongestSubstring { @Test fun `find the length of the longest substring without repeating characters`() { "".longestSubstring() shouldEqual 0 "a".longestSubstring() shouldEqual 1 "abc".longestSubstring() shouldEqual 3 "abca".longestSubstring() shouldEqual 3 "aabbc".longestSubstring() shouldEqual 2 "abcabcbb".longestSubstring() shouldEqual 3 "bbbbb".longestSubstring() shouldEqual 1 "pwwkew".longestSubstring() shouldEqual 3 } } private fun String.longestSubstring(): Int { var maxSize = 0 val visited = HashSet<Char>() var from = 0 var to = 0 while (to < length) { val added = visited.add(this[to]) if (!added) { while (this[from] != this[to]) { visited.remove(this[from]) from++ } from++ } maxSize = maxOf(maxSize, to - from + 1) to++ } return maxSize }
7
Roff
3
5
0f169804fae2984b1a78fc25da2d7157a8c7a7be
1,159
katas
The Unlicense
src/main/kotlin/org/ojacquemart/eurobets/firebase/management/table/TableCalculator.kt
ojacquemart
58,000,277
false
{"Kotlin": 119977, "Shell": 7058, "Java": 6830, "Batchfile": 5006}
package org.ojacquemart.eurobets.firebase.management.table import kotlin.comparisons.compareBy import kotlin.comparisons.thenBy class TableCalculator(val bets: List<BetData>, val recentsSize: Int = TableCalculator.RECENTS_SIZE) { fun getRows(): List<TableRow> { val tableRows = getTableRows() val positions = TableRow.getPositions(tableRows) val rowsWithPosition = tableRows .map { val position = positions.indexOf(it.points) + 1 val last10Recents = it.recents.takeLast(recentsSize).toTypedArray() it.copy(position = position, recents = last10Recents) } .filterNot { val undefinedRecents = it.recents.filter { it == Result.UNDEFINED.id } undefinedRecents.size == recentsSize } return rowsWithPosition.sortedWith(COMPARATOR) } private fun getTableRows(): List<TableRow> { return bets.groupBy { bet -> bet.user } .map { entry -> val user = entry.key!! val bets = entry.value bets.filter { it.user!!.uid.equals(user.uid) } } .map { bet -> reduce(bet) } } fun reduce(bets: List<BetData>): TableRow { val tableRow = bets.map { bet -> val user = bet.user!! val resultPoints = bet.getResultPoints() val result = resultPoints?.result TableRow( uid = user.uid, displayName = user.displayName, profileImageURL = user.profileImageURL, points = resultPoints?.points ?: 0, bets = if (result != null) 1 else 0, percentage = 0, perfects = if (result == Result.PERFECT) 1 else 0, goodGaps = if (result == Result.GOOD_GAP) 1 else 0, goods = if (result == Result.GOOD) 1 else 0, bads = if (result == Result.BAD) 1 else 0, recents = arrayOf(if (result != null) result.id else Result.UNDEFINED.id) ) }.reduce { current, next -> current.copy( points = current.points + next.points, bets = current.bets + next.bets, percentage = TableRow.percentage(next, current), perfects = current.perfects + next.perfects, goodGaps = current.goodGaps + next.goodGaps, goods = current.goods + next.goods, bads = current.bads + next.bads, recents = current.recents.plus(next.recents[0])) } val winnerBet = bets.filter { it.winner != null }.getOrNull(0) val winnerPoints = winnerBet?.getFinalePoints() ?: 0 return tableRow.copy(points = tableRow.points + winnerPoints, winner = winnerBet?.winner) } companion object { val RECENTS_SIZE = 10 val COMPARATOR = compareBy<TableRow> { it.position } .thenBy { -it.bets }.thenBy { -it.perfects }.thenBy { -it.goodGaps }.thenBy { -it.goods } .thenBy { it.displayName } } }
0
Kotlin
1
1
1b5a2bc9568cac6921680369862c04b9617a9438
3,246
spring-kotlin-euro-bets
The Unlicense
src/main/kotlin/com/wabradshaw/claptrap/generation/SetupConstraints.kt
wabradshaw
154,681,482
false
null
package com.wabradshaw.claptrap.generation import com.wabradshaw.claptrap.structure.Form import com.wabradshaw.claptrap.structure.JokeSpec import com.wabradshaw.claptrap.structure.PartOfSpeech import com.wabradshaw.claptrap.structure.Relationship /** * A template constraint type defines a type of constraint that can be put on the joke spec. For example, SECONDARY_POS * is a constraint on the part of speech for the secondary setup word. * * @property function The function that checks whether the constraint is true for the given joke spec and argument */ enum class TemplateConstraintType(val function: (spec: JokeSpec, arg: String) -> Boolean) { /* Constrains whether or not the primary setup exists as a known word. */ PRIMARY_KNOWN({spec, known -> known.toBoolean() == (spec.primarySetup != null)}), /* Constrains whether or not the nucleus exists as a known word. */ NUCLEUS_KNOWN({spec, known -> known.toBoolean() == (spec.nucleusWord != null)}), /* Constrains what the part of speech the primary setup word must have. Fails if unknown. */ PRIMARY_POS({spec, pos -> PartOfSpeech.valueOf(pos) == spec.primarySetup?.substitution?.partOfSpeech}), /* Constrains what the part of speech the secondary setup word must have. */ SECONDARY_POS({spec, pos -> PartOfSpeech.valueOf(pos) == spec.secondarySetup.substitution.partOfSpeech}), /* Constrains what the part of speech the nucleus word must have. Fails if unknown. */ NUCLEUS_POS({spec, pos -> PartOfSpeech.valueOf(pos) == spec.nucleusWord?.partOfSpeech}), /* Constrains what the relationship is between the primary setup word and the nucleus. Fails if unknown. */ PRIMARY_RELATIONSHIP({spec, rel -> Relationship.valueOf(rel) == spec.primarySetup?.relationship}), /* Constrains what the relationship is between the secondary setup word and the nucleus substitute. */ SECONDARY_RELATIONSHIP({spec, rel -> Relationship.valueOf(rel) == spec.secondarySetup.relationship}), /* Constrains what the form of the nucleus must be. Assumes normal if unknown. */ NUCLEUS_FORM({spec, form -> Form.valueOf(form) == spec.nucleusWord?.form?:Form.NORMAL}), /* Constrains what the form of the nucleus must not be. Assumes normal if unknown. */ NUCLEUS_FORM_NOT({spec, form -> Form.valueOf(form) != spec.nucleusWord?.form?:Form.NORMAL}), } /** * A TemplateConstraint defines a constraint that must be true for a SetupTemplate to be used. */ class TemplateConstraint(val constraint: TemplateConstraintType, val arg: String){ /** * Checks whether or not this particular constraint applies to the given joke. * * @param spec The JokeSpec to evaluate */ fun applies(spec: JokeSpec): Boolean{ return constraint.function.invoke(spec, arg) } }
0
Kotlin
0
0
7886787603e477d47ea858a8d9c76e11c4c25fe3
2,862
claptrap
Apache License 2.0
src/main/kotlin/com/ab/advent/day02/Puzzle.kt
battagliandrea
574,137,910
false
{"Kotlin": 27923}
package com.ab.advent.day02 import com.ab.advent.utils.readLines /* PART 01 The Elves begin to set up camp on the beach. To decide whose tent gets to be closest to the snack storage, a giant Rock Paper Scissors tournament is already in progress. Rock Paper Scissors is a game between two players. Each game contains many rounds; in each round, the players each simultaneously choose one of Rock, Paper, or Scissors using a hand shape. Then, a winner for that round is selected: Rock defeats Scissors, Scissors defeats Paper, and Paper defeats Rock. If both players choose the same shape, the round instead ends in a draw. Appreciative of your help yesterday, one Elf gives you an encrypted strategy guide (your puzzle input) that they say will be sure to help you win. "The first column is what your opponent is going to play: A for Rock, B for Paper, and C for Scissors. The second column--" Suddenly, the Elf is called away to help with someone's tent. The second column, you reason, must be what you should play in response: X for Rock, Y for Paper, and Z for Scissors. Winning every time would be suspicious, so the responses must have been carefully chosen. The winner of the whole tournament is the player with the highest score. Your total score is the sum of your scores for each round. The score for a single round is the score for the shape you selected (1 for Rock, 2 for Paper, and 3 for Scissors) plus the score for the outcome of the round (0 if you lost, 3 if the round was a draw, and 6 if you won). Since you can't be sure if the Elf is trying to help you or trick you, you should calculate the score you would get if you were to follow the strategy guide. For example, suppose you were given the following strategy guide: A Y B X C Z This strategy guide predicts and recommends the following: In the first round, your opponent will choose Rock (A), and you should choose Paper (Y). This ends in a win for you with a score of 8 (2 because you chose Paper + 6 because you won). In the second round, your opponent will choose Paper (B), and you should choose Rock (X). This ends in a loss for you with a score of 1 (1 + 0). The third round is a draw with both players choosing Scissors, giving you a score of 3 + 3 = 6. In this example, if you were to follow the strategy guide, you would get a total score of 15 (8 + 1 + 6). What would your total score be if everything goes exactly according to your strategy guide? PART 02 The Elf finishes helping with the tent and sneaks back over to you. "Anyway, the second column says how the round needs to end: X means you need to lose, Y means you need to end the round in a draw, and Z means you need to win. Good luck!" The total score is still calculated in the same way, but now you need to figure out what shape to choose so the round ends as indicated. The example above now goes like this: In the first round, your opponent will choose Rock (A), and you need the round to end in a draw (Y), so you also choose Rock. This gives you a score of 1 + 3 = 4. In the second round, your opponent will choose Paper (B), and you choose Rock so you lose (X) with a score of 1 + 0 = 1. In the third round, you will defeat your opponent's Scissors with Rock for a score of 1 + 6 = 7. Now that you're correctly decrypting the ultra top secret strategy guide, you would get a total score of 12. Following the Elf's instructions for the second column, what would your total score be if everything goes exactly according to your strategy guide? */ fun main() { println("Day 2 - Puzzle 2") println("What would your total score be if everything goes exactly according to your strategy guide?") println(answer1("puzzle_02_input.txt".readLines())) println("Following the Elf's instructions for the second column.\nWhat would your total score be if everything goes exactly according to your strategy guide?") println(answer2("puzzle_02_input.txt".readLines())) } fun answer1(input: List<String>) = input.map { it.split(" ") }.toTournament1().totalScore fun answer2(input: List<String>) = input.map { it.split(" ") }.toTournament2().totalScore
0
Kotlin
0
0
cb66735eea19a5f37dcd4a31ae64f5b450975005
4,135
Advent-of-Kotlin
Apache License 2.0
src/main/java/com/booknara/problem/tree/traverse/VerticalOrderTraversalofBinaryTreeKt.kt
booknara
226,968,158
false
{"Java": 1128390, "Kotlin": 177761}
package com.booknara.problem.tree.traverse import java.util.* import kotlin.collections.ArrayList /** * 987. Vertical Order Traversal of a Binary Tree (Medium) * https://leetcode.com/problems/vertical-order-traversal-of-a-binary-tree/ */ class VerticalOrderTraversalofBinaryTreeKt { // T:O(n*logn), S:O(n) fun verticalTraversal(root: TreeNode?): List<List<Int>> { // input check, the number of nodes >= 1 // BFS val res = mutableListOf<ArrayList<Int>>() if (root == null) return res val map = mutableMapOf<Int, ArrayList<Int>>() val queue = LinkedList<Pair<Int,TreeNode?>>() queue.offer(Pair(0, root)) var min = 0 while (!queue.isEmpty()) { val temp = mutableMapOf<Int, PriorityQueue<Int>>() val size = queue.size for (i in 0 until size) { val n = queue.poll() min = Math.min(min, n.first) val list = temp.getOrDefault(n.first, PriorityQueue<Int>()) list.offer(n.second?.`val`) temp.put(n.first, list) if (n.second?.left != null) { queue.offer(Pair(n.first - 1, n.second?.left)) } if (n.second?.right != null) { queue.offer(Pair(n.first + 1, n.second?.right)) } } temp.forEach { (k, v) -> val list = map.getOrDefault(k, ArrayList()) while (!v.isEmpty()) { list.add(v.poll()) } map.put(k, list) } } while (true) { if (map[min] == null) { break; } val list = ArrayList<Int>() map[min]?.forEach { list.add(it) } res.add(list) min++ } return res } class TreeNode(var `val`: Int) { var left: TreeNode? = null var right: TreeNode? = null } }
0
Java
1
1
04dcf500ee9789cf10c488a25647f25359b37a53
1,750
playground
MIT License
src/main/kotlin/Day18.kt
Yeah69
317,335,309
false
{"Kotlin": 73241}
class Day18 : Day() { override val label: String get() = "18" private interface Token private data class Number (val value: Long) : Token private enum class OpType { ADD, MUL } private data class Operator (val type: OpType) : Token private enum class ParType { OPENING, CLOSING } private data class Parentheses (val type: ParType) : Token private val expressions by lazy { input.lineSequence().map { it.tokenize().toList() }.toList() } private fun String.tokenize(): Sequence<Token> { val expression = this return sequence { for (c in expression) when (c) { '+' -> yield(Operator(OpType.ADD)) '*' -> yield(Operator(OpType.MUL)) '(' -> yield(Parentheses(ParType.OPENING)) ')' -> yield(Parentheses(ParType.CLOSING)) ' ' -> {} else -> yield(Number(c.toString().toLong())) } } } private fun MutableList<Token>.evaluate(evaluateParenthesesFree: (MutableList<Token>) -> Number): Number { do { var foundSome = false var firstClosing = 0 var lastOpening = 0 var i = 0 while (i < this.size) { if (this[i] is Parentheses){ val parentheses = this[i] as Parentheses if (parentheses.type == ParType.OPENING) lastOpening = i else { firstClosing = i break } } i++ } if (firstClosing != 0) { val number = evaluateParenthesesFree(this.subList(lastOpening + 1, firstClosing).toMutableList()) this[lastOpening] = number ((lastOpening + 1)..firstClosing).forEach { _ -> this.removeAt(lastOpening + 1) } foundSome = true } } while (foundSome) return evaluateParenthesesFree(this) } private fun logic(evaluateParenthesesFree: (MutableList<Token>) -> Number): String = expressions.map { it.toMutableList().evaluate(evaluateParenthesesFree).value }.sum().toString() override fun taskZeroLogic(): String = logic { list -> while (list.size != 1) { val first = (list[0] as Number).value val second = (list[2] as Number).value val op = (list[1] as Operator).type list[0] = Number(when (op) { OpType.ADD -> first + second OpType.MUL -> first * second }) list.removeAt(1) list.removeAt(1) } list[0] as Number } override fun taskOneLogic(): String = logic { list -> var i = 0 while (i < list.size) { if (list[i] == Operator(OpType.ADD)) { val first = (list[i - 1] as Number).value val second = (list[i + 1] as Number).value list[i - 1] = Number(first + second) list.removeAt(i) list.removeAt(i) } else i++ } list.removeIf{ it == Operator(OpType.MUL) } list.fold(Number(1)) { prev, curr -> Number(prev.value * (curr as Number).value) } } }
0
Kotlin
0
0
23121ede8e3e8fc7aa1e8619b9ce425b9b2397ec
3,329
AdventOfCodeKotlin
The Unlicense
src/chapter1/problem4/solution1.kts
neelkamath
395,940,983
false
null
/* Question: Palindrome Permutation: Given a string, write a function to check if it is a permutation of a palindrome. A palindrome is a word or phrase that is the same forwards and backwards. A permutation is a rearrangement of letters. The palindrome does not need to be limited to just dictionary words. EXAMPLE Input: <NAME> Output: True (permutations: "taco cat", "atco cta", etc.) Solution: Using a set. */ setOf("tact coa", "neel", "neeln").forEach { println("$it: ${isPermutationOfPalindrome(it)}") } fun isPermutationOfPalindrome(string: String): Boolean { val set = mutableSetOf<Char>() val input = string.filter { it != ' ' } input.forEach { if (it in set) set.remove(it) else set.add(it) } return set.size == input.length % 2 }
0
Kotlin
0
0
4421a061e5bf032368b3f7a4cee924e65b43f690
762
ctci-practice
MIT License
src/commonMain/kotlin/io/github/alexandrepiveteau/graphs/algorithms/Dijkstra.kt
alexandrepiveteau
630,931,403
false
{"Kotlin": 132267}
@file:JvmName("Algorithms") @file:JvmMultifileClass package io.github.alexandrepiveteau.graphs.algorithms import io.github.alexandrepiveteau.graphs.* import io.github.alexandrepiveteau.graphs.internal.collections.IntMinPriorityQueue import kotlin.jvm.JvmMultifileClass import kotlin.jvm.JvmName /** * Returns the list of parents for each vertex in the shortest path tree from the [from] vertex. * * @param from the [Vertex] to start the search from. * @return the map of parents for each vertex in the shortest path tree from the [from] vertex. */ private fun <N> N.shortestPathDijkstraParents( from: Vertex, ): VertexMap where N : SuccessorsWeight { val parents = VertexMap(size) { Vertex.Invalid } val queue = IntMinPriorityQueue(size) val distances = IntArray(size) { Int.MAX_VALUE } val visited = BooleanArray(size) { false } distances[index(from)] = 0 queue[index(from)] = 0 while (queue.size > 0) { val v1 = vertex(queue.remove()) visited[index(v1)] = true forEachSuccessor(v1) { v2, weight -> if (!visited[index(v2)]) { // Note : we only throw on negative weights if they are visited, so a graph with negative // weights in a component disconnected from the source will not throw. if (weight < 0) throw IllegalArgumentException("Negative weights are not supported.") val d1 = distances[index(v1)] val d2 = distances[index(v2)] val alt = d1 + weight if (alt < d2) { distances[index(v2)] = alt parents[v2] = v1 queue[index(v2)] = alt } } } } return parents } /** * Computes the shortest path from the given [from] vertex to all the other vertices in the network, * using Dijkstra's algorithm. * * ## Asymptotic complexity * - **Time complexity**: O(|N| * log(|N|) + |E|), where |N| is the number of vertices, and |E| is * the number of edges in this graph. * - **Space complexity**: O(|N|), where |N| is the number of vertices in this graph. * * @param from the [Vertex] to start the search from. * @return the [DirectedNetwork] containing the shortest paths from the [from] vertex to all the * other vertices in the network. * @throws NoSuchVertexException if the [from] vertex is not in this network. * @throws IllegalArgumentException if the network contains negative weights. */ public fun <N> N.shortestPathDijkstra( from: Vertex, ): DirectedNetwork where N : SuccessorsWeight { if (from !in this) throw NoSuchVertexException() return computeNetwork(shortestPathDijkstraParents(from)) } /** * Computes the shortest path from the given [from] vertex to the [to] vertex in the network, using * Dijkstra's algorithm. * * ## Asymptotic complexity * - **Time complexity**: O(|N| * log(|N|) + |E|), where |N| is the number of vertices, and |E| is * the number of edges in this graph. * - **Space complexity**: O(|N|), where |N| is the number of vertices in this graph. * * @param from the source vertex. * @param to the target vertex. * @return the shortest path from the given [from] vertex to the given [to] vertex in the network, * or `null` if no such path exists. * @throws NoSuchVertexException if the [from] or [to] vertices are not in this graph. * @throws IllegalArgumentException if the network contains negative weights. */ public fun <N> N.shortestPathDijkstra( from: Vertex, to: Vertex, ): VertexArray? where N : SuccessorsWeight { if (from !in this) throw NoSuchVertexException() if (to !in this) throw NoSuchVertexException() return computePath(shortestPathDijkstraParents(from), from, to) }
9
Kotlin
0
6
a4fd159f094aed5b6b8920d0ceaa6a9c5fc7679f
3,634
kotlin-graphs
MIT License
src/days/Day03.kt
EnergyFusion
572,490,067
false
{"Kotlin": 48323}
import java.io.BufferedReader fun main() { val day = 3 fun calculatePriority(char: Char):Int { return if (char.isUpperCase()) { char.code - 38 } else { char.code - 96 } } fun part1(inputReader: BufferedReader): Int { var totalPriority = 0 inputReader.forEachLine { line -> val mid = line.length / 2 val container1 = line.substring(0, mid).toSet() val container2 = line.substring(mid).toSet() val commonChars = container1.filter { char -> container2.contains(char) } // println(commonChars) if (commonChars.size == 1) { totalPriority += calculatePriority(commonChars[0]) } } return totalPriority } fun part2(inputReader: BufferedReader): Int { var totalPriority = 0 inputReader.useLines { it.chunked(3).forEach { group -> val groupSets = group.map { sack -> sack.toSet() }.sortedBy { sackSet -> sackSet.size } val commonChars = groupSets[0].filter { char -> groupSets[1].contains(char) && groupSets[2].contains(char) } // println(commonChars) if (commonChars.size == 1) { totalPriority += calculatePriority(commonChars[0]) } } } return totalPriority } val testInputReader = readBufferedInput("tests/Day%02d".format(day)) // println(part1(testInputReader)) // check(part1(testInputReader) == 157) check(part2(testInputReader) == 70) val input = readBufferedInput("input/Day%02d".format(day)) // println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
06fb8085a8b1838289a4e1599e2135cb5e28c1bf
1,732
advent-of-code-kotlin
Apache License 2.0
leetcode/src/dp/OneZeroPackage.kt
zhangweizhe
387,808,774
false
null
package dp /** * 01背包问题 */ fun main() { val packageSize = 6 val objSize = 4 val weightArray = intArrayOf(2,3,1,5) val valueArray = intArrayOf(1,4,2,3) val dp = Array<Array<Int>>(objSize + 1) { Array<Int>(packageSize + 1) { 0 } } for (i in 1..objSize) { for (j in 0..packageSize) { val currentValue = valueArray[i-1] val currentWeight = weightArray[i-1] if (currentWeight > j) { // 背包容量放不下当前物品,取上一个物品的价值 dp[i][j] = dp[i-1][j] }else { // 背包容量可以放下当前物品 // 不拿当前物品时的价值,也就是当前容量下上一个物品的价值(最优解) val noTakeValue = dp[i-1][j] // 拿当前物品时的价值,背包容量减去当前物品重量j-currentWeight,剩余容量的最优解dp[i-1][j-currentWeight],再加上当前物品的价值currentValue val takeValue = dp[i-1][j-currentWeight] + currentValue dp[i][j] = Math.max(noTakeValue, takeValue) } } } for (i in dp) { println(i.contentToString()) } solution2() } /** * 01 背包问题,一维数组解决 */ fun solution2() { val packageSize = 6 val objSize = 4 val weightArray = intArrayOf(2,3,1,5) val valueArray = intArrayOf(1,4,2,3) val dp = Array<Int>(packageSize + 1) { 0 } for (i in 1..objSize) { val currentWeight = weightArray[i-1] val currentValue = valueArray[i-1] // 从后往前遍历,因为要用到的 dp[j-currentWeight] 其实是上一轮的值,如果从前往后遍历,dp[j-currentWeight] 会被覆盖 for (j in packageSize downTo 0) { if (currentWeight <= j) { dp[j] = Math.max(dp[j], dp[j-currentWeight] + currentValue) } } } println(dp.contentToString()) }
0
Kotlin
0
0
1d213b6162dd8b065d6ca06ac961c7873c65bcdc
2,043
kotlin-study
MIT License
src/main/kotlin/g0601_0700/s0673_number_of_longest_increasing_subsequence/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g0601_0700.s0673_number_of_longest_increasing_subsequence // #Medium #Array #Dynamic_Programming #Segment_Tree #Binary_Indexed_Tree // #Algorithm_II_Day_16_Dynamic_Programming #2023_02_15_Time_226_ms_(91.67%)_Space_36.3_MB_(83.33%) class Solution { fun findNumberOfLIS(nums: IntArray): Int { val dp = IntArray(nums.size) val count = IntArray(nums.size) dp[0] = 1 count[0] = 1 var result = 0 var max = Int.MIN_VALUE for (i in 1 until nums.size) { dp[i] = 1 count[i] = 1 for (j in i - 1 downTo 0) { if (nums[j] < nums[i]) { if (dp[i] < dp[j] + 1) { dp[i] = dp[j] + 1 count[i] = count[j] } else if (dp[i] == dp[j] + 1) { count[i] += count[j] } } } } for (i in nums.indices) { if (max < dp[i]) { result = count[i] max = dp[i] } else if (max == dp[i]) { result += count[i] } } return result } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,192
LeetCode-in-Kotlin
MIT License
src/main/kotlin/dev/claudio/adventofcode2021/Day15Part2.kt
ClaudioConsolmagno
434,559,159
false
{"Kotlin": 78336}
package dev.claudio.adventofcode2021 import dev.claudio.adventofcode2021.Support.Companion.printGrid import dev.claudio.adventofcode2021.Support.Companion.surroundingPoints4 import org.jgrapht.Graph import org.jgrapht.alg.shortestpath.DijkstraShortestPath import org.jgrapht.graph.DefaultWeightedEdge import org.jgrapht.graph.builder.GraphTypeBuilder import java.awt.Point fun main() { Day15Part2().main() } private class Day15Part2 { // https://jgrapht.org/guide/UserOverview#graph-algorithms val graph: Graph<Point, DefaultWeightedEdge> = GraphTypeBuilder .directed<Point, DefaultWeightedEdge>() .weighted(true) .edgeClass(DefaultWeightedEdge::class.java) .buildGraph() fun main() { val input = Support.readFileAsListString("day15-input-test.txt") val ySize = input.size val xSize = input[0].length val maxPoint = Point(5 * xSize - 1, 5 * ySize - 1) (0 until 5).map { it * ySize}.forEach { tileY -> (0 until 5).map { it * xSize }.forEach { tileX -> (0 until ySize).forEach { y -> (0 until xSize).forEach { x -> graph.addVertex(Point(tileX + x, tileY + y)) } } } } (0 until 5).forEach { yCount -> val tileY = yCount * ySize (0 until 5).forEach { xCount -> val tileX = xCount * xSize input.forEachIndexed { y, str -> str.toList().forEachIndexed { x, weight -> val currentPoint = Point(tileX + x, tileY + y) val adjustedWeight = (xCount + yCount + weight.digitToInt().toDouble()).let { if (it > 9) { it % 9 } else { it } } currentPoint.surroundingPoints4(maxPoint).forEach { graph.addEdge(currentPoint, it) .apply { graph.setEdgeWeight(this, adjustedWeight) } } } } } } val dijkstraAlg = DijkstraShortestPath(graph).getPaths(maxPoint) println(dijkstraAlg.getWeight(Point(0,0))) // dijkstraAlg.getPath(Point(0,0)).vertexList.printGrid() } }
0
Kotlin
0
0
5f1aff1887ad0a7e5a3af9aca7793f1c719e7f1c
2,284
adventofcode-2021
Apache License 2.0