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
advent-of-code-2020/src/test/java/aoc/Day10AdapterArray.kt
yuriykulikov
159,951,728
false
{"Kotlin": 1666784, "Rust": 33275}
package aoc import org.assertj.core.api.Assertions.assertThat import org.junit.Test class Day10AdapterArray { @Test fun silverTest() { val zipped = connectAdapters(testInput) assertThat(zipped.count { it == 1 }).isEqualTo(7) assertThat(zipped.count { it == 3 }).isEqualTo(5) } @Test fun silverTest2() { val zipped = connectAdapters(testInput2) assertThat(zipped.count { it == 1 }).isEqualTo(22) assertThat(zipped.count { it == 3 }).isEqualTo(10) } @Test fun silver() { val zipped = connectAdapters(taskInput) val ones = zipped.count { it == 1 } val threes = zipped.count { it == 3 } assertThat(ones * threes).isEqualTo(2100) } private fun connectAdapters(input: List<Int>): List<Int> { return input .plus(0) .plus((input.maxOrNull() ?: 0) + 3) .sorted() .zipWithNext { l, r -> r - l } .apply { require(all { it <= 3 }) } } /** * (0), 1, 4, 5, 6, 7, 10, 11, 12, 15, 16, 19, (22) * (0), 1, 4, 5, 6, 7, 10, 12, 15, 16, 19, (22) * (0), 1, 4, 5, 7, 10, 11, 12, 15, 16, 19, (22) * (0), 1, 4, 5, 7, 10, 12, 15, 16, 19, (22) * (0), 1, 4, 6, 7, 10, 11, 12, 15, 16, 19, (22) * (0), 1, 4, 6, 7, 10, 12, 15, 16, 19, (22) * (0), 1, 4, 7, 10, 11, 12, 15, 16, 19, (22) * (0), 1, 4, 7, 10, 12, 15, 16, 19, (22) */ @Test fun goldTest() { // 19,208 // 2^3 × 7^4 val combinations = countCombinations(testInput2) println("and we have $combinations combinations") assertThat(combinations).isEqualTo(19208) } @Test fun gold() { val combinations = countCombinations(taskInput) println("and we have $combinations combinations") assertThat(combinations).isEqualTo(16198260678656L) } private fun countCombinations(input: List<Int>): Long { val counts = input .plus(0) .sorted() .zipWithNext { l, r -> r - l } .joinToString(separator = "") .split("3") .filter { it.isNotEmpty() } .map { it.length } return counts.map { it.combinations() }.reduce(Long::times) } private fun Int.combinations(): Long { return when (this) { 1 -> 1 2 -> 2 3 -> 4 4 -> 7 else -> error("No idea") } } private val testInput = """ 16 10 15 5 1 11 7 19 6 12 4 """.trimIndent() .lines() .map { it.toInt() } private val testInput2 = """ 28 33 18 42 31 14 46 20 48 47 24 23 49 45 19 38 39 11 1 32 25 35 8 17 7 9 4 2 34 10 3 """.trimIndent() .lines() .map { it.toInt() } private val taskInput = """ 151 94 14 118 25 143 33 23 80 95 87 44 150 39 148 51 138 121 70 69 90 155 144 40 77 8 97 45 152 58 65 63 128 101 31 112 140 86 30 55 104 135 115 16 26 60 96 85 84 48 4 131 54 52 139 76 91 46 15 17 37 156 134 98 83 111 72 34 7 108 149 116 32 110 47 157 75 13 10 145 1 127 41 53 2 3 117 71 109 105 64 27 38 59 24 20 124 9 66 """.trimIndent() .lines() .map { it.toInt() } }
0
Kotlin
0
1
f5efe2f0b6b09b0e41045dc7fda3a7565cb21db3
4,103
advent-of-code
MIT License
lib/src/main/kotlin/com/bloidonia/advent/day21/Day21.kt
timyates
433,372,884
false
{"Kotlin": 48604, "Groovy": 33934}
package com.bloidonia.advent.day21 class Die(var next: Int = 0) { fun next(): Int = (next + 1).apply { next = this.mod(100) } fun three(): Int = listOf(next(), next(), next()).sum() } class Game(private val die: Die, val turn: Int, private val pos: IntArray, val scores: IntArray = IntArray(2) { 0 }) { fun roll(): Game { val player = turn.mod(2) pos[player] = (pos[player] + die.three()).mod(10) scores[player] += pos[player] + 1 return Game(die, turn + 1, pos, scores) } } // This is my tests this time... fun example() { val die = Die() generateSequence(Game(die, 0, listOf(4 - 1, 8 - 1).toIntArray())) { it.roll() } .dropWhile { game -> game.scores.all { it < 1000 } } .first() .apply { (this.turn * 3 * this.scores.find { it < 1000 }!!).apply { if (this != 739785) { throw IllegalArgumentException("Nope $this") } println(this) } } } fun part1() { val die = Die() generateSequence(Game(die, 0, listOf(8 - 1, 2 - 1).toIntArray())) { it.roll() } .dropWhile { game -> game.scores.all { it < 1000 } } .first() .apply { println(this.turn * 3 * this.scores.find { it < 1000 }!!) } } data class Player(val pos: Int, val score: Int) data class Win(val player1: Long, val player2: Long) val dirac = (1..3).flatMap { a -> (1..3).flatMap { b -> (1..3).map { c -> a + b + c } } } // I miss Groovy's @Memoized fun <X, R> cacheBiFunction(fn: (X, X) -> R): (X, X) -> R { val cache: MutableMap<Pair<X, X>, R> = HashMap() return { a, b -> cache.getOrPut(Pair(a, b)) { fn(a, b) } } } val cachedPart2 = cacheBiFunction(::part2) fun part2(a: Player, b: Player): Win { if (a.score >= 21) { return Win(1, 0) } if (b.score >= 21) { return Win(0, 1) } var myWins = 0L var theirWins = 0L for (die in dirac) { val pos = (a.pos + die) % 10 val (other, me) = cachedPart2(b, Player(pos, a.score + pos + 1)) myWins += me theirWins += other } return Win(myWins, theirWins) } fun main() { example() part1() println(dirac) println(cachedPart2(Player(8 - 1, 0), Player(2 - 1, 0))) }
0
Kotlin
0
1
9714e5b2c6a57db1b06e5ee6526eb30d587b94b4
2,328
advent-of-kotlin-2021
MIT License
src/main/kotlin/year2022/day-12.kt
ppichler94
653,105,004
false
{"Kotlin": 182859}
package year2022 import lib.TraversalBreadthFirstSearch import lib.aoc.Day import lib.aoc.Part import lib.math.Vector import lib.math.plus fun main() { Day(12, 2022, Part12('S', "31"), Part12('a', "29")).run() } open class Part12(private val startChar: Char, private val example: String) : Part() { private lateinit var hillsMap: List<String> private lateinit var startPositions: List<Vector> private lateinit var endPosition: Vector private lateinit var limits: List<IntRange> operator fun List<String>.get(pos: Vector) = this[pos.y][pos.x] override fun parse(text: String) { hillsMap = text.split("\n") startPositions = hillsMap.flatMapIndexed { y, line -> line.mapIndexedNotNull { x, c -> if (c == 'E') { endPosition = Vector.at(x, y) } if (c == startChar) { Vector.at(x, y) } else null } } limits = listOf(hillsMap.indices, hillsMap[0].indices) } override fun compute(): String { val traversal = TraversalBreadthFirstSearch(::neighbours) .startFrom(startPositions) .goTo(endPosition) return traversal.getPath().size.toString() } private fun neighbours(node: Vector, t: TraversalBreadthFirstSearch<Vector>): List<Vector> { return listOf(Vector.at(-1, 0), Vector.at(1, 0), Vector.at(0, -1), Vector.at(0, 1)) .map { it + node } .filter { it within listOf(limits[1], limits[0]) } .filter { elevationOfChar(hillsMap[it]) <= elevationOfChar(hillsMap[node.y][node.x]) + 1 } } private fun elevationOfChar(c: Char) = when (c) { in 'a'..'z' -> c.code - 'a'.code 'S' -> 0 'E' -> 25 else -> throw IllegalArgumentException("invalid char $c") } override val exampleAnswer: String get() = example }
0
Kotlin
0
0
49dc6eb7aa2a68c45c716587427353567d7ea313
2,023
Advent-Of-Code-Kotlin
MIT License
Kotlin/problems/0052_eventual_safe_nodes.kt
oxone-999
243,366,951
true
{"C++": 961697, "Kotlin": 99948, "Java": 17927, "Python": 9476, "Shell": 999, "Makefile": 187}
//Problem Statement // In a directed graph, we start at some node and every turn, walk along a directed // edge of the graph. If we reach a node that is terminal // (that is, it has no outgoing directed edges), we stop. // // Now, say our starting node is eventually safe if and only if we must eventually // walk to a terminal node. More specifically, there exists a natural number K so // that for any choice of where to walk, we must have stopped at a terminal node in // less than K steps. // // Which nodes are eventually safe? Return them as an array in sorted order. // // The directed graph has N nodes with labels 0, 1, ..., N-1, where N is the length // of graph. The graph is given in the following form: graph[i] is a list of labels // j such that (i, j) is a directed edge of the graph. class Solution constructor() { val memo:HashMap<Int,Boolean> = HashMap<Int,Boolean>(); fun eventualSafeNodes(graph: Array<IntArray>): List<Int> { val result:MutableList<Int> = mutableListOf<Int>(); for(i in graph.indices){ if(!memo.containsKey(i)){ val visited:HashSet<Int> = HashSet<Int>(); dfs(graph,i,visited); } if(memo[i]!!){ result.add(i); } } return result; } fun dfs(graph:Array<IntArray>, vertex : Int, visited: HashSet<Int>) : Boolean{ if(memo.containsKey(vertex)) return memo[vertex]!!; if(visited.contains(vertex)){ memo.put(vertex,false); return memo[vertex]!!; } visited.add(vertex); var isSafe:Boolean = true; for(neighbor in graph[vertex]){ isSafe = isSafe && dfs(graph,neighbor,visited); } memo.put(vertex,isSafe); return memo[vertex]!!; } } fun main(args:Array<String>){ var graph:Array<IntArray> = arrayOf(intArrayOf(1,2),intArrayOf(2,3),intArrayOf(5),intArrayOf(0),intArrayOf(5),intArrayOf(),intArrayOf()); var sol : Solution = Solution(); println(sol.eventualSafeNodes(graph)); }
0
null
0
0
52dc527111e7422923a0e25684d8f4837e81a09b
2,093
algorithms
MIT License
src/nativeMain/kotlin/com.qiaoyuang.algorithm/round0/Questions14.kt
qiaoyuang
100,944,213
false
{"Kotlin": 338134}
package com.qiaoyuang.algorithm.round0 import kotlin.math.* /** * 将长度为n的绳子剪成m段,求每段乘积相乘最大时的最大乘积 */ fun test14() { println("绳子长度为8时,最大乘积为:${maxProductAfterCutting1(8)}") println("绳子长度为8时,最大乘积为:${maxProductAfterCutting2(8)}") } // 动态规划 fun maxProductAfterCutting1(length: Int): Int = when { length < 2 -> throw IllegalArgumentException("绳子的长度必须大于 2") length == 2 -> 1 length == 3 -> 2 else -> IntArray(length + 1).let { for (i in 0..3) it[i] = i for (i in 4..length) { var max = 0 val temp = i / 2 for (j in 1..temp) { val product = it[j] * it[i - j] if (max < product) max = product it[i] = max } } it[length] } } // 贪心算法 fun maxProductAfterCutting2(length: Int): Int = when { length < 2 -> throw IllegalArgumentException("绳子的长度必须大于 2") length == 2 -> 1 length == 3 -> 2 else -> { var timesOf3 = length / 3 if (length - timesOf3 * 3 == 1) timesOf3 -= 1 val timesOf2 = (length - timesOf3 * 3) / 2 (3.0f.pow(timesOf3.toFloat()) * 2.0f.pow(timesOf2.toFloat())).toInt() } }
0
Kotlin
3
6
66d94b4a8fa307020d515d4d5d54a77c0bab6c4f
1,195
Algorithm
Apache License 2.0
src/main/kotlin/g1801_1900/s1815_maximum_number_of_groups_getting_fresh_donuts/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g1801_1900.s1815_maximum_number_of_groups_getting_fresh_donuts // #Hard #Array #Dynamic_Programming #Bit_Manipulation #Bitmask #Memoization // #2023_06_20_Time_1073_ms_(100.00%)_Space_71.3_MB_(100.00%) import java.util.Objects class Solution { inner class Data(var idx: Int, var arrHash: Int) { override fun equals(other: Any?): Boolean { if (this === other) { return true } if (other == null || javaClass != other.javaClass) { return false } val data = other as Data return idx == data.idx && arrHash == data.arrHash } override fun hashCode(): Int { return Objects.hash(idx, arrHash) } } private var dp: HashMap<Data, Int> = HashMap() fun maxHappyGroups(batchSize: Int, groups: IntArray): Int { val arr = IntArray(batchSize) for (group in groups) { arr[group % batchSize]++ } return arr[0] + solve(0, arr) } private fun solve(num: Int, arr: IntArray): Int { if (isFull(arr)) { return 0 } val key = Data(num, arr.contentHashCode()) if (dp.containsKey(key)) { return dp[key]!! } var best = Int.MIN_VALUE / 2 if (num == 0) { for (i in 1 until arr.size) { if (arr[i] <= 0) { continue } arr[i]-- best = Math.max(best, 1 + solve(i, arr)) arr[i]++ } } else { for (i in 1 until arr.size) { if (arr[i] > 0) { arr[i]-- best = best.coerceAtLeast(solve((num + i) % arr.size, arr)) arr[i]++ } } } dp[key] = best return best } private fun isFull(arr: IntArray): Boolean { var sum = 0 for (i in 1 until arr.size) { sum += arr[i] } return sum == 0 } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
2,076
LeetCode-in-Kotlin
MIT License
Main.kt
MBM1607
330,647,417
false
null
package processor import java.util.Scanner import kotlin.math.min import kotlin.math.pow val scanner = Scanner(System.`in`) fun readMatrix(messageInfix: String = ""): Array<DoubleArray> { print("Enter size of ${messageInfix}matrix: ") val row = scanner.nextInt() val col = scanner.nextInt() val matrix = Array(row) { DoubleArray(col) } println("Enter ${messageInfix}matrix:") for (i in 0 until row) { for (j in 0 until col) { matrix[i][j] = scanner.nextDouble() } } return matrix } fun printMatrix(matrix: Array<DoubleArray>) { for (i in matrix.indices) { var line = "" for (j in matrix[0].indices) { line += "${matrix[i][j]} " } println(line) } } fun addMatrices(matrix1: Array<DoubleArray>, matrix2: Array<DoubleArray>, log: Boolean = true): Array<DoubleArray> { if (log) println("The result is:") val sumMatrix = Array(matrix1[0].size) { DoubleArray(matrix2.size) } if (matrix1.size == matrix2.size && matrix1[0].size == matrix2[0].size) { for (i in matrix1.indices) { for (j in matrix1[0].indices) sumMatrix[i][j] = matrix1[i][j] + matrix2[i][j] } } else { if (log) println("The operation cannot be performed.") } return sumMatrix } fun multiplyMatrices(matrix1: Array<DoubleArray>, matrix2: Array<DoubleArray>, log: Boolean = true): Array<DoubleArray> { if (log) println("The result is:") val productMatrix = Array(matrix1.size) { DoubleArray(matrix2[0].size) } if (matrix1[0].size == matrix2.size) { for (i in matrix1.indices) { for (j in matrix2[0].indices) { var sum = 0.0 for (k in matrix1[0].indices) { sum += matrix1[i][k] * matrix2[k][j] } productMatrix[i][j] = sum } } } else { if (log) println("The operation cannot be performed.") } return productMatrix } fun multiplyByConstant(constant: Double, matrix: Array<DoubleArray>, log: Boolean = true): Array<DoubleArray> { if (log) println("The result is:") val productMatrix = Array(matrix.size) { DoubleArray(matrix[0].size) } for (i in matrix.indices) { for (j in matrix[0].indices) { productMatrix[i][j] = constant * matrix[i][j] } } return productMatrix } fun transposeMatrix() { println() println("1. Main diagonal\n" + "2. Side diagonal\n" + "3. Vertical line\n" + "4. Horizontal line") print("Your choice: ") val choice = readLine()!! println("The result is:") when (choice) { "1" -> printMatrix(transposeMain(readMatrix())) "2" -> printMatrix(transposeSide(readMatrix())) "3" -> printMatrix(transposeVertical(readMatrix())) "4" -> printMatrix(transposeHorizontal(readMatrix())) else -> println("Invalid choice") } } fun transposeMain(matrix: Array<DoubleArray>): Array<DoubleArray> { val transpose = Array(matrix[0].size) { DoubleArray(matrix.size) } for (i in matrix.indices) { for (j in matrix[0].indices) { transpose[j][i] = matrix[i][j] } } return transpose } fun transposeSide(matrix: Array<DoubleArray>): Array<DoubleArray> { val transpose = Array(matrix[0].size) { DoubleArray(matrix.size) } for (i in matrix.indices) { for (j in matrix[0].indices) { transpose[matrix.lastIndex - j][matrix[0].lastIndex - i] = matrix[i][j] } } return transpose } fun transposeVertical(matrix: Array<DoubleArray>): Array<DoubleArray> { val transpose = Array(matrix[0].size) { DoubleArray(matrix.size) } for (i in matrix.indices) { for (j in matrix[0].indices) { transpose[i][matrix[0].lastIndex - j] = matrix[i][j] } } return transpose } fun transposeHorizontal(matrix: Array<DoubleArray>): Array<DoubleArray> { val transpose = Array(matrix[0].size) { DoubleArray(matrix.size) } for (i in matrix.indices) { for (j in matrix[0].indices) { transpose[matrix.lastIndex - i][j] = matrix[i][j] } } return transpose } // Get the minor matrix from the original matrix after excluding the given row and column fun getCofactor(matrix: Array<DoubleArray>, row: Int, col: Int): Double { val minor = Array(matrix[0].size - 1) { DoubleArray(matrix.size - 1) } val temp = matrix.filterIndexed { i, _ -> i != row }.toTypedArray() for (i in temp.indices) { minor[i] = temp[i].filterIndexed { j, _ -> j != col }.toDoubleArray() } return determinant(minor) * (-1.0).pow(row + col) } // Get the determinant of a matrix fun determinant(matrix: Array<DoubleArray>): Double { return if (matrix.size == 2) { matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0] } else { var result = 0.0 for (j in matrix.indices) result += getCofactor(matrix, 0, j) * matrix[0][j] result } } fun calcDeterminant() { val matrix = readMatrix() println("The result is:") if (matrix.size == matrix[0].size) { println(determinant(matrix)) } else { println("The operation cannot be performed.") } } fun getAdjoint(matrix: Array<DoubleArray>): Array<DoubleArray> { val adjoint = Array(matrix.size) { DoubleArray(matrix[0].size) } for (i in matrix.indices) { for (j in matrix[0].indices) { adjoint[i][j] = getCofactor(matrix, i, j) } } return transposeMain(adjoint) } fun inverseMatrix(matrix: Array<DoubleArray>, log: Boolean = true): Array<DoubleArray> { if (log) println("The result is:") val det = determinant(matrix) return if (det != 0.0) { multiplyByConstant(1 / det, getAdjoint(matrix), false) } else { if (log) println("This matrix doesn't have an inverse.") Array(matrix.size) { DoubleArray(matrix[0].size) } } } fun main() { while (true) { println("1. Add matrices\n" + "2. Multiply matrix by a constant\n" + "3. Multiply matrices\n" + "4. Transpose matrix\n" + "5. Calculate a determinant\n" + "6. Inverse matrix\n" + "0. Exit") print("Your choice: ") when (readLine()) { "0" -> return "1" -> printMatrix(addMatrices(readMatrix("first "), readMatrix("second "))) "2" -> { val matrix = readMatrix() print("Enter constant:") printMatrix(multiplyByConstant(scanner.nextDouble(), matrix)) } "3" -> printMatrix(multiplyMatrices(readMatrix("first "), readMatrix("second "))) "4" -> transposeMatrix() "5" -> calcDeterminant() "6" -> printMatrix(inverseMatrix(readMatrix())) else -> println("Invalid choice") } println() } }
0
Kotlin
0
0
9619a1b91aae5783395ebba81d69a8466c07e532
7,064
matrix-calculator
MIT License
src/Day04.kt
kmakma
574,238,598
false
null
fun main() { fun part1(input: List<List<Int>>): Int { return input.count { list -> (list[0] <= list[2] && list[1] >= list[3]) || (list[0] >= list[2] && list[1] <= list[3]) } } fun part2(input: List<List<Int>>): Int { return input.count { list -> (list[0] <= list[2] && list[2] <= list[1]) || (list[2] <= list[0] && list[0] <= list[3]) } } val input = readInput("Day04") .map { line -> line.split(',', '-') .map { it.toInt() } } println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
950ffbce2149df9a7df3aac9289c9a5b38e29135
648
advent-of-kotlin-2022
Apache License 2.0
src/main/aoc2023/Day19.kt
nibarius
154,152,607
false
{"Kotlin": 963896}
package aoc2023 import size import kotlin.math.max import kotlin.math.min class Day19(input: List<String>) { private fun String.toIntRange(): IntRange { val i = this.toInt() return i..i } private val partRatings = input.last().split("\n").map { line -> val regex = """\{x=(\d+),m=(\d+),a=(\d+),s=(\d+)}""".toRegex() val (x, m, a, s) = regex.matchEntire(line)!!.destructured "in" to mapOf('x' to x.toIntRange(), 'm' to m.toIntRange(), 'a' to a.toIntRange(), 's' to s.toIntRange()) } private val workflows = input.first().split("\n").map { line -> val name = line.substringBefore("{") val rules = line.substringAfter("{").dropLast(1).split(",") name to rules }.toMap() /** * Lookup all the possible different scenarios for the given workflow. The given part will be split up into * several new parts, one for each matching rule with smaller ranges for each sub part. * @param workflow The workflow to work with * @param part The possible category ratings for the part * @returns A list of workflow to possible category ratings. */ private fun lookupWorkflow( workflow: String, part: Map<Char, IntRange> ): MutableList<Pair<String, Map<Char, IntRange>>> { val ret = mutableListOf<Pair<String, Map<Char, IntRange>>>() val currentPart = part.toMutableMap() for (rule in workflows[workflow]!!) { if (!rule.contains(":")) { // Fallback rule, all remaining ranges leads to this rule. ret.add(rule to currentPart) break } val regex = """([amsx])([<>])([0-9]+):([RAa-z]+)""".toRegex() val (category, op, amount, nextWorkflow) = regex.matchEntire(rule)!!.destructured val currentRange = currentPart[category.first()]!! // Split the current range into two ranges, one that fits the current rule and one for all that remains val (fitsRuleRange, remainingRange) = when (op) { "<" -> { currentRange.first..min(currentRange.last, amount.toInt() - 1) to max(amount.toInt(), currentRange.first)..currentRange.last } ">" -> { max(currentRange.first, amount.toInt() + 1)..currentRange.last to currentRange.first..min(amount.toInt(), currentRange.last) } else -> error("unknown op") } if (fitsRuleRange.size() > 0) { ret.add(nextWorkflow to currentPart.toMutableMap().apply { this[category.first()] = fitsRuleRange }) } if (remainingRange.size() > 0) { currentPart[category.first()] = remainingRange } else { // There is nothing left for any other rules, so no need to continue break } } return ret } /** * Find all parts that are accepted given the given initial list of parts. * @param toCheck A list of a workflow to parts pairs that makes up the parts to check. */ private fun findAcceptedParts(toCheck: MutableList<Pair<String, Map<Char, IntRange>>>): MutableSet<Map<Char, IntRange>> { val accepted = mutableSetOf<Map<Char, IntRange>>() while (toCheck.isNotEmpty()) { val (workflow, currentPart) = toCheck.removeFirst() if (workflow == "A") { accepted.add(currentPart) continue } else if (workflow == "R") { continue } val next = lookupWorkflow(workflow, currentPart) toCheck.addAll(next) } return accepted } fun solvePart1(): Long { val accepted = findAcceptedParts(partRatings.toMutableList()) return accepted.sumOf { it.values.sumOf { it.first }.toLong() } } fun solvePart2(): Long { val accepted = findAcceptedParts(mutableListOf("in" to listOf('x', 'm', 'a', 's').associateWith { 1..4000 })) return accepted.sumOf { it.values.map { range -> range.size().toLong() }.reduce(Long::times) } } }
0
Kotlin
0
6
f2ca41fba7f7ccf4e37a7a9f2283b74e67db9f22
4,252
aoc
MIT License
src/main/kotlin/Extensions.kt
nishtahir
91,517,572
false
null
import java.util.* import java.util.concurrent.locks.Lock fun isValidTriangle(values: List<Int>): Boolean = values[0] + values[1] > values[2] && values[0] + values[2] > values[1] && values[1] + values[2] > values[0] inline fun <reified T> List<T>.grouped(by: Int): List<List<T>> { require(by > 0) { "Groupings can't be less than 1" } return if (isEmpty()) { emptyList() } else { (0..lastIndex / by).map { val fromIndex = it * by val toIndex = Math.min(fromIndex + by, this.size) subList(fromIndex, toIndex) } } } /** * Not a very good transpose function. Works for squares though... */ inline fun <reified T> transpose(values: List<List<T>>): List<List<T>> { return values.indices.map { i -> values[0].indices.map { values[it][i] } } } fun randomSequence(upper: Int = 10, lower: Int = 0): List<Int> { return (lower..upper).distinct().toMutableList().apply { Collections.shuffle(this) } } fun <T> List<T>.pickRandom(num: Int = 4): List<T> { return randomSequence(upper = this.size, lower = 0).take(num).map { this[it] } }
0
Kotlin
0
0
51115e3405ac75e436b783ceeca74afe120243f3
1,157
scratchpad
Apache License 2.0
2022/Day21/problems.kt
moozzyk
317,429,068
false
{"Rust": 102403, "C++": 88189, "Python": 75787, "Kotlin": 72672, "OCaml": 60373, "Haskell": 53307, "JavaScript": 51984, "Go": 49768, "Scala": 46794}
import java.io.File fun main(args: Array<String>) { val lines = File(args[0]).readLines() val regex = """(.*): (.*)""".toRegex() val monkeys = lines .map { regex.matchEntire(it)!!.destructured } .map { (name, operation) -> name to operation } .toMap() println(problem1(monkeys)) println(problem2(monkeys)) } fun problem1(monkeys: Map<String, String>): Long { return computeValue("root", monkeys) } fun problem2(monkeys: Map<String, String>): Long { val (m1, m2) = "(.+) . (.+)".toRegex().matchEntire(monkeys["root"]!!)!!.destructured if (hasHumn(m1, monkeys)) { val target = computeValue(m2, monkeys) return findHumnValue(m1, target, monkeys) } else { val target = computeValue(m1, monkeys) return findHumnValue(m2, target, monkeys) } } fun computeValue(monkey: String, monkeys: Map<String, String>): Long { val regex = "(.+) (.) (.+)".toRegex() val operation = monkeys[monkey] var matches = regex.matchEntire(operation!!) if (matches == null) { return operation.toLong() } val (m1, op, m2) = matches.destructured return when (op) { "-" -> computeValue(m1, monkeys) - computeValue(m2, monkeys) "+" -> computeValue(m1, monkeys) + computeValue(m2, monkeys) "*" -> computeValue(m1, monkeys) * computeValue(m2, monkeys) "/" -> computeValue(m1, monkeys) / computeValue(m2, monkeys) else -> throw Exception("Invalid operator") } } fun hasHumn(monkey: String, monkeys: Map<String, String>): Boolean { if (monkey == "humn") { return true } val regex = "(.+) . (.+)".toRegex() val operation = monkeys[monkey] var matches = regex.matchEntire(operation!!) if (matches == null) { return false } val (m1, m2) = matches.destructured return hasHumn(m1, monkeys) || hasHumn(m2, monkeys) } fun findHumnValue(monkey: String, target: Long, monkeys: Map<String, String>): Long { if (monkey == "humn") { return target } val (m1, operation, m2) = "(.+) (.) (.+)".toRegex().matchEntire(monkeys[monkey]!!)!!.destructured if (hasHumn(m1, monkeys)) { val value = computeValue(m2, monkeys) val newTarget = calculateNewTarget(target, operation, value, isLeft = true) return findHumnValue(m1, newTarget, monkeys) } else { val value = computeValue(m1, monkeys) var newTarget = calculateNewTarget(target, operation, value, isLeft = false) return findHumnValue(m2, newTarget, monkeys) } } fun calculateNewTarget(target: Long, operation: String, knownOperand: Long, isLeft: Boolean): Long { return when (operation) { "+" -> target - knownOperand "-" -> if (isLeft) { target + knownOperand } else { -(target - knownOperand) } "*" -> target / knownOperand "/" -> if (isLeft) { target * knownOperand } else { knownOperand / target } else -> throw Exception("Invalid operation") } }
0
Rust
0
0
c265f4c0bddb0357fe90b6a9e6abdc3bee59f585
3,246
AdventOfCode
MIT License
src/main/kotlin/me/consuegra/algorithms/KPascalTriangle.kt
aconsuegra
91,884,046
false
{"Java": 113554, "Kotlin": 79568}
package me.consuegra.algorithms /** * Given numRows, generate the first numRows of Pascal’s triangle. * <p> * Pascal’s triangle : To generate A[C] in row R, sum up A’[C] and A’[C-1] from previous row R - 1. * <p> * Example: * <p> * Given numRows = 5, * <p> * Return * <p> * [ * [1], * [1,1], * [1,2,1], * [1,3,3,1], * [1,4,6,4,1] * ] */ class KPascalTriangle { fun generate(rows: Int): Array<IntArray> { val triangle = Array(rows, { intArrayOf() }) for (i in 0 until rows) { triangle[i] = IntArray(i + 1) for (j in 0..i) { triangle[i][j] = calculateValue(triangle, i - 1, j) } } return triangle } private fun calculateValue(triangle: Array<IntArray>, i: Int, j: Int): Int { if (i < 0) { return 1 } val row = triangle[i] if (j <= 0 || j >= row.size) { return 1 } return row[j] + row[j - 1] } }
0
Java
0
7
7be2cbb64fe52c9990b209cae21859e54f16171b
995
algorithms-playground
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/MergeSortedArray.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 /** * 88. Merge Sorted Array * @see <a href="https://leetcode.com/problems/merge-sorted-array">Source</a> */ fun interface MergeSortedArray { operator fun invoke(nums1: IntArray, m: Int, nums2: IntArray, n: Int) } class MergeSortedArrayStl : MergeSortedArray { override fun invoke(nums1: IntArray, m: Int, nums2: IntArray, n: Int) { var j = 0 var i = m while (j < n) { nums1[i] = nums2[j] i++ j++ } nums1.sort() } } class MergeSortedArrayTwoPointer : MergeSortedArray { override fun invoke(nums1: IntArray, m: Int, nums2: IntArray, n: Int) { var i = m - 1 var j = n - 1 var k = m + n - 1 while (j >= 0) { if (i >= 0 && nums1[i] > nums2[j]) { nums1[k--] = nums1[i--] } else { nums1[k--] = nums2[j--] } } } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,559
kotlab
Apache License 2.0
24.kt
pin2t
725,922,444
false
{"Kotlin": 48856, "Go": 48364, "Shell": 54}
data class Pos3D(val x: Long, val y: Long, val z: Long) data class Hailstone(val pos: Pos3D, val velocity: Pos3D) class Day24 { var hailstones = ArrayList<Hailstone>() val number = Regex("-?\\d+") fun run() { while (true) { val line = readlnOrNull() ?: break val items = number.findAll(line).map { it.value.toLong() }.toList() hailstones.add(Hailstone(Pos3D(items[0], items[1], items[2]), Pos3D(items[3], items[4], items[5]))) } var result1 = 0 for (i in 0..<(hailstones.size - 1)) { for (j in (i + 1)..<hailstones.size) { val h1 = hailstones[i]; val h2 = hailstones[j] if (h1.velocity.x * h2.velocity.y == h1.velocity.y * h2.velocity.x) continue // parallel val t: Long = ((h2.pos.x - h1.pos.x) * h2.velocity.y + (h1.pos.y - h2.pos.y) * h2.velocity.x) / (h1.velocity.x * h2.velocity.y - h1.velocity.y * h2.velocity.x) if (t < 0) continue // in the past for 1 val s: Long = ((h1.pos.y - h2.pos.y) + t * h1.velocity.y) / h2.velocity.y if (s < 0) continue // in the past for 2 if ((h1.pos.x + h1.velocity.x * t) in 200000000000000L..400000000000000L && (h1.pos.y + h1.velocity.y * t) in 200000000000000L..400000000000000L) { result1++ } } } println(result1) // print equations to solve using online solver for (i in 0..5) { val h = hailstones[i] println("(x - ${h.pos.x}) * (${h.velocity.y} - vy) - (y - ${h.pos.y}) * (${h.velocity.x} - vx)") println("(y - ${h.pos.y}) * (${h.velocity.z} - vz) - (z - ${h.pos.z}) * (${h.velocity.y} - vy)") } } } fun main() { Day24().run() }
0
Kotlin
1
0
7575ab03cdadcd581acabd0b603a6f999119bbb6
1,868
aoc2023
MIT License
app/src/main/kotlin/ch/empa/openbisio/interfaces/Tree.kt
empa-scientific-it
618,383,912
false
null
/* * 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 ch.empa.openbisio.interfaces typealias Algebra<T, R> = (T, List<R>) -> R interface Tree<T> { fun value(): T fun hasChildren(): Boolean fun children(): Collection<Tree<T>> fun <R> cata(transformer: Algebra<T, R>): R { return when (hasChildren()) { false -> transformer(value(), emptyList()) true -> { val mapped = children().map { it.cata(transformer) } transformer(value(), mapped) } } } fun pprint(): String { fun helper(tree: Tree<T>, indent: Int): String { val spaces = " ".repeat(indent) when (tree.hasChildren()) { false -> return spaces + tree.value().toString() true -> return spaces + tree.value().toString() + "\n" + tree.children() .joinToString("\n") { helper(it, indent + 2) } } } return helper(this, 0) } fun <R> flatMap(transform: (T) -> R): List<R> { return when (hasChildren()) { false -> listOf(transform(value())) true -> listOf(transform(value())) + children().flatMap { it.flatMap(transform) } } } } fun <T, R, U : Tree<R>, V : Tree<T>> iterateWithParentHelper( tree: V, parent: U, transformer: (T, U) -> R, builder: (R, List<U>) -> U ): U { return when (tree.hasChildren()) { false -> { val mapped = transformer(tree.value(), parent) builder(mapped, listOf()) } true -> { val mapped = builder(transformer(tree.value(), parent), listOf()) val updatedChildren = tree.children().map { iterateWithParentHelper(it, mapped, transformer, builder) } builder(mapped.value(), updatedChildren) } } } fun <R : Tree<T>, T> toListTreee(input: R): ListTree<T> { return ListTree(input.value(), input.children().map { toListTreee(it) }) } fun <T, R, U : Tree<R>, V : Tree<T>> iterateWithParent( tree: V, transformer: (T, U) -> R, builder: (R, List<U>) -> U, seed: R ): U { return iterateWithParentHelper(tree, builder(seed, listOf()), transformer, builder) }
0
Kotlin
0
0
39396bb489fa91e8e65f83206e806b67fcd3ac65
2,806
instanceio
Apache License 2.0
src/Day01.kt
leeturner
572,659,397
false
{"Kotlin": 13839}
fun main() { fun part1(input: List<List<Int>>): Int { return input.maxOf { it.sum() } } fun part2(input: List<List<Int>>): Int { return input.map { it.sum() }.sortedDescending().take(3).sum() } // test if implementation meets criteria from the description, like: val testInput = readInputSplitBy("Day01_test", "\n\n").map { it.split("\n").map { calories -> calories.toInt() } } check(part1(testInput) == 24000) check(part2(testInput) == 45000) val input = readInputSplitBy("Day01", "\n\n").map { it.split("\n").map { calories -> calories.toInt() } } println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
8da94b6a0de98c984b2302b2565e696257fbb464
655
advent-of-code-2022
Apache License 2.0
app/src/y2021/day04/Day04GiantSquid.kt
henningBunk
432,858,990
false
{"Kotlin": 124495}
package y2021.day04 import common.Answers import common.AocSolution import common.annotations.AoCPuzzle fun main(args: Array<String>) { Day04GiantSquid().solveThem() } @AoCPuzzle(2021, 4) class Day04GiantSquid : AocSolution { override val answers = Answers(samplePart1 = 4512, samplePart2 = 1924, part1 = 10680, part2 = 31892) override fun solvePart1(input: List<String>): Any { val (drawnNumbers, boards) = readInput(input) drawnNumbers.takeWhile { boards.forEach { board -> board.check(it) } boards.none { it.hasWon() } } return boards.find { board -> board.hasWon() }?.getScore() ?: -1 } override fun solvePart2(input: List<String>): Any { val (drawnNumbers, boards) = readInput(input) drawnNumbers.takeWhile { boards.forEach { board -> board.check(it) } boards.count { !it.hasWon() } > 1 } val lastBoardToWin = boards.find { !it.hasWon() } drawnNumbers.takeWhile { lastBoardToWin?.check(it) lastBoardToWin?.hasWon() == false } return lastBoardToWin?.getScore() ?: -1 } fun readInput(input: List<String>, boardHeight: Int = 5): Pair<MutableList<Int>, List<Board>> { val inputs = input .first() .split(',') .map { it.toInt() } .toMutableList() val boards = input .drop(1) .filter { it.isNotEmpty() } .chunked(boardHeight) .map(::Board) return Pair(inputs, boards) } }
0
Kotlin
0
0
94235f97c436f434561a09272642911c5588560d
1,595
advent-of-code-2021
Apache License 2.0
src/main/kotlin/com/jacobhyphenated/advent2022/day14/Day14.kt
jacobhyphenated
573,603,184
false
{"Kotlin": 144303}
package com.jacobhyphenated.advent2022.day14 import com.jacobhyphenated.advent2022.Day import kotlin.math.max import kotlin.math.min /** * Day 14: Regolith Reservoir * * Sand is dropping from the ceiling of the cave. The puzzle input is the rock structure of the cave in 2D. * The input shows lists of pairs that represent points in a continuous line. * * Sand falls from a point at (500,0) with every increase in the y-axes being the sand dropping by 1. */ class Day14: Day<Set<Pair<Int,Int>>> { override fun getInput(): Set<Pair<Int,Int>> { val input = readInputFile("day14").lines().map { line -> line.split(" -> ").map { val (x,y) = it.split(",") Pair(x.toInt(),y.toInt()) } } return buildRockStructure(input) } /** * Sand comes to rest against the rock formations lines. * If a piece of sand falls below the highest y value of the rock structure, it will fall forever. * Drop sand until one grain falls forever. How many grains of sand are dropped? */ override fun part1(input: Set<Pair<Int,Int>>): Int { val rockStructure = input.toMutableSet() val maxY = rockStructure.maxOf { (_,y) -> y } var sandCount = 0 while(dropSand(rockStructure, maxY)?.also { rockStructure.add(it) } != null){ sandCount++ } return sandCount } /** * There is an invisible floor that goes infinitely in the x direction. * It's 2 units beyond the highest y value of the rock structure. * * Drop sand until it covers the starting drop point (500,0) * How many grains of sand are dropped? */ override fun part2(input: Set<Pair<Int,Int>>): Int { val rockStructure = input.toMutableSet() val maxY = rockStructure.maxOf { (_,y) -> y } var sandCount = 0 while (dropSandWithBottom(rockStructure, maxY + 2).also { rockStructure.add(it) } != Pair(500,0)) { sandCount++ } return sandCount + 1 } // Use the code from part2 to solve part1 // return null if the sand falls forever (beyond maxY) private fun dropSand(rockStructure: Set<Pair<Int,Int>>, maxY: Int): Pair<Int,Int>? { val sand = dropSandWithBottom(rockStructure, maxY + 1) return if (sand.second < maxY) { sand } else { null } } /** * Let the sand fall until it hits a supplied bottom y-axis * Return the location where it comes to rest. * * If the sand can drop 1 y, it does. * If not, it tries to move diagonally to the left * If not, it tries to move diagonally to the right * otherwise, it comes to rest */ private fun dropSandWithBottom(rockStructure: Set<Pair<Int, Int>>, bottom: Int): Pair<Int,Int> { // sand starts at 500,0 var (x,y) = Pair(500, 0) while (y < bottom - 1){ val (newX, newY) = listOf(Pair(x, y+1), Pair(x-1, y+1), Pair(x+1, y+1)) .firstOrNull { it !in rockStructure } ?: return Pair(x,y) x = newX y = newY } return Pair(x,y) } /** * Represent the rocks as a set of all points that rocks occupy. * Go through each line segment and add all points to a set of rock locations */ fun buildRockStructure(input: List<List<Pair<Int,Int>>>): Set<Pair<Int,Int>> { val set = mutableSetOf<Pair<Int,Int>>() for (rockSegment in input) { rockSegment.reduce { (x1, y1), (x2, y2) -> val rockLine = if (x1 == x2) { (min(y1,y2)..max(y1,y2)).map { Pair(x1, it) } } else { (min(x1,x2)..max(x1,x2)).map { Pair(it, y1) } } set.addAll(rockLine) Pair(x2,y2) } } return set } }
0
Kotlin
0
0
9f4527ee2655fedf159d91c3d7ff1fac7e9830f7
3,897
advent2022
The Unlicense
src/Day08.kt
aaronbush
571,776,335
false
{"Kotlin": 34359}
enum class ForestDirection { N, S, E, W } enum class TreeVisibility { VISIBLE, NOT_VISIBLE, UNKNOWN } fun main() { data class Tree( val row: Int, val column: Int, val height: Int, var visibility: TreeVisibility = TreeVisibility.UNKNOWN, var treesVisible: Int = 0 ) data class Forest(val trees: List<Tree>) { val maxRow: Int get() { val last = trees.last() return last.row } val maxColumn: Int get() { val last = trees.last() return last.column } override fun toString(): String { var output = "" trees.chunked(maxColumn + 1).forEach { row -> row.forEach { tree -> if (tree.visibility == TreeVisibility.VISIBLE) { output += "\u001b[31m" output += "${tree.height}(${tree.treesVisible})* " output += "\u001b[0m" } else if (tree.visibility == TreeVisibility.NOT_VISIBLE) output += "${tree.height}(${tree.treesVisible})- " else output += "${tree.height}(${tree.treesVisible})? " } output += "\n" } return output } fun markBorder() { trees.filter { it.row == 0 || it.row == maxRow || it.column == 0 || it.column == maxColumn } .forEach { it.visibility = TreeVisibility.VISIBLE } } fun findTree(direction: ForestDirection, ofTree: Tree): Tree? { val (row, column) = when (direction) { ForestDirection.N -> ofTree.row - 1 to ofTree.column ForestDirection.S -> ofTree.row + 1 to ofTree.column ForestDirection.E -> ofTree.row to ofTree.column + 1 ForestDirection.W -> ofTree.row to ofTree.column - 1 } return trees.find { it.row == row && it.column == column } } fun toEdge(direction: ForestDirection, fromTree: Tree): List<Tree> { val remainingTrees = mutableListOf<Tree>() var next: Tree? = findTree(direction, fromTree) while (next != null) { remainingTrees += next next = findTree(direction, next) } return remainingTrees } fun Tree.visibleVia(direction: ForestDirection): TreeVisibility { // check to edge of forest val remainingTrees = toEdge(direction, this) val visibilityToEdge = remainingTrees.map { if (it.height >= this.height) TreeVisibility.NOT_VISIBLE else TreeVisibility.VISIBLE } return if (visibilityToEdge.contains(TreeVisibility.NOT_VISIBLE)) { TreeVisibility.NOT_VISIBLE } else TreeVisibility.VISIBLE } private fun Tree.visibility(): TreeVisibility { val visibilityStates = setOf( this.visibleVia(ForestDirection.N), this.visibleVia(ForestDirection.S), this.visibleVia(ForestDirection.E), this.visibleVia(ForestDirection.W) ) return if (visibilityStates.contains(TreeVisibility.VISIBLE)) TreeVisibility.VISIBLE else TreeVisibility.NOT_VISIBLE } fun markTrees() { trees.filter { it.row in 1 until maxRow && it.column in 1 until maxColumn } .forEach { it.visibility = it.visibility() } } fun updateVisibleTrees() { fun numTreesInLineOfSight(direction: ForestDirection, tree: Tree): Int { val lineOfSight = toEdge(direction, tree).takeWhile { it.height < tree.height } return if (lineOfSight.size < toEdge(direction, tree).size) lineOfSight.size + 1 else lineOfSight.size } // don't need to check edges as they are 0 - todo: optimize trees.forEach { tree -> val n = numTreesInLineOfSight(ForestDirection.N, tree) val e = numTreesInLineOfSight(ForestDirection.E, tree) val s = numTreesInLineOfSight(ForestDirection.S, tree) val w = numTreesInLineOfSight(ForestDirection.W, tree) tree.treesVisible = n * s * e * w } } } fun part1(input: List<String>): Int { val trees = input.flatMapIndexed { row, line -> line.mapIndexed { column, tree -> Tree(row, column, tree.toString().toInt()) } } val forest = Forest(trees) forest.markBorder() forest.markTrees() // println(forest) return forest.trees.count { it.visibility == TreeVisibility.VISIBLE } } fun part2(input: List<String>): Int { val trees = input.flatMapIndexed { row, line -> line.mapIndexed { column, tree -> Tree(row, column, tree.toString().toInt()) } } val forest = Forest(trees) forest.updateVisibleTrees() // println(forest) return forest.trees.maxOf { it.treesVisible } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day08_test") check(part1(testInput) == 21) check(part2(testInput) == 8) val input = readInput("Day08") // println("p1: ${part1(input)}") println("p2: ${part2(input)}") }
0
Kotlin
0
0
d76106244dc7894967cb8ded52387bc4fcadbcde
5,712
aoc-2022-kotlin
Apache License 2.0
src/Day03.kt
touchman
574,559,057
false
{"Kotlin": 16512}
fun main() { val input = readInput("Day03") fun getNumberForChar(it: String) = it.toCharArray()[0] .let { if (it.isLowerCase()) { it - 'a' + 1 } else { it - 'A' + 1 + 26 } } fun part1(input: List<String>) = input.map { it.chunked(it.length/2) .let { it[0].split("").intersect(it[1].split("")) }.filterNot { it == "" } .map { getNumberForChar(it) }[0] }.reduce { acc, i -> acc + i } fun part2(input: List<String>) = input.chunked(3) .let { it.map { group -> val firstAndSecondIntersect = group[0].toSet() .intersect( group[1].toSet() ) val secondAndThirdIntersect = group[1].toSet() .intersect( group[2].toSet() ) firstAndSecondIntersect.intersect(secondAndThirdIntersect) }.map { String(it.toCharArray()) }.filterNot { it == "" } .let { it.map { getNumberForChar(it) }.reduce { acc, i -> acc + i } } } println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
4f7402063a4a7651884be77bb9e97828a31459a7
1,502
advent-of-code-2022
Apache License 2.0
src/main/kotlin/com/github/shmvanhouten/adventofcode/day24airductmaze/RouteFinder.kt
SHMvanHouten
109,886,692
false
{"Kotlin": 616528}
package com.github.shmvanhouten.adventofcode.day24airductmaze class RouteFinder { fun getPossibleRoutes(possibleRoutesAndSizes: Map<Route, Int>, relevantLocations: Set<Int>): Set<WeightedNode> { return getPossibleRoutesVisitingAllLocations(possibleRoutesAndSizes, relevantLocations) } fun getPossibleRoutesReturningToZero(possibleRoutesAndSizes: Map<Route, Int>, relevantLocations: Set<Int>): Set<WeightedNode> { val oneWayRoutes = getPossibleRoutesVisitingAllLocations(possibleRoutesAndSizes, relevantLocations) return doOneMoreMoveBackToZero(oneWayRoutes, possibleRoutesAndSizes) } private fun getPossibleRoutesVisitingAllLocations(possibleRoutesAndSizes: Map<Route, Int>, relevantLocations: Set<Int>): Set<WeightedNode> { var unVisitedRoutes = setOf(WeightedNode(0, listOf(0))) var completedRoutes = setOf<WeightedNode>() while (unVisitedRoutes.isNotEmpty()) { val currentNode = unVisitedRoutes.first() unVisitedRoutes -= currentNode val newNodes = getPossibleNodesStemmingFromCurrent(possibleRoutesAndSizes, relevantLocations, currentNode) unVisitedRoutes += newNodes if (currentNode.locationsVisited.size == relevantLocations.size) { completedRoutes += currentNode } } return completedRoutes } private fun getPossibleNodesStemmingFromCurrent(possibleRoutesAndSizes: Map<Route, Int>, relevantLocations: Set<Int>, currentNode: WeightedNode): List<WeightedNode> { val unvisitedLocations = relevantLocations.filter { location -> !currentNode.locationsVisited.any { it == location } } return unvisitedLocations.map { buildNodeWithNewLocation(possibleRoutesAndSizes, it, currentNode) } } private fun buildNodeWithNewLocation(possibleRoutesAndSizes: Map<Route, Int>, locationToAdd: Int, currentNode: WeightedNode): WeightedNode { val weightToAdd = getWeightOfNextStep(possibleRoutesAndSizes, locationToAdd, currentNode) return WeightedNode(locationToAdd, currentNode.locationsVisited.plus(locationToAdd), currentNode.weight + weightToAdd) } private fun getWeightOfNextStep(possibleRoutesAndSizes: Map<Route, Int>, unvisitedLocation: Int, currentNode: WeightedNode): Int { val currentLocationNumber = currentNode.locationNumber return if (unvisitedLocation > currentLocationNumber) { possibleRoutesAndSizes.getValue(Route(currentLocationNumber, unvisitedLocation)) } else { possibleRoutesAndSizes.getValue(Route(unvisitedLocation, currentLocationNumber)) } } private fun doOneMoreMoveBackToZero(possibleRoutesVisitingAllLocations: Set<WeightedNode>, possibleRoutesAndSizes: Map<Route, Int>): Set<WeightedNode> { return possibleRoutesVisitingAllLocations.map { buildNodeWithNewLocation(possibleRoutesAndSizes, 0, it) }.toSet() } }
0
Kotlin
0
0
a8abc74816edf7cd63aae81cb856feb776452786
2,986
adventOfCode2016
MIT License
src/main/kotlin/de/pgebert/aoc/days/Day15.kt
pgebert
724,032,034
false
{"Kotlin": 65831}
package de.pgebert.aoc.days import de.pgebert.aoc.Day class Day15(input: String? = null) : Day(15, "Lens Library", input) { override fun partOne() = inputList.first().split(",").sumOf { it.hash() } private fun String.hash() = fold(0) { agg, char -> ((agg + char.code) * 17) % 256 } data class Lens(val label: String, val focal: Int) { override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is Lens) return false if (label != other.label) return false return true } } override fun partTwo(): Int { val boxes = mutableMapOf<Int, MutableList<Lens>>() inputList.first().split(",").forEach { instruction -> if (instruction.contains('=')) { val (label, focal) = instruction.split('=') val lens = Lens(label, focal.toInt()) val boxNumber = label.hash() val box = boxes.getOrPut(boxNumber) { mutableListOf() } when { lens in box -> box.update(lens) else -> box.add(lens) } } else { val label = instruction.dropLast(1) val boxNumber = label.hash() val box = boxes.getOrPut(boxNumber) { mutableListOf() } val lens = Lens(label, 0) box.remove(lens) } } return boxes.map { (boxNumber, box) -> box.mapIndexed { index, lens -> (boxNumber + 1) * (index + 1) * lens.focal }.sum() }.sum() } private fun <T> MutableList<T>.update(item: T) { val index = indexOf(item) removeAt(index) add(index, item) } }
0
Kotlin
1
0
a30d3987f1976889b8d143f0843bbf95ff51bad2
1,764
advent-of-code-2023
MIT License
year2015/src/main/kotlin/net/olegg/aoc/year2015/day13/Day13.kt
0legg
110,665,187
false
{"Kotlin": 511989}
package net.olegg.aoc.year2015.day13 import net.olegg.aoc.someday.SomeDay import net.olegg.aoc.utils.permutations import net.olegg.aoc.year2015.DayOf2015 /** * See [Year 2015, Day 13](https://adventofcode.com/2015/day/13) */ object Day13 : DayOf2015(13) { private val PATTERN = "^\\b(\\w+)\\b.*\\b(gain|lose) \\b(\\d+)\\b.*\\b(\\w+)\\b\\.$".toRegex() private val EDGES = lines.associate { line -> val match = checkNotNull(PATTERN.matchEntire(line)) val (name, type, amount, otherName) = match.destructured Pair(name, otherName) to amount.toInt() * (if (type == "gain") 1 else -1) } private val NAMES = EDGES.keys.flatMap { listOf(it.first, it.second) }.distinct() override fun first(): Any? { return NAMES .permutations() .map { it + it.first() } .map { order -> order.zipWithNext().sumOf { EDGES[it] ?: 0 } + order.reversed().zipWithNext().sumOf { EDGES[it] ?: 0 } } .max() } override fun second(): Any? { return NAMES .permutations() .map { order -> order.zipWithNext().sumOf { EDGES[it] ?: 0 } + order.reversed().zipWithNext().sumOf { EDGES[it] ?: 0 } } .max() } } fun main() = SomeDay.mainify(Day13)
0
Kotlin
1
7
e4a356079eb3a7f616f4c710fe1dfe781fc78b1a
1,239
adventofcode
MIT License
src/main/kotlin/g0101_0200/s0126_word_ladder_ii/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g0101_0200.s0126_word_ladder_ii // #Hard #String #Hash_Table #Breadth_First_Search #Backtracking // #2022_10_08_Time_418_ms_(51.45%)_Space_41.1_MB_(65.94%) import java.util.Collections import java.util.LinkedList import java.util.Queue class Solution { fun findLadders(beginWord: String, endWord: String, wordList: List<String>): List<List<String>> { val ans: MutableList<List<String>> = ArrayList() // reverse graph start from endWord val reverse: MutableMap<String, MutableSet<String>> = HashMap() // remove the duplicate words val wordSet: MutableSet<String> = HashSet(wordList) // remove the first word to avoid cycle path wordSet.remove(beginWord) // store current layer nodes val queue: Queue<String> = LinkedList() // first layer has only beginWord queue.add(beginWord) // store nextLayer nodes val nextLevel: MutableSet<String> = HashSet() // find endWord flag var findEnd = false // traverse current layer nodes while (queue.isNotEmpty()) { val word = queue.remove() for (next in wordSet) { // is ladder words if (isLadder(word, next)) { // construct the reverse graph from endWord val reverseLadders = reverse.computeIfAbsent( next ) { _: String? -> HashSet() } reverseLadders.add(word) if (endWord == next) { findEnd = true } // store next layer nodes nextLevel.add(next) } } // when current layer is all visited if (queue.isEmpty()) { // if find the endWord, then break the while loop if (findEnd) { break } // add next layer nodes to queue queue.addAll(nextLevel) // remove all next layer nodes in wordSet wordSet.removeAll(nextLevel) nextLevel.clear() } } // if can't reach endWord from startWord, then return ans. if (!findEnd) { return ans } val path: MutableSet<String> = LinkedHashSet() path.add(endWord) // traverse reverse graph from endWord to beginWord findPath(endWord, beginWord, reverse, ans, path) return ans } private fun findPath( endWord: String, beginWord: String, graph: Map<String, MutableSet<String>>, ans: MutableList<List<String>>, path: MutableSet<String> ) { val next = graph[endWord] ?: return for (word in next) { path.add(word) if (beginWord == word) { val shortestPath: List<String> = ArrayList(path) // reverse words in shortest path Collections.reverse(shortestPath) // add the shortest path to ans. ans.add(shortestPath) } else { findPath(word, beginWord, graph, ans, path) } path.remove(word) } } private fun isLadder(s: String, t: String): Boolean { if (s.length != t.length) { return false } var diffCount = 0 val n = s.length for (i in 0 until n) { if (s[i] != t[i]) { diffCount++ } if (diffCount > 1) { return false } } return diffCount == 1 } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
3,700
LeetCode-in-Kotlin
MIT License
day3/src/main/kotlin/main.kt
jorgensta
434,206,181
false
{"Kotlin": 8252, "Assembly": 62}
import java.io.File fun parseFileAndGetInput(): List<String> { val filepath = "/Users/jorgenstamnes/Documents/own/AdventOfCode2021/day3/src/main/kotlin/input.txt" return File(filepath).readLines(Charsets.UTF_8).toList() } fun first() { val inputs = parseFileAndGetInput() val one = '1' val zero = '0' var gammaRateBits: String = "" var epsilonRateBits: String = "" val lengthOfBits = "110111100101".length for (i in 0 until lengthOfBits) { var numberOf0s = 0 var numberOf1s = 0 inputs.forEach { bits -> val bit: Char = bits[i] if (bit == '1') { numberOf1s += 1 } if (bit == '0') { numberOf0s += 1 } } if (numberOf1s > numberOf0s) { gammaRateBits += one epsilonRateBits += zero } if (numberOf0s > numberOf1s) { gammaRateBits += zero epsilonRateBits += one } println("1s: $numberOf1s, gammaRate: $gammaRateBits") println("0s: $numberOf0s") } val powerConsumption = Integer.parseInt(epsilonRateBits, 2) * Integer.parseInt(gammaRateBits, 2) println("Power consumption: $powerConsumption") } fun getBitCountAtPosition(inputs: List<String>, position: Int): Pair<Int, Int> { var numberOf0s = 0 var numberOf1s = 0 inputs.forEach { bits -> val bit: Char = bits[position] if (bit == '1') { numberOf1s += 1 } if (bit == '0') { numberOf0s += 1 } } return Pair(numberOf1s, numberOf0s) } fun getRecursiveAnswer(inputs: List<String>, position: Int, searchForFewest: Boolean = false): List<String> { if (inputs.size == 1) return inputs val (oneCount, zeroCount) = getBitCountAtPosition(inputs, position) if (oneCount == zeroCount) { return getRecursiveAnswer( inputs.filter { when (searchForFewest) { false -> it[position] != '1' else -> it[position] != '0' } }, position + 1, searchForFewest ) } if (oneCount > zeroCount) { return getRecursiveAnswer( inputs.filter { when (searchForFewest) { false -> it[position] != '1' else -> it[position] != '0' } }, position + 1, searchForFewest ) } return getRecursiveAnswer( inputs.filter { when (searchForFewest) { false -> it[position] != '0' true -> it[position] != '1' } }, position + 1, searchForFewest ) } fun second() { val inputs = parseFileAndGetInput() var oxygenList = mutableListOf<String>() var co2List = mutableListOf<String>() oxygenList.addAll(inputs) co2List.addAll(inputs) val oxygen = getRecursiveAnswer(oxygenList, 0) val co2 = getRecursiveAnswer(co2List, 0, true) println("OxygenList: $oxygen") println("co2List: $co2") println("Answer: ${Integer.parseInt(oxygen[0], 2) * Integer.parseInt(co2[0], 2)}") } fun main() { // first() second() }
0
Kotlin
0
0
5e296aaad25d1538306fa514c27efc35505e3a18
3,272
AdventOfCode2021
MIT License
src/Day07.kt
zsmb13
572,719,881
false
{"Kotlin": 32865}
import java.io.File fun main() { val elfDrive = File("elfdrive") fun initializeElfDrive(testInput: List<String>) { var file = elfDrive file.deleteRecursively() file.mkdir() testInput.drop(1).forEach { line -> when (line.first()) { '$' -> { val command = line.split(" ") if (command[1] == "cd") { file = when (val target = command[2]) { ".." -> file.parentFile else -> file.resolve(target) } } } else -> { val info = line.split(" ") when (info[0]) { "dir" -> file.resolve(info[1]).mkdir() else -> file.resolve(info[1]).writeBytes(ByteArray(info[0].toInt())) } } } } } fun File.totalSize() = walk().filter(File::isFile).sumOf(File::length) fun part1(testInput: List<String>): Long { initializeElfDrive(testInput) return elfDrive.walk() .filter { it.isDirectory } .filter { it.totalSize() < 100_000 } .sumOf { it.totalSize() } } fun part2(testInput: List<String>): Long { initializeElfDrive(testInput) val required = 30_000_000L - (70_000_000L - elfDrive.totalSize()) return elfDrive.walk() .filter(File::isDirectory) .filter { it.totalSize() >= required } .minOf(File::totalSize) } val testInput = readInput("Day07_test") check(part1(testInput) == 95_437L) check(part2(testInput) == 24_933_642L) val input = readInput("Day07") println(part1(input)) println(part2(input)) elfDrive.deleteRecursively() }
0
Kotlin
0
6
32f79b3998d4dfeb4d5ea59f1f7f40f7bf0c1f35
1,884
advent-of-code-2022
Apache License 2.0
src/main/kotlin/katas/15.duplicateCount.kt
ch8n
312,467,034
false
null
@file:Suppress("PackageDirectoryMismatch") package katas.longestCount //https://www.codewars.com/kata/5656b6906de340bd1b0000ac/train/kotlin import kotlin.time.measureTimedValue /** * * Take 2 strings s1 and s2 including only letters from a to z. * Return a new sorted string, the longest possible, containing distinct letters, each taken only once - coming from s1 or s2. Examples: a = "xyaabbbccccdefww" b = "xxxxyyyyabklmopq" longest(a, b) -> "abcdefklmopqwxy" a = "abcdefghijklmnopqrstuvwxyz" longest(a, a) -> "abcdefghijklmnopqrstuvwxyz" * * */ @kotlin.time.ExperimentalTime fun code() { val s1 = "xyaabbbccccdefww" val s2 = "xxxxyyyyabklmopq" measure("ch8n-1") { longest(s1, s2) } measure("ch8n-2") { longest2(s1, s2) } measure("ch8n-3") { longest3(s1, s2) } measure("ch8n-4") { longest4(s1, s2) } } fun longest(s1:String, s2:String):String { return "$s1$s2".toCharArray().sorted().toSet().joinToString("").also(::println) } fun longest2(s1:String, s2:String):String { return "$s1$s2".toSortedSet().joinToString("").also(::println) } fun longest3(s1:String, s2:String):String { return (s1.toList() union s2.toList()).sorted().joinToString("").also(::println) } fun longest4(s1:String, s2:String):String { return "$s1$s2".toCharArray().distinct().sorted().joinToString("").also(::println) } // ------------------------------------------ val collector = mutableMapOf<String, String>() @kotlin.time.ExperimentalTime fun main() { code() val usMap = collector.filter { (_, value) -> value.contains("us") }.map { (key, value) -> val spec = value.split("us")[0].toFloat() key to spec }.sortedBy { (_, value) -> value }.map { (key, value) -> key to "$value us" }.toMap() val msMap = collector.filter { (_, value) -> value.contains("ms") }.map { (key, value) -> val spec = value.split("ms")[0].toFloat() key to spec }.sortedBy { (_, value) -> value }.map { (key, value) -> key to "$value ms" }.toMap() val resultMap = mutableMapOf<String, String>().apply { putAll(usMap) putAll(msMap) } println("=================") println("=================") resultMap.forEach { (key, value) -> println(" $key --- $value") } println("=================") println("=================") } @kotlin.time.ExperimentalTime fun measure(tag: String, block: () -> Unit) { measureTimedValue { block.invoke() }.also { collector.put(tag, "${it.duration}") } }
3
Kotlin
0
1
e0619ebae131a500cacfacb7523fea5a9e44733d
2,649
Big-Brain-Kotlin
Apache License 2.0
src/Day07.kt
JonasDBB
573,382,821
false
{"Kotlin": 17550}
import java.lang.Exception data class Dir(val name: String, val parent: Dir?) { val subdir = mutableSetOf<Dir>() val files = mutableMapOf<String, Int>() val size: Int by lazy { subdir.sumOf { it.size } + files.values.sum() } } private fun createFS(input: List<String>): MutableSet<Dir> { val fileSys = Dir("/", null) val dirs = mutableSetOf(fileSys) var current = fileSys for (line in input) { if (line == "$ ls" || line == "$ cd /") { continue } if (line.startsWith("dir")) { val words = line.split(" ") val newDir = Dir(words[1], current) current.subdir.add(newDir) dirs.add(newDir) continue } if (line[0].isDigit()) { val words = line.split(" ") current.files[words[1]] = words[0].toInt() continue } if (line == "$ cd ..") { current = current.parent!! continue } if (line.startsWith("$ cd ")) { val dirname = line.split(" ")[2] current = current.subdir.find { it.name == dirname}!! continue } throw Exception("unknown command $line") } return dirs } private fun part1(dirs: MutableSet<Dir>) { println(dirs.filter { it.size <= 100000 }.sumOf { it.size }) } private fun part2(dirs: MutableSet<Dir>) { val spaceStillNeeded = 30000000 - (70000000 - dirs.first().size) println(dirs.filter { it.size >= spaceStillNeeded }.minBy { it.size }.size) } fun main() { val input = readInput("07") val dirs = createFS(input) println("part 1") part1(dirs) println("part 2") part2(dirs) }
0
Kotlin
0
0
199303ae86f294bdcb2f50b73e0f33dca3a3ac0a
1,707
AoC2022
Apache License 2.0
src/main/kotlin/g0601_0700/s0687_longest_univalue_path/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g0601_0700.s0687_longest_univalue_path // #Medium #Depth_First_Search #Tree #Binary_Tree // #2023_02_17_Time_303_ms_(100.00%)_Space_39.2_MB_(100.00%) 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 { fun longestUnivaluePath(root: TreeNode?): Int { if (root == null) { return 0 } val res = IntArray(1) preorderLongestSinglePathLen(root, res) return res[0] } private fun preorderLongestSinglePathLen(root: TreeNode?, res: IntArray): Int { if (root == null) { return -1 } var left = preorderLongestSinglePathLen(root.left, res) var right = preorderLongestSinglePathLen(root.right, res) left = if (root.left == null || root.`val` == root.left!!.`val`) { left + 1 } else { 0 } right = if (root.right == null || root.`val` == root.right!!.`val`) { right + 1 } else { 0 } val longestPathLenPassingThroughRoot = left + right res[0] = res[0].coerceAtLeast(longestPathLenPassingThroughRoot) return left.coerceAtLeast(right) } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,376
LeetCode-in-Kotlin
MIT License
src/day5/Day05.kt
jorgensta
573,824,365
false
{"Kotlin": 31676}
import java.util.* fun main() { val day = "day5" val filename = "Day05" val WHITESPACE = 32 class Action(val numCrates: Int, val from: Int, val to: Int) class Crate(val name: Char) { override fun toString(): String { return "[$name]" } } class Stack(val crates: LinkedList<Crate>) { fun initializeAdd(crate: Crate) { crates.addLast(crate) } fun add(crate: Crate) { crates.addFirst(crate) } fun pop(): Crate { return crates.removeFirst() } fun addOrdered(crts: List<Crate>) { crts.reversed().forEach { add(it) } } fun popOrdered(n: Int): List<Crate> { val elements = crates.take(n) elements.forEach { pop() } return elements } override fun toString(): String { return "Stack(crates = ${crates.joinToString{ "[${it.name}]"}})" } } val stacks: MutableMap<Int, Stack> = mutableMapOf() fun setup(input: List<String>, endOfCratesInputLineNumber: Int) { input.forEachIndexed inputIndex@{ lineNumber, line -> val windows = line.toList().windowed(3, 4) if (lineNumber + 1 > endOfCratesInputLineNumber) { return@inputIndex } windows.forEachIndexed { index, window -> stacks.putIfAbsent(index + 1, Stack(LinkedList())) if (window.all { it.code == WHITESPACE }) { return@forEachIndexed } stacks[index + 1]?.initializeAdd(Crate(window[1])) } } } fun lineToAction(line: String): Action { val digits = line.split(" ").mapNotNull { it.toIntOrNull() } return Action(digits[0], digits[1], digits[2]) } fun doAction(action: Action) { (1..action.numCrates).forEach { val releasedCrate = stacks[action.from]?.pop() if (releasedCrate != null) { stacks[action.to]?.add(releasedCrate) } } } fun doActionStep2(action: Action) { val releasedCrates = stacks[action.from]?.popOrdered(action.numCrates) if (releasedCrates != null) { stacks[action.to]?.addOrdered(releasedCrates) } } fun part1(input: List<String>, endOfCratesInputLineNumber: Int, instructionStart: Int): String { setup(input, endOfCratesInputLineNumber) input .subList(instructionStart, input.size) .map { lineToAction(it) } .forEach { doAction(it) } return stacks.values.map { it.pop().name }.joinToString("") } fun part2(input: List<String>, endOfCratesInputLineNumber: Int, instructionStart: Int): String { setup(input, endOfCratesInputLineNumber) input .subList(instructionStart, input.size) .map { lineToAction(it) } .forEach { doActionStep2(it) } return stacks.values.map { it.pop().name }.joinToString("") } // test if implementation meets criteria from the description, like: val testInput = readInput("/$day/${filename}_test") val input = readInput("/$day/$filename") // val partOneTest = part1(testInput, 3, 5) // check(partOneTest == "CMZ") // println("Part one: ${part1(input, 8, 10)}") // val partTwoTest = part2(testInput, 3, 5) // check(partTwoTest == "MCD") println("Part two: ${part2(input, 8, 10)}") }
0
Kotlin
0
0
7243e32351a926c3a269f1e37c1689dfaf9484de
3,540
AoC2022
Apache License 2.0
src/Constraint.kt
jonward1982
350,285,956
true
{"Kotlin": 213021, "Java": 286}
import lib.sparseVector.SparseVector import lib.sparseVector.asVector interface Constraint<out COEFF> { val coefficients: Map<Int, COEFF> val relation: String val constant: COEFF fun numVars(): Int = coefficients.keys.max()?.let { it+1 }?:0 } fun<COEFF: Comparable<COEFF>> Constraint<COEFF>.isSatisfiedBy(x: SparseVector<COEFF>): Boolean { val lhs = coefficients.asVector(x.operators).dotProduct(x) println("$lhs $relation $constant") return when(relation) { "<=" -> lhs <= constant ">=" -> lhs >= constant else -> lhs == constant } } // returns the absolute value of the difference between lhs and rhs //fun<COEFF: Number> Constraint<COEFF>.slackness(values: SparseVector<COEFF>): Double { // if(relation == "==") return 0.0 // val lhs = coefficients.asVector(values.operators).dotProduct(values).toDouble() // return with(values.operators) { // if (relation == "<=") constant.toDouble() - lhs else lhs - constant.toDouble() // } //} // returns the absolute value of the difference between lhs and rhs fun<COEFF: Number> Constraint<COEFF>.slackness(values: Map<Int,Double>): Double { if(relation == "==") return 0.0 val lhs = values.entries.sumByDouble { coefficients[it.key]?.toDouble()?:0.0 * it.value } return if (relation == "<=") constant.toDouble() - lhs else lhs - constant.toDouble() }
0
Kotlin
0
0
621d32d5e2d9d363c753d42cd1ede6b31195e716
1,392
AgentBasedMCMC
MIT License
src/chapter4/section3/ex32_SpecifiedSet.kt
w1374720640
265,536,015
false
{"Kotlin": 1373556}
package chapter4.section3 import chapter1.section5.CompressionWeightedQuickUnionUF import chapter2.section4.HeapMinPriorityQueue import chapter3.section5.LinearProbingHashSET import chapter3.section5.SET /** * 指定的集合 * 给定一幅连通的加权图G和一个边的集合S(不含环),给出一种算法得到含有S中所有边的最小加权生成树 * * 解:使用Kruskal算法计算最小生成树时,先将集合S内的所有边都加入到最小生成树中,然后再执行正常逻辑 */ class SpecifiedSetMST(graph: EWG, S: SET<Edge>) : MST() { init { val uf = CompressionWeightedQuickUnionUF(graph.V) // 先将集合S中的所有边都加入最小生成树中 S.forEach { edge -> val v = edge.either() val w = edge.other(v) queue.enqueue(edge) weight += edge.weight uf.union(v, w) } // 下面是正常逻辑 val pq = HeapMinPriorityQueue<Edge>() graph.edges().forEach { pq.insert(it) } while (!pq.isEmpty() && queue.size() < graph.V - 1) { val edge = pq.delMin() val v = edge.either() val w = edge.other(v) if (uf.connected(v, w)) continue queue.enqueue(edge) weight += edge.weight uf.union(v, w) } check(queue.size() == graph.V - 1) { "All vertices should be connected." } } } fun main() { val graph = getTinyWeightedGraph() val S = LinearProbingHashSET<Edge>() S.add(Edge(4, 7, 0.37)) S.add(Edge(0, 4, 0.38)) S.add(Edge(3, 6, 0.52)) val mst = SpecifiedSetMST(graph, S) println(mst.toString()) }
0
Kotlin
1
6
879885b82ef51d58efe578c9391f04bc54c2531d
1,716
Algorithms-4th-Edition-in-Kotlin
MIT License
src/main/kotlin/com/colinodell/advent2016/Day17.kt
colinodell
495,627,767
false
{"Kotlin": 80872}
package com.colinodell.advent2016 class Day17(private val input: String) { private val start = State(Vector2(0, 0)) private val reachedGoal: (State) -> Boolean = { it.pos == Vector2(3, 3) } fun solvePart1() = AStar(start, reachedGoal, ::generateNextMoves).end!!.path fun solvePart2() = DFS_all(start, reachedGoal, ::generateNextMoves).maxOf { it.path.length } private val possibleMoves = linkedMapOf( 'U' to Vector2(0, -1), 'D' to Vector2(0, 1), 'L' to Vector2(-1, 0), 'R' to Vector2(1, 0) ) private fun generateNextMoves(current: State): Sequence<State> { val hash = md5(input + current.path) val allowedDirs = possibleMoves.keys.filterIndexed { i, _ -> hash[i] in "bcdef" } val nextMoves = allowedDirs.map { State(current.pos + possibleMoves[it]!!, current.path + it) }.filter { it.pos.x in 0..3 && it.pos.y in 0..3 } return nextMoves.asSequence() } private data class State(val pos: Vector2, val path: String = "") }
0
Kotlin
0
0
8a387ddc60025a74ace8d4bc874310f4fbee1b65
1,025
advent-2016
Apache License 2.0
src/main/kotlin/g1601_1700/s1691_maximum_height_by_stacking_cuboids/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g1601_1700.s1691_maximum_height_by_stacking_cuboids // #Hard #Array #Dynamic_Programming #Sorting // #2023_06_15_Time_187_ms_(100.00%)_Space_38.6_MB_(100.00%) import java.util.Arrays class Solution { fun maxHeight(cuboids: Array<IntArray>): Int { for (a in cuboids) { a.sort() } Arrays.sort( cuboids ) { a: IntArray, b: IntArray -> if (a[0] != b[0]) { return@sort a[0] - b[0] } else if (a[1] != b[1]) { return@sort a[1] - b[1] } a[2] - b[2] } var ans = 0 val dp = IntArray(cuboids.size) for (i in cuboids.indices) { dp[i] = cuboids[i][2] for (j in 0 until i) { if (cuboids[i][0] >= cuboids[j][0] && cuboids[i][1] >= cuboids[j][1] && cuboids[i][2] >= cuboids[j][2] ) { dp[i] = Math.max(dp[i], cuboids[i][2] + dp[j]) } } ans = Math.max(ans, dp[i]) } return ans } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,102
LeetCode-in-Kotlin
MIT License
src/day01/Day01.kt
dkoval
572,138,985
false
{"Kotlin": 86889}
package day01 import readInputAsString import java.util.* private const val DAY_ID = "01" fun main() { fun parseInput(input: String): List<List<Int>> = input.split("\n\n").map { group -> group.lines().map { it.toInt() } } fun part1(input: String): Int { val groups = parseInput(input) return groups.maxOf { it.sum() } } fun part2(input: String): Int { val groups = parseInput(input) // min heap to keep top k integers val k = 3 val pq = PriorityQueue<Int>() for (group in groups) { pq.offer(group.sum()) if (pq.size > k) { pq.poll() } } return pq.sum() } // test if implementation meets criteria from the description, like: val testInput = readInputAsString("day${DAY_ID}/Day${DAY_ID}_test") check(part1(testInput) == 24000) check(part2(testInput) == 45000) val input = readInputAsString("day${DAY_ID}/Day$DAY_ID") println(part1(input)) // answer = 69310 println(part2(input)) // answer = 206104 }
0
Kotlin
1
0
791dd54a4e23f937d5fc16d46d85577d91b1507a
1,087
aoc-2022-in-kotlin
Apache License 2.0
src/main/kotlin/com/hj/leetcode/kotlin/problem1834/Solution.kt
hj-core
534,054,064
false
{"Kotlin": 619841}
package com.hj.leetcode.kotlin.problem1834 import java.util.* /** * LeetCode page: [1834. Single-Threaded CPU](https://leetcode.com/problems/single-threaded-cpu/); */ class Solution { /* Complexity: * Time O(NLogN) and Space O(N) where N is the size of tasks; */ fun getOrder(tasks: Array<IntArray>): IntArray { val sortedTasks = sortedTasksByEnqueueTime(tasks) val taskComparator = compareBy<Task>({ it.processingTime }, { it.index }) val taskPq = PriorityQueue(taskComparator) var currentTime = 0 var nextOfferIndex = 0 // first index at sortedTasks that not yet offered to taskPq; val order = IntArray(tasks.size) var nextAssignIndex = 0 // index at order that current task should assign to; while (nextAssignIndex < sortedTasks.size) { while (nextOfferIndex < sortedTasks.size && sortedTasks[nextOfferIndex].enqueueTime <= currentTime ) { taskPq.offer(sortedTasks[nextOfferIndex]) nextOfferIndex++ } if (taskPq.isEmpty()) { currentTime = sortedTasks[nextOfferIndex].enqueueTime continue } val executeTask = taskPq.poll() order[nextAssignIndex] = executeTask.index nextAssignIndex++ currentTime += executeTask.processingTime } return order } private fun sortedTasksByEnqueueTime(tasks: Array<IntArray>): List<Task> { val tasksList = MutableList(tasks.size) { index -> Task(index, tasks[index][0], tasks[index][1]) } tasksList.sortBy { task -> task.enqueueTime } return tasksList } private data class Task(val index: Int, val enqueueTime: Int, val processingTime: Int) }
1
Kotlin
0
1
14c033f2bf43d1c4148633a222c133d76986029c
1,828
hj-leetcode-kotlin
Apache License 2.0
src/main/kotlin/com/nibado/projects/advent/y2017/Day12.kt
nielsutrecht
47,550,570
false
null
package com.nibado.projects.advent.y2017 import com.nibado.projects.advent.Day import com.nibado.projects.advent.resourceRegex object Day12 : Day { private val input = resourceRegex(2017, 12, Regex("^([0-9]+) <-> ([0-9 ,]+)$")).map { Pair(it[1].toInt(), it[2].split(", ").map { it.toInt() }) } private val solution: Map<Int, Int> by lazy { solve(connections()) } private fun connections(): Map<Int, Set<Int>> { val map = mutableMapOf<Int, MutableSet<Int>>() fun get(id: Int) = map.computeIfAbsent(id, { mutableSetOf() }) input.forEach { a -> a.second.forEach { b -> get(a.first).add(b) get(b).add(a.first) } } return map } private fun solve(connections: Map<Int, Set<Int>>): Map<Int, Int> { val visited = mutableSetOf<Int>() val groups = mutableMapOf<Int, Int>() while (connections.size > visited.size) { val subVisited = mutableSetOf<Int>() val group = connections.keys.filterNot { visited.contains(it) }.sorted().first() fill(group, connections, subVisited) groups[group] = subVisited.size visited += subVisited } return groups } private fun fill(current: Int, nodes: Map<Int, Set<Int>>, visited: MutableSet<Int>) { visited += current nodes[current]!!.filterNot { visited.contains(it) }.forEach { fill(it, nodes, visited) } } override fun part1() = solution[0]!!.toString() override fun part2() = solution.size.toString() }
1
Kotlin
0
15
b4221cdd75e07b2860abf6cdc27c165b979aa1c7
1,611
adventofcode
MIT License
src/main/kotlin/g2301_2400/s2328_number_of_increasing_paths_in_a_grid/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g2301_2400.s2328_number_of_increasing_paths_in_a_grid // #Hard #Array #Dynamic_Programming #Depth_First_Search #Breadth_First_Search #Matrix #Graph // #Memoization #Topological_Sort #2023_07_01_Time_689_ms_(79.53%)_Space_59.1_MB_(91.34%) class Solution { private fun help(a: Array<IntArray>, i: Int, j: Int, n: Int, m: Int, dp: Array<IntArray>): Int { if (i < 0 || i >= n || j >= m || j < 0) { return 0 } if (dp[i][j] != 0) { return dp[i][j] } var res: Long = 0 if (i < n - 1 && a[i + 1][j] > a[i][j]) { res += (1 + help(a, i + 1, j, n, m, dp)).toLong() } if (i > 0 && a[i - 1][j] > a[i][j]) { res += (1 + help(a, i - 1, j, n, m, dp)).toLong() } if (j > 0 && a[i][j - 1] > a[i][j]) { res += (1 + help(a, i, j - 1, n, m, dp)).toLong() } if (j < m - 1 && a[i][j + 1] > a[i][j]) { res += (1 + help(a, i, j + 1, n, m, dp)).toLong() } dp[i][j] = res.toInt() % 1000000007 return dp[i][j] } fun countPaths(grid: Array<IntArray>): Int { val n = grid.size val m = grid[0].size var ans = n.toLong() * m val dp = Array(n) { IntArray(m) } for (i in 0 until n) { for (j in 0 until m) { ans += (help(grid, i, j, n, m, dp) % 1000000007).toLong() } } ans %= 1000000007 return ans.toInt() } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,499
LeetCode-in-Kotlin
MIT License
src/day05/Day05.kt
Puju2496
576,611,911
false
{"Kotlin": 46156}
package day05 import readInput import java.util.* fun main() { // test if implementation meets criteria from the description, like: val input = readInput("src/day05", "Day05") println("Part1") part1(input) println("Part2") part2(input) } private fun part1(inputs: List<String>) { val stackData = getStack(inputs) println("stack - $stackData") val procedureList = getProcedure(inputs) procedureList.forEach { for (i in 0 until it[0].toInt()) { val last = stackData[it[1].toInt() - 1]?.pop() if (last != null) stackData[it[2].toInt() - 1]?.push(last) } } println("after procedure - $stackData") val top = StringBuilder() stackData.forEach { top.append(it?.peek()) } println("top - $top") } private fun part2(inputs: List<String>) { val stackData = getStack(inputs) println("stack -$stackData") val procedureList = getProcedure(inputs) procedureList.forEach { if (it[0].toInt() == 1) { val last = stackData[it[1].toInt() - 1]?.pop() if (last != null) stackData[it[2].toInt() - 1]?.push(last) } else { val list = mutableListOf<Char>() for (i in 0 until it[0].toInt()) { val last = stackData[it[1].toInt() - 1]?.pop() if (last != null) list.add(last) } list.reversed().forEach { char -> stackData[it[2].toInt() - 1]?.push(char) } } } println("after procedure - $stackData") val top = StringBuilder() stackData.forEach { top.append(it?.peek()) } println("top - $top") } private fun getStack(inputs: List<String>): MutableList<ArrayDeque<Char>?> { var index = 0 val stack: List<String> = inputs.takeWhile { it.contains('[') }.reversed() val dataMap: MutableList<ArrayDeque<Char>?> = mutableListOf() for (i in 0 until inputs[inputs.indexOf("") - 1].last().digitToInt()) { dataMap.add(ArrayDeque()) } for (i in 1..stack.first().length step 4) { stack.forEach { if (i < it.length && it[i].isUpperCase()) dataMap[index]?.push(it[i]) } index++ } return dataMap } private fun getProcedure(inputs: List<String>): List<List<String>> { val procedureList = inputs.subList(inputs.indexOf("") + 1, inputs.size).map { value -> value.split(" ").filter { it.toIntOrNull() != null } } return procedureList }
0
Kotlin
0
0
e04f89c67f6170441651a1fe2bd1f2448a2cf64e
2,577
advent-of-code-2022
Apache License 2.0
AdventOfCodeDay19/src/nativeMain/kotlin/Scanner.kt
bdlepla
451,510,571
false
{"Kotlin": 165771}
import kotlin.math.absoluteValue data class Point3d(val x: Int, val y: Int, val z: Int) { operator fun plus(other: Point3d): Point3d = Point3d(x + other.x, y + other.y, z + other.z) operator fun minus(other: Point3d): Point3d = Point3d(x - other.x, y - other.y, z - other.z) infix fun distanceTo(other: Point3d): Int = (this.x - other.x).absoluteValue + (this.y - other.y).absoluteValue + (this.z - other.z).absoluteValue fun face(facing: Int): Point3d = when (facing) { 0 -> this 1 -> Point3d(x, -y, -z) 2 -> Point3d(x, -z, y) 3 -> Point3d(-y, -z, x) 4 -> Point3d(y, -z, -x) 5 -> Point3d(-x, -z, -y) else -> error("Invalid facing") } fun rotate(rotating: Int): Point3d = when (rotating) { 0 -> this 1 -> Point3d(-y, x, z) 2 -> Point3d(-x, -y, z) 3 -> Point3d(y, -x, z) else -> error("Invalid rotation") } companion object { fun of(rawInput: String): Point3d = rawInput.split(",").let { part -> Point3d(part[0].toInt(), part[1].toInt(), part[2].toInt()) } } } fun <T> Collection<T>.pairs(): List<Pair<T,T>> = this.flatMapIndexed { index, a -> this.drop(index).map { b -> a to b } }
0
Kotlin
0
0
1d60a1b3d0d60e0b3565263ca8d3bd5c229e2871
1,382
AdventOfCode2021
The Unlicense
src/main/kotlin/dev/shtanko/algorithms/leetcode/JobScheduling.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2024 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import java.util.TreeMap /** * 1235. Maximum Profit in Job Scheduling * @see <a href="<link>">Source</a> */ interface JobScheduling { operator fun invoke(startTime: IntArray, endTime: IntArray, profit: IntArray): Int } class JobSchedulingDp : JobScheduling { override fun invoke(startTime: IntArray, endTime: IntArray, profit: IntArray): Int { val n: Int = startTime.size val jobs: Array<IntArray> = Array(n) { IntArray(3) } for (i in 0 until n) { jobs[i] = intArrayOf(startTime[i], endTime[i], profit[i]) } jobs.sortWith { a: IntArray, b: IntArray -> a[1] - b[1] } val dp: TreeMap<Int, Int> = TreeMap() dp[0] = 0 for (job: IntArray in jobs) { val cur: Int = dp.floorEntry(job[0]).value + job[2] if (cur > dp.lastEntry().value) dp[job[1]] = cur } return dp.lastEntry().value } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,574
kotlab
Apache License 2.0
src/Day03.kt
TinusHeystek
574,474,118
false
{"Kotlin": 53071}
class Day03 : Day(3) { private val priorities = " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" // --- Part 1 --- private fun calculateRucksack(rucksack : String) : Int { val middle = rucksack.length / 2 val compartment1 = rucksack.substring(0, middle).toCharArray() val compartment2 = rucksack.substring(middle).toCharArray() val intersecting = compartment1.intersect(compartment2.toSet()) val duplicate = intersecting.first() return priorities.indexOf(duplicate) } override fun part1ToInt(input: String): Int { var total = 0 val rucksacks = input.lines() for (rucksack in rucksacks) { total += calculateRucksack(rucksack) } return total } // --- Part 2 --- private fun calculateRucksackGroup(group: List<String>) : Int { var intersecting = group.first().toCharArray().toSet() for (rucksack in group.subList(1, group.count())) { intersecting = intersecting.intersect(rucksack.toCharArray().toSet()) } val duplicate = intersecting.first() return priorities.indexOf(duplicate) } override fun part2ToInt(input: String): Int { var total = 0 val rucksacks = input.lines() val groups = rucksacks.chunked(3) for (group in groups) { total += calculateRucksackGroup(group) } return total } } fun main() { val day = Day03() day.printToIntResults(157, 70) }
0
Kotlin
0
0
80b9ea6b25869a8267432c3a6f794fcaed2cf28b
1,531
aoc-2022-in-kotlin
Apache License 2.0
app/src/main/kotlin/day06/Day06.kt
KingOfDog
433,706,881
false
{"Kotlin": 76907}
package day06 import common.InputRepo import common.readSessionCookie import common.solve fun main(args: Array<String>) { val day = 6 val input = InputRepo(args.readSessionCookie()).get(day = day) solve(day, input, ::solveDay06Part1, ::solveDay06Part2) } fun solveDay06Part1(input: List<String>): Int { val numberOfDays = 80 val fish = input.first().split(",").map { it.toInt() } .overfishing(numberOfDays) return howMuchIsTheFish(fish) } fun solveDay06Part2(input: List<String>): Long { val numberOfDays = 256 val fishingNet = parseFishingNet(input) for (d in 1..numberOfDays) { decreaseAllCounters(fishingNet) resetAndGiveBirth(fishingNet) } return howMuchIsTheFish(fishingNet) } private fun decreaseAllCounters(fishingNet: MutableMap<Int, Long>) { for (i in 0..8) { fishingNet[i - 1] = fishingNet.getOrZero(i) fishingNet[i] = 0 } } private fun resetAndGiveBirth(fishingNet: MutableMap<Int, Long>) { fishingNet[6] = fishingNet.getOrZero(6) + fishingNet.getOrZero(-1) fishingNet[8] = fishingNet.getOrZero(8) + fishingNet.getOrZero(-1) fishingNet[-1] = 0 } @OptIn(ExperimentalStdlibApi::class) private fun parseFishingNet(input: List<String>): MutableMap<Int, Long> { val fish = input.first().split(",").map { it.toInt() } val fishingNet = buildMap<Int, Long> { fish.forEach { this.increase(it) } }.toMutableMap() return fishingNet } private fun howMuchIsTheFish(fish: List<Int>) = fish.size private fun howMuchIsTheFish(fishingNet: Map<Int, Long>) = fishingNet.values.sum() private fun List<Int>.overfishing( numberOfDays: Int ): List<Int> { var soundsFishy = this for (d in 1..numberOfDays) { val offspring = soundsFishy.filter { it == 0 }.map { 8 } soundsFishy = soundsFishy.map { it - 1 }.map { if (it < 0) it + 7 else it } soundsFishy = soundsFishy + offspring } return soundsFishy } fun MutableMap<Int, Long>.increase(key: Int) { this[key] = getOrDefault(key, 0) + 1 } private fun Map<Int, Long>.getOrZero(number: Int) = getOrDefault(number, 0)
0
Kotlin
0
0
576e5599ada224e5cf21ccf20757673ca6f8310a
2,165
advent-of-code-kt
Apache License 2.0
algorithms/src/main/kotlin/org/baichuan/sample/algorithms/leetcode/middle/Divide.kt
scientificCommunity
352,868,267
false
{"Java": 154453, "Kotlin": 69817}
package org.baichuan.sample.algorithms.leetcode.middle /** * https://leetcode.cn/problems/divide-two-integers/ * 两数相除 * 核心思路: 38/3 = 3*2 + 32 = 3*2*2+26= 3*2*2*2 + 14 = 3*2*2*2 + 3*2*2 +2 = 3(2*2*2 + 2*2) +2 = 3 * 12 + 2 = 12 */ class Divide { fun divide(dividend: Int, divisor: Int): Int { if (dividend == 0) { return 0 } if (dividend == Integer.MIN_VALUE) { if (divisor == 1) { return Integer.MIN_VALUE; } if (divisor == -1) { return Integer.MAX_VALUE; } } if (divisor == 1) { return dividend } if (divisor == -1) { return -dividend } var result = 1 var sign = 0 var divided1 = if (dividend > 0) { sign++ -dividend } else { sign-- dividend } var divisor1 = if (divisor > 0) { sign++ -divisor } else { sign-- divisor } val divisor2 = divisor1 if (divided1 > divisor1) { return 0 } if (divisor1 == divided1) { return if (sign == 0) -result else result } while (divided1 - divisor1 <= divisor1) { divisor1 = divisor1 shl 1 result += result } divided1 -= divisor1 var tmp1 = result while (divided1 < divisor2) { divisor1 = divisor1 shr 1 tmp1 = tmp1 shr 1 if (divided1 - divisor1 <= 0) { divided1 -= divisor1 result += tmp1 } } if (divided1 == divisor2) { result += 1 } return if (sign == 0) -result else result } } fun main() { println(Divide().divide(2147483647, 1)) println(-10 shr 1) }
1
Java
0
8
36e291c0135a06f3064e6ac0e573691ac70714b6
1,923
blog-sample
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/CountVowelsPermutation.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2021 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import dev.shtanko.algorithms.MOD /** * 1220. Count Vowels Permutation * @see <a href="https://leetcode.com/problems/count-vowels-permutation/">Source</a> */ fun interface CountVowelsPermutationStrategy { operator fun invoke(n: Int): Int } sealed interface CountVowelsPermutation { /** * Approach 1: Dynamic Programming (Bottom-up) */ class BottomUp : CountVowelsPermutationStrategy { override operator fun invoke(n: Int): Int { val aVowelPermutationCount = LongArray(n) val eVowelPermutationCount = LongArray(n) val iVowelPermutationCount = LongArray(n) val oVowelPermutationCount = LongArray(n) val uVowelPermutationCount = LongArray(n) aVowelPermutationCount[0] = 1L eVowelPermutationCount[0] = 1L iVowelPermutationCount[0] = 1L oVowelPermutationCount[0] = 1L uVowelPermutationCount[0] = 1L for (i in 1 until n) { val eiCount = eVowelPermutationCount[i - 1].plus(iVowelPermutationCount[i - 1]) aVowelPermutationCount[i] = eiCount.plus(uVowelPermutationCount[i - 1]).rem(MOD) eVowelPermutationCount[i] = aVowelPermutationCount[i - 1].plus(iVowelPermutationCount[i - 1]).rem(MOD) iVowelPermutationCount[i] = (eVowelPermutationCount[i - 1] + oVowelPermutationCount[i - 1]) % MOD oVowelPermutationCount[i] = iVowelPermutationCount[i - 1] % MOD uVowelPermutationCount[i] = (iVowelPermutationCount[i - 1] + oVowelPermutationCount[i - 1]) % MOD } val aeCount = aVowelPermutationCount[n - 1].plus(eVowelPermutationCount[n - 1]) val ioCount = iVowelPermutationCount[n - 1].plus(oVowelPermutationCount[n - 1]) val result: Long = aeCount.plus(ioCount).plus(uVowelPermutationCount[n - 1]).rem(MOD) return result.toInt() } override fun toString() = "bottom up" } class OptimizedSpace : CountVowelsPermutationStrategy { override operator fun invoke(n: Int): Int { var aCount: Long = 1 var eCount: Long = 1 var iCount: Long = 1 var oCount: Long = 1 var uCount: Long = 1 for (i in 1 until n) { val aCountNew = eCount.plus(iCount).plus(uCount).rem(MOD) val eCountNew = aCount.plus(iCount).rem(MOD) val iCountNew = eCount.plus(oCount).rem(MOD) val oCountNew = iCount.rem(MOD) val uCountNew = iCount.plus(oCount).rem(MOD) aCount = aCountNew eCount = eCountNew iCount = iCountNew oCount = oCountNew uCount = uCountNew } val aeCount = aCount + eCount val ioCount = iCount + oCount val result = aeCount.plus(ioCount).plus(uCount).rem(MOD) return result.toInt() } override fun toString(): String = "optimized space" } /** * Approach 3: Dynamic Programming (Top-down, Recursion) */ class TopDown : CountVowelsPermutationStrategy { private lateinit var memo: Array<LongArray> override operator fun invoke(n: Int): Int { // each row stands for the length of string // each column indicates the vowels // specifically, a: 0, e: 1, i: 2, o: 3, u: 4 memo = Array(n) { LongArray(5) } var result: Long = 0 for (i in 0..4) { result = (result + vowelPermutationCount(n - 1, i)) % MOD } return result.toInt() } private fun vowelPermutationCount(i: Int, vowel: Int): Long { if (memo[i][vowel] != 0L) return memo[i][vowel] if (i == 0) { memo[i][vowel] = 1 } else { when (vowel) { 0 -> { val local = vowelPermutationCount(i - 1, 1) + vowelPermutationCount(i - 1, 2) memo[i][vowel] = (local + vowelPermutationCount(i - 1, 4)) % MOD } 1 -> { val local = vowelPermutationCount(i - 1, 0) + vowelPermutationCount(i - 1, 2) memo[i][vowel] = local % MOD } 2 -> { val local = vowelPermutationCount(i - 1, 1) + vowelPermutationCount(i - 1, 3) memo[i][vowel] = local % MOD } 3 -> { memo[i][vowel] = vowelPermutationCount(i - 1, 2) } 4 -> { val local = vowelPermutationCount(i - 1, 2) + vowelPermutationCount(i - 1, 3) memo[i][vowel] = local % MOD } } } return memo[i][vowel] } override fun toString(): String = "top down" } class Matrix : CountVowelsPermutationStrategy { override fun invoke(n: Int): Int { var countA: Long = 1 var countE: Long = 1 var countI: Long = 1 var countO: Long = 1 var countU: Long = 1 for (length in 1 until n) { // Calculate the next counts for each vowel based on the previous counts val nextCountA = countE val nextCountE = (countA + countI) % MOD val nextCountI = (countA + countE + countO + countU) % MOD val nextCountO = (countI + countU) % MOD val nextCountU = countA // Update the counts with the newly calculated values for the next length countA = nextCountA countE = nextCountE countI = nextCountI countO = nextCountO countU = nextCountU } // Calculate the total count of valid strings for length n val totalCount = (countA + countE + countI + countO + countU) % MOD return totalCount.toInt() } override fun toString(): String = "matrix" } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
6,920
kotlab
Apache License 2.0
src/main/kotlin/me/circuitrcay/euler/challenges/twentySixToFifty/Problem33.kt
adamint
134,989,381
false
null
package me.circuitrcay.euler.challenges.twentySixToFifty import me.circuitrcay.euler.Problem import java.math.BigInteger class Problem33 : Problem<String>() { override fun calculate(): Any { val numerators = mutableListOf<Int>() val denominators = mutableListOf<Int>() (10..99).forEach { num -> (10..99).forEach { denom -> if (hasEditedFactor(num, denom)) { numerators.add(num) denominators.add(denom) } } } var numProducts = BigInteger.ONE var denomProducts = BigInteger.ONE numerators.forEach { numProducts = numProducts.times(BigInteger.valueOf(it.toLong())) } denominators.forEach { denomProducts = denomProducts.times(BigInteger.valueOf(it.toLong())) } val gcm = gcm(numProducts.toInt(), denomProducts.toInt()) return denomProducts.divide(BigInteger.valueOf(gcm.toLong())) } private fun hasEditedFactor(numerator: Int, denominator: Int): Boolean { if (numerator / denominator.toFloat() > 1f) return false var numStr = numerator.toString() var denomStr = denominator.toString() numStr.forEachIndexed { i, c -> if (denomStr.contains(c)) { numStr = numStr.replaceFirst(c.toString(), "") denomStr = denomStr.replaceFirst(c.toString(), "") } } return numStr != numerator.toString() && numStr.isNotBlank() && denomStr.isNotBlank() && denomStr.toInt() != 0 && numStr.toInt() != 0 && numerator / denominator.toFloat() == numStr.toInt() / denomStr.toFloat() && !numerator.toString().endsWith("0") } private fun gcm(one: Int, two: Int): Int { return if (two == 0) one else gcm(two, one.mod(two)) } }
0
Kotlin
0
0
cebe96422207000718dbee46dce92fb332118665
1,825
project-euler-kotlin
Apache License 2.0
src/main/kotlin/Day02.kt
todynskyi
573,152,718
false
{"Kotlin": 47697}
fun main() { fun part1(input: List<String>): Int = input.sumOf { val player = it[0] val you = it[2] val yourScore = when (you) { 'X' -> 1 'Y' -> 2 'Z' -> 3 else -> 0 } val score = when (player) { 'A' -> { when (you) { 'X' -> 3 'Y' -> 6 else -> 0 } } 'B' -> { when (you) { 'X' -> 0 'Y' -> 3 else -> 6 } } else -> { when (you) { 'X' -> 6 'Y' -> 0 else -> 3 } } } yourScore + score } fun part2(input: List<String>): Int = input.sumOf { val player = it[0] val you = it[2] val yourScore = when (you) { 'X' -> 0 'Y' -> 3 'Z' -> 6 else -> 0 } val score = when (you) { 'X' -> { when (player) { 'A' -> 3 'B' -> 1 'C' -> 2 else -> 0 } } 'Y' -> { when (player) { 'A' -> 1 'B' -> 2 'C' -> 3 else -> 0 } } else -> { when (player) { 'A' -> 2 'B' -> 3 'C' -> 1 else -> 0 } } } yourScore + score } // test if implementation meets criteria from the description, like: val testInput = readInput("Day02_test") check(part1(testInput) == 15) println(part2(testInput)) val input = readInput("Day02") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
5f9d9037544e0ac4d5f900f57458cc4155488f2a
2,042
KotlinAdventOfCode2022
Apache License 2.0
src/main/kotlin/tr/emreone/adventofcode/days/Day05.kt
EmRe-One
568,569,073
false
{"Kotlin": 166986}
package tr.emreone.adventofcode.days import tr.emreone.adventofcode.readTextGroups import tr.emreone.kotlin_utils.Logger.logger import java.util.Stack object Day05 { private val pattern = "move (\\d+) from (\\d+) to (\\d+)".toRegex() private fun printCrates(crates: List<Stack<Char>>) { val sb = StringBuilder() crates.forEachIndexed { index, crate -> sb.append("Crate $index: ") crate.forEach { sb.append("$it ") } sb.appendLine() } logger.info { sb.toString() } } private fun stackOf(input: String): Stack<Char> { val stack = Stack<Char>() input.forEach { stack.push(it) } return stack } private fun stackOf(vararg elements: Char): Stack<Char> { val stack = Stack<Char>() elements.forEach { stack.push(it) } return stack } // 111111... // index: 0123456789012345... // [Z]·········[C]·... // distribution: [X]·[Y]·[A]·[B]·... // cratesIds: ·1···2···3···4··... private fun parseStackOfCrates(input: List<String>): List<Stack<Char>> { val cratesLine = input.last() val stackOfCrates = mutableListOf<Stack<Char>>() """(\d+)""".toRegex().findAll(cratesLine).forEach { _ -> stackOfCrates.add(stackOf()) } val stacksDistribution = input.dropLast(1).reversed() stacksDistribution.forEach { row -> val lineLength = row.length stackOfCrates.forEachIndexed { index, crate -> val crateIdIndex = (index * 4) + 1 if (crateIdIndex < lineLength) { val crateId = row[crateIdIndex] if (crateId != ' ') { crate.push(crateId) } } } } return stackOfCrates } private fun solveCrateMovements(input: String, moveOneByOne: Boolean = true): String { // TODO split text into header and movements val (header, movements) = input.readTextGroups() val stackOfCrates = parseStackOfCrates(header.lines()) movements.lines().forEach { val (no, from, to) = pattern.matchEntire(it)!!.destructured if (moveOneByOne) { for (i in 0 until no.toInt()) { stackOfCrates[to.toInt() - 1].push(stackOfCrates[from.toInt() - 1].pop()) } } else { val temp = Stack<Char>() for (i in 0 until no.toInt()) { temp.push(stackOfCrates[from.toInt() - 1].pop()) } for (i in 0 until no.toInt()) { stackOfCrates[to.toInt() - 1].push(temp.pop()) } } } return stackOfCrates.map { it.last() }.joinToString("") } fun part1(input: String): String { return solveCrateMovements(input, true) } fun part2(input: String): String { return solveCrateMovements(input, false) } }
0
Kotlin
0
0
a951d2660145d3bf52db5cd6d6a07998dbfcb316
3,135
advent-of-code-2022
Apache License 2.0
src/Day05.kt
sushovan86
573,586,806
false
{"Kotlin": 47064}
import java.io.File import java.util.* import kotlin.collections.ArrayDeque import kotlin.collections.component1 import kotlin.collections.component2 import kotlin.collections.component3 import kotlin.collections.set typealias StackElements = ArrayDeque<Char> fun StackElements.removeLast(n: Int): List<Char> { val list = ArrayList<Char>() repeat(n) { list += removeLast() } return list } fun StackElements.addLast(element: List<Char>, maintainOrder: Boolean = false) { if (maintainOrder) { element.reversed().forEach { addLast(it) } } else { element.forEach { addLast(it) } } } class Instruction(val moveCount: Int, val fromStack: Int, val toStack: Int) typealias Instructions = List<Instruction> class WorkingStack { private val stackElementsByStackNumberMap = TreeMap<Int, StackElements>() private val stackElementsByPositionMap = mutableMapOf<Int, StackElements>() fun initializeStackWithCharacterPosition(stackNumber: Int, position: Int) { val stackElements = StackElements() stackElementsByStackNumberMap[stackNumber] = stackElements stackElementsByPositionMap[position] = stackElements } fun addToStack(position: Int, stackValue: Char) { stackElementsByPositionMap[position]?.addLast(stackValue) } fun executeInstructions(instructions: Instructions, maintainOrder: Boolean = false) { for (instruction in instructions) { val movedElements = stackElementsByStackNumberMap[instruction.fromStack] ?.removeLast(instruction.moveCount) movedElements?.apply { stackElementsByStackNumberMap[instruction.toStack]?.addLast(this, maintainOrder) } } } fun topStackElements() = stackElementsByStackNumberMap .map { it.value.last() } .joinToString(separator = "") override fun toString(): String { val sb = StringBuilder() stackElementsByStackNumberMap.forEach { sb.append("${it.key} --> ${it.value}") sb.append(System.lineSeparator()) } return sb.toString() } } fun main() { val (workingStackTest1, instructionsTest1) = parseInput("Day05_test") workingStackTest1.executeInstructions(instructionsTest1) check(workingStackTest1.topStackElements() == "CMZ") val (workingStackTest2, instructionsTest2) = parseInput("Day05_test") workingStackTest2.executeInstructions(instructionsTest2, maintainOrder = true) check(workingStackTest2.topStackElements() == "MCD") val (workingStackActual1, instructionsActual1) = parseInput("Day05") workingStackActual1.executeInstructions(instructionsActual1) println(workingStackActual1.topStackElements()) val (workingStackActual2, instructionsActual2) = parseInput("Day05") workingStackActual2.executeInstructions(instructionsActual2, maintainOrder = true) println(workingStackActual2.topStackElements()) } private fun parseInput(fileName: String): Pair<WorkingStack, Instructions> { val testInput = File("resource", fileName).readText() val (workingStackData, instructionData) = testInput.split(System.lineSeparator().repeat(2)) val workingStack = parseWorkingStackData(workingStackData) val instructions = parseInstructions(instructionData) return workingStack to instructions } fun parseInstructions(instructionData: String): Instructions = instructionData .lines() .map { val (count, fromStack, toStack) = it.split(" ", "move", "from", "to") .filterNot(String::isBlank) Instruction(count.toInt(), fromStack.toInt(), toStack.toInt()) } fun parseWorkingStackData(workingStackData: String): WorkingStack { val workingStack = WorkingStack() val lines = workingStackData.lines() lines.last() .withIndex() .filter { it.value.isDigit() } .forEach { workingStack.initializeStackWithCharacterPosition(it.value.digitToInt(), it.index) } lines.reversed() .drop(1) .forEach { line -> line.withIndex() .filter { it.value.isLetter() } .forEach { workingStack.addToStack(it.index, it.value) } } return workingStack }
0
Kotlin
0
0
d5f85b6a48e3505d06b4ae1027e734e66b324964
4,289
aoc-2022
Apache License 2.0
src/nativeMain/kotlin/com.qiaoyuang.algorithm/round1/Questions55.kt
qiaoyuang
100,944,213
false
{"Kotlin": 338134}
package com.qiaoyuang.algorithm.round1 import com.qiaoyuang.algorithm.round0.BinaryTreeNode import kotlin.math.abs import kotlin.math.max fun test55() { printlnResult1(testCase1()) printlnResult1(testCase2()) printlnResult1(testCase3()) printlnResult2(testCase1()) printlnResult2(testCase2()) printlnResult2(testCase3()) } /** * Questions 55-1: Get the depth of a binary-tree */ private fun <T> BinaryTreeNode<T>.depth(): Int = 1 + max(left?.depth() ?: 0, right?.depth() ?: 0) private fun testCase1(): BinaryTreeNode<Int> = BinaryTreeNode( value = 1, left = BinaryTreeNode( value = 2, left = BinaryTreeNode(value = 4), right = BinaryTreeNode( value = 5, right = BinaryTreeNode(value = 7), ) ), right = BinaryTreeNode( value = 3, right = BinaryTreeNode(value = 6), ) ) private fun printlnResult1(node: BinaryTreeNode<Int>) = println("The depth of binary tree: ${node.inOrderList()} is: ${node.depth()}") /** * Questions 55-2: Judge weather a binary tree is a balance binary tree */ private fun <T> BinaryTreeNode<T>.isBalance(): Boolean = isBalanceRec().first private fun <T> BinaryTreeNode<T>.isBalanceRec(): Pair<Boolean, Int> { val (isLeftBalance, leftDepth) = left?.isBalanceRec() ?: (true to 0) val (isRightBalance, rightDepth) = right?.isBalanceRec() ?: (true to 0) val depth = max(leftDepth, rightDepth) + 1 return if (isLeftBalance && isRightBalance) (abs(leftDepth - rightDepth) <= 1) to depth else false to depth } private fun testCase2(): BinaryTreeNode<Int> = BinaryTreeNode( value = 5, left = BinaryTreeNode( value = 3, left = BinaryTreeNode(value = 2), right = BinaryTreeNode(value = 4), ), right = BinaryTreeNode( value = 7, left = BinaryTreeNode(value = 6), right = BinaryTreeNode(value = 8), ), ) private fun testCase3(): BinaryTreeNode<Int> = BinaryTreeNode( value = 1, left = BinaryTreeNode( value = 2, left = BinaryTreeNode(value = 4), right = BinaryTreeNode( value = 5, right = BinaryTreeNode(value = 7), ) ), right = BinaryTreeNode( value = 3, right = BinaryTreeNode( value = 6, right = BinaryTreeNode(value = 8), ), ) ) private fun printlnResult2(node: BinaryTreeNode<Int>) = println("Is the binary tree: ${node.inOrderList()} balance binary tree: ${node.isBalance()}")
0
Kotlin
3
6
66d94b4a8fa307020d515d4d5d54a77c0bab6c4f
2,582
Algorithm
Apache License 2.0
src/main/kotlin/dk/lessor/Day7.kt
aoc-team-1
317,571,356
false
{"Java": 70687, "Kotlin": 34171}
package dk.lessor fun main() { val lines = readFile("day_7.txt") val bags = bagParser(lines) val canHaveShiny = containsBag(bags) println(canHaveShiny.size) println(countBags(bags)) } fun containsBag(bags: Map<String, List<Bag>>, name: String = "shiny gold"): List<String> { val result = mutableListOf<String>() result += bags.filter { it.value.any { b -> b.name == name } }.keys return (result + result.flatMap { containsBag(bags, it) }).distinct() } fun countBags(bags: Map<String, List<Bag>>, name: String = "shiny gold"): Int { val contains = bags[name] ?: return 0 return contains.sumBy(Bag::count) + contains.sumBy { it.count * countBags(bags, it.name) } } fun bagParser(lines: List<String>): Map<String, List<Bag>> { val result = mutableMapOf<String, List<Bag>>() for (line in lines) { val (main, inside) = line.split(" contain ") val key = main.replace(" bag[s]?\\.?".toRegex(), "").trim() if (inside == "no other bags.") { result[key] = emptyList() continue } val contains = inside.split(", ").map { b -> val count = b.take(1).toInt() val name = b.drop(2).replace(" bag[s]?\\.?".toRegex(), "").trim() Bag(name, count) } result[key] = contains } return result } data class Bag(val name: String, val count: Int) { override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as Bag if (name != other.name) return false return true } override fun hashCode(): Int { return name.hashCode() } }
0
Java
0
0
48ea750b60a6a2a92f9048c04971b1dc340780d5
1,718
lessor-aoc-comp-2020
MIT License
src/main/kotlin/biodivine/algebra/ia/Interval.kt
daemontus
160,796,526
false
null
package biodivine.algebra.ia import biodivine.algebra.NumQ import biodivine.algebra.rootisolation.Root import cc.redberry.rings.Rational import cc.redberry.rings.Rings import cc.redberry.rings.bigint.BigDecimal import cc.redberry.rings.bigint.BigInteger import biodivine.algebra.rootisolation.compareTo import kotlin.math.max import kotlin.math.min data class Interval( val low: NumQ, val high: NumQ ) { init { if (low > high) error("Empty interval [$low,$high]") } constructor(low: Int, high: Int) : this( NumQ(Rings.Q.ring, BigInteger.valueOf(low)), NumQ(Rings.Q.ring, BigInteger.valueOf(high)) ) val size: NumQ get() = high - low val hasZero: Boolean get() = low <= Rings.Q.zero && high >= Rings.Q.zero val center: NumQ get() = low + size/2 operator fun plus(that: Interval): Interval { return Interval(this.low + that.low, this.high + that.high) } operator fun minus(that: Interval): Interval { return Interval(this.low - that.high, this.high - that.low) } operator fun times(that: Interval): Interval { val (x1, x2) = this val (y1, y2) = that val x1y1 = x1 * y1 val x1y2 = x1 * y2 val x2y1 = x2 * y1 val x2y2 = x2 * y2 return Interval( low = min(min(x1y1, x1y2), min(x2y1,x2y2)), high = max(max(x1y1, x1y2), max(x2y1,x2y2)) ) } operator fun div(that: Interval): Interval { if (that.low.signum() != that.high.signum()) error("Zero in division $this / $that") val (y1, y2) = that return this * Interval( NumQ(y2.ring, y2.denominator(), y2.numerator()), NumQ(y1.ring, y1.denominator(), y1.numerator()) ) } operator fun times(that: NumQ): Interval { return if (that < Rings.Q.zero) { Interval(high * that, low * that) } else { Interval(low * that, high * that) } } infix fun intersects(that: Interval): Boolean = this.high >= that.low && this.low <= that.high infix fun intersect(that: Interval): Interval? { val low = if (this.low < that.low) that.low else this.low val high = if (this.high < that.high) this.high else that.high return Interval(low, high) } operator fun contains(num: NumQ): Boolean = this.low <= num && num <= this.high operator fun contains(root: Root): Boolean = this.low <= root && root <= this.high fun isNumber(): Boolean = this.low == this.high } operator fun NumQ.plus(that: NumQ): NumQ = this.add(that) operator fun NumQ.times(that: NumQ): NumQ = this.multiply(that) operator fun NumQ.minus(that: NumQ): NumQ = this.subtract(that) operator fun NumQ.times(that: Interval) = Interval(this * that.low, this * that.high) operator fun NumQ.unaryMinus(): NumQ = this.negate() operator fun NumQ.div(that: Int): NumQ = this.divide(BigInteger.valueOf(that)) operator fun NumQ.times(that: Int): NumQ = this.multiply(BigInteger.valueOf(that)) operator fun NumQ.div(that: NumQ) = this.divide(that) fun min(a: NumQ, b: NumQ): NumQ { return if (a < b) a else b } fun max(a: NumQ, b: NumQ): NumQ { return if (a > b) a else b } fun NumQ.decimalString(): String { return BigDecimal(this.numerator()).divide(BigDecimal(this.denominator())).toString() }
0
Kotlin
0
0
ed4fd35015b73ea3ac36aecb1c5a568f6be7f14c
3,372
biodivine-algebraic-toolkit
MIT License
src/main/kotlin/leetcode/Problem2222.kt
fredyw
28,460,187
false
{"Java": 1280840, "Rust": 363472, "Kotlin": 148898, "Shell": 604}
package leetcode /** * https://leetcode.com/problems/number-of-ways-to-select-buildings/ */ class Problem2222 { fun numberOfWays(s: String): Long { data class Binary(val zero: Int = 0, val one: Int = 0) val left = Array(s.length) { Binary() } for (i in s.indices) { val zero = if (s[i] == '0') 1 else 0 val one = if (s[i] == '1') 1 else 0 left[i] = if (i == 0) { Binary(zero, one) } else { Binary(zero + left[i - 1].zero, one + left[i - 1].one) } } val right = Array(s.length) { Binary() } for (i in s.length - 1 downTo 0) { val zero = if (s[i] == '0') 1 else 0 val one = if (s[i] == '1') 1 else 0 right[i] = if (i == s.length - 1) { Binary(zero, one) } else { Binary(zero + right[i + 1].zero, one + right[i + 1].one) } } var answer = 0L for (i in 1..s.length - 2) { if (s[i] == '0') { // look for 101 answer += left[i - 1].one * right[i + 1].one } else { // look for 010 answer += left[i - 1].zero * right[i + 1].zero } } return answer } }
0
Java
1
4
a59d77c4fd00674426a5f4f7b9b009d9b8321d6d
1,292
leetcode
MIT License
src/main/kotlin/be/tabs_spaces/advent2021/days/Day04.kt
janvryck
433,393,768
false
{"Kotlin": 58803}
package be.tabs_spaces.advent2021.days class Day04: Day(4) { override fun partOne(): Any { val bingoSubsystem = BingoSubsystem(inputList) return bingoSubsystem.firstWinningBoard() } override fun partTwo(): Any { val bingoSubsystem = BingoSubsystem(inputList) return bingoSubsystem.lastWinningBoard() } class BingoSubsystem(rawInput: List<String>) { private val bingoNumbers: MutableList<Int> = rawInput.first().split(",").map { it.toInt() }.toMutableList() private val boards: MutableList<Board> = rawInput.subList(1, rawInput.size).chunked(6).map { Board(it) }.toMutableList() fun firstWinningBoard() = play() fun lastWinningBoard() = play(keepPlaying = true) private fun play(keepPlaying: Boolean = false): Int { var currentNumber = 0 while (boards.none { it.isWinningBoard() }) { currentNumber = bingoNumbers.removeFirst() boards.forEach { it.crossOff(currentNumber) } if (keepPlaying && boards.size > 1) { boards.removeIf { it.isWinningBoard() } } } return boards.first { it.isWinningBoard() }.totalSum() * currentNumber } } class Board(rawBoard: List<String>) { private var matrix: List<List<Int?>> = rawBoard .filter { it.isNotBlank() } .map { it.split(" ").mapNotNull { number -> number.toIntOrNull() } } fun crossOff(number: Int) { matrix = matrix.map { row -> row.map { if (it == number) null else it }} } fun isWinningBoard(): Boolean { return matrix.any { row -> row.mapNotNull{ it }.isEmpty() } || matrix.first().indices.any { index -> matrix.mapNotNull { it[index] }.isEmpty() } } fun totalSum() = matrix.sumOf { row -> row.mapNotNull { it }.sum() } } }
0
Kotlin
0
0
f6c8dc0cf28abfa7f610ffb69ffe837ba14bafa9
1,980
advent-2021
Creative Commons Zero v1.0 Universal
src/main/kotlin/adventofcode/y2021/Day07.kt
Tasaio
433,879,637
false
{"Kotlin": 117806}
import adventofcode.* import java.math.BigInteger fun main() { val testInput = """ 16,1,2,0,4,2,7,1,2,14 """.trimIndent() val test = Day07(testInput) println("TEST: " + test.part1()) println("TEST: " + test.part2()) val day = Day07() val t1 = System.currentTimeMillis() println("${day.part1()} (${System.currentTimeMillis() - t1}ms)") day.reset() val t2 = System.currentTimeMillis() println("${day.part2()} (${System.currentTimeMillis() - t2}ms)") } open class Day07(staticInput: String? = null) : Y2021Day(7, staticInput) { private val input = fetchInputAsSingleLineInteger(",") override fun part1(): Number? { val minValue = MinValue() for (i in input.minOf { it }..input.maxOf { it }) { val sum = input.sumOf { (it - i).toBigInteger().abs() } minValue.next(sum) } return minValue.get() } override fun part2(): Number? { val minValue = MinValue() for (i in input.minOf { it }..input.maxOf { it }) { val sum = input.sumOf { fuelCost((it - i).toBigInteger().abs()) } minValue.next(sum) } return minValue.get() } val mem = hashMapOf<Int, BigInteger>() fun fuelCost(i: BigInteger): BigInteger { if (mem.containsKey(i.toInt())) return mem[i.toInt()]!! var sum = BigInteger.ZERO for (j in 1..i.toInt()) { sum += j.toBigInteger() mem[j] = sum } return sum } }
0
Kotlin
0
0
cc72684e862a782fad78b8ef0d1929b21300ced8
1,527
adventofcode2021
The Unlicense
src/main/kotlin/com/kishor/kotlin/algo/problems/arrayandstrings/SpecialPalindromeString.kt
kishorsutar
276,212,164
false
null
package com.kishor.kotlin.algo.problems.arrayandstrings import java.util.* import kotlin.text.* // Complete the substrCount function below. /** - get all combinations of the strings / O(n^2) - check all chars are same or all except one in the middle O(m) - return the count which follows the above condition O(n^2m) */ fun substrCount(n: Int, s: String): Long { var count = 0L val listOfString = getAllCombination(s) for (string in listOfString) { if (isSpecialString(string)) { count++ } } return count } fun isSpecialString(string: String): Boolean { if (string.length == 1) return true val char = string[0] val mid = 0 + (string.length - 1)/2 for (i in 1 until string.length) { if (i == mid) continue if (string[i] != char) { return false } } return true } fun getAllCombination(s: String): List<String> { val subStringList = mutableListOf<String>() for (i in s.indices) { subStringList.add(s[i].toString()) for (j in i+1 until s.length) { subStringList.add(s.substring(i, j+1)) } } return subStringList } fun main(args: Array<String>) { val scan = Scanner(System.`in`) val n = scan.nextLine().trim().toInt() val s = scan.nextLine() val result = substrCount(n, s) println(result) }
0
Kotlin
0
0
6672d7738b035202ece6f148fde05867f6d4d94c
1,376
DS_Algo_Kotlin
MIT License
src/main/kotlin/extractors/AprioriExtractor.kt
Albaross
98,739,245
false
null
package org.albaross.agents4j.extraction.extractors import org.albaross.agents4j.extraction.* import org.albaross.agents4j.extraction.bases.MultiAbstractionLevelKB import java.util.* class AprioriExtractor<A>( private val new: () -> KnowledgeBase<A> = { MultiAbstractionLevelKB() }, private val minsupp: Double = 0.0, private val minconf: Double = 0.0) : Extractor<A> { override fun extract(input: Collection<Pair<State, A>>): KnowledgeBase<A> { val kb = new() if (input.isEmpty()) return kb var items = initialize(kb, input) val n = input.first().state.size for (k in 1..n) { if (k > 1) items = merge(items, input) if (items.isEmpty()) break kb.addAll(create(items, input)) } return kb } private fun initialize(kb: KnowledgeBase<A>, input: Collection<Pair<State, A>>): List<State> { // create rules with empty premise for all actions val grouped = input.groupBy { it.action } for ((action, pairs) in grouped) { val conf = pairs / input if (conf > minconf) kb.add(Rule(emptySet(), action, conf)) } // collect all literals return input.flatMap { it.state.toList() } .distinct() .map { setOf(it) } } private fun create(items: Collection<State>, input: Collection<Pair<State, A>>): Collection<Rule<A>> { val rules = ArrayList<Rule<A>>() for (item in items) { val supp = input.filter { it.state.containsAll(item) } val grouped = supp.groupBy { it.action } for ((action, pairs) in grouped) { val conf = pairs / supp if (conf > minconf) rules.add(Rule(item, action, conf)) } } return rules } private fun merge(items: List<State>, input: Collection<Pair<State, A>>): List<State> { val merged = ArrayList<State>() val itemSet = items.toSet() // merge pairwise for (i in 0 until items.size) { for (k in (i + 1) until items.size) { val combined = (items[i] as SortedSet or items[k] as SortedSet) ?: continue // subset check for (s in combined) { val subset = combined.toMutableSet() subset.remove(s) if (subset !in itemSet) continue } // check for support if (minsupp == 0.0) { // shortcut if (input.none { it.state.containsAll(combined) }) continue } else { val supp = input.filter { it.state.containsAll(combined) } if (supp.isEmpty() || supp / input <= minsupp) continue } // provide merged state merged.add(combined) } } return merged } }
1
Kotlin
0
0
36bbbccd8ff9a88ea8745a329a446912d4de007d
3,143
agents4j-extraction
MIT License
src/main/kotlin/quantum/core/Measurement.kt
AlexanderScherbatiy
155,193,555
false
{"Kotlin": 58447}
package quantum.core import kotlin.random.Random /** * Return index of the basis which has been measured */ fun QuantumState.measureBasisIndex(): Int { val array = Array(size) { this[it].sqr() } for (i in (1 until size)) { array[i] += array[i - 1] } val probability = Random.nextDouble(1.0) for (i in 0 until size) { if (probability < array[i]) { return i } } return size - 1 } data class Measurement(val bits: Bits, val state: QuantumState) fun QuantumState.measureBits(vararg indices: Int): Measurement { val bitsSize = kotlin.math.log2(size.toDouble()).toInt() val measuredBitsMap = (0 until size) .map { it to this[it] } .groupBy { it.first.toBitsArray(bitsSize).slice(*indices) } val measuredBitsAmplitudesArray = measuredBitsMap .mapValues { it.value.map { it.second.sqr() }.sum() } .entries.toTypedArray() val probabilities = measuredBitsAmplitudesArray.map { it.value }.toDoubleArray() val measuredIndex = measureIndex(*probabilities) val measuredBits = measuredBitsAmplitudesArray[measuredIndex].key val measuredStateMap = measuredBitsMap .getOrDefault(measuredBits, listOf()) .filter { it.second != Complex.Zero } .toMap() return Measurement(measuredBits, quantumState(size, measuredStateMap)) } private fun measureIndex(vararg probabilities: Double): Int { val size = probabilities.size val array = probabilities.toTypedArray() for (i in (1 until size)) { array[i] += array[i - 1] } val probability = Random.nextDouble(1.0) for (i in 0 until size) { if (probability < array[i]) { return i } } return size - 1 }
0
Kotlin
0
0
673dd1c2a6c9964700ea682d49410d10843070db
1,794
quntum-gates
Apache License 2.0
src/nativeMain/kotlin/com.qiaoyuang.algorithm/round1/Questions50.kt
qiaoyuang
100,944,213
false
{"Kotlin": 338134}
package com.qiaoyuang.algorithm.round1 fun test50() { printlnResult1("abaccdeff") printlnResult2("We are students.", "aeiou") printlnResult3("google") printlnResult4("silent", "listen") getFirstCharacterAppearOnce(sequence { "google".forEach { yield(it) } }) } /** * Questions 50-1: Find a character in a string that just appear once */ private fun String.findCharacterWithOnce(): Char? { // The string could contain any character require(isNotEmpty()) { "The string must be not empty" } val map = HashMap<Char, Int>() forEach { c -> map[c] = 1 + (map[c] ?: 0) } return map.entries.find { it.value == 1 }?.key } private fun printlnResult1(str: String) = println("The character: '${str.findCharacterWithOnce()}' just appear once in \"$str\"") /** * Questions 50-2: Define a function that receives two string parameters a and b, delete all characters appear in b from a */ private fun deleteCharacters(a: String, b: String): String { val set = buildSet { b.forEach { if (!contains(it)) add(it) } } val builder = StringBuilder(a) var index = 0 while (index < builder.length) { if (set.contains(builder[index])) builder.deleteAt(index) else index++ } return builder.toString() } private fun printlnResult2(a: String, b: String) = println("Delete all characters in \"$b\" from \"$a\", we can get: \"${deleteCharacters(a, b)}\"") /** * Questions 50-3: Delete the repeated characters in a string */ private fun deleteRepeatCharacters(str: String): String { val builder = StringBuilder(str) val set = HashSet<Char>() var index = 0 while (index < builder.length) { if (set.contains(builder[index])) builder.deleteAt(index) else set.add(builder[index++]) } return builder.toString() } private fun printlnResult3(str: String) = println("Delete the repeated characters in \"$str\", we can get: \"${deleteRepeatCharacters(str)}\"") /** * Questions 50-4: Judge if the two words are anagrams for each other */ private infix fun String.isAnagram(str: String): Boolean { if (length != str.length) return false val map = HashMap<Char, Int>(length) forEach { map[it] = 1 + (map[it] ?: 0) } str.forEach { if (!map.containsKey(it)) return false if (map[it] == 1) map.remove(it) else map[it] = map[it]!! - 1 } return map.isEmpty() } private fun printlnResult4(a: String, b: String) = println("If \"$a\" and \"$b\" are anagrams for each other: \"${a isAnagram b}\"") /** * Questions 50-5: Find the first character that appear once in a characters sequence */ private fun getFirstCharacterAppearOnce(sequence: Sequence<Char>) { val map = HashMap<Char, Int>() sequence.forEachIndexed { index, c -> if (map.containsKey(c)) map[c] = Int.MAX_VALUE else map[c] = index println("Current the first character that appear once is: ${map.minBy { it.value }.takeIf { it.value != Int.MAX_VALUE }?.key}") } }
0
Kotlin
3
6
66d94b4a8fa307020d515d4d5d54a77c0bab6c4f
3,211
Algorithm
Apache License 2.0
aoc-2022/src/main/kotlin/nerok/aoc/aoc2022/day09/Day09.kt
nerok
572,862,875
false
{"Kotlin": 113337}
package nerok.aoc.aoc2022.day09 import nerok.aoc.utils.Input import java.util.* import kotlin.math.abs import kotlin.time.DurationUnit import kotlin.time.measureTime fun main() { fun part1(input: List<String>): Long { val H = GeoPoint(0, 0) val T = GeoPoint(0, 0) val visited = emptySet<GeoPoint>().toMutableSet() input.forEach { line -> val (direction, distance) = line.split(' ', limit = 2) // println("Direction: $direction, distance: $distance") when (direction) { "R" -> (1L..distance.toLong()).forEach { _ -> H.moveRight() if (!T.isAdjacent(H)) { T.moveTowards(H) } visited.add(T.copy()) } "U" -> (1L..distance.toLong()).forEach { _ -> H.moveUp() if (!T.isAdjacent(H)) { T.moveTowards(H) } visited.add(T.copy()) } "L" -> (1L..distance.toLong()).forEach { _ -> H.moveLeft() if (!T.isAdjacent(H)) { T.moveTowards(H) } visited.add(T.copy()) } "D" -> (1L..distance.toLong()).forEach { _ -> H.moveDown() if (!T.isAdjacent(H)) { T.moveTowards(H) } visited.add(T.copy()) } else -> {} } } return visited.size.toLong() } fun part2(input: List<String>): Long { val tail = Collections.nCopies(10, GeoPoint(0, 0)).map { it.copy() }.toMutableList() val visited = emptySet<GeoPoint>().toMutableSet() input.forEach { line -> val (direction, distance) = line.split(' ', limit = 2) when (direction) { "R" -> (1L..distance.toLong()).forEach { _ -> tail[0].moveRight() tail.windowed(2).forEach { (tmpHead, tmpTail) -> if (!tmpTail.isAdjacent(tmpHead)) { tmpTail.moveTowards(tmpHead) } } visited.add(tail.last().copy()) } "U" -> (1L..distance.toLong()).forEach { _ -> tail.first().moveUp() tail.windowed(2).forEach { (tmpHead, tmpTail) -> if (!tmpTail.isAdjacent(tmpHead)) { tmpTail.moveTowards(tmpHead) } } visited.add(tail.last().copy()) } "L" -> (1L..distance.toLong()).forEach { _ -> tail.first().moveLeft() tail.windowed(2).forEach { (tmpHead, tmpTail) -> if (!tmpTail.isAdjacent(tmpHead)) { tmpTail.moveTowards(tmpHead) } } visited.add(tail.last().copy()) } "D" -> (1L..distance.toLong()).forEach { _ -> tail.first().moveDown() tail.windowed(2).forEach { (tmpHead, tmpTail) -> if (!tmpTail.isAdjacent(tmpHead)) { tmpTail.moveTowards(tmpHead) } } visited.add(tail.last().copy()) } else -> {} } } return visited.size.toLong() } // test if implementation meets criteria from the description, like: val testInput = Input.readInput("Day09_test") check(part1(testInput) == 88L) check(part2(testInput) == 36L) val input = Input.readInput("Day09") println(measureTime { println(part1(input)) }.toString(DurationUnit.SECONDS, 3)) println(measureTime { println(part2(input)) }.toString(DurationUnit.SECONDS, 3)) } data class GeoPoint(var row: Int, var column: Int) { private fun distance(other: GeoPoint): Pair<Long, Long> { return (this.row - other.row).toLong() to (this.column - other.column).toLong() } private fun normalDistance(other: GeoPoint): Long { return maxOf(abs(this.column - other.column), abs(this.row - other.row)).toLong() } fun isAdjacent(other: GeoPoint): Boolean { return this.normalDistance(other) < 2 } fun moveUp() { row-- } fun moveDown() { row++ } fun moveRight() { column++ } fun moveLeft() { column-- } fun moveTowards(other: GeoPoint) { val (rowDistance, columnDistance) = distance(other) if (rowDistance < -1) { moveDown() if (columnDistance >= 1) { moveLeft() } else if (columnDistance <= -1) { moveRight() } } else if (rowDistance > 1) { moveUp() if (columnDistance >= 1) { moveLeft() } else if (columnDistance <= -1) { moveRight() } } else { if (columnDistance > 1) { moveLeft() if (rowDistance >= 1) { moveUp() } else if (rowDistance <= -1) { moveDown() } } else if (columnDistance < -1) { moveRight() if (rowDistance >= 1) { moveUp() } else if (rowDistance <= -1) { moveDown() } } } } }
0
Kotlin
0
0
7553c28ac9053a70706c6af98b954fbdda6fb5d2
5,828
AOC
Apache License 2.0
2021/src/Day16.kt
Bajena
433,856,664
false
{"Kotlin": 65121, "Ruby": 14942, "Rust": 1698, "Makefile": 454}
import java.util.* // https://adventofcode.com/2021/day/16 fun main() { class Packet(typeId: Int, version: Int) { val typeId = typeId val version = version var literal : Long = -1 var packets = mutableListOf<Packet>() fun isLiteral() : Boolean { return (typeId == 4) } fun compute() : Long { if (isLiteral()) return literal return when (typeId) { 0 -> packets.sumOf { it.compute() } 1 -> packets.fold(1) { acc, packet -> acc * packet.compute() } 2 -> packets.minOf { it.compute() } 3 -> packets.maxOf { it.compute() } 5 -> if (packets.first()!!.compute() > packets.last()!!.compute()) 1 else 0 6 -> if (packets.first()!!.compute() < packets.last()!!.compute()) 1 else 0 7 -> if (packets.first()!!.compute() == packets.last()!!.compute()) 1 else 0 else -> throw Exception("Bad type! ($typeId)") } } override fun toString() : String { if (isLiteral()) return "PACKET (v. $version): Literal with value:$literal" return "PACKET (v. $version, t. $typeId): Operator with ${packets.count()} sub-packets: (${packets}" } fun totalVersions() : Int { return version + packets.sumOf { it.totalVersions() } } } fun hexToBin(input: String) : String { return input.map { val binary = it.toString().toInt(16).toString(2) binary.padStart(4, '0') }.joinToString("") } // Returns <Literal value, Rest of input> fun readLiteralPacket(inputWithoutHeader: String) : Pair<Long, String> { var rest = inputWithoutHeader var literalBinary = "" var lastLiteralPart = "" var literalParts = 0 do { lastLiteralPart = rest.take(5) literalBinary += lastLiteralPart.drop(1) literalParts++ rest = rest.drop(5) } while(lastLiteralPart.first() != '0') // rest = rest.drop((literalParts) % 4) return Pair(literalBinary.toLong(2), rest) } // Returns <Packet, Rest of input> fun readPacket(input: String, level: Int = 0) : Pair<Packet, String> { println("Reading packet from $input (level: $level)") var rest = input var version = rest.take(3).toInt(2) rest = rest.drop(3) var typeId = rest.take(3).toInt(2) rest = rest.drop(3) val packet = Packet(typeId, version) if (packet.isLiteral()) { val (literal, r) = readLiteralPacket(rest) packet.literal = literal rest = r } else { val lengthType = rest.take(1) rest = rest.drop(1) if (lengthType == "0") { val subPacketsLength = rest.take(15).toInt(2) rest = rest.drop(15) val initialRestLength = rest.length while (initialRestLength - rest.length < subPacketsLength) { val (p, r) = readPacket(rest, level + 1) packet.packets.add(p) rest = r } } else { val subPacketsCount = rest.take(11).toInt(2) rest = rest.drop(11) for (i in 1..subPacketsCount) { val (p, r) = readPacket(rest, level + 1) packet.packets.add(p) rest = r } } } println("Read $packet (level:$level)") return Pair(packet, rest) } fun part1() { var input = readInput("Day16").first() var binary = hexToBin(input) var packets = mutableListOf<Packet>() while (binary.isNotEmpty() && binary.contains("1")) { var (packet, rest) = readPacket(binary) packets.add(packet) binary = rest } println("Sum of versions: ${packets.sumOf { it.totalVersions() }}") } fun part2() { var input = readInput("Day16").first() var binary = hexToBin(input) var packets = mutableListOf<Packet>() while (binary.isNotEmpty() && binary.contains("1")) { var (packet, rest) = readPacket(binary) packets.add(packet) binary = rest } println(packets.map { it.compute() }) } // part1() part2() }
0
Kotlin
0
0
a5ca56b7ac8d9d48f82dc079c8ea0cf06d17109a
3,937
advent-of-code
Apache License 2.0
lib/src/main/kotlin/com/bloidonia/advent/day10/Day10.kt
timyates
433,372,884
false
{"Kotlin": 48604, "Groovy": 33934}
package com.bloidonia.advent.day10 import com.bloidonia.advent.readList import kotlin.collections.ArrayDeque fun opener(ch: Char) = when (ch) { ')' -> '(' ']' -> '[' '}' -> '{' else -> '<' } private fun corruptScore(ch: Char) = when (ch) { ')' -> 3 ']' -> 57 '}' -> 1197 else -> 25137 } private fun completionScore(ch: Char) = when (ch) { '(' -> 1L '[' -> 2L '{' -> 3L else -> 4L } data class Score(val corrupt: Int, val autoComplete: Long) fun String.score(): Score { val expected = ArrayDeque<Char>(this.length) for (ch in this) { when (ch) { '{', '(', '[', '<' -> expected.addFirst(ch) else -> { if (expected.removeFirst() != opener(ch)) { return Score(corruptScore(ch), 0) } } } } return Score(0, expected.fold(0L) { acc: Long, c: Char -> acc * 5 + completionScore(c) }) } // Only works as the input list is an odd length fun List<Long>.median() = this.sorted()[this.size / 2] fun main() { println(readList("/day10input.txt") { it.score() }.sumOf { it.corrupt }) println(readList("/day10input.txt") { it.score().autoComplete }.filter { it > 0 }.median()) }
0
Kotlin
0
1
9714e5b2c6a57db1b06e5ee6526eb30d587b94b4
1,244
advent-of-kotlin-2021
MIT License
tasks-2/lib/src/main/kotlin/trees/structures/Graph.kt
AzimMuradov
472,473,231
false
{"Kotlin": 127576}
package trees.structures public class Graph<V, out E : Edge<V, E, EE>, out EE : EdgeEnd<V, E, EE>> private constructor( public val vertices: Set<V>, public val edges: Set<E>, public val adjList: Map<V, List<EE>>, ) { override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is Graph<*, *, *>) return false if (vertices != other.vertices) return false if (edges != other.edges) return false return true } override fun hashCode(): Int { var result = vertices.hashCode() result = 31 * result + edges.hashCode() return result } override fun toString(): String { return "Graph(vertices=$vertices, edges=$edges, adjList=$adjList)" } public companion object { public fun <V, E : Edge<V, E, EE>, EE : EdgeEnd<V, E, EE>> from( vertices: Set<V>, edges: Set<E>, ): Graph<V, E, EE> { require(edges.all { (v, u) -> v in vertices && u in vertices }) { "ERROR" } val allEdges = edges + edges.map { it.swap() } val adjList = allEdges.groupBy( keySelector = { it.from }, valueTransform = { it.edgeEnd() } ) return Graph(vertices, allEdges, adjList) } public fun <V, E : Edge<V, E, EE>, EE : EdgeEnd<V, E, EE>> from( vertices: Set<V>, adjList: Map<V, List<EE>>, ): Graph<V, E, EE> = from( vertices, edges = adjList.flatMapTo(mutableSetOf()) { (from, ends) -> ends.map { end -> end.edge(from) } } ) } } public fun <V, E : Edge<V, E, EE>, EE : EdgeEnd<V, E, EE>> graph( vertices: Set<V>, edges: Set<E>, ): Graph<V, E, EE> = Graph.from(vertices, edges) public fun <V, E : Edge<V, E, EE>, EE : EdgeEnd<V, E, EE>> graph( vertices: Set<V>, adjList: Map<V, List<EE>>, ): Graph<V, E, EE> = Graph.from(vertices, adjList)
0
Kotlin
0
0
01c0c46df9dc32c2cc6d3efc48b3a9ee880ce799
1,981
discrete-math-spbu
Apache License 2.0
kt/problem_493.main.kts
dfings
31,622,045
false
{"Go": 12328, "Kotlin": 12241, "Clojure": 11585, "Python": 9457, "Haskell": 8314, "Dart": 5990, "Rust": 5389, "TypeScript": 4158, "Elixir": 3093, "F#": 2745, "C++": 1608}
#!/usr/bin/env kotlin import java.math.BigDecimal import java.math.RoundingMode val NUM_COLORS = 7 val NUM_PER_COLOR = 10 val NUM_TO_PICK = 20 val SUM_ALL_PICKED = NUM_COLORS * NUM_PER_COLOR - NUM_TO_PICK /** * Represents the state of the urn. The slots are the colors, and the value of the slot is the * number of balls left for that color. */ class Urn(val slots: List<Int>) { fun colorsPicked(): Int = slots.count { it < NUM_PER_COLOR } fun allPicked() = slots.sum() == SUM_ALL_PICKED fun cacheKey() = slots.sorted() fun pick(color: Int) = Urn(slots.mapIndexed { i, count -> if (i == color) count - 1 else count }) } /** * Consider the ways to pick colors from the urn as a tree with depth NUM_TO_PICK and * a branching factor of the number of balls left at each node. For any given node, the class * encapsulate the stats for all leaves below that node (i.e., all possible ways to pick from this * node). * @val totalColorsPicks Sum of colors picked across each leaf * @val totalPicks Total number of leaves below this node */ data class UrnStats(val totalColorsPicked: BigDecimal, val totalPicks: BigDecimal) { fun average() = totalColorsPicked.divide(totalPicks, 12, RoundingMode.UP) operator fun plus(other: UrnStats) = UrnStats(totalColorsPicked + other.totalColorsPicked, totalPicks + other.totalPicks) } /** * The stats at a given node are the same for any other node with the same color histogram shape, * ignoring the specific colors. For example, [1 2 3 4 5 6 7] and [7, 6, 5, 4, 3, 2, 1] will have * the same stats due to symmetry. Thus we can memoize computing the stats by sorting the slots. */ val urnCache = hashMapOf<List<Int>, UrnStats>() fun urnStats(urn: Urn): UrnStats = urnCache.getOrPut(urn.cacheKey()) { if (urn.allPicked()) { UrnStats(urn.colorsPicked().toBigDecimal(), 1.toBigDecimal()) } else { // Branch by each possible pick. (0..NUM_COLORS - 1).flatMap { color -> (1..urn.slots[color]).map { urnStats(urn.pick(color)) } }.reduce(UrnStats::plus) } } val urn = Urn(IntArray(NUM_COLORS) { NUM_PER_COLOR }.asList()) val stats = urnStats(urn) println("Total colors = ${stats.totalColorsPicked}") println("Total picks = ${stats.totalPicks}") println("Cache size = ${urnCache.size}") println("Average = %.9f".format(stats.average()))
0
Go
0
0
f66389dcd8ff4e4d64fbd245cfdaebac7b9bd4ef
2,324
project-euler
The Unlicense
src/main/kotlin/kr/co/programmers/P87377.kt
antop-dev
229,558,170
false
{"Kotlin": 695315, "Java": 213000}
package kr.co.programmers // https://school.programmers.co.kr/learn/courses/30/lessons/87377 class P87377 { fun solution(line: Array<IntArray>): Array<String> { // 교점 좌표를 기록할 Set val set = mutableSetOf<Pair<Long, Long>>() // 가장자리 좌표 var minX = Long.MAX_VALUE var maxX = Long.MIN_VALUE var minY = Long.MAX_VALUE var maxY = Long.MIN_VALUE // Int * Int = Long 이 될 수 있기 때문에 처음부터 Long 변환 후 계산한다. val rows = line.map { (a, b, c) -> longArrayOf(a.toLong(), b.toLong(), c.toLong()) } for (i in 0 until rows.size - 1) { for (j in i + 1 until rows.size) { val (a, b, e) = rows[i] val (c, d, f) = rows[j] // 교점 계산식 val adbc = (a * d) - (b * c) val bfed = (b * f) - (e * d) val ecaf = (e * c) - (a * f) // 평행하거나 좌표가 정수가 아니면 패스 if (adbc == 0L || bfed % adbc != 0L || ecaf % adbc != 0L) continue // 교점 기록 val x = bfed / adbc val y = ecaf / adbc set += x to y // 좌표의 최대치 minX = minOf(minX, x) maxX = maxOf(maxX, x) minY = minOf(minY, y) maxY = maxOf(maxY, y) } } // "*" 찍기 val row = (maxY - minY + 1).toInt() val col = (maxX - minX + 1).toInt() val arr = Array(row) { CharArray(col) { '.' } } for ((x, y) in set) { arr[(maxY - y).toInt()][(x - minX).toInt()] = '*' } // List → Array return arr.map { it.joinToString("") }.toTypedArray() } }
1
Kotlin
0
0
9a3e762af93b078a2abd0d97543123a06e327164
1,849
algorithm
MIT License
src/Day10.kt
andrewgadion
572,927,267
false
{"Kotlin": 16973}
fun main() { fun interpret(input: List<String>) = sequence { var x = 1L input.forEach { yield(x) if (it.startsWith("addx")) { yield(x) x += it.split(" ")[1].toLong() } } } fun part1(input: List<String>) = interpret(input) .mapIndexed { index, l -> index + 1 to l } .filter { (20..220 step 40).contains(it.first) } .sumOf { it.first * it.second } fun part2(input: List<String>) = interpret(input) .chunked(40) .joinToString("\n") { it.mapIndexed { pI, x -> if ((x..x + 2).contains(pI + 1)) "#" else "." }.joinToString("") } val input = readInput("day10") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
4d091e2da5d45a786aee4721624ddcae681664c9
811
advent-of-code-2022
Apache License 2.0
src/main/kotlin/com/github/ferinagy/adventOfCode/aoc2022/2022-22.kt
ferinagy
432,170,488
false
{"Kotlin": 787586}
package com.github.ferinagy.adventOfCode.aoc2022 import com.github.ferinagy.adventOfCode.CharGrid import com.github.ferinagy.adventOfCode.Coord2D import com.github.ferinagy.adventOfCode.contains import com.github.ferinagy.adventOfCode.get import com.github.ferinagy.adventOfCode.println import com.github.ferinagy.adventOfCode.readInputText import kotlin.math.abs fun main() { val input = readInputText(2022, "22-input") val testInput1 = readInputText(2022, "22-test1") println("Part1:") part1(testInput1).println() part1(input).println() println() println("Part2:") part2(testInput1, 4).println() part2(input, 50).println() } private fun part1(input: String): Int { return solve(input, 0, ::nextPosition2d) } private fun part2(input: String, size: Int): Int { return solve(input, size, ::nextPosition3d) } private fun solve( input: String, size: Int, newPosition: (Coord2D, Coord2D, CharGrid, Int) -> Pair<Coord2D, Coord2D> ): Int { val (map, path) = input.split("\n\n") val lines = map.lines() val width = lines.maxOf { it.length } val grid = CharGrid(width, lines.size) { x, y -> lines[y].getOrElse(x) { ' ' } } val instructions = path.split("(?=[RL])".toRegex()).mapIndexed { index, s -> if (index == 0) "R$s" else s } var position = Coord2D(x = grid.xRange.first { grid[it, 0] != ' ' }, y = 0) var direction = Coord2D(x = 0, y = -1) instructions.forEach { instruction -> direction = if (instruction.first() == 'R') { direction.rotate(1, 1) } else { direction.rotate(3, 1) } val steps = instruction.drop(1).toInt() for (i in 1..steps) { val (newPosition, newDirection) = newPosition(position, direction, grid, size) if (grid[newPosition] == '#') break position = newPosition direction = newDirection } } return result(position, direction) } private fun nextPosition2d(position: Coord2D, direction: Coord2D, grid: CharGrid, size: Int): Pair<Coord2D, Coord2D> { var newPosition = (position + direction).wrapIn(grid) while (grid[newPosition] == ' ') newPosition = (newPosition + direction).wrapIn(grid) return newPosition to direction } private fun nextPosition3d(position: Coord2D, direction: Coord2D, grid: CharGrid, size: Int): Pair<Coord2D, Coord2D> { var newPosition = position + direction var newDirection = direction if (newPosition !in grid || grid[newPosition] == ' ') { data class Config(val rotate: Int, val final: Coord2D, val path: List<Coord2D>) val onFace = Coord2D(x = position.x % size, y = position.y % size) val right = direction.rotate(1, 1) val configs = listOf( Config(1, Coord2D(0, 1), listOf(Coord2D(1, 0), Coord2D(1, 1))), Config(3, Coord2D(0, 1), listOf(Coord2D(-1, 0), Coord2D(-1, 1))), Config(2, Coord2D(-2, 2), listOf(Coord2D(-1, 0), Coord2D(-2, 0), Coord2D(-2, 1))), Config(2, Coord2D(2, 0), listOf(Coord2D(0, -1), Coord2D(1, -1), Coord2D(2, -1))), Config(1, Coord2D(-2, -3), listOf(Coord2D(0, -1), Coord2D(0, -2), Coord2D(-1, -2), Coord2D(-1, -3))), Config( 0, Coord2D(-2, -4), listOf(Coord2D(0, -1), Coord2D(-1, -1), Coord2D(-1, -2), Coord2D(-1, -3), Coord2D(-2, -3)) ), Config( 0, Coord2D(-2, -4), listOf(Coord2D(-1, 0), Coord2D(-1, -1), Coord2D(-1, -2), Coord2D(-2, -2), Coord2D(-2, -3)) ), Config(3, Coord2D(4, -1), listOf(Coord2D(1, 0), Coord2D(1, -1), Coord2D(2, -1), Coord2D(3, -1))), ) val config = configs.single { (_, _, path) -> path.all { val check = position + (direction * size * it.y) + (right * size * it.x) check in grid && grid[check] != ' ' } } val newDir = direction.rotate(config.rotate, 1) val emptyNeighbor = position + (direction * size * config.final.y) + (right * size * config.final.x) val pair = emptyNeighbor - onFace + onFace.rotate(config.rotate, size) + newDir to newDir newPosition = pair.first newDirection = pair.second } return Pair(newPosition, newDirection) } private fun result(position: Coord2D, direction: Coord2D): Int { val dir = abs(direction.x) * (1 - direction.x) + abs(direction.y) * (2 - direction.y) return (position.y + 1) * 1000 + (position.x + 1) * 4 + dir } private fun Coord2D.wrapIn(grid: CharGrid) = if (grid.width <= x || y <= grid.height) Coord2D(x.mod(grid.width), y.mod(grid.height)) else this private fun Coord2D.rotate(times: Int, size: Int): Coord2D = if (times == 0) this else Coord2D(x = size - 1 - y, y = x).rotate(times - 1, size)
0
Kotlin
0
1
f4890c25841c78784b308db0c814d88cf2de384b
4,883
advent-of-code
MIT License
src/aoc2022/Day09.kt
anitakar
576,901,981
false
{"Kotlin": 124382}
package aoc2022 import println import readInput fun main() { data class Position(val x: Int, val y: Int) fun part1(input: List<String>): Int { val moveRegex = """(\w) (\d+)""".toRegex() var head = Position(0, 0) var tail = Position(0, 0) val unique = mutableSetOf<Position>() unique.add(Position(0, 0)) for (line in input) { val match = moveRegex.find(line) val (dir, steps) = match!!.destructured val xInc = when (dir) { "R" -> 1 "L" -> -1 else -> 0 } val yInc = when (dir) { "U" -> 1 "D" -> -1 else -> 0 } for (i in 0 until steps.toInt()) { head = Position(head.x + xInc, head.y + yInc) if (tail.y == head.y && head.x - tail.x == 2) { tail = Position(tail.x + 1, tail.y) } else if (tail.y == head.y && head.x - tail.x == -2) { tail = Position(tail.x - 1, tail.y) } else if (tail.x == head.x && head.y - tail.y == 2) { tail = Position(tail.x, tail.y + 1) } else if (tail.x == head.x && head.y - tail.y == -2) { tail = Position(tail.x, tail.y - 1) } else if (Math.abs(tail.x - head.x) + Math.abs(tail.y - head.y) > 2) { if (head.x > tail.x) { tail = Position(tail.x + 1, tail.y) } else { tail = Position(tail.x - 1, tail.y) } if (head.y > tail.y) { tail = Position(tail.x, tail.y + 1) } else { tail = Position(tail.x, tail.y - 1) } } unique.add(tail) } } return unique.size } fun part2(input: List<String>): Int { val moveRegex = """(\w) (\d+)""".toRegex() var knots = mutableListOf<Position>( Position(0, 0), Position(0, 0), Position(0, 0), Position(0, 0), Position(0, 0), Position(0, 0), Position(0, 0), Position(0, 0), Position(0, 0), Position(0, 0), ) val unique = mutableSetOf<Position>() unique.add(Position(0, 0)) for (line in input) { val match = moveRegex.find(line) val (dir, steps) = match!!.destructured val xInc = when (dir) { "R" -> 1 "L" -> -1 else -> 0 } val yInc = when (dir) { "U" -> 1 "D" -> -1 else -> 0 } for (i in 0 until steps.toInt()) { knots[0] = Position(knots[0].x + xInc, knots[0].y + yInc) for (i in 1 until knots.size) { var head = knots[i - 1] var tail = knots[i] if (tail.y == head.y && head.x - tail.x == 2) { tail = Position(tail.x + 1, tail.y) } else if (tail.y == head.y && head.x - tail.x == -2) { tail = Position(tail.x - 1, tail.y) } else if (tail.x == head.x && head.y - tail.y == 2) { tail = Position(tail.x, tail.y + 1) } else if (tail.x == head.x && head.y - tail.y == -2) { tail = Position(tail.x, tail.y - 1) } else if (Math.abs(tail.x - head.x) + Math.abs(tail.y - head.y) > 2) { if (head.x > tail.x) { tail = Position(tail.x + 1, tail.y) } else { tail = Position(tail.x - 1, tail.y) } if (head.y > tail.y) { tail = Position(tail.x, tail.y + 1) } else { tail = Position(tail.x, tail.y - 1) } } knots[i] = tail } unique.add(knots[9]) } } return unique.size } // test if implementation meets criteria from the description, like: val testInput = readInput("Day09_test") check(part1(testInput) == 13) check(part2(testInput) == 1) val testInput2 = readInput("Day09_test2") check(part2(testInput2) == 36) val input = readInput("Day09") part1(input).println() part2(input).println() }
0
Kotlin
0
1
50998a75d9582d4f5a77b829a9e5d4b88f4f2fcf
4,693
advent-of-code-kotlin
Apache License 2.0
src/main/kotlin/me/dkim19375/adventofcode2022/day/Day7.kt
dkim19375
573,172,567
false
{"Kotlin": 13147}
package me.dkim19375.adventofcode2022.day import me.dkim19375.adventofcode2022.AdventOfCodeDay object Day7 : AdventOfCodeDay() { @JvmStatic fun main(args: Array<String>) = solve() override val day: Int = 7 override fun solve() { val input = getInputString().lines() val files = FolderData() var directory = "" for (inputLine in input) { val split = inputLine.split(' ') if (split[0] == "$") { if (split[1] != "cd") { continue } val cdTo = split[2] if (cdTo == "..") { directory = directory.split("/").dropLast(1).joinToString("/") continue } if (cdTo == "/") { directory = "" continue } directory += "/$cdTo" directory = directory.removePrefix("/") continue } val size = split[0].toIntOrNull() val name = split[1] var newFiles = files if (directory.isNotBlank()) { for (folder in directory.split("/")) { val subFolder = newFiles.subFolders[folder] if (subFolder != null) { newFiles = subFolder continue } val newFolder = FolderData() newFiles.subFolders[folder] = newFolder newFiles = newFolder } } if (size != null) { newFiles.files.add(FileData(name, size)) continue } newFiles.subFolders[name] = FolderData() } fun addSum(folder: FolderData): Int = folder.subFolders.values.sumOf(::addSum) + (folder.getSize().takeIf { it <= 100000 } ?: 0) val sum = addSum(files) var smallest = Int.MAX_VALUE val sizeNeeded = 30000000 - (70000000 - files.getSize()) fun calculateSmallest(folder: FolderData) { val size = folder.getSize() if (size >= sizeNeeded) { smallest = minOf(smallest, size) } folder.subFolders.values.forEach(::calculateSmallest) } calculateSmallest(files) println( """ Part 1: $sum Part 2: $smallest """.trimIndent() ) } } private data class FileData( val name: String, val size: Int, ) private data class FolderData( val files: MutableSet<FileData> = mutableSetOf(), val subFolders: MutableMap<String, FolderData> = mutableMapOf(), ) { fun getSize(): Int = files.sumOf(FileData::size) + subFolders.values.sumOf(FolderData::getSize) }
1
Kotlin
0
0
f77c4acec08a4eca92e6d68fe2a5302380688fe6
2,856
AdventOfCode2022
The Unlicense
src/chapter3/section2/ex26_ExactProbabilities.kt
w1374720640
265,536,015
false
{"Kotlin": 1373556}
package chapter3.section2 import chapter1.section4.factorial import chapter2.sleep import edu.princeton.cs.algs4.StdDraw import extensions.formatDouble /** * 准确的概率 * 计算用N个随机的互不相同的键构造出练习3.2.9中每一棵树的概率 * * 解:创建一个新类,继承BinarySearchTree,并实现Comparable接口, * 以二叉查找树为key,出现次数为value,将3.2.9中未去重的全量二叉查找树列表依次插入另一颗二叉查找树中, * 遍历所有二叉查找树,打印出二叉查找树的图形以及概率 */ fun ex26_ExactProbabilities(N: Int, delay: Long) { val allBinaryTree = createAllComparableBST(N) val bst = BinarySearchTree<ComparableBST<Int, Int>, Int>() allBinaryTree.forEach { tree -> val count = bst.get(tree) if (count == null) { bst.put(tree, 1) } else { bst.put(tree, count + 1) } } val total = allBinaryTree.size bst.keys().forEach { tree -> drawBST(tree) val count = bst.get(tree) ?: 1 StdDraw.textLeft(0.02, 0.98, "${count}/$total = ${formatDouble(count.toDouble() / total * 100, 2)}%") sleep(delay) } } fun createAllComparableBST(N: Int): Array<ComparableBST<Int, Int>> { val array = Array(N) { it + 1 } val list = ArrayList<Array<Int>>() fullArray(array, 0, list) check(list.size == factorial(N).toInt()) return Array(list.size) { index -> ComparableBST<Int, Int>().apply { list[index].forEach { key -> put(key, 0) } } } } /** * 可比较大小的二叉查找树 */ class ComparableBST<K : Comparable<K>, V : Any> : BinarySearchTree<K, V>(), Comparable<ComparableBST<K, V>> { override fun compareTo(other: ComparableBST<K, V>): Int { return compare(this.root, other.root) } fun compare(node1: Node<K, V>?, node2: Node<K, V>?): Int { if (node1 == null && node2 == null) return 0 if (node1 == null) return -1 if (node2 == null) return 1 val result1 = node1.key.compareTo(node2.key) if (result1 != 0) return result1 val result2 = compare(node1.left, node2.left) if (result2 != 0) return result2 return compare(node1.right, node2.right) } } fun main() { val N = 5 val delay = 1000L ex26_ExactProbabilities(N, delay) }
0
Kotlin
1
6
879885b82ef51d58efe578c9391f04bc54c2531d
2,408
Algorithms-4th-Edition-in-Kotlin
MIT License
kotlinLeetCode/src/main/kotlin/leetcode/editor/cn/[113]路径总和 II.kt
maoqitian
175,940,000
false
{"Kotlin": 354268, "Java": 297740, "C++": 634}
import java.util.* import javax.swing.tree.TreeNode import kotlin.collections.ArrayList //给你二叉树的根节点 root 和一个整数目标和 targetSum ,找出所有 从根节点到叶子节点 路径总和等于给定目标和的路径。 // // 叶子节点 是指没有子节点的节点。 // // // // // // 示例 1: // // //输入:root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22 //输出:[[5,4,11,2],[5,8,4,5]] // // // 示例 2: // // //输入:root = [1,2,3], targetSum = 5 //输出:[] // // // 示例 3: // // //输入:root = [1,2], targetSum = 0 //输出:[] // // // // // 提示: // // // 树中节点总数在范围 [0, 5000] 内 // -1000 <= Node.val <= 1000 // -1000 <= targetSum <= 1000 // // // // Related Topics 树 深度优先搜索 回溯 二叉树 // 👍 614 👎 0 //leetcode submit region begin(Prohibit modification and deletion) /** * 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 { var res: ArrayList<List<Int>> = ArrayList() var path: ArrayList<Int> = ArrayList() fun pathSum(root: TreeNode?, targetSum: Int): List<List<Int>> { //方法一 DFS //深度优先遍历 dfs(root,targetSum) return res //方法二 BFS //二叉树层序遍历 时间复杂度 O(n) //使用两个队列,一个存储结点,一个存储从根结点到当前节点的路径 var res = ArrayList<ArrayList<Int>>() if (root == null) return res var queue = LinkedList<TreeNode>() var queueList = LinkedList<ArrayList<Int>>() //根节点的路径入队 val list: ArrayList<Int> = ArrayList() queue.addFirst(root) list.add(root.`val`) queueList.add(list) while (!queue.isEmpty()){ val node = queue.removeLast() //获取当前队列 val templist = queueList.removeLast() //符合条件 保存对应队列 if (node.`val` == targetSum && node.left == null && node.right == null){ res.add(templist) } //不符合条件 继续遍历 if (node.left != null) { templist.add(node.left.`val`) //加入下一层的路径list queueList.addFirst(ArrayList(templist)) node.left.`val` += node.`val` queue.addFirst(node.left) //当前队列删除无用数据 templist.removeAt(templist.size-1) } if (node.right != null) { templist.add(node.right.`val`) //加入下一层的路径list queueList.addFirst(ArrayList(templist)) node.right.`val` += node.`val` queue.addFirst(node.right) } } return res } private fun dfs(root: TreeNode?, targetSum: Int) { //递归结束条件 if (root == null) return //逻辑处理 进入下层循环 var tempSum = targetSum path.add(root.`val`) tempSum -= root.`val` //符合条件 保存对应队列 if (0 == tempSum && root.left == null && root.right == null){ res.add(ArrayList<Int>(path)) } //继续遍历 dfs(root.left,tempSum) dfs(root.right,tempSum) //数据reverse path.removeAt(path.size -1) } } //leetcode submit region end(Prohibit modification and deletion)
0
Kotlin
0
1
8a85996352a88bb9a8a6a2712dce3eac2e1c3463
3,707
MyLeetCode
Apache License 2.0
src/Day03.kt
nikolakasev
572,681,478
false
{"Kotlin": 35834}
fun main() { fun part1(input: List<String>): Int { return input.sumOf { val firstHalf = it.chunked(it.length/2)[0].toCharArray().toSet() val secondHalf = it.chunked(it.length/2)[1].toCharArray().toSet() val asciiCode = (firstHalf intersect secondHalf).first().code.toByte() if (asciiCode >= 97) asciiCode - 96 else asciiCode - 38 } } fun part2(input: List<String>): Int { return input.chunked(3).sumOf { val first = it[0].toCharArray().toSet() val second = it[1].toCharArray().toSet() val third = it[2].toCharArray().toSet() val asciiCode = (first intersect second intersect third).first().code.toByte() if (asciiCode >= 97) asciiCode - 96 else asciiCode - 38 } } val testInput = readLines("Day03_test") check(part1(testInput) == 157) check(part2(testInput) == 70) val input = readLines("Day03") println(part1(input)) println(part2(input)) }
0
Kotlin
0
1
5620296f1e7f2714c09cdb18c5aa6c59f06b73e6
1,032
advent-of-code-kotlin-2022
Apache License 2.0
src/main/kotlin/d9/d9.kt
LaurentJeanpierre1
573,454,829
false
{"Kotlin": 118105}
package d9 import readInput import java.lang.IllegalArgumentException import java.util.Scanner data class Point(val x : Int, val y: Int) {} fun moveHead(pt : Point, dir: String) : Point = when(dir) { "U" -> Point(pt.x, pt.y+1) "D" -> Point(pt.x, pt.y-1) "L" -> Point(pt.x-1, pt.y) "R" -> Point(pt.x+1, pt.y) else -> throw IllegalArgumentException(dir) } fun moveTail(head: Point, tail: Point): Point { var dx = head.x - tail.x var dy = head.y - tail.y if (dx in -1..+1 && dy in -1..+1) return tail if (dx==-2 || dx==+2) if (dy in -1.. +1) return Point(tail.x + dx/2, head.y) if (dy==-2 || dy==+2) if (dx in -1.. +1) return Point(head.x , tail.y + dy/2) if (dx<=-2) dx = -1 if (dy<=-2) dy = -1 if (dx>=+2) dx = +1 if (dy>=+2) dy = +1 return Point(tail.x + dx, tail.y + dy) } fun part1(input: List<String>): Int { var head = Point(0,0) var tail = Point(0,0,) val positions = mutableSetOf<Point>(tail) for (line in input) { val scan = Scanner(line) val dir = scan.next() val count = scan.nextInt() repeat(count) { println(dir) head = moveHead(head, dir) tail = moveTail(head, tail) println("$head - $tail") positions.add(tail) } } return positions.size } fun part2(input: List<String>): Int { var head = Point(0,0) val tail = mutableListOf<Point>() tail.addAll(List(9) {Point(0,0,)} ) val positions = mutableSetOf<Point>() for (line in input) { val scan = Scanner(line) val dir = scan.next() val count = scan.nextInt() repeat(count) { println(dir) head = moveHead(head, dir) var prec = head for ((idx,node) in tail.withIndex()) { val next = moveTail(prec, node) tail[idx] = next prec = next } print("$head") tail.forEach{print(" - $it")} println() positions.add(prec) } } return positions.size } fun main() { //val input = readInput("d9/test") //val input = readInput("d9/test2") val input = readInput("d9/input1") //println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
5cf6b2142df6082ddd7d94f2dbde037f1fe0508f
2,354
aoc2022
Creative Commons Zero v1.0 Universal
src/main/kotlin/dev/shtanko/algorithms/leetcode/ConcatenatedWords.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 /** * 472. Concatenated Words * @see <a href="https://leetcode.com/problems/concatenated-words/">Source</a> */ fun interface ConcatenatedWords { fun findAllConcatenatedWordsInADict(words: Array<String>): List<String> } class ConcatenatedWordsDP : ConcatenatedWords { override fun findAllConcatenatedWordsInADict(words: Array<String>): List<String> { words.sortWith { w1, w2 -> w1.length - w2.length } val ans: MutableList<String> = ArrayList() val dict: MutableSet<String> = HashSet() for (w in words) { val dp = BooleanArray(w.length + 1) dp[0] = true for (i in 1..w.length) { for (j in i downTo -1 + 1) { if (dp[j] && dict.contains(w.substring(j, i))) { dp[i] = true break } } } if (w.isNotEmpty() && dp[w.length]) ans.add(w) dict.add(w) } return ans } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,655
kotlab
Apache License 2.0
src/leetcodeProblem/leetcode/editor/en/TwoSum.kt
faniabdullah
382,893,751
false
null
//Given an array of integers nums and an integer target, return indices of the //two numbers such that they add up to target. // // You may assume that each input would have exactly one solution, and you may //not use the same element twice. // // You can return the answer in any order. // // // Example 1: // // //Input: nums = [2,7,11,15], target = 9 //Output: [0,1] //Output: Because nums[0] + nums[1] == 9, we return [0, 1]. // // // Example 2: // // //Input: nums = [3,2,4], target = 6 //Output: [1,2] // // // Example 3: // // //Input: nums = [3,3], target = 6 //Output: [0,1] // // // // Constraints: // // // 2 <= nums.length <= 10⁴ // -10⁹ <= nums[i] <= 10⁹ // -10⁹ <= target <= 10⁹ // Only one valid answer exists. // // // //Follow-up: Can you come up with an algorithm that is less than O(n²) time //complexity? Related Topics Array Hash Table 👍 25239 👎 820 package leetcodeProblem.leetcode.editor.en class TwoSum { fun solution() { } //below code is used to auto submit to leetcode.com (using ide plugin) //leetcode submit region begin(Prohibit modification and deletion) class Solution { fun twoSum(nums: IntArray, target: Int): IntArray { val mutableMap = mutableMapOf<Int, Int>() nums.forEachIndexed { index, it -> if (mutableMap.containsKey(target - it)) { return intArrayOf(mutableMap[target - it] ?: 0, index) } else { mutableMap[it] = index } } return intArrayOf() } } //leetcode submit region end(Prohibit modification and deletion) } fun main() {}
0
Kotlin
0
6
ecf14fe132824e944818fda1123f1c7796c30532
1,698
dsa-kotlin
MIT License
src/day01/Code.kt
ldickmanns
572,675,185
false
{"Kotlin": 48227}
package day01 import readInput fun main() { val input = readInput("day01/input") val inputAsInt = input.map { if (it.isEmpty()) null else it.toInt() } println(part1(inputAsInt)) println(part2(inputAsInt)) } fun part1(input: List<Int?>): Int { var max = Int.MIN_VALUE input.fold(0) { acc, curr -> curr?.let { acc + curr } ?: run { if (acc > max) max = acc 0 } } return max } fun part2(input: List<Int?>): Int { val maxes = mutableListOf(0, 0, 0) input.fold(0) { acc, curr -> curr?.let { acc + curr } ?: run { if (maxes.min() < acc) { maxes.removeFirst() maxes.add(acc) maxes.sort() } 0 } } println(maxes) return maxes.sum() }
0
Kotlin
0
0
2654ca36ee6e5442a4235868db8174a2b0ac2523
874
aoc-kotlin-2022
Apache License 2.0
src/main/kotlin/days/Day23.kt
andilau
399,220,768
false
{"Kotlin": 85768}
package days @AdventOfCodePuzzle( name = "<NAME>", url = "https://adventofcode.com/2020/day/23", date = Date(day = 23, year = 2020) ) class Day23(val input: String) : Puzzle { override fun partOne(): String { return CupGame(input) .playRounds(100) .getCupsAfter(1) .getCupsAsString() } override fun partTwo(): Long { return CupGame(input, 1_000_000) .playRounds(10_000_000) .getCupsAfter(1) .take(2) .map { it.toLong() } .reduce { a, b -> a * b } } fun playRoundsAndGetCups(times: Int = 100) = CupGame(input) .playRounds(times) .getCupsAfter(1) .getCupsAsString() /* input: 389125467 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | #cup | 2 | 5 | 8 | 6 | 4 | 7 | 3 | 9 | 1 | points to #cup */ class CupGame(val input: String, numberOfCups: Int = input.length) { private val nextCupOf: IntArray = IntArray(numberOfCups + 1) { it + 1 } private val cups: List<Int> = input.map(Character::getNumericValue) private var currentCup: Int = cups.first() init { cups.zipWithNext { a, b -> nextCupOf[a] = b } nextCupOf[cups.last()] = cups.first() if (cups.size < numberOfCups) { // nextCupOf elements are preset in property initializer nextCupOf[cups.last()] = cups.size + 1 nextCupOf[numberOfCups] = cups.first() } } fun playRounds(times: Int): CupGame { repeat(times) { val a = nextCupOf[currentCup] val b = nextCupOf[a] val c = nextCupOf[b] val destination = findDestination(currentCup, a, b, c) // link currentCup nextCupOf[currentCup] = nextCupOf[c] currentCup = nextCupOf[currentCup] // link three elements val save = nextCupOf[destination] nextCupOf[destination] = a nextCupOf[c] = save } return this } fun getCupsAfter(cup: Int): Sequence<Int> { var current = nextCupOf[cup] return sequence { while (current != cup) { yield(current) current = nextCupOf[current] } } } private fun findDestination(cup: Int, a: Int, b: Int, c: Int): Int { var position = cup - 1 while (true) { if (position != a && position != b && position != c && position >= 1) break if (position == 0) position = nextCupOf.size - 1 else position-- } return position } } private fun Sequence<Int>.getCupsAsString(): String = joinToString("") }
7
Kotlin
0
0
2809e686cac895482c03e9bbce8aa25821eab100
2,895
advent-of-code-2020
Creative Commons Zero v1.0 Universal
src/main/kotlin/adventofcode2020/Day07HandyHaversacks.kt
n81ur3
484,801,748
false
{"Kotlin": 476844, "Java": 275}
package adventofcode2020 class Day07HandyHaversacks data class Bag(val type: String, val color: String, val canContain: Pair<Bag, Int>?) { val bagName: String get() = type + " " + color fun containsBag(type: String, color: String, count: Int, recursive: Boolean = false): Boolean { if (recursive) { if (this.type == type && this.color == color) return true } val result = false canContain ?: return false val (containingBag, containingCount) = canContain if (containingBag.type == type && containingBag.color == color) return true else if (containingBag.canContain != null) return containingBag.canContain.first.containsBag( type, color, count, recursive = true ) return result } fun containingBags(): List<Pair<Bag, Int>> { val result = mutableListOf<Pair<Bag, Int>>() var currentPair = canContain while (currentPair != null) { result.add(Bag(currentPair.first.type, currentPair.first.color, null) to currentPair.second) currentPair = currentPair.first.canContain } return result } fun getNumberOfContainingBags(): Int { canContain ?: return 1 return canContain.second + canContain.first.getNumberOfContainingBags() } } object BagCreator { fun createBag(input: String): Bag { if (!input.contains(',')) { val parts = input.split(" ") val type = parts[0] val color = parts[1] if (parts.size == 3 || parts[4] == "no") return Bag(type, color, null) val otherType = parts[5] val otherColor = parts[6] return Bag(type, color, Pair(Bag(otherType, otherColor, null), parts[4].toInt())) } else { val subbags = input.split(".") val part = subbags[0].trim() val parts = part.split(" ") val type = parts[0] val color = parts[1] val count = parts[4] val otherType = parts[5] val otherColor = parts[6] if (subbags.size == 1) { return Bag(type, color, Pair(Bag(otherType, otherColor, null), count.toInt())) } else { val remaining = input.substringAfter(",").trim() val (remainingCount, remainingBag) = createBagWithCount(remaining) return Bag( type, color, Pair( Bag( otherType, otherColor, Pair(remainingBag, remainingCount) ), count.toInt() ) ) } } } fun createBagWithCount(input: String): Pair<Int, Bag> { val count = input.first { it.isDigit() }.toString() var remaining = input.substring(input.indexOf(count) + 2).trim() remaining = remaining.replaceFirst(", ", " contains ") return Pair(Integer.parseInt(count), createBag(remaining)) } } data class HandBag( val type: String, val color: String, val canContain: MutableList<Pair<HandBag, Int>> = mutableListOf() ) { val name: String get() = type + " " + color companion object { fun from(input: String): HandBag { if (!input.contains(',')) { val parts = input.split(" ") val type = parts[0] val color = parts[1] if (parts.size == 3 || parts[4] == "no") return HandBag(type, color) val otherCount = parts[4].toInt() val otherType = parts[5] val otherColor = parts[6] return HandBag(type, color, mutableListOf(Pair(HandBag(otherType, otherColor), otherCount))) } else { val firstBag = input.substringBefore("contain").trim().split(" ") val result = HandBag(firstBag[0], firstBag[1]) val subbags = input.substringAfter("contain").trim().split(",") val containingBags = mutableListOf<Pair<HandBag, Int>>() subbags.forEach { containingBags.add(handBagFromString(it)) } result.canContain.addAll(containingBags) return result } } private fun handBagFromString(input: String): Pair<HandBag, Int> { val parts = input.trim().split(" ") return Pair(HandBag(parts[1], parts[2]), parts[0].toInt()) } } }
0
Kotlin
0
0
fdc59410c717ac4876d53d8688d03b9b044c1b7e
4,635
kotlin-coding-challenges
MIT License
day10/Kotlin/day10.kt
Ad0lphus
353,610,043
false
{"C++": 195638, "Python": 139359, "Kotlin": 80248}
import java.io.* import java.util.* fun print_day_10() { val yellow = "\u001B[33m" val reset = "\u001b[0m" val green = "\u001B[32m" println(yellow + "-".repeat(25) + "Advent of Code - Day 10" + "-".repeat(25) + reset) println(green) val process = Runtime.getRuntime().exec("figlet Syntax Scoring -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_10() Day10().part_1() Day10().part_2() println("\n" + "\u001B[33m" + "=".repeat(72) + "\u001b[0m" + "\n") } class Day10 { private val lines = File("../Input/day10.txt").readLines() private val opening = arrayOf('{', '[', '(', '<') private val bracketPairs = mapOf('{' to '}', '[' to ']', '(' to ')', '<' to '>') private fun checkMatchingBrackets(stack: Stack<Char>, remainingChars: String): Int { if (remainingChars.isEmpty()) return 0 val c = remainingChars.first() if (c in opening) { stack.push(c) } else { val matchTo = stack.pop() if (bracketPairs[matchTo] != c) { return when(c) { ')' -> 3 ']' -> 57 '}' -> 1197 '>' -> 25137 else -> 0 } } } return checkMatchingBrackets(stack, remainingChars.substring(1)) } fun part_1() { val total = lines.sumOf { checkMatchingBrackets(Stack<Char>(), it) } println("Puzzle 1: " + total) } fun part_2() { val total = lines.map { val stack = Stack<Char>() if (checkMatchingBrackets(stack, it) == 0) { stack.foldRight(0L) { c, acc -> acc * 5 + when(bracketPairs[c]) { ')' -> 1 ']' -> 2 '}' -> 3 '>' -> 4 else -> 0 } } } else 0 } .filterNot { it == 0L } .sorted() println("Puzzle 2: " + total[(total.size / 2)]) } }
0
C++
0
0
02f219ea278d85c7799d739294c664aa5a47719a
2,336
AOC2021
Apache License 2.0
app/src/main/kotlin/aoc2022/day05/Day05.kt
dbubenheim
574,231,602
false
{"Kotlin": 18742}
package aoc2022.day05 import aoc2022.day05.Day05.part1 import aoc2022.day05.Day05.part2 import aoc2022.toFile object Day05 { private val stacksRegex = "^\\s+[0-9](\\s+[0-9]+)*\$".toRegex() private val cratesRegex = "([A-Z])|\\s{2}(\\s)\\s".toRegex() private val rearrangementRegex = "move ([0-9]+) from ([0-9]+) to ([0-9]+)".toRegex() fun part1(): String { val lines = "input-day05.txt".toFile() .readLines() .also { println("amount of lines:\t${it.size}") } val cratesCount = lines .single { it.matches(stacksRegex) } .substringAfterLast(" ") .toInt() .also { println("amount of crates:\t$it") } val stacks = mutableListOf<ArrayDeque<String>>() repeat(cratesCount) { stacks.add(ArrayDeque()) } lines.takeWhile { it.isNotBlank() } .dropLast(1) .reversed() .map { it.addCratesTo(stacks) } lines.takeLastWhile { it.isNotBlank() } .map { it.toRearrangementProcedure() } .also { println(it) } .forEach { proc -> repeat(proc.amount) { stacks[proc.to].add(stacks[proc.from].removeLast()) } } return stacks.joinToString("") { it.last() } } fun part2(): String { val lines = "input-day05.txt".toFile() .readLines() .also { println("amount of lines:\t${it.size}") } val cratesCount = lines .single { it.matches(stacksRegex) } .substringAfterLast(" ") .toInt() .also { println("amount of crates:\t$it") } val stacks = mutableListOf<ArrayDeque<String>>() repeat(cratesCount) { stacks.add(ArrayDeque()) } lines.takeWhile { it.isNotBlank() } .dropLast(1) .reversed() .map { it.addCratesTo(stacks) } lines.takeLastWhile { it.isNotBlank() } .map { it.toRearrangementProcedure() } .also { println(it) } .forEach { proc -> val list = mutableListOf<String>() repeat(proc.amount) { list.add(stacks[proc.from].removeLast()) } stacks[proc.to].addAll(list.reversed()) } return stacks.joinToString("") { it.last() } } data class RearrangementProcedure(val amount: Int, val from: Int, val to: Int) private fun String.toRearrangementProcedure(): RearrangementProcedure { val (amount, from, to) = requireNotNull(rearrangementRegex.find(this)?.destructured?.toList()).map { it.toInt() } return RearrangementProcedure(amount, from - 1, to - 1) } private fun String.addCratesTo(stacks: MutableList<ArrayDeque<String>>) { cratesRegex.findAll(this).toList() .filter { it.value.isNotBlank() } .forEach { stacks[it.range.first / 4].add(it.value) } } } fun main() { println(part1()) println(part2()) }
8
Kotlin
0
0
ee381bb9820b493d5e210accbe6d24383ae5b4dc
3,063
advent-of-code-2022
MIT License
src/Day01/Day01.kt
thmsbdr
574,632,643
false
{"Kotlin": 6603}
package Day01 import readInput fun main() { fun part1(input: List<String>): Int { var max = 0 var current = 0 input.forEach { if (it == "") { if (current > max) { max = current } current = 0 } else { current += it.toInt() } } return max } fun part2(input: List<String>): Int { val max = IntArray(3) var current = 0 input.forEach { if (it == "") { if (current > max[0]) { val tmp = max[0] max[0] = current current = tmp } if (current > max[1]) { val tmp = max[1] max[1] = current current = tmp } if (current > max[2]) { val tmp = max[2] max[2] = current current = tmp } current = 0 } else { current += it.toInt() } } return max.sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01/Day01_test") // check(part1(testInput) == 24000) // check(part2(testInput) == 45000) val input = readInput("Day01/Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
b9ac3ed8b52a95dcc542f4de79fb24163f3929a4
1,502
AoC-2022
Apache License 2.0
src/day07/Day07.kt
maxmil
578,287,889
false
{"Kotlin": 32792}
package day07 import println import readInputAsText import kotlin.math.abs import kotlin.math.min fun main() { fun shortest(input: String, fuelUsed: (Int, Int) -> Int): Int { val start = input.split(",").map { it.toInt() } return (start.min()..start.max()).fold(Int.MAX_VALUE) { acc, position -> min(acc, start.sumOf { fuelUsed(it, position) }) } } fun part1(input: String) = shortest(input) { start, end -> abs(start - end) } fun part2(input: String) = shortest(input) { start, end -> abs(start - end).let { it * (it + 1) / 2 } } val testInput = readInputAsText("day07/input_test") check(part1(testInput) == 37) check(part2(testInput) == 168) val input = readInputAsText("day07/input") part1(input).println() part2(input).println() }
0
Kotlin
0
0
246353788b1259ba11321d2b8079c044af2e211a
817
advent-of-code-2021
Apache License 2.0
app/src/main/kotlin/com/resurtm/aoc2023/day07/Solution.kt
resurtm
726,078,755
false
{"Kotlin": 119665}
package com.resurtm.aoc2023.day07 fun launchDay07(testCase: String) { val ex = Exception("Cannot read the input") val rawReader = object {}.javaClass.getResourceAsStream(testCase)?.bufferedReader() val reader = rawReader ?: throw ex val result = listOf(mutableListOf<Hand>(), mutableListOf()) while (true) { val line = reader.readLine() ?: break val cards = line.split(' ')[0].trim() val score = line.split(' ')[1].trim().toInt() main@ for (ver in 0..1) { val hand = Hand(cards = cards, score = score, version = ver + 1) if (result[ver].size == 0) { result[ver].add(hand) continue@main } for (idx in 0..<result[ver].size) { if (result[ver][idx] > hand) { result[ver].add(idx, hand) continue@main } } result[ver].add(hand) } } for (ver in 0..1) { val total = result[ver].foldIndexed(0) { index, acc, hand -> acc + (index + 1) * hand.score } println("Day 07, part ${ver + 1}: $total") } } private data class Hand( val cards: String, val score: Int, val version: Int = 1, private var assessment: Assessment = Assessment.UNKNOWN, private var lookup: Map<Char, Int> = emptyMap(), ) : Comparable<Hand> { init { assessment = if (version == 1) assessV1(cards) else assessV2(cards) lookup = if (version == 1) lookupV1 else lookupV2 } override fun compareTo(other: Hand): Int { if (this.assessment.prio == other.assessment.prio) { for (idx in 0..<this.cards.length) { val a = lookup[this.cards[idx]] val b = lookup[other.cards[idx]] if (a != null && b != null && a > b) return 1 if (a != null && b != null && a < b) return -1 } return 0 } return if (this.assessment.prio > other.assessment.prio) 1 else -1 } private fun assessV1(inp: String): Assessment { val uniq = inp.toSet() val freq = mutableMapOf<Char, Int>() lookupV1.forEach { freq[it.key] = 0 } inp.forEach { val prev = freq[it]; freq[it] = if (prev == null) 0 else prev + 1 } val vals = freq.values.filter { it > 0 }.toSet() if (uniq.size == 1) return Assessment.FIVE_OF_A_KIND if (uniq.size == 2 && vals == setOf(4, 1)) return Assessment.FOUR_OF_A_KIND if (uniq.size == 2 && vals == setOf(3, 2)) return Assessment.FULL_HOUSE if (uniq.size == 3 && vals == setOf(3, 1, 1)) return Assessment.THREE_OF_A_KIND if (uniq.size == 3 && vals == setOf(2, 2, 1)) return Assessment.TWO_PAIR if (uniq.size == 4 && vals == setOf(2, 1, 1, 1)) return Assessment.ONE_PAIR return Assessment.HIGH_CARD } private fun assessV2(inp: String): Assessment { val pos = inp.indexOf('J') if (pos == -1) return assessV1(inp) var max = Assessment.UNKNOWN for (k in lookupV2Min.keys) { val res = assessV2(inp.substring(0, pos) + k + inp.substring(pos + 1, inp.length)) if (max.prio < res.prio) max = res } return max } } private enum class Assessment(val prio: Int) { FIVE_OF_A_KIND(7), FOUR_OF_A_KIND(6), FULL_HOUSE(5), THREE_OF_A_KIND(4), TWO_PAIR(3), ONE_PAIR(2), HIGH_CARD(1), UNKNOWN(-1), } private val lookupV1 = mapOf( 'A' to 13, 'K' to 12, 'Q' to 11, 'J' to 10, 'T' to 9, '9' to 8, '8' to 7, '7' to 6, '6' to 5, '5' to 4, '4' to 3, '3' to 2, '2' to 1, ) private val lookupV2Min = mapOf( 'A' to 13, 'K' to 12, 'Q' to 11, 'T' to 10, '9' to 9, '8' to 8, '7' to 7, '6' to 6, '5' to 5, '4' to 4, '3' to 3, '2' to 2, ) private val lookupV2 = lookupV2Min + mapOf('J' to 1)
0
Kotlin
0
0
fb8da6c246b0e2ffadb046401502f945a82cfed9
3,843
advent-of-code-2023
MIT License
src/Day04.kt
svignesh93
572,116,133
false
{"Kotlin": 33603}
/** * Advent of Code 2022 * * --- Day 4: Camp Cleanup --- * * Space needs to be cleared before the last supplies can be unloaded from the ships, * and so several Elves have been assigned the job of cleaning up sections of the camp. * Every section has a unique ID number, and each Elf is assigned a range of section IDs. * * However, as some Elves compare their section assignments with each other, * they've noticed that many of the assignments overlap. To try to quickly find overlaps and reduce duplicated effort, * the Elves pair up and make a big list of the section assignments for each pair (your puzzle input). * * For example, consider the following list of section assignment pairs: * * 2-4,6-8 * 2-3,4-5 * 5-7,7-9 * 2-8,3-7 * 6-6,4-6 * 2-6,4-8 * * For the first few pairs, this list means: * * Within the first pair of Elves, the first Elf was assigned sections 2-4 (sections 2, 3, and 4), * while the second Elf was assigned sections 6-8 (sections 6, 7, 8). * * The Elves in the second pair were each assigned two sections. * * The Elves in the third pair were each assigned three sections: one got sections 5, 6, and 7, * while the other also got 7, plus 8 and 9. * * This example list uses single-digit section IDs to make it easier to draw; * your actual list might contain larger numbers. Visually, these pairs of section assignments look like this: * * .234..... 2-4 * .....678. 6-8 * * .23...... 2-3 * ...45.... 4-5 * * ....567.. 5-7 * ......789 7-9 * * .2345678. 2-8 * ..34567.. 3-7 * * .....6... 6-6 * ...456... 4-6 * * .23456... 2-6 * ...45678. 4-8 * * Some of the pairs have noticed that one of their assignments fully contains the other. * * For example, 2-8 fully contains 3-7, and 6-6 is fully contained by 4-6. * In pairs where one assignment fully contains the other, one Elf in the pair would be exclusively cleaning * sections their partner will already be cleaning, so these seem like the most in need of reconsideration. * In this example, there are 2 such pairs. * * In how many assignment pairs does one range fully contain the other? * * Your puzzle answer was 433. * * --- Part Two --- * * It seems like there is still quite a bit of duplicate work planned. * Instead, the Elves would like to know the number of pairs that overlap at all. * * In the above example, the first two pairs (2-4,6-8 and 2-3,4-5) don't overlap, * while the remaining four pairs (5-7,7-9, 2-8,3-7, 6-6,4-6, and 2-6,4-8) do overlap: * * 5-7,7-9 overlaps in a single section, 7. * 2-8,3-7 overlaps all sections 3 through 7. * 6-6,4-6 overlaps in a single section, 6. * 2-6,4-8 overlaps in sections 4, 5, and 6. * * So, in this example, the number of overlapping assignment pairs is 4. * * In how many assignment pairs do the ranges overlap? */ fun main() { fun countFullyOverlappingAssignments(input: List<String>): Int { var counter = 0 input.forEach { line -> val pairs = line.split(",") .flatMap { pairStr -> pairStr.split("-").map { str -> str.toInt() } } val (firstMin, firstMax, secondMin, secondMax) = pairs if ((firstMin <= secondMin && firstMax >= secondMax) || (secondMin <= firstMin && secondMax >= firstMax) ) { ++counter } } return counter } fun countOverlappingAssignments(input: List<String>): Int { var counter = 0 input.forEach { line -> val pairs = line.split(",") .flatMap { pairStr -> pairStr.split("-").map { str -> str.toInt() } } val (firstMin, firstMax, secondMin, secondMax) = pairs if (!(firstMax < secondMin || secondMax < firstMin)) { ++counter } } return counter } val input = readInput("Day04") // Part One println("Fully overlapping assignments: ${countFullyOverlappingAssignments(input)}") // Part Two println("overlapping assignments: ${countOverlappingAssignments(input)}") }
0
Kotlin
0
1
ea533d256ba16c0210c2daf16ad1c6c37318b5b4
4,108
AOC-2022
Apache License 2.0
src/nativeMain/kotlin/com.qiaoyuang.algorithm/round1/Questions56.kt
qiaoyuang
100,944,213
false
{"Kotlin": 338134}
package com.qiaoyuang.algorithm.round1 fun test56() { printlnResult1(intArrayOf(2, 4, 3, 6, 3, 2, 5, 5)) printlnResult1(intArrayOf(1, 1, 2, 3)) printlnResult1(intArrayOf(2, 3)) printlnResult2(intArrayOf(1, 2, 1, 1)) printlnResult2(intArrayOf(2, 3, 2, 1, 2, 3, 3)) printlnResult2(intArrayOf(1)) } /** * Questions 56-1: Find two numbers in an IntArray that only appear once, all other numbers appear twice */ private fun IntArray.findTwoNumberAppearOnce(): Pair<Int, Int> { require(size % 2 == 0) { "The IntArray is illegal" } var xorResult = first() for (i in 1..lastIndex) xorResult = xorResult xor this[i] val indexOf1 = xorResult.findFirstBitIs1() var num1 = 0 var num2 = 0 forEach { if (it isBit1 indexOf1) num1 = num1 xor it else num2 = num2 xor it } return num1 to num2 } private fun Int.findFirstBitIs1(): Int { var indexBit = 0 var num = this while (num and 1 == 0 && indexBit < 8 * Int.SIZE_BITS) { num = num shr 1 indexBit++ } return indexBit } private infix fun Int.isBit1(indexBit: Int): Boolean = this shr indexBit and 1 != 0 private fun printlnResult1(array: IntArray) = println("The two numbers just appear once are ${array.findTwoNumberAppearOnce()}, in array: ${array.toList()}") /** * Questions 56-2: Find a number in an IntArray that only appear once, all other numbers appear thirds */ private fun IntArray.findNumberAppearOnce(): Int { require(isNotEmpty()) { "The IntArray is illegal" } val bitsSum = IntArray(32) forEach { num -> var bitMusk = 1 for (j in 31 downTo 0) { val bit = num and bitMusk if (bit != 0) bitsSum[j]++ bitMusk = bitMusk shl 1 } } var result = 0 repeat(32) { result = result shl 1 result += bitsSum[it] % 3 } return result } private fun printlnResult2(array: IntArray) = println("The number just appear once is ${array.findNumberAppearOnce()} in array: ${array.toList()}")
0
Kotlin
3
6
66d94b4a8fa307020d515d4d5d54a77c0bab6c4f
2,105
Algorithm
Apache License 2.0
src/day1/Day01.kt
francoisadam
573,453,961
false
{"Kotlin": 20236}
package day1 import readInput fun main() { fun part1(input: List<String>): Int { val elvesSupplies = input.joinToString(",") .split(",,") .map { elfSupplies -> elfSupplies.split(",").sumOf { it.toInt() } } return elvesSupplies.max() } fun part2(input: List<String>): Int { val elvesSupplies = input.joinToString(",") .split(",,") .map { elfSupplies -> elfSupplies.split(",").sumOf { it.toInt() } } .sortedDescending() return elvesSupplies[0] + elvesSupplies[1] + elvesSupplies[2] } // test if implementation meets criteria from the description, like: val testInput = readInput("day1/Day01_test") val testPart1 = part1(testInput) println("testPart1: $testPart1") val testPart2 = part2(testInput) println("testPart2: $testPart2") check(testPart1 == 24000) check(testPart2 == 45000) val input = readInput("day1/Day01") println("part1 : ${part1(input)}") println("part2 : ${part2(input)}") }
0
Kotlin
0
0
e400c2410db4a8343c056252e8c8a93ce19564e7
1,100
AdventOfCode2022
Apache License 2.0
src/main/kotlin/days/aoc2020/Day24.kt
bjdupuis
435,570,912
false
{"Kotlin": 537037}
package days.aoc2020 import days.Day class Day24: Day(2020, 24) { override fun partOne(): Any { return partOneSolution(inputList) } fun calculateStartingGrid(list: List<String>) : HexGrid<HexTile> { val grid = HexGrid<HexTile>() var currentCoordinate = Triple(0,0,0) list.forEach { directions -> var i = 0 while (i in directions.indices) { when (directions[i]) { 'n' -> { i++ when (directions[i]) { 'e' -> { currentCoordinate = grid.coordinateTo(currentCoordinate, HexGrid.Direction.NORTHEAST) } 'w' -> { currentCoordinate = grid.coordinateTo(currentCoordinate, HexGrid.Direction.NORTHWEST) } } } 's' -> { i++ when (directions[i]) { 'e' -> { currentCoordinate = grid.coordinateTo(currentCoordinate, HexGrid.Direction.SOUTHEAST) } 'w' -> { currentCoordinate = grid.coordinateTo(currentCoordinate, HexGrid.Direction.SOUTHWEST) } } } 'e' -> { currentCoordinate = grid.coordinateTo(currentCoordinate, HexGrid.Direction.EAST) } 'w' -> { currentCoordinate = grid.coordinateTo(currentCoordinate, HexGrid.Direction.WEST) } } i++ } grid.getOrInsertDefault(currentCoordinate, HexTile()).flip() currentCoordinate = Triple(0,0,0) } return grid } fun partOneSolution(list: List<String>): Int { return calculateStartingGrid(list).map.count { it.value.color == HexTile.Color.BLACK} } override fun partTwo(): Any { val grid = calculateStartingGrid(inputList) println("There are ${grid.map.count { it.value.color == HexTile.Color.BLACK }} tiles initially") for (i in 1..100) { val currentMap = mutableMapOf<Triple<Int, Int, Int>, HexTile>() grid.map.forEach { (triple, hexTile) -> currentMap.putIfAbsent(triple, HexTile()) if (hexTile.color == HexTile.Color.BLACK) { currentMap[triple]!!.flip() } } grid.map.keys.forEach { coordinate -> HexGrid.Direction.values().forEach { direction -> currentMap.getOrPut(grid.coordinateTo(coordinate, direction)) { HexTile() } } } currentMap.forEach { entry -> val countOfBlackNeighboringTiles = HexGrid.Direction.values().count { direction -> currentMap.getOrDefault(grid.coordinateTo(entry.key, direction), HexTile()).color == HexTile.Color.BLACK } when { entry.value.color == HexTile.Color.BLACK && (countOfBlackNeighboringTiles == 0 || countOfBlackNeighboringTiles > 2) -> { val actualTile = grid.getOrInsertDefault(entry.key, HexTile()) if (actualTile.color == HexTile.Color.BLACK) { actualTile.flip() } } entry.value.color == HexTile.Color.WHITE && countOfBlackNeighboringTiles == 2 -> { val actualTile = grid.getOrInsertDefault(entry.key, HexTile()) if (actualTile.color == HexTile.Color.WHITE) { actualTile.flip() } } else -> { // do nothing } } } println("After $i day(s) there are ${grid.map.count { it.value.color == HexTile.Color.BLACK }} tiles") } return grid.map.count { it.value.color == HexTile.Color.BLACK} } } class HexTile { var color = Color.WHITE fun flip() { color = if (color == Color.WHITE) Color.BLACK else Color.WHITE } enum class Color { WHITE, BLACK } } class HexGrid<T> { val map = mutableMapOf<Triple<Int,Int,Int>, T>() fun getOrInsertDefault(coordinate: Triple<Int,Int,Int>, default: T): T { return if (map.containsKey(coordinate)) { map[coordinate]!! } else { map[coordinate] = default map[coordinate]!! } } fun set(coordinate: Triple<Int,Int,Int>, value: T) { map[coordinate] = value } fun coordinateTo(startingCoordinate: Triple<Int, Int, Int>, direction: Direction): Triple<Int,Int,Int> { val delta = direction.delta() return Triple( startingCoordinate.first + delta.first, startingCoordinate.second + delta.second, startingCoordinate.third + delta.third ) } enum class Direction(val value: String) { NORTHEAST("ne"), EAST("e"), SOUTHEAST("se"), SOUTHWEST("sw"), WEST("w"), NORTHWEST("nw"); fun delta(): Triple<Int,Int,Int> { return when(this) { NORTHEAST -> Triple(1, 0, -1) EAST -> Triple(1, -1, 0) SOUTHEAST -> Triple(0, -1, 1) SOUTHWEST -> Triple(-1, 0, 1) WEST -> Triple(-1, 1, 0) NORTHWEST -> Triple(0, 1, -1) } } } }
0
Kotlin
0
1
c692fb71811055c79d53f9b510fe58a6153a1397
5,840
Advent-Of-Code
Creative Commons Zero v1.0 Universal
kotlin/structures/Treap.kt
polydisc
281,633,906
true
{"Java": 540473, "Kotlin": 515759, "C++": 265630, "CMake": 571}
package structures import java.util.Random // https://cp-algorithms.com/data_structures/treap.html object Treap { var random: Random = Random() fun split(root: Node?, minRight: Long): TreapPair { if (root == null) return TreapPair(null, null) root.push() return if (root.key >= minRight) { val sub = split(root.left, minRight) root.left = sub.right root.pull() sub.right = root sub } else { val sub = split(root.right, minRight) root.right = sub.left root.pull() sub.left = root sub } } fun merge(left: Node?, right: Node?): Node? { if (left == null) return right if (right == null) return left left.push() right.push() return if (left.prio > right.prio) { left.right = merge(left.right, right) left.pull() left } else { right.left = merge(left, right.left) right.pull() right } } fun insert(root: Node?, key: Long, value: Long): Node? { val t = split(root, key) return merge(merge(t.left, Node(key, value)), t.right) } fun remove(root: Node?, key: Long): Node? { val t = split(root, key) return merge(t.left, split(t.right, key + 1).right) } fun modify(root: Node?, ll: Long, rr: Long, delta: Long): Node? { val t1 = split(root, rr + 1) val t2 = split(t1.left, ll) if (t2.right != null) t2.right!!.apply(delta) return merge(merge(t2.left, t2.right), t1.right) } fun query(root: Node?, ll: Long, rr: Long): TreapAndResult { val t1 = split(root, rr + 1) val t2 = split(t1.left, ll) val mx = Node.getMx(t2.right) val sum = Node.getSum(t2.right) return TreapAndResult(merge(merge(t2.left, t2.right), t1.right), mx, sum) } fun kth(root: Node?, k: Int): Node? { if (k < Node.getSize(root!!.left)) return kth(root.left, k) else if (k > Node.getSize( root.left ) ) return kth(root.right, k - Node.getSize(root.left) - 1) return root } fun print(root: Node?) { if (root == null) return root.push() print(root.left) System.out.print(root.nodeValue.toString() + " ") print(root.right) } // Random test fun main(args: Array<String?>?) { var treap: Node? = null treap = insert(treap, 5, 3) treap = insert(treap, 3, 2) treap = insert(treap, 6, 1) System.out.println(kth(treap, 1)!!.key) System.out.println(query(treap, 1, 10).mx) treap = remove(treap, 5) System.out.println(query(treap, 1, 10).mx) } class Node internal constructor(// keys should be unique var key: Long, var nodeValue: Long ) { var mx: Long var sum: Long var add: Long var size: Int var prio: Long var left: Node? = null var right: Node? = null fun apply(v: Long) { nodeValue += v mx += v sum += v * size add += v } fun push() { if (add != 0L) { if (left != null) left!!.apply(add) if (right != null) right!!.apply(add) add = 0 } } fun pull() { mx = Math.max(nodeValue, Math.max(getMx(left), getMx(right))) sum = nodeValue + getSum(left) + getSum(right) size = 1 + getSize(left) + getSize(right) } companion object { fun getMx(root: Node?): Long { return root?.mx ?: Long.MIN_VALUE } fun getSum(root: Node?): Long { return root?.sum ?: 0 } fun getSize(root: Node?): Int { return root?.size ?: 0 } } init { mx = nodeValue sum = nodeValue add = 0 size = 1 prio = random.nextLong() } } class TreapPair internal constructor(var left: Node?, var right: Node?) class TreapAndResult internal constructor(var treap: Node?, var mx: Long, var sum: Long) }
1
Java
0
0
4566f3145be72827d72cb93abca8bfd93f1c58df
4,347
codelibrary
The Unlicense
kotlin/src/main/kotlin/io/github/ocirne/aoc/year2023/Day19.kt
ocirne
327,578,931
false
{"Python": 323051, "Kotlin": 67246, "Sage": 5864, "JavaScript": 832, "Shell": 68}
package io.github.ocirne.aoc.year2023 import io.github.ocirne.aoc.AocChallenge class Day19(val lines: List<String>) : AocChallenge(2023, 19) { companion object { private val IDENTIFIER_PATTERN = """[a-z]+""".toRegex() private val END_STATE_PATTERN = """[AR]""".toRegex() private val PART_PATTERN = """\{x=(\d+),m=(\d+),a=(\d+),s=(\d+)}""".toRegex() private val WORKFLOW_PATTERN = """([a-z]+)\{(.*)}""".toRegex() private val LESS_THAN_PATTERN = """([xmas])<(\d+):([ARa-z]+)""".toRegex() private val GREATER_THAN_PATTERN = """([xmas])>(\d+):([ARa-z]+)""".toRegex() } data class Part(val line: String) { val registers = "xmas".toCharArray() .zip(PART_PATTERN.find(line)!!.groupValues.drop(1).map { it.toInt() }) .toMap() fun rating(): Int = registers.values.sum() } abstract class Rule(val nextWorkflow: String) { abstract fun match(part: Part): Boolean abstract fun anti(): Rule } class LessThanRule(val variable: Char, val value: Int, nextWorkflow: String) : Rule(nextWorkflow) { override fun match(part: Part): Boolean = part.registers[variable]!! < value override fun anti(): Rule = GreaterThanRule(variable, value - 1, "anti") } class GreaterThanRule(val variable: Char, val value: Int, nextWorkflow: String) : Rule(nextWorkflow) { override fun match(part: Part): Boolean = part.registers[variable]!! > value override fun anti(): Rule = LessThanRule(variable, value + 1, "anti") } class DirectRule(nextWorkflow: String) : Rule(nextWorkflow) { override fun match(part: Part): Boolean = true override fun anti(): Rule = this } class Workflow(rulesString: String) { val rules = rulesString.split(",").map { rule -> when { LESS_THAN_PATTERN.matches(rule) -> { val (variable, value, nextWorkflow) = LESS_THAN_PATTERN.find(rule)!!.destructured LessThanRule(variable.first(), value.toInt(), nextWorkflow) } GREATER_THAN_PATTERN.matches(rule) -> { val (variable, value, nextWorkflow) = GREATER_THAN_PATTERN.find(rule)!!.destructured GreaterThanRule(variable.first(), value.toInt(), nextWorkflow) } END_STATE_PATTERN.matches(rule) -> DirectRule(rule) IDENTIFIER_PATTERN.matches(rule) -> DirectRule(rule) else -> throw IllegalStateException(rule) } } fun process(part: Part): String = rules.first { it.match(part) }.nextWorkflow } class Workflows(val lines: List<String>) { private val workflows: Map<String, Workflow> private val parts: List<Part> init { if (lines.isNotEmpty()) { val sep = lines.indexOf("") workflows = lines.subList(0, sep).associate { line -> val (name, rules) = WORKFLOW_PATTERN.find(line)!!.destructured name to Workflow(rules) } parts = lines.subList(sep + 1, lines.size).map { Part(it) } } else { workflows = mapOf() parts = listOf() } } private fun handlePart(part: Part): Boolean { var currentWorkflow = workflows["in"]!! while (true) { val result = currentWorkflow.process(part) if (result == "A") return true if (result == "R") return false currentWorkflow = workflows[result]!! } } fun sumAcceptedParts(): Int = parts.filter(::handlePart).sumOf { it.rating() } private fun upperBound(constraints: List<Rule>, category: Char): Int = constraints .filter { rule -> rule is LessThanRule && rule.variable == category } .minOfOrNull { (it as LessThanRule).value } ?: 4001 private fun lowerBound(constraints: List<Rule>, category: Char): Int = constraints .filter { rule -> rule is GreaterThanRule && rule.variable == category } .maxOfOrNull { (it as GreaterThanRule).value } ?: 0 private fun collectResult(collectedRules: List<Rule>): Long = "xmas".map { v -> upperBound(collectedRules, v) - lowerBound(collectedRules, v) - 1 } .map { it.toLong() } .reduce { acc, i -> acc * i } fun dfs(currentNode: String = "in", i: Int = 0, constraints: List<Rule> = listOf()): Long { if (currentNode == "A") { return collectResult(constraints) } if (currentNode == "R") { return 0 } val currentWorkflow = workflows[currentNode]!! val currentRule = currentWorkflow.rules[i] // match var total = dfs(currentRule.nextWorkflow, 0, constraints + currentRule) // no match if (i + 1 < currentWorkflow.rules.size) { total += dfs(currentNode, i + 1, constraints + currentRule.anti()) } return total } } private val workflows = Workflows(lines) override fun part1(): Int { return workflows.sumAcceptedParts() } override fun part2(): Long { return workflows.dfs() } }
0
Python
0
1
b8a06fa4911c5c3c7dff68206c85705e39373d6f
5,609
adventofcode
The Unlicense
src/test/kotlin/Day05.kt
christof-vollrath
317,635,262
false
null
import io.kotest.core.spec.style.FunSpec import io.kotest.data.forAll import io.kotest.data.headers import io.kotest.data.row import io.kotest.data.table import io.kotest.matchers.shouldBe /* --- Day 5: Binary Boarding --- See https://adventofcode.com/2020/day/5 */ fun decodeBoardingPass(passString: String): Int = decodeRows(passString.take(7)) * 8 + decodeColumns(passString.drop(7)) fun decodeRows(rowString: String) = decodeBinaryString( rowString.map { when(it) { 'B' -> '1' 'F' -> '0' else -> throw IllegalArgumentException("Unexpected row char $it") } }) fun decodeColumns(colString: String) = decodeBinaryString( colString.map { when(it) { 'R' -> '1' 'L' -> '0' else -> throw IllegalArgumentException("Unexpected row char $it") } }) fun decodeBinaryString(binaryString: List<Char>): Int = binaryString.fold(0) { current, n -> current * 2 + when(n) { '1' -> 1 else -> 0 } } class Day05_Part1 : FunSpec({ context("decode row") { table( headers("row", "expected"), row("BFFFBBF", 70), row("FFFBBBF", 14), row("BBFFBBF", 102) ).forAll { rowString, expected -> val result = decodeRows(rowString) result shouldBe expected } } context("decode columns") { table( headers("columns", "expected"), row("RRR", 7), row("RLL", 4), ).forAll { colString, expected -> val result = decodeColumns(colString) result shouldBe expected } } context("decode boarding pass") { table( headers("boading pass", "expected"), row("BFFFBBFRRR", 567), row("FFFBBBFRRR", 119), row("BBFFBBFRLL", 820) ).forAll { passString, expected -> val result = decodeBoardingPass(passString) result shouldBe expected } } }) class Day05_Part1_Exercise: FunSpec({ val input = readResource("day05Input.txt")!! val passStrings = input.split("\n") val highestId = passStrings.map { decodeBoardingPass(it) }.maxOrNull() test("solution") { highestId shouldBe 978 } }) class Day05_Part2_Exercise: FunSpec({ val input = readResource("day05Input.txt")!! val passStrings = input.split("\n") val ids = passStrings.map { decodeBoardingPass(it) } val idsInRowWithEmptySeat = ids.groupBy { id -> val row = id / 8 row } .entries.filter { (_, value) -> value.size < 8 }.first { (key, _) -> key != 1 && key != 122 } .value val row = idsInRowWithEmptySeat.first() / 8 val allSeatsInRow = (0..7).map { row * 8 + it } val freeSeat = (allSeatsInRow - idsInRowWithEmptySeat).first() test("solution") { freeSeat shouldBe 727 } })
1
Kotlin
0
0
8ad08350aa4bd1a29b7e18765fc7a2d6de8021e8
2,917
advent_of_code_2020
Apache License 2.0
src/main/kotlin/com/ginsberg/advent2020/Day09.kt
tginsberg
315,060,137
false
null
/* * Copyright (c) 2020 by <NAME> */ /** * Advent of Code 2020, Day 9 - Encoding Error * Problem Description: http://adventofcode.com/2020/day/9 * Blog Post/Commentary: https://todd.ginsberg.com/post/advent-of-code/2020/day9/ */ package com.ginsberg.advent2020 class Day09(private val input: List<Long>) { fun solvePart1(preamble: Int = 25): Long = input.windowed(preamble+1, 1, false).first { !it.preambleIsValid() }.last() fun solvePart2(preamble: Int = 25): Long { val target = solvePart1(preamble) val range = input.takeWhile { it != target }.findRangeSummingTo(target) return range.minOrNull()!! + range.maxOrNull()!! } private fun List<Long>.preambleIsValid(): Boolean { val target = this.last() val subjects = this.dropLast(1).toSet() return subjects.any { target - it in subjects } } private fun List<Long>.findRangeSummingTo(target: Long): List<Long> = this.indices.mapNotNull { start -> this.indices.drop(start+1).reversed().mapNotNull { end -> this.subList(start, end).takeIf { it.sum() == target } }.firstOrNull() }.first() }
0
Kotlin
2
38
75766e961f3c18c5e392b4c32bc9a935c3e6862b
1,195
advent-2020-kotlin
Apache License 2.0
src/main/kotlin/com/manalili/advent/Day02.kt
maines-pet
162,116,190
false
null
package com.manalili.advent class Day02 { fun checksum(input: List<String>): Int { var twos = 0 var threes = 0 input.map { boxId: String -> val uniqueChars = boxId.toSet() val uniqueCharsCount = uniqueChars.map { boxId.count { c -> it == c } }.filter { it in 2..3 } if (uniqueCharsCount.contains(2)) twos++ if (uniqueCharsCount.contains(3)) threes++ } return twos * threes } fun rightBoxId(ids: List<String>): String{ var match = "" for (i in ids.indices) { //last element ie nothing to compare if (i == ids.size - 1) { break } for (j in i + 1 until ids.size){ val commonLetters = ids[i] diff ids[j] if (commonLetters != null) { match = commonLetters break } } } return match } } infix fun String.diff(other: String): String? { var numOfCharsDiff = 0 var posOfDifference: Int? = null for (i in this.indices) { if (this[i] != other[i]) { posOfDifference = i numOfCharsDiff++ } } return if (numOfCharsDiff != 1) null else this.filterIndexed { index, _ -> index != posOfDifference } }
0
Kotlin
0
0
25a01e13b0e3374c4abb6d00cd9b8d7873ea6c25
1,377
adventOfCode2018
MIT License
core-kotlin-modules/core-kotlin-collections-2/src/main/kotlin/com/baeldung/aggregate/AggregateOperations.kt
Baeldung
260,481,121
false
{"Kotlin": 1476024, "Java": 43013, "HTML": 4883}
package com.baeldung.aggregate class AggregateOperations { private val numbers = listOf(1, 15, 3, 8) fun countList(): Int { return numbers.count() } fun sumList(): Int { return numbers.sum() } fun averageList(): Double { return numbers.average() } fun maximumInList(): Int? { return numbers.maxOrNull() } fun minimumInList(): Int? { return numbers.minOrNull() } fun maximumByList(): Int? { return numbers.maxByOrNull { it % 5 } } fun minimumByList(): Int? { return numbers.minByOrNull { it % 5 } } fun maximumWithList(): String? { val strings = listOf("Berlin", "Kolkata", "Prague", "Barcelona") return strings.maxWithOrNull(compareBy { it.length % 4 }) } fun minimumWithList(): String? { val strings = listOf("Berlin", "Kolkata", "Prague", "Barcelona") return strings.minWithOrNull(compareBy { it.length % 4 }) } fun sumByList(): Int { return numbers.sumBy { it * 5 } } fun sumByDoubleList(): Double { return numbers.sumByDouble { it.toDouble() / 8 } } fun foldList(): Int { return numbers.fold(100) { total, it -> println("total = $total, it = $it") total - it } // ((((100 - 1)-15)-3)-8) = 73 } fun foldRightList(): Int { return numbers.foldRight(100) { it, total -> println("total = $total, it = $it") total - it } // ((((100-8)-3)-15)-1) = 73 } fun foldIndexedList(): Int { return numbers.foldIndexed(100) { index, total, it -> println("total = $total, it = $it, index = $index") if (index.minus(2) >= 0) total - it else total } // ((100 - 3)-8) = 89 } fun foldRightIndexedList(): Int { return numbers.foldRightIndexed(100) { index, it, total -> println("total = $total, it = $it, index = $index") if (index.minus(2) >= 0) total - it else total } // ((100 - 8)-3) = 89 } fun reduceList(): Int { return numbers.reduce { total, it -> println("total = $total, it = $it") total - it } // (((1 - 15)-3)-8) = -25 } fun reduceRightList(): Int { return numbers.reduceRight() { it, total -> println("total = $total, it = $it") total - it } // ((8-3)-15)-1) = -11 } fun reduceIndexedList(): Int { return numbers.reduceIndexed { index, total, it -> println("total = $total, it = $it, index = $index") if (index.minus(2) >= 0) total - it else total } // ((1-3)-8) = -10 } fun reduceRightIndexedList(): Int { return numbers.reduceRightIndexed { index, it, total -> println("total = $total, it = $it, index = $index") if (index.minus(2) >= 0) total - it else total } // ((8-3) = 5 } }
10
Kotlin
273
410
2b718f002ce5ea1cb09217937dc630ff31757693
2,977
kotlin-tutorials
MIT License
src/main/kotlin/adventOfCode2015/Day13.kt
TetraTsunami
716,279,556
false
{"Kotlin": 29433}
package adventOfCode2015 import util.* import org.apache.commons.collections4.iterators.PermutationIterator @Suppress("unused") class Day13(input: String) : Day(input) { override fun solve() { val moodMap = mutableMapOf<Pair<String, String>, Int>() for (line in lines) { val words = line.split(" ") val p1 = words[0] val p2 = words[10].dropLast(1) val key = Pair(p1, p2) val amt = words[3].toInt() when (words[2] == "gain") { true -> moodMap[key] = amt false -> moodMap[key] = -amt } } // Part 1 val people1 = moodMap.keys.map { it.first }.toSet() val permutations1 = PermutationIterator(people1) var max1 = 0 for (perm in permutations1) { var total = 0 for (i in 0..<perm.size) { val person1 = perm[i] val person2 = perm[(i + 1) % perm.size] total += moodMap[Pair(person1, person2)]!! total += moodMap[Pair(person2, person1)]!! } if (total > max1) max1 = total } a(max1) // Part 2 val people2 = people1.plus("Me") val permutations2 = PermutationIterator(people2) var max2 = 0 for (perm in permutations2) { var total = 0 for (i in 0..<perm.size) { if (perm[i] == "Me" || perm[(i + 1) % perm.size] == "Me") continue val p1 = perm[i] val p2 = perm[(i + 1) % perm.size] total += moodMap[Pair(p1, p2)]!! total += moodMap[Pair(p2, p1)]!! } if (total > max2) max2 = total } a(max2) } }
0
Kotlin
0
0
2a150a3381e790a5b45c9b74f77c1997315a5ba0
1,785
AdventOfCode2015
Apache License 2.0
src/main/kotlin/net/codetreats/aoc/day02/Game.kt
codetreats
725,535,998
false
{"Kotlin": 45007, "Shell": 1060}
package net.codetreats.aoc.day02 import kotlin.math.max data class Game(val id: Int, val extractions: List<Extraction>) { fun isPossible(input: Map<String, Int>) = extractions.map { it.dices }.flatten().none { input[it.color]!! < it.amount } fun power(): Int { val min = mutableMapOf("green" to 0, "red" to 0, "blue" to 0) extractions.map { it.dices }.flatten().forEach { dices -> min[dices.color] = max(dices.amount, min[dices.color]!!) } return min.map { it.value }.reduce { min1, min2 -> min1 * min2 } } companion object { fun from(line: String): Game { val id = line.split(":")[0].split(" ")[1].toInt() val extractions: List<Extraction> = line.split(":")[1].trim().split(";").map { Extraction.from(it.trim()) } return Game(id, extractions) } } } data class Extraction(val dices: List<ColorDices>) { companion object { fun from(part: String): Extraction = Extraction(part.trim().split(",").map { ColorDices.from(it.trim()) }) } } data class ColorDices(val color: String, val amount: Int) { companion object { fun from(part: String): ColorDices { val amount = part.split(" ")[0].trim().toInt() val color = part.split(" ")[1].trim() return ColorDices(color, amount) } } }
0
Kotlin
0
1
3cd4aa53093b5f95328cf478e63fe2a7a4e90961
1,432
aoc2023
MIT License
archive/src/main/kotlin/com/grappenmaker/aoc/year15/Day14.kt
770grappenmaker
434,645,245
false
{"Kotlin": 409647, "Python": 647}
package com.grappenmaker.aoc.year15 import com.grappenmaker.aoc.PuzzleSet fun PuzzleSet.day14() = puzzle { val allReindeer = inputLines.map { l -> val split = l.split(" ") Reindeer(split[0], split[3].toInt(), split[6].toInt(), split[13].toInt()) } val timeRange = 0..<2503 // seconds val travelMap = allReindeer.associateWith { reindeer -> timeRange.scan(0) { acc, curr -> acc + if (reindeer.isResting(curr)) 0 else reindeer.speed } }.toList() partOne = travelMap.maxOf { (_, travels) -> travels.last() }.s() val leads = timeRange.map { curr -> val sorted = travelMap.map { (reindeer, travels) -> reindeer to travels[curr + 1] } .sortedByDescending { (_, d) -> d } val maxDistance = sorted.first().second sorted.takeWhile { (_, d) -> d == maxDistance }.map { (r) -> r } } partTwo = travelMap.maxOf { (reindeer) -> leads.count { reindeer in it } }.s() } data class Reindeer( val name: String, // km/s val speed: Int, // s val flightDuration: Int, // s val restTime: Int ) val Reindeer.period get() = flightDuration + restTime fun Reindeer.isResting(time: Int) = time % period >= flightDuration
0
Kotlin
0
7
92ef1b5ecc3cbe76d2ccd0303a73fddda82ba585
1,226
advent-of-code
The Unlicense
app/src/main/kotlin/solution/Solution1392.kt
likexx
559,794,763
false
{"Kotlin": 136661}
package solution import solution.annotation.Leetcode import kotlin.math.exp class Solution1392 { @Leetcode(1392) class Solution { fun longestPrefix(s: String): String { val dp = IntArray(s.length) { 0 } var len = 0 var i = 1 while (i < s.length) { if (s[len] == s[i]) { len+=1 dp[i] = len i+=1 } else if (len == 0) { dp[i]=0 i+=1 } else { len = dp[len-1] } } return s.substring(0, dp.last()) } fun longestPrefix_binary(s: String): String { val first = s[0] val last = s[s.length-1] val indexes1 = mutableListOf<Int>() val indexes2 = mutableListOf<Int>() for (i in 1..s.length-1) { if (s[i]==first) { indexes1.add(i) } } for (i in s.length-2 downTo 0) { if (s[i]==last) { indexes2.add(i) } } if (indexes2.isEmpty()) { return "" } var maxLen = 0 for (i in indexes1) { val expectLen = s.length - i if (expectLen <= maxLen) { break } var l = 0 var r = indexes2.size - 1 while (l<r) { val m = (l+r)/2 val curLen = indexes2[m] + 1 if (curLen <= expectLen) { r = m } else { l = m+1 } } val curLen = indexes2[l] + 1 if (curLen == expectLen) { var isSame = true for (k in 0..curLen-1) { if (s[k] != s[i+k]) { isSame = false break } } if (isSame) { maxLen = kotlin.math.max(maxLen, curLen) break } } } return s.substring(0, maxLen) } fun longestPrefix_Better(s: String): String { val first = s[0] for (j in 1..s.length-1) { if (s[j] != first) { continue } var i=0 val len = s.length - j var k = 0 while (k<len && s[i]==s[j+k]) { i+=1 k+=1 } if (k==len) { return s.substring(0, k) } } return "" } fun longestPrefix_Naive(s: String): String { var maxLength = 0 for (l in 1..s.length-1) { val prefix = s.substring(0, l) val suffix = s.substring(s.length-l, s.length) if (prefix == suffix) { maxLength = kotlin.math.max(maxLength, l) } } return s.substring(0, maxLength) } } }
0
Kotlin
0
0
376352562faf8131172e7630ab4e6501fabb3002
3,381
leetcode-kotlin
MIT License
src/main/kotlin/com/leetcode/random_problems/easy/maximum_product_in_array/Main.kt
frikit
254,842,734
false
null
package com.leetcode.random_problems.easy.maximum_product_in_array fun main() { println("Test case 1:") // Explanation: We can choose indices 1 and 3 for the first pair (6, 7) and indices 2 and 4 for the second pair (2, 4). // The product difference is (6 * 7) - (2 * 4) = 34. println(Solution().maxProductDifference(intArrayOf(5, 6, 2, 7, 4))) // 34 println() println("Test case 2:") // Explanation: We can choose indices 3 and 6 for the first pair (9, 8) and indices 1 and 5 for the second pair (2, 4). // The product difference is (9 * 8) - (2 * 4) = 64. println(Solution().maxProductDifference(intArrayOf(4, 2, 5, 9, 7, 4, 8))) // 64 println() } class Solution { fun maxProductDifference(nums: IntArray): Int { val pairs = nums.sortedDescending().zipWithNext() val maxProduct = pairs.first().first * pairs.first().second val minProduct = pairs.last().first * pairs.last().second return maxProduct - minProduct } }
0
Kotlin
0
0
dda68313ba468163386239ab07f4d993f80783c7
1,000
leet-code-problems
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/MatrixBlockSum.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2021 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import kotlin.math.max import kotlin.math.min /** * Time: O(m*n). * Space: O(m*n). */ object MatrixBlockSum { operator fun invoke(mat: Array<IntArray>, k: Int): Array<IntArray> { val m: Int = mat.size val n: Int = mat.first().size val sum = Array(m + 1) { IntArray(n + 1) } for (r in 1..m) { for (c in 1..n) { sum[r][c] = mat[r - 1][c - 1] + sum[r - 1][c] + sum[r][c - 1] - sum[r - 1][c - 1] } } val ans = Array(m) { IntArray(n) } for (r in 0 until m) { for (c in 0 until n) { var r1 = max(0, r - k) var c1 = max(0, c - k) var r2 = min(m - 1, r + k) var c2 = min(n - 1, c + k) r1++ c1++ r2++ c2++ // Since `sum` start with 1 so we need to increase r1, c1, r2, c2 by 1 ans[r][c] = sum[r2][c2] - sum[r2][c1 - 1] - sum[r1 - 1][c2] + sum[r1 - 1][c1 - 1] } } return ans } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,704
kotlab
Apache License 2.0
src/Day01.kt
SnyderConsulting
573,040,913
false
{"Kotlin": 46459}
fun main() { fun getElvesList(input: List<String>): List<List<Int>> { val elves = mutableListOf(mutableListOf<Int>()) var counter = 0 input.forEach { if (it.isBlank()) { counter += 1 elves.add(mutableListOf()) } else { elves[counter].add(it.toInt()) } } return elves } fun part1(input: List<String>): Int { val elves = getElvesList(input) return elves .maxBy { elf -> elf.sumOf { calorie -> calorie } }.sumOf { calorie -> calorie } } fun part2(input: List<String>): Int { val elves = getElvesList(input) return elves .sortedByDescending { elf -> elf.sumOf { calorie -> calorie } } .take(3) .sumOf { it.sum() } } val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
ee8806b1b4916fe0b3d576b37269c7e76712a921
993
Advent-Of-Code-2022
Apache License 2.0