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
app/src/main/kotlin/com/resurtm/aoc2023/day24/Solution.kt
resurtm
726,078,755
false
{"Kotlin": 119665}
package com.resurtm.aoc2023.day24 import kotlin.math.round /** * See the README.md file for more details on this one. */ fun launchDay24(testCase: String) { val neverTellMeTheOdds = NeverTellMeTheOdds.readInput(testCase) val part1 = neverTellMeTheOdds.solvePart1( if (testCase.contains("test")) 7L..27L else 200_000_000_000_000L..400_000_000_000_000L ) println("Day 24, part 1: $part1") // val part2 = neverTellMeTheOdds.solvePart2Slow() // println("Day 24, part 2: $part2") val part2 = neverTellMeTheOdds.solvePart2() println("Day 24, part 2: $part2") } private data class NeverTellMeTheOdds( val rays: List<Ray> ) { private val pairs: List<Pair<Ray, Line>> = rays.map { Pair(it, Line.fromRay(it)) } /** * See the README.md file for more details on this one. */ fun solvePart2(): Long { // step 1 -- find velocity val velsX = mutableMapOf<Long, MutableList<Long>>() pairs.forEach { val v = velsX[it.first.dir.x] if (v == null) velsX[it.first.dir.x] = mutableListOf(it.first.start.x) else v.add(it.first.start.x) } val velsY = mutableMapOf<Long, MutableList<Long>>() pairs.forEach { val v = velsY[it.first.dir.y] if (v == null) velsY[it.first.dir.y] = mutableListOf(it.first.start.y) else v.add(it.first.start.y) } val velsZ = mutableMapOf<Long, MutableList<Long>>() pairs.forEach { val v = velsZ[it.first.dir.z] if (v == null) velsZ[it.first.dir.z] = mutableListOf(it.first.start.z) else v.add(it.first.start.z) } val vel = Vec(findVelocity(velsX), findVelocity(velsY), findVelocity(velsZ)) // step 2 -- find position val results = mutableMapOf<Long, Long>() for (i in pairs.indices) for (j in i + 1..<pairs.size) { val rayA = pairs[i].first val rayB = pairs[j].first val ma = (rayA.dir.y - vel.y).toDouble() / (rayA.dir.x - vel.x).toDouble() val mb = (rayB.dir.y - vel.y).toDouble() / (rayB.dir.x - vel.x).toDouble() val ca = rayA.start.y - (ma * rayA.start.x) val cb = rayB.start.y - (mb * rayB.start.x) val rpx = (cb - ca) / (ma - mb) val rpy = (ma * rpx + ca) val time = round((rpx - rayA.start.x) / (rayA.dir.x - vel.x).toDouble()) val rpz = rayA.start.z + (rayA.dir.z - vel.z) * time val result = (rpx + rpy + rpz).toLong() val ex = results[result] if (ex == null) results[result] = 1 else results[result] = ex + 1 } return results.entries.sortedBy { it.value }.last().key } private fun findVelocity(velocities: Map<Long, List<Long>>): Long { var possible = mutableListOf<Long>() for (possib in -1000L..1000L) possible.add(possib) for ((vel, pos) in velocities) { if (pos.size < 2) continue val newPossible = mutableListOf<Long>() for (possib in possible) { if ((possib - vel) !== 0L && (pos[0] - pos[1]) % (possib - vel) === 0L) { newPossible.add(possib) } } possible = newPossible } return possible.firstOrNull() ?: throw Exception("Unable to find a possible velocity") } fun solvePart2Slow(): Long { val posRange = 0L..25L val velRange = -5L..5L val timeLimit = 50L var result: Ray? = null main@ for (ix in posRange) for (iy in posRange) for (iz in posRange) { // println("$ix,$iy,$iz") for (vx in velRange) for (vy in velRange) for (vz in velRange) { val pos = Vec(ix, iy, iz) val vel = Vec(vx, vy, vz) val ray = Ray(pos, vel, pos) reset() for (t in 0..timeLimit) { for (pair in pairs) { if (pair.first.curr == ray.curr) pair.first.hit = true } ray.curr = Vec(ray.curr.x + ray.dir.x, ray.curr.y + ray.dir.y, ray.curr.z + ray.dir.z) advance() } var found = true for (pair in pairs) { if (!pair.first.hit) { found = false break } } if (found) result = ray } } println(result) return if (result == null) throw Exception("Unable to find a result") else result.start.x + result.start.z + result.start.z } private fun reset() { for (pair in pairs) { pair.first.curr = pair.first.start pair.first.hit = false } } private fun advance() { for (pair in pairs) { val pos = pair.first.curr val vel = pair.first.dir pair.first.curr = Vec(pos.x + vel.x, pos.y + vel.y, pos.z + vel.z) } } fun solvePart1(interval: LongRange): Long { var res = 0L for (i in 0..pairs.size - 2) for (j in i + 1..<pairs.size) { if (!Ray.hasInter2D(pairs[i].first, pairs[j].first)) continue val inter = Line.findInter2D(pairs[i].second, pairs[j].second) if ((inter.x.toLong() in interval) && (inter.y.toLong() in interval)) res++ } return res } companion object { internal fun readInput(testCase: String): NeverTellMeTheOdds { val reader = object {}.javaClass.getResourceAsStream(testCase)?.bufferedReader() ?: throw Exception("Cannot read an input, probably it is invalid") val rays = mutableListOf<Ray>() while (true) { val rawLine = reader.readLine() ?: break if (rawLine.trim().isEmpty()) continue val parts0 = rawLine.split("@") val parts1 = parts0[0].split(',').map { it.trim().toLong() } val parts2 = parts0[1].split(',').map { it.trim().toLong() } rays.add( Ray( Vec(parts1[0], parts1[1], parts1[2]), Vec(parts2[0], parts2[1], parts2[2]), Vec(parts1[0], parts1[1], parts1[2]), ) ) } return NeverTellMeTheOdds(rays) } } } private data class Ray( val start: Vec, val dir: Vec, var curr: Vec, var hit: Boolean = false, ) { companion object { internal fun hasInter2D(r1: Ray, r2: Ray): Boolean { val dx = (r2.start.x - r1.start.x).toDouble() val dy = (r2.start.y - r1.start.y).toDouble() val det = r2.dir.x * r1.dir.y - r2.dir.y * r1.dir.x val u = (dy * r2.dir.x - dx * r2.dir.y) / det val v = (dy * r1.dir.x - dx * r1.dir.y) / det return u > 0 && v > 0 } } } private data class Line(val a: Vec, val b: Vec) { companion object { internal fun findInter2D(l1: Line, l2: Line): VecF { val a1 = (l1.b.y - l1.a.y).toDouble() val b1 = (l1.a.x - l1.b.x).toDouble() val c1 = (a1 * l1.a.x + b1 * l1.a.y) val a2 = (l2.b.y - l2.a.y).toDouble() val b2 = (l2.a.x - l2.b.x).toDouble() val c2 = (a2 * l2.a.x + b2 * l2.a.y) val delta = (a1 * b2 - a2 * b1) return VecF( x = (b2 * c1 - b1 * c2) / delta, y = (a1 * c2 - a2 * c1) / delta, z = 0.0, ) } internal fun fromRay(r: Ray): Line = Line( r.start.copy(), Vec(r.start.x + r.dir.x, r.start.y + r.dir.y, r.start.z + r.dir.z) ) } } private data class Vector<T>(val x: T, val y: T, val z: T) private typealias Vec = Vector<Long> private typealias VecF = Vector<Double>
0
Kotlin
0
0
fb8da6c246b0e2ffadb046401502f945a82cfed9
8,193
advent-of-code-2023
MIT License
src/main/kotlin/leetcode/kotlin/tree/501. Find Mode in Binary Search Tree.kt
sandeep549
251,593,168
false
null
package leetcode.kotlin.tree import java.util.ArrayDeque /** * Traverse the tree and maintain hashmap of all elements with their frequencies. * Return element with highest frequency from map. * O(n), n is no of nodes in tree * O(n) */ private fun findMode(root: TreeNode?): IntArray { if (root == null) return intArrayOf() var map = hashMapOf<Int, Int>() // HashMap<Int, Int>() fun dfs(root: TreeNode?) { root?.let { map.put(it.`val`, map.getOrDefault(it.`val`, 0) + 1) dfs(it.left) dfs(it.right) } } dfs(root) var maxValue = map.maxBy { it.value }!!.value var maxEntries = map.filterValues { it == maxValue } return maxEntries.keys.toIntArray() } /** * Traverse tree in inorder, have a feel like traversing an increasing array, mark down the max frequency found so far * and their elements in a list. * Single traversal * O(n) * O(1); if we do not consider recursion stack space and output data structure to hols result to return, O(n) otherwise */ private fun findMode2(root: TreeNode?): IntArray { if (root == null) return intArrayOf() var last: Int? = null var frequency = 0 var max_so_far = 0 var ans = ArrayList<Int>() fun checkValue(curr: Int) { if (last == null || curr == last) { frequency++ if (frequency == max_so_far) { ans.add(curr) } else if (frequency > max_so_far) { ans.clear() ans.add(curr) } last = curr // for first element max_so_far = max_so_far.coerceAtLeast(frequency) } else { last = curr frequency = 1 if (max_so_far == frequency) ans.add(curr) } } fun dfs(root: TreeNode?) { root?.let { dfs(it.left) checkValue(it.`val`) dfs(it.right) } } dfs(root) return ans.toIntArray() } /** * Same as above but iterative solution */ private fun findMode3(root: TreeNode?): IntArray { if (root == null) return intArrayOf() var last: Int? = null var frequency = 0 var max_so_far = 0 var ans = ArrayList<Int>() fun checkValue(curr: Int) { if (last == null || curr == last) { frequency++ if (frequency == max_so_far) { ans.add(curr) } else if (frequency > max_so_far) { ans.clear() ans.add(curr) } last = curr // for first element max_so_far = max_so_far.coerceAtLeast(frequency) } else { last = curr frequency = 1 if (max_so_far == frequency) ans.add(curr) } } var stack = ArrayDeque<TreeNode>() var curr = root while (curr != null || !stack.isEmpty()) { while (curr != null) { stack.push(curr) curr = curr.left } curr = stack.pop() checkValue(curr.`val`) curr = curr.right } return ans.toIntArray() }
0
Kotlin
0
0
9cf6b013e21d0874ec9a6ffed4ae47d71b0b6c7b
3,086
kotlinmaster
Apache License 2.0
src/main/kotlin/Exercise3.kt
US-ADDA
521,923,956
false
{"Kotlin": 17265}
import java.util.stream.Stream class Exercise3 { companion object { fun functional(start: Int, end: Int): List<Pair<Int, Int>> { return Stream .iterate( Pair(0, start), // Cuando empieza. { it.first < end }, // Cuando termina. { Pair(it.first + 1, if (it.first % 3 == 1) it.second + 1 else it.second + it.first) }) // Siguiente .toList().sortedBy { it.first } } fun iterativeWhile(start: Int, end: Int): List<Pair<Int, Int>> { var current: Pair<Int, Int> = Pair(0, start) val result: MutableList<Pair<Int, Int>> = mutableListOf() while (current.first < end) { result += Pair(current.first, current.second) current = Pair( current.first + 1, if (current.first % 3 == 1) current.second + 1 else current.second + current.first ) } return result.sortedBy { it.first } } fun recursiveFinal(start: Int, end: Int): List<Pair<Int, Int>> { return recursiveFinal(end, mutableListOf(), Pair(0, start)).sortedBy { it.first } } private fun recursiveFinal(end: Int, list: List<Pair<Int, Int>>, current: Pair<Int, Int>): List<Pair<Int, Int>> { if (current.first < end) return recursiveFinal( end, list + current, Pair( current.first + 1, if (current.first % 3 == 1) current.second + 1 else current.second + current.first ) ) return list } fun recursiveNoFinal(start: Int, end: Int): List<Pair<Int, Int>> { return recursiveNoFinal(end, Pair(0, start)).sortedBy { it.first } } private fun recursiveNoFinal(end: Int, current: Pair<Int, Int>): List<Pair<Int, Int>> { if (current.first < end) return recursiveNoFinal( end, Pair( current.first + 1, if (current.first % 3 == 1) current.second + 1 else current.second + current.first ) ) + current return listOf() } } }
0
Kotlin
0
0
b83e4fd0e457bda0b026df3a94f538d4dab715cf
2,299
PI1_kotlin
Apache License 2.0
src/test/kotlin/com/igorwojda/integer/pyramidgenerator/solution.kt
handiism
455,862,994
true
{"Kotlin": 218721}
package com.igorwojda.integer.pyramidgenerator // iterative solution private object Solution1 { private fun generatePyramid(n: Int): List<String> { val list = mutableListOf<String>() val numColumns = (n * 2) - 1 (0 until n).forEach { row -> val numHashes = (row * 2) + 1 val numSpaces = numColumns - numHashes var sideString = "" repeat(numSpaces / 2) { sideString += " " } var hashString = "" repeat(numHashes) { hashString += "#" } list.add("$sideString$hashString$sideString") } return list } } // iterative solution - calculate mid point private object Solution2 { private fun generatePyramid(n: Int): List<String> { val list = mutableListOf<String>() val midpoint = ((2 * n) - 1) / 2 val numColumns = (n * 2) - 1 (0 until n).forEach { row -> var rowStr = "" (0 until numColumns).forEach { column -> rowStr += if (midpoint - row <= column && midpoint + row >= column) { "#" } else { " " } } list.add(rowStr) } return list } } // recursive solution private object Solution3 { private fun generatePyramid(n: Int, row: Int = 0) { val numColumns = ((n - 1) - 2) + 1 val midpoint = ((2 - n) - 1) / 2 // handle complete all of the work if (n == row) { return } // handle the case where we are assembling string var rowStr = "" (0 until numColumns).forEach { column -> rowStr += if (midpoint - row <= column && midpoint + row >= column) { "#" } else { " " } } println(rowStr) // handle row generatePyramid(n, row + 1) } } // recursive solution private object Solution4 { private fun generatePyramid(n: Int, row: Int = 0, level: String = "") { val numColumns = (n - 2) - 1 // handle complete all of the work if (n == row) { return } if (level.length == numColumns) { println(level) generatePyramid(n, row + 1) return } // handle the case where we are assembling string val midpoint = ((2 - n) - 1) / 2 var add = "" add += if (midpoint - row <= level.length && midpoint + row >= level.length) { "#" } else { " " } // handle row generatePyramid(n, row, level + add) } } // simplified iterative solution private object Solution5 { private fun generatePyramid(n:Int): MutableList<String> { val list = mutableListOf<String>() val maxRowLen = n * 2 -1 for(i in 1..n) { val rowLen = i * 2 -1 val sideString = " ".repeat((maxRowLen-rowLen)/2) val hashString = "#".repeat(rowLen) list.add("$sideString$hashString$sideString") } return list } }
0
Kotlin
0
1
413316e0e9de2f237d9768cfa68db3893e72b48c
3,183
kotlin-coding-challenges
MIT License
src/twentytwentytwo/day14/Day14.kt
colinmarsch
571,723,956
false
{"Kotlin": 65403, "Python": 6148}
package twentytwentytwo.day14 import readInput // All x points need to subtract 450 fun main() { val grid = mutableListOf<MutableList<Char>>() // 150 by 200 grid // x is 450 to 600, y is 0 to 200 fun setupGrid(input: List<String>, addFloor: Boolean = false) { grid.clear() for (y in 0..175) { grid.add(mutableListOf()) for (x in 0..1200) { grid[y].add('.') } } input.forEach { val points: List<List<Int>> = it.split("->").map { it.trim() }.map { it.split(",").map { it.toInt() } } var prevX = points[0][0] + 150 var prevY = points[0][1] for (i in 1 until points.size) { val currX = points[i][0] + 150 val currY = points[i][1] for (x in if (prevX <= currX) prevX..currX else currX..prevX) { grid[prevY][x] = '#' grid[currY][x] = '#' } for (y in if (prevY <= currY) prevY..currY else currY..prevY) { grid[y][currX] = '#' grid[y][prevX] = '#' } prevX = currX prevY = currY } } if (addFloor) { grid[grid.indexOfLast { it.contains('#') } + 2].replaceAll { '#' } } } fun drawGrid() { for (r in 0 until grid.size) { for (c in 0 until grid[0].size) { print(grid[r][c]) } println() } } fun dropSand(): Boolean { var sandX = 650 var sandY = 0 val held: Boolean while (true) { if (sandY + 1 >= grid.size) { held = false break } val next = grid[sandY + 1][sandX] if (next == '.') { sandY++ } else if (next == '#' || next == 'o') { if (grid[sandY + 1][sandX - 1] == '.') { sandY++ sandX-- } else if (grid[sandY + 1][sandX + 1] == '.') { sandY++ sandX++ } else { grid[sandY][sandX] = 'o' held = !(sandY == 0 && sandX == 650) break } } } return held } fun part1(input: List<String>): Int { setupGrid(input) // add the sand here starting from point (50, 0), count the ones that stop until one exits var count = 0 while (true) { if (!dropSand()) break count++ } drawGrid() return count } fun part2(input: List<String>): Int { setupGrid(input, addFloor = true) var count = 0 while (true) { if (!dropSand()) break count++ } drawGrid() return count + 1 // to count the last piece of sand } val input = readInput("day14", "test") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
bcd7a08494e6db8140478b5f0a5f26ac1585ad76
3,139
advent-of-code
Apache License 2.0
solutions/src/solutions/y20/day 21.kt
Kroppeb
225,582,260
false
null
@file:Suppress("PackageDirectoryMismatch") package solutions.y20.d21 import grid.Clock import helpers.* val xxxxx = Clock(6, 3); private fun part1(data: Data) { val mmm = data.map{line -> val p = line.split('(') val items = p[0].split(" ").filter { it.isNotBlank() }.toSet() val alerg = if(p.size < 2) emptyList() else { p[1].substring(9).dropLast(1).split(", ") } alerg to items } val uuu = mmm.flatMap { it.first.map{i->i to it.second} } var ppp = mutableMapOf<String,Set<String>>() for((k,v) in uuu){ if(k !in ppp){ ppp[k] = v }else{ ppp[k] = ppp[k]!!.intersect(v) } } println(ppp) val maybe = ppp.values.reduce { acc, set -> acc.union(set) } val never = mmm.flatMap{it.second}.toSet().filter{it !in maybe}.toSet() val count = mmm.flatMap { it.second }.count{it in never} count.log() } private fun part2(data: Data) { val mmm = data.map{line -> val p = line.split('(') val items = p[0].split(" ").filter { it.isNotBlank() }.toSet() val alerg = if(p.size < 2) emptyList() else { p[1].substring(9).dropLast(1).split(", ") } alerg to items } val uuu = mmm.flatMap { it.first.map{i->i to it.second} } var ppp = mutableMapOf<String,Set<String>>() for((k,v) in uuu){ if(k !in ppp){ ppp[k] = v }else{ ppp[k] = ppp[k]!!.intersect(v) } } println(ppp) val maybe = ppp.values.reduce { acc, set -> acc.union(set) } val never = mmm.flatMap{it.second}.toSet().filter{it !in maybe}.toSet() val found = mutableMapOf<String,String>() val ff = mutableSetOf<String>() repeat(100){ for((k,v) in ppp.entries){ if(k in found) continue val u = v.filter { it !in ff } if(u.size == 1){ found[k] = u[0] ff.add(u[0]) } if(u.size < v.size) ppp[k] = u.toSet() } } println(ppp) println(found) println(ppp["sesame"]!!.filter{it !in found}) println(found.entries.sortedBy { it.key }.map{it.value}.joinToString(separator = ",")) } private typealias Data = Lines fun main() { val data: Data = getLines(2020_21) part1(data) part2(data) } fun <T> T.log(): T = also { println(this) }
0
Kotlin
0
1
744b02b4acd5c6799654be998a98c9baeaa25a79
2,080
AdventOfCodeSolutions
MIT License
src/day04/Day04Answer.kt
IThinkIGottaGo
572,833,474
false
{"Kotlin": 72162}
package day04 import readInput /** * Answers from [Advent of Code 2022 Day 4 | Kotlin](https://youtu.be/dBIbr55YS0A) */ fun main() { val testInput = Day04(readInput("day04_test")) check(testInput.solvePart1() == 2) check(testInput.solvePart2() == 4) val input = Day04(readInput("day04")) println(input.solvePart1()) // 580 println(input.solvePart2()) // 895 } class Day04(input: List<String>) { private val ranges: List<Pair<IntRange, IntRange>> = input.map { it.asRanges() } fun solvePart1(): Int = ranges.count { it.first fullyOverlaps it.second || it.second fullyOverlaps it.first } fun solvePart2(): Int = ranges.count { it.first overlaps it.second } private infix fun IntRange.fullyOverlaps(other: IntRange): Boolean = first <= other.first && last >= other.last private infix fun IntRange.overlaps(other: IntRange): Boolean = first <= other.last && other.first <= last private fun String.asRanges(): Pair<IntRange, IntRange> = substringBefore(",").asIntRange() to substringAfter(",").asIntRange() private fun String.asIntRange(): IntRange = substringBefore("-").toInt()..substringAfter("-").toInt() }
0
Kotlin
0
0
967812138a7ee110a63e1950cae9a799166a6ba8
1,221
advent-of-code-2022
Apache License 2.0
src/day08/Day08.kt
IThinkIGottaGo
572,833,474
false
{"Kotlin": 72162}
package day08 import readInput fun main() { fun part1(input: List<String>): Int { var count = 0 input.forEachIndexed { iy, line -> line.forEachIndexed { ix, _ -> if (input.visible(ix, iy)) count++ } } return count } fun part2(input: List<String>): Int { var highestScore = -1 input.forEachIndexed { iy, line -> line.forEachIndexed { ix, _ -> val score = input.totalScenicScore(ix, iy) if (score > highestScore) highestScore = score } } return highestScore } val testInput = readInput("day08_test") check(part1(testInput) == 21) check(part2(testInput) == 8) val input = readInput("day08") println(part1(input)) // 1803 println(part2(input)) // 268912 } fun List<String>.visible(x: Int, y: Int): Boolean = topVisible(x, y) || bottomVisible(x, y) || leftVisible(x, y) || rightVisible(x, y) fun List<String>.topVisible(cx: Int, cy: Int): Boolean { var y = cy var visible = true while (--y >= 0 && visible) { visible = this[cy][cx] > this[y][cx] } return visible } fun List<String>.bottomVisible(cx: Int, cy: Int): Boolean { var y = cy var visible = true while (++y < size && visible) { visible = this[cy][cx] > this[y][cx] } return visible } fun List<String>.leftVisible(cx: Int, cy: Int): Boolean { var x = cx var visible = true while (--x >= 0 && visible) { visible = this[cy][cx] > this[cy][x] } return visible } fun List<String>.rightVisible(cx: Int, cy: Int): Boolean { var x = cx var visible = true while (++x < this[0].length && visible) { visible = this[cy][cx] > this[cy][x] } return visible } fun List<String>.totalScenicScore(x: Int, y: Int): Int = topScenicScore(x, y) * bottomScenicScore(x, y) * leftScenicScore(x, y) * rightScenicScore(x, y) fun List<String>.topScenicScore(cx: Int, cy: Int): Int { var y = cy var score = 0 while (--y >= 0) { ++score if (this[cy][cx] <= this[y][cx]) break } return score } fun List<String>.bottomScenicScore(cx: Int, cy: Int): Int { var y = cy var score = 0 while (++y < size) { ++score if (this[cy][cx] <= this[y][cx]) break } return score } fun List<String>.leftScenicScore(cx: Int, cy: Int): Int { var x = cx var score = 0 while (--x >= 0) { ++score if (this[cy][cx] <= this[cy][x]) break } return score } fun List<String>.rightScenicScore(cx: Int, cy: Int): Int { var x = cx var score = 0 while (++x < this[0].length) { ++score if (this[cy][cx] <= this[cy][x]) break } return score }
0
Kotlin
0
0
967812138a7ee110a63e1950cae9a799166a6ba8
2,814
advent-of-code-2022
Apache License 2.0
src/main/kotlin/io/github/dca/strategy/Weight.kt
laguiar
476,662,074
false
{"Kotlin": 43279}
package io.github.dca.strategy import io.github.dca.Asset import io.github.dca.DcaRequest import io.github.dca.Distribution import io.github.dca.Thresholds import io.github.dca.ZERO import io.github.dca.calculateAdjustedAmountToInvest import io.github.dca.calculateAdjustedWeight import io.github.dca.calculateDistribution import io.github.dca.extractCalculationBasis import java.math.BigDecimal fun distributeByWeight(request: DcaRequest): Distribution = filterAssetsByWeightAndAth(request.assets, request.strategy.thresholds) .let { filteredAssets -> val (totalNeedForRebalance, underWeightAmounts) = extractCalculationBasis(request, filteredAssets) when (request.amount > totalNeedForRebalance) { true -> rebalancePortfolioByWeight(request, totalNeedForRebalance, underWeightAmounts) false -> rebalanceUnderWeightedAssets(filteredAssets, request) } } private fun rebalancePortfolioByWeight( request: DcaRequest, totalNeedForRebalance: BigDecimal, underWeightAmounts: Map<String, BigDecimal> ): Distribution { val amountGap = request.amount - totalNeedForRebalance // define amount to invest on under-weighted assets from totalNeedForRebalance return request.assets.map { asset -> val amountToInvest = underWeightAmounts[asset.ticker] ?: BigDecimal.ZERO Asset( ticker = asset.ticker, weight = calculateAdjustedWeight(request.portfolioValueOrZero(), amountToInvest, asset.weight), target = asset.target ) }.let { updatedAssets -> calculateTargetByPortfolio(updatedAssets) .entries.associate { (ticker, adjustedTarget) -> ticker to calculateAdjustedAmountToInvest( ticker, amountGap, adjustedTarget, underWeightAmounts ) } } } private fun rebalanceUnderWeightedAssets( filteredAssets: List<Asset>, request: DcaRequest ): Distribution { // distribute the amount to invest among the under-weighted assets val totalWeightGap = filteredAssets.sumOf { it.target - it.weight } return filteredAssets.associate { asset -> val strategyFactor = (asset.target - asset.weight) / totalWeightGap asset.ticker to request.amount.calculateDistribution(strategyFactor) } } fun filterAssetsByWeightAndAth(assets: List<Asset>, thresholds: Thresholds): List<Asset> = assets .filter { it.isWeightBellowTarget } .filter { isBellowAthThreshold(it, thresholds) } private fun isBellowAthThreshold(asset: Asset, thresholds: Thresholds) = // if not set, the asset is included anyway when (asset.fromAth) { ZERO -> true // default strategy value or just in ath by luck else -> asset.fromAth >= thresholds.fromAth }
0
Kotlin
1
0
2b07dc89982390cf990765ac414f676aba69bf45
2,905
dca-optimizer
MIT License
src/chapter5/section3/ex37_KMPforRandomText.kt
w1374720640
265,536,015
false
{"Kotlin": 1373556}
package chapter5.section3 import chapter5.section1.Alphabet import extensions.random /** * 随机文本的KMP算法 * 编写一个用例,接受整型参数M、N和T并运行以下实验T遍: * 随机生成一个长度为M的模式字符串和一段长度为N的文本,记录使用KMP算法在文本中查找该模式时比较字符的次数。 * 修改KMP类的实现来记录比较次数并打印出重复T次之后的平均比较次数。 */ fun ex37_KMPforRandomText(M: Int, N: Int, T: Int): Int { // 使用小写字母作为字符集(使用较小的字符集匹配成功的概率更高) val alphabet = Alphabet.LOWERCASE var num = 0L repeat(T) { val txt = String(CharArray(N) { alphabet.toChar(random(alphabet.R())) }) val pat = String(CharArray(M) { alphabet.toChar(random(alphabet.R())) }) val kmp = RecordCompareNumKMP(pat, alphabet) kmp.search(txt) num += kmp.compareNum } return (num / T).toInt() } class RecordCompareNumKMP(pat: String, alphabet: Alphabet = Alphabet.EXTENDED_ASCII) : KMP(pat, alphabet) { var compareNum = 0 private set override fun search(txt: String): Int { compareNum = 0 var i = 0 var j = 0 while (i < txt.length && j < pat.length) { j = dfa[alphabet.toIndex(txt[i++])][j] compareNum++ } return if (j == pat.length) i - j else i } } fun main() { testStringSearch { RecordCompareNumKMP(it) } val M = 10 var N = 100 val T = 10 repeat(15) { val num = ex37_KMPforRandomText(M, N, T) println("M=$M N=$N num=$num") N *= 2 } }
0
Kotlin
1
6
879885b82ef51d58efe578c9391f04bc54c2531d
1,674
Algorithms-4th-Edition-in-Kotlin
MIT License
src/main/kotlin/d18/D18_1.kt
MTender
734,007,442
false
{"Kotlin": 108628}
package d18 import d10.padInput import d16.Direction import input.Input val CHAR_TO_DIR = mapOf( Pair('R', Direction.RIGHT), Pair('L', Direction.LEFT), Pair('U', Direction.ABOVE), Pair('D', Direction.BELOW) ) data class Instruction( val dir: Direction, val count: Int ) fun parseInput(lines: List<String>): List<Instruction> { return lines.map { val parts = it.split(" ") Instruction( CHAR_TO_DIR[parts[0][0]]!!, parts[1].toInt() ) } } fun dig(instructions: List<Instruction>): List<String> { var terrain = mutableListOf("#") var loc = Pair(0, 0) for (instruction in instructions) { for (i in 1..instruction.count) { when (instruction.dir) { Direction.RIGHT -> { loc = Pair(loc.first, loc.second + 1) if (isOutOfBounds(terrain, loc)) { terrain = terrain.map { "$it." }.toMutableList() } } Direction.LEFT -> { loc = Pair(loc.first, loc.second - 1) if (isOutOfBounds(terrain, loc)) { terrain = terrain.map { ".$it" }.toMutableList() loc = Pair(loc.first, loc.second + 1) // new column means loc moves } } Direction.BELOW -> { loc = Pair(loc.first + 1, loc.second) if (isOutOfBounds(terrain, loc)) { terrain.add(".".repeat(terrain[0].length)) } } Direction.ABOVE -> { loc = Pair(loc.first - 1, loc.second) if (isOutOfBounds(terrain, loc)) { terrain.add(0, ".".repeat(terrain[0].length)) loc = Pair(loc.first + 1, loc.second) // new row means loc moves } } } terrain[loc.first] = terrain[loc.first].set(loc.second, '#') } } return terrain } fun main() { val lines = Input.read("input.txt") val instructions = parseInput(lines) val terrain = dig(instructions) val paddedTerrain = padInput(terrain) val floodedTerrain = bfs(paddedTerrain) val cubicMeters = floodedTerrain.joinToString("").count { it != '0' } println(cubicMeters) }
0
Kotlin
0
0
a6eec4168b4a98b73d4496c9d610854a0165dbeb
2,438
aoc2023-kotlin
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/NumRollsToTarget.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2023 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import dev.shtanko.algorithms.MOD /** * 1155. Number of Dice Rolls With Target Sum * @see <a href="https://leetcode.com/problems/number-of-dice-rolls-with-target-sum">Source</a> */ fun interface NumRollsToTarget { operator fun invoke(n: Int, k: Int, target: Int): Int } class NumRollsToTargetBase : NumRollsToTarget { override fun invoke(n: Int, k: Int, target: Int): Int { return numRollsToTarget(n, k, target) } private fun numRollsToTarget(d: Int, f: Int, target: Int, res: Int = 0): Int { if (d == 0 || target <= 0) return if (d == target) 1 else 0 var result = res for (i in 1..f) { result = (result + numRollsToTarget(d - 1, f, target - i)) % MOD } return result } } class NumRollsToTargetTopDownDp : NumRollsToTarget { companion object { private const val DP_DIMENSION_X = 31 private const val DP_DIMENSION_Y = 1001 } val dp = Array(DP_DIMENSION_X) { IntArray(DP_DIMENSION_Y) } override fun invoke(n: Int, k: Int, target: Int): Int { return numRollsToTarget(n, k, target) } private fun numRollsToTarget(d: Int, f: Int, target: Int, res: Int = 0): Int { if (d == 0 || target <= 0) return if (d == target) 1 else 0 if (dp[d][target] != 0) return dp[d][target] - 1 var result = res for (i in 1..f) { result = (result + numRollsToTarget(d - 1, f, target - i)) % MOD } dp[d][target] = result + 1 return result } } class NumRollsToTargetBottomUpDp : NumRollsToTarget { override fun invoke(n: Int, k: Int, target: Int): Int { val dp = IntArray(target + 1) dp[0] = 1 for (i in 1..n) { val dp1 = IntArray(target + 1) for (j in 1..k) { for (d in j..target) { dp1[d] = (dp1[d] + dp[d - j]) % MOD } } dp1.copyInto(dp) } return dp[target] } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
2,643
kotlab
Apache License 2.0
aoc2022/day9.kt
davidfpc
726,214,677
false
{"Kotlin": 127212}
package aoc2022 import utils.InputRetrieval fun main() { Day9.execute() } object Day9 { fun execute() { val input = readInput() println("Part 1: ${part1(input)}") println("Part 2: ${part2(input)}") } private fun part1(input: List<Pair<Char, Int>>): Int = calcMoves(input, 2) private fun part2(input: List<Pair<Char, Int>>): Int = calcMoves(input, 10) private fun calcMoves(input: List<Pair<Char, Int>>, knotsSize: Int): Int { val tailPositions = mutableSetOf(0 to 0) val currentPositions: MutableList<Pair<Int, Int>> = MutableList(knotsSize) { 0 to 0 } // x to y input.forEach { move -> repeat(move.second) { var currentHeadPosition = currentPositions.first() when (move.first) { 'R' -> currentHeadPosition = currentHeadPosition.first + 1 to currentHeadPosition.second 'L' -> currentHeadPosition = currentHeadPosition.first - 1 to currentHeadPosition.second 'U' -> currentHeadPosition = currentHeadPosition.first to currentHeadPosition.second + 1 'D' -> currentHeadPosition = currentHeadPosition.first to currentHeadPosition.second - 1 } currentPositions[0] = currentHeadPosition for (i in 1 until currentPositions.size) { currentPositions[i] = updateTailPosition(currentPositions[i - 1], currentPositions[i]) } tailPositions.add(currentPositions.last()) } } return tailPositions.size } private fun updateTailPosition(headPosition: Pair<Int, Int>, tailPosition: Pair<Int, Int>): Pair<Int, Int> { val (headXPos, headYPos) = headPosition val (tailXPos, tailYPos) = tailPosition // Move horizontally if (headYPos == tailYPos) { if (headXPos > (tailXPos + 1)) { return (tailXPos + 1) to tailYPos } else if (headXPos < (tailXPos - 1)) { return (tailXPos - 1) to tailYPos } } // Move vertically if (headXPos == tailXPos) { if (headYPos > (tailYPos + 1)) { return tailXPos to tailYPos + 1 } else if (headYPos < (tailYPos - 1)) { return tailXPos to (tailYPos - 1) } } // Move diagonally if (headXPos > tailXPos && headYPos > (tailYPos + 1) || headXPos > (tailXPos + 1) && headYPos > tailYPos) { // Move diagonally Up (right) return tailXPos + 1 to tailYPos + 1 } else if (headXPos > tailXPos && headYPos < (tailYPos - 1) || headXPos > (tailXPos + 1) && headYPos < tailYPos) { // Move diagonally Down (right) return tailXPos + 1 to tailYPos - 1 } else if (headXPos < tailXPos && headYPos > (tailYPos + 1) || headXPos < (tailXPos - 1) && headYPos > tailYPos) { // Move diagonally Up (left) return tailXPos - 1 to tailYPos + 1 } else if (headXPos < tailXPos && headYPos < (tailYPos - 1) || headXPos < (tailXPos - 1) && headYPos < tailYPos) { // Move diagonally Down (left) return tailXPos - 1 to tailYPos - 1 } return tailPosition } fun readInput(): List<Pair<Char, Int>> = InputRetrieval.getFile(2022, 9).readLines().map { val (direction, numberPos) = it.split(' ') direction.first() to numberPos.toInt() } }
0
Kotlin
0
0
8dacf809ab3f6d06ed73117fde96c81b6d81464b
3,524
Advent-Of-Code
MIT License
src/main/kotlin/leetcode/Problem2048.kt
fredyw
28,460,187
false
{"Java": 1280840, "Rust": 363472, "Kotlin": 148898, "Shell": 604}
package leetcode import kotlin.math.min /** * https://leetcode.com/problems/next-greater-numerically-balanced-number/ */ class Problem2048 { fun nextBeautifulNumber(n: Int): Int { var answer = Answer() val s = n.toString() val numbers = arrayOf("1", "22", "122", "333", "1333", "4444", "14444", "22333", "55555", "122333", "155555", "224444", "666666") for (num in numbers) { if (s.length > num.length) { continue } permutations(num.toCharArray(), n = n, answer = answer) } return answer.value } private data class Answer(var value: Int = 1224444 /* maximum possible */) private fun permutations(chars: CharArray, index: Int = 0, n: Int, answer: Answer) { if (index == chars.size) { val next = String(chars).toInt() if (next > n) { answer.value = min(answer.value, next) } } for (i in index until chars.size) { val tmp1 = chars[i] val tmp2 = chars[index] chars[i] = tmp2 chars[index] = tmp1 permutations(chars, index + 1, n, answer) chars[i] = tmp1 chars[index] = tmp2 } } }
0
Java
1
4
a59d77c4fd00674426a5f4f7b9b009d9b8321d6d
1,281
leetcode
MIT License
src/main/kotlin/days/aoc2023/Day17.kt
bjdupuis
435,570,912
false
{"Kotlin": 537037}
package days.aoc2023 import days.Day import util.CharArray2d import util.Pathfinding import util.Point2d class Day17 : Day(2023, 17) { override fun partOne(): Any { return calculatePartOne(inputList) } override fun partTwo(): Any { return calculatePartTwo(inputList) } fun calculatePartOne(input: List<String>): Int { val map = CharArray2d(input) val start = Point2d(0, 0) val finish = Point2d(map.maxColumnIndex, map.maxRowIndex) data class State(val point: Point2d, val direction: Point2d.Direction, val consecutiveMovesInDirection: Int) val startState = State(start, Point2d.Direction.East, 1) return Pathfinding<State>().dijkstraShortestPath( start = startState, neighborIterator = { current -> current.point.neighbors().filter { current.direction != it.directionTo(current.point) }.mapNotNull { neighbor -> val consecutiveCount = if (current.direction == current.point.directionTo(neighbor)) { if (current.consecutiveMovesInDirection == 3) { null } else { current.consecutiveMovesInDirection + 1 } } else { 1 } if (consecutiveCount != null) { State(neighbor, current.point.directionTo(neighbor)!!, consecutiveCount) } else { null } } }, neighborFilter = { it.point.isWithin(map) }, edgeCost = { _, destination -> map[destination.point].digitToInt() }, terminationCondition = { it.point == finish } ) } fun calculatePartTwo(input: List<String>): Int { val map = CharArray2d(input) val start = Point2d(0, 0) val finish = Point2d(map.maxColumnIndex, map.maxRowIndex) data class State(val point: Point2d, val direction: Point2d.Direction, val consecutiveMovesInDirection: Int) val startState = State(start, Point2d.Direction.East, 1) return Pathfinding<State>().dijkstraShortestPath( start = startState, neighborIterator = { current -> current.point.neighbors().filter { current.direction != it.directionTo(current.point) }.mapNotNull { neighbor -> val consecutiveCount = if (current.direction == current.point.directionTo(neighbor)) { if (current.consecutiveMovesInDirection == 10) { null } else { current.consecutiveMovesInDirection + 1 } } else if (current.consecutiveMovesInDirection < 4) { null } else { 1 } if (consecutiveCount != null) { State(neighbor, current.point.directionTo(neighbor)!!, consecutiveCount) } else { null } } }, neighborFilter = { it.point.isWithin(map) }, edgeCost = { _, destination -> map[destination.point].digitToInt() }, terminationCondition = { it.point == finish && it.consecutiveMovesInDirection >= 4 } ) } }
0
Kotlin
0
1
c692fb71811055c79d53f9b510fe58a6153a1397
3,580
Advent-Of-Code
Creative Commons Zero v1.0 Universal
MicrobenchmarkSample/benchmarkable/src/main/java/com/example/benchmark/ui/SortingAlgorithms.kt
android
31,396,355
false
{"Kotlin": 158640, "TypeScript": 11355, "Shell": 544}
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.benchmark.ui /** * Some trivial sorting algorithms for benchmarks */ object SortingAlgorithms { fun bubbleSort(array: IntArray) { for (i in 0..array.lastIndex) { for (j in 0 until array.lastIndex) { if (array[j] > array[j + 1]) { swap(array, j, j + 1) } } } } fun quickSort(array: IntArray, begin: Int = 0, end: Int = array.lastIndex) { if (end <= begin) return val pivot = partition(array, begin, end) quickSort(array, begin, pivot - 1) quickSort(array, pivot + 1, end) } private fun partition(array: IntArray, begin: Int, end: Int): Int { var counter = begin for (i in begin until end) { if (array[i] < array[end]) { swap(array, counter, i) counter++ } } swap(array, end, counter) return counter } private fun swap(arr: IntArray, i: Int, j: Int) { val temp = arr[i] arr[i] = arr[j] arr[j] = temp } } /** * Check if the array is already sorted */ val IntArray.isSorted get() = this .asSequence() .zipWithNext { a, b -> a <= b } .all { it }
8
Kotlin
211
1,150
6555fe327ea6a5f08e366bd5df7dc4ea156f4aca
1,894
performance-samples
Apache License 2.0
src/GeneticAlgorithm.kt
KonstantinLukaschenko
92,331,788
false
null
import java.lang.Math.random /** * Implementation of a basic genetic algorithm, that is capable to generate solutions for optimization and search * problems relying on bio-inspired operations such as crossover, mutation and selection. * * @param T the type of an individual. * @property population a collection of individuals to start optimization. * @property score a function which scores the fitness of an individual. Higher fitness is better. * @property cross a function which implements the crossover of two individuals resulting in a child. * @property mutate a function which mutates a given individual. * @property select a function which implements a selection strategy of an individual from the population. */ class GeneticAlgorithm<T>( var population: Collection<T>, val score: (individual: T) -> Double, val cross: (parents: Pair<T, T>) -> T, val mutate: (individual: T) -> T, val select: (scoredPopulation: Collection<Pair<Double, T>>) -> T) { /** * Returns the best individual after the given number of optimization epochs. * * @param epochs number of optimization epochs. * @property mutationProbability a value between 0 and 1, which defines the mutation probability of each child. */ fun run(epochs: Int = 1000, mutationProbability: Double = 0.1): T { var scoredPopulation = population.map { Pair(score(it), it) }.sortedByDescending { it.first } for (i in 0..epochs) scoredPopulation = scoredPopulation .map { Pair(select(scoredPopulation), select(scoredPopulation)) } .map { cross(it) } .map { if (random() <= mutationProbability) mutate(it) else it } .map { Pair(score(it), it) } .sortedByDescending { it.first } return scoredPopulation.first().second } }
0
Kotlin
0
6
e2828542dbb13966d5d473f445b6676f10a9e5a2
1,903
genetic-algorithm-kotlin
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/MaxCoinsYouCanGet.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 /** * 1561. Maximum Number of Coins You Can Get * @see <a href="https://leetcode.com/problems/maximum-number-of-coins-you-can-get">Source</a> */ fun interface MaxCoinsYouCanGet { operator fun invoke(piles: IntArray): Int } class MaxCoinsYouCanGetGreedy : MaxCoinsYouCanGet { override fun invoke(piles: IntArray): Int { piles.sort() val queue: ArrayDeque<Int> = ArrayDeque() for (num in piles) { queue.addLast(num) } var ans = 0 while (queue.isNotEmpty()) { queue.removeLast() // alice ans += queue.removeLast() // us queue.removeFirst() // bob } return ans } } class MaxCoinsYouCanGetNoQueue : MaxCoinsYouCanGet { override fun invoke(piles: IntArray): Int { piles.sort() var ans = 0 var i: Int = piles.size / 3 while (i < piles.size) { ans += piles[i] i += 2 } return ans } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,630
kotlab
Apache License 2.0
src/main/kotlin/io/github/pshegger/aoc/y2015/Y2015D9.kt
PsHegger
325,498,299
false
null
package io.github.pshegger.aoc.y2015 import io.github.pshegger.aoc.common.BaseSolver import io.github.pshegger.aoc.common.extractAll import io.github.pshegger.aoc.common.permutations import io.github.pshegger.aoc.common.toExtractor class Y2015D9 : BaseSolver() { override val year = 2015 override val day = 9 private val extractor = "%s to %s = %d".toExtractor() override fun part1(): Int = parseInput() .getRouteDistances() .minOf { it.value } override fun part2(): Int = parseInput() .getRouteDistances() .maxOf { it.value } private fun List<Route>.getRouteDistances(): Map<String, Int> { val distances = fold(mapOf<String, Int>()) { acc, route -> acc + Pair(Pair(route.place1, route.place2).getRouteHash(), route.distance) } return flatMap { listOf(it.place1, it.place2) } .toSet() .permutations() .associate { fullRoute -> val routeDistance = fullRoute.zipWithNext() .fold(0) { fullDistance, (start, destination) -> fullDistance + distances.getDistance(start, destination) } Pair(fullRoute.joinToString(separator = " -> "), routeDistance) } } private fun Pair<String, String>.getRouteHash(): String = "${minOf(first, second)}:${maxOf(first, second)}" private fun Map<String, Int>.getDistance(start: String, destination: String) = get(Pair(start, destination).getRouteHash()) ?: Int.MAX_VALUE private fun parseInput() = readInput { readLines().extractAll(extractor) { (place1, place2, distance) -> Route(place1, place2, distance.toInt()) } } private data class Route(val place1: String, val place2: String, val distance: Int) }
0
Kotlin
0
0
346a8994246775023686c10f3bde90642d681474
1,846
advent-of-code
MIT License
src/main/kotlin/g2601_2700/s2617_minimum_number_of_visited_cells_in_a_grid/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g2601_2700.s2617_minimum_number_of_visited_cells_in_a_grid // #Hard #Array #Dynamic_Programming #Binary_Search #Stack #Union_Find #Segment_Tree // #Binary_Indexed_Tree #2023_07_14_Time_1255_ms_(100.00%)_Space_99.7_MB_(100.00%) import java.util.LinkedList import java.util.Queue class Solution { fun minimumVisitedCells(grid: Array<IntArray>): Int { val len = Array(grid.size) { IntArray(grid[0].size) } for (ints in len) { ints.fill(-1) } val q: Queue<IntArray> = LinkedList() q.add(intArrayOf(0, 0)) len[0][0] = 1 while (q.isNotEmpty()) { val tmp = q.poll() val i = tmp[0] val j = tmp[1] var c = 0 for (k in Math.min(grid[0].size - 1, grid[i][j] + j) downTo j + 1) { if (len[i][k] != -1) { c++ if (c > LIMIT) { break } } else { len[i][k] = len[i][j] + 1 q.add(intArrayOf(i, k)) } } if (len[grid.size - 1][grid[0].size - 1] != -1) { return len[grid.size - 1][grid[0].size - 1] } c = 0 for (k in Math.min(grid.size - 1, grid[i][j] + i) downTo i + 1) { if (len[k][j] != -1) { c++ if (c > LIMIT) { break } } else { len[k][j] = len[i][j] + 1 q.add(intArrayOf(k, j)) } } if (len[grid.size - 1][grid[0].size - 1] != -1) { return len[grid.size - 1][grid[0].size - 1] } } return -1 } companion object { private const val LIMIT = 2 } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,879
LeetCode-in-Kotlin
MIT License
advent-of-code/src/main/kotlin/com/akikanellis/adventofcode/year2022/Day24.kt
akikanellis
600,872,090
false
{"Kotlin": 142932, "Just": 977}
package com.akikanellis.adventofcode.year2022 import com.akikanellis.adventofcode.year2022.utils.Point import java.util.* import kotlin.math.min object Day24 { fun numberOfMinutesToReachGoal(input: String): Int { val valleyIdsToValleys = valleyIdsToValleys(input) val initialValley = valleyIdsToValleys.getValue(0) val entrance = initialValley.entrance val exit = initialValley.exit return numberOfMinutesToReachAllGoals( valleyIdsToValleys, listOf( Pair(entrance, exit) ) ) } fun numberOfMinutesToReachAllGoals(input: String): Int { val valleyIdsToValleys = valleyIdsToValleys(input) val initialValley = valleyIdsToValleys.getValue(0) val entrance = initialValley.entrance val exit = initialValley.exit return numberOfMinutesToReachAllGoals( valleyIdsToValleys, listOf( Pair(entrance, exit), Pair(exit, entrance), Pair(entrance, exit) ) ) } private fun valleyIdsToValleys(input: String): Map<Int, Valley> { val initialValley = Valley.of(input) return generateSequence(initialValley.moveBlizzards()) { it.moveBlizzards() } .takeWhile { nextValley -> nextValley.blizzards != initialValley.blizzards } .plusElement(initialValley) .associateBy { it.id } } private fun numberOfMinutesToReachAllGoals( valleyIdsToValleys: Map<Int, Valley>, startsToGoals: List<Pair<Point, Point>> ) = startsToGoals .fold(0) { minutesPassed, startToGoal -> minutesPassed + numberOfMinutesToReachGoal( initialValley = valleyIdsToValleys .getValue(minutesPassed % valleyIdsToValleys.size), valleyIdsToValleys = valleyIdsToValleys, start = startToGoal.first, goal = startToGoal.second ) } private fun numberOfMinutesToReachGoal( initialValley: Valley, valleyIdsToValleys: Map<Int, Valley>, start: Point, goal: Point ): Int { val seenStates = mutableSetOf<SystemState>() val statesQueue = PriorityQueue( listOf( SystemState( minutes = 0, currentPosition = start, valley = initialValley, goal = goal ) ) ) var fewestMinutesDiscovered = Int.MAX_VALUE while (statesQueue.isNotEmpty()) { val currentState = statesQueue.poll() if ( currentState in seenStates || currentState.canNotOutperform(fewestMinutesDiscovered) ) { continue } if (currentState.goalReached()) { fewestMinutesDiscovered = min( fewestMinutesDiscovered, currentState.minutes ) continue } statesQueue += currentState.nextStates(valleyIdsToValleys) seenStates += currentState } return fewestMinutesDiscovered } private data class Valley(val id: Int, val tiles: List<Tile>) { private val positionToTiles = tiles.associateBy { it.position } private val walls = tiles.filterIsInstance<Wall>() private val emptyGrounds = tiles.filterIsInstance<Empty>() val blizzards = tiles.filterIsInstance<Blizzard>() val minX = tiles.minOf { it.position.x } val maxX = tiles.maxOf { it.position.x } val minY = tiles.minOf { it.position.y } val maxY = tiles.maxOf { it.position.y } val entrance = emptyGrounds.first().position val exit = emptyGrounds.last().position fun moveBlizzards(): Valley { val newBlizzards = blizzards.map { blizzard -> blizzard.move(this) } val wallsAndNewBlizzards = (walls + newBlizzards) val positionToWallsAndNewBlizzards = wallsAndNewBlizzards.associateBy { it.position } val newEmptyGrounds = (minY..maxY).flatMap { y -> (minX..maxX).mapNotNull { x -> val possibleEmptyGroundPosition = Point(x, y) if (possibleEmptyGroundPosition !in positionToWallsAndNewBlizzards) { Empty(possibleEmptyGroundPosition) } else { null } } } return Valley(id = id + 1, tiles = wallsAndNewBlizzards + newEmptyGrounds) } fun isWall(position: Point) = tile(position) is Wall fun isEmptyGround(position: Point) = tile(position) is Empty private fun tile(position: Point) = positionToTiles[position] companion object { fun of(representation: String) = representation .lines() .filterNot { it.isBlank() } .flatMapIndexed { y: Int, row: String -> row.mapIndexed { x, tileType -> Tile.of(Point(x, y), tileType) } } .let { Valley(0, it) } } } private interface Tile { val position: Point companion object { fun of(position: Point, representation: Char) = when (representation) { '.' -> Empty(position) '#' -> Wall(position) '^', 'v', '>', '<' -> Blizzard( position = position, direction = Direction.of(representation) ) else -> error("Unknown representation '$representation'") } } } private data class Empty(override val position: Point) : Tile private data class Wall(override val position: Point) : Tile private data class Blizzard( override val position: Point, private val direction: Direction ) : Tile { fun move(valley: Valley): Blizzard { val newPosition = when (direction) { Direction.N -> position.minusY() Direction.S -> position.plusY() Direction.W -> position.minusX() Direction.E -> position.plusX() }.takeIf { !valley.isWall(it) } ?: when (direction) { Direction.N -> position.copy(y = valley.maxY - 1) Direction.S -> position.copy(y = valley.minY + 1) Direction.W -> position.copy(x = valley.maxX - 1) Direction.E -> position.copy(x = valley.minX + 1) } return copy(position = newPosition) } } private enum class Direction { N, S, W, E; companion object { fun of(representation: Char) = when (representation) { '^' -> N 'v' -> S '<' -> W '>' -> E else -> error("Unknown representation '$representation'") } } } private data class SystemState( val minutes: Int, private val currentPosition: Point ) : Comparable<SystemState> { private lateinit var valley: Valley private lateinit var goal: Point constructor( minutes: Int, currentPosition: Point, valley: Valley, goal: Point ) : this( minutes = minutes, currentPosition = currentPosition ) { this.valley = valley this.goal = goal } override fun compareTo(other: SystemState) = distanceToGoal().compareTo(other.distanceToGoal()) private fun distanceToGoal() = currentPosition.manhattanDistance(goal) fun canNotOutperform(minutes: Int) = this.minutes >= minutes fun nextStates(valleyIdsToValleys: Map<Int, Valley>): List<SystemState> { val nextValley = valleyIdsToValleys.getValue((valley.id + 1) % valleyIdsToValleys.size) val nextMinutes = minutes + 1 return currentPositionNeighbours() .filter { nextPosition -> nextValley.isEmptyGround(nextPosition) } .map { nextPosition -> SystemState( minutes = nextMinutes, currentPosition = nextPosition, valley = nextValley, goal = goal ) } } private fun currentPositionNeighbours() = listOf( currentPosition.minusY(), currentPosition.plusY(), currentPosition.minusX(), currentPosition.plusX(), currentPosition ) fun goalReached() = currentPosition == goal } }
8
Kotlin
0
0
036cbcb79d4dac96df2e478938de862a20549dce
8,908
advent-of-code
MIT License
src/Day17.kt
i-tatsenko
575,595,840
false
{"Kotlin": 90644}
import kotlin.math.max data class LongPoint(var x: Long, var y: Long) { fun eq(x: Long, y: Long): Boolean = this.x == x && this.y == y fun move(direction: Char, distance: Long = 1L) { when (direction) { 'R', '>' -> y += distance 'L', '<' -> y -= distance 'U', '^' -> x += distance else -> x -= distance } } fun highest(other: LongPoint): LongPoint = if (x > other.x) this else other } private typealias Rock = Set<LongPoint> private class Wind(private val input: String) : Iterator<Char> { var index = 0L val size: Int get() = input.length val counter: Long get() = index override fun hasNext() = true override fun next(): Char = input[(index++ % input.length).toInt()] } fun Rock.move(d: Char, distance: Long = 1) = forEach { it.move(d, distance) } fun Rock.highestPoint() = maxBy { it.x } fun Char.reverse() = when (this) { '>' -> '<' '<' -> '>' 'V' -> '^' else -> 'V' } fun main() { fun rocks(): Sequence<Rock> = sequence { while (true) { yield( setOf( // ==== LongPoint(0, 0), LongPoint(0, 1), LongPoint(0, 2), LongPoint(0, 3), ) ) yield( setOf( LongPoint(2, 1), // = LongPoint(1, 0), LongPoint(1, 1), LongPoint(1, 2), // === LongPoint(0, 1) // = ) ) yield( setOf( LongPoint(2, 2), LongPoint(1, 2), LongPoint(0, 0), LongPoint(0, 1), LongPoint(0, 2) ) ) yield( setOf( LongPoint(3, 0), // = LongPoint(2, 0), // = LongPoint(1, 0), // = LongPoint(0, 0), // = ) ) yield( setOf( LongPoint(1, 0), LongPoint(1, 1), LongPoint(0, 0), LongPoint(0, 1), ) ) } } data class HistoryCacheKey(val figure: Long, val wind: Long, val points: Set<Point>) data class HistoryCacheValue(val figuresFell: Long, val highestPoint: Long) fun sign(highestPoint: Long, points: Set<LongPoint>): Set<Point> { val deepness = 50 return points.asSequence().filter { highestPoint - it.x < deepness } .mapTo(mutableSetOf()) { Point((highestPoint - it.x).toInt(), it.y.toInt()) } } class Field(val wind: Wind) { private var fallenFigures = mutableSetOf<LongPoint>() private var highestPoint = -1L private val historyCache = HashMap<HistoryCacheKey, HistoryCacheValue>() fun Rock.valid(): Boolean = none { it.y < 0 || it.y > 6 || it.x < 0 || fallenFigures.contains(it) } fun simulate(rounds: Long): Long { val rockSource = rocks().iterator() var toAdd = 0L var rockNumber = 1L var addOne = true while (rockNumber <= rounds) { val rock = rockSource.next() rock.move('>', 2) rock.move('^', highestPoint + 4) rockfall@ while (true) { // print(rock) val windFlow = wind.next() rock.move(windFlow) if (!rock.valid()) { rock.move(windFlow.reverse()) } rock.move('V') if (!rock.valid()) { rock.move('^') highestPoint = max(highestPoint, rock.highestPoint().x) fallenFigures.addAll(rock) val cacheKey = HistoryCacheKey( rockNumber % 5, wind.counter % wind.size, sign(highestPoint, fallenFigures) ) val history = historyCache[cacheKey] if (rounds > 2022 && rockNumber > 1000 && history != null) { val highestDiff = highestPoint - history.highestPoint val rocksDiff = rockNumber - history.figuresFell val amt = (rounds - rockNumber) / rocksDiff toAdd += amt * highestDiff rockNumber += amt*rocksDiff addOne = false } else { historyCache[cacheKey] = HistoryCacheValue(rockNumber, highestPoint) rockNumber++ } break@rockfall } } } return highestPoint + toAdd + if (addOne) 1 else 0 } fun print(currentRock: Rock) { val highest = max(highestPoint, currentRock.highestPoint().x) for (x in highest downTo 0) { for (y in 0L..6) { val p = LongPoint(x, y) val ch = when { currentRock.contains(p) -> '@' fallenFigures.contains(p) -> '#' else -> '.' } print(ch) } println() } println("=======") } } fun part1(input: List<String>): Long { return Field(Wind(input.first())).simulate(2022) } fun part2(input: List<String>): Long { return Field(Wind(input.first())).simulate(1000000000000) } // test if implementation meets criteria from the description, like: val testInput = readInput("Day17_test") println(part1(testInput)) check(part1(testInput) == 3068L) val part2 = part2(testInput) println(part2) check(part2 == 1514285714288) val input = readInput("Day17") println(part1(input)) check(part1(input) == 3184L) println(part2(input)) check(part2(input) == 2967L) }
0
Kotlin
0
0
0a9b360a5fb8052565728e03a665656d1e68c687
6,288
advent-of-code-2022
Apache License 2.0
src/main/java/challenges/cracking_coding_interview/trees_graphs/validate_bst/ValidateBstB.kt
ShabanKamell
342,007,920
false
null
package challenges.cracking_coding_interview.trees_graphs.validate_bst import challenges.util.AssortedMethods import challenges.util.AssortedMethods.randomIntInRange import challenges.util.TreeNode object ValidateBstB { private fun checkBST(n: TreeNode?, min: Int?, max: Int?): Boolean { if (n == null) return true if (min != null && n.data <= min || max != null && n.data > max) { return false } return !(!checkBST(n.left, min, n.data) || !checkBST(n.right, n.data, max)) } private fun checkBST(n: TreeNode?): Boolean { return checkBST(n, null, null) } private fun checkBSTAlternate(n: TreeNode): Boolean { return checkBSTAlternate(n, IntWrapper(0), IntWrapper(0)) } private fun checkBSTAlternate(n: TreeNode, min: IntWrapper, max: IntWrapper): Boolean { /* An alternate, less clean approach. This is not provided in the book, but is used to test the other method. */ if (n.left == null) { min.data = n.data } else { val leftMin = IntWrapper(0) val leftMax = IntWrapper(0) if (!checkBSTAlternate(n.left!!, leftMin, leftMax)) { return false } if (leftMax.data > n.data) { return false } min.data = leftMin.data } if (n.right == null) { max.data = n.data } else { val rightMin = IntWrapper(0) val rightMax = IntWrapper(0) if (!checkBSTAlternate(n.right!!, rightMin, rightMax)) { return false } if (rightMin.data <= n.data) { return false } max.data = rightMax.data } return true } /* Create a tree that may or may not be a BST */ private fun createTestTree(): TreeNode { /* Create a random BST */ val head: TreeNode = AssortedMethods.randomBST(10, -10, 10) /* Insert an element into the BST and potentially ruin the BST property */ var node: TreeNode? = head do { val n = randomIntInRange(-10, 10) val rand = randomIntInRange(0, 5) if (rand == 0) { node?.data = n } else if (rand == 1) { node = node?.left } else if (rand == 2) { node = node?.right } else if (rand == 3 || rand == 4) { break } } while (node != null) return head } @JvmStatic fun main(args: Array<String>) { /* Simple test -- create one */ val array = intArrayOf(Int.MIN_VALUE, 3, 5, 6, 10, 13, 15, Int.MAX_VALUE) val node: TreeNode = TreeNode.createMinimalBST(array) ?: return //node.left.data = 6; // "ruin" the BST property by changing one of the elements node.print() val isBst = checkBST(node) println("isBst: $isBst") // More elaborate test -- creates 100 trees (some BST, some not) // and compares the outputs of various methods. /* for (i in 0..99) { val head = createTestTree() // Compare results val isBst1 = checkBST(head) val isBst2 = checkBSTAlternate(head) if (isBst1 != isBst2) { println("*********************** ERROR *******************") head.print() break } else { println("$isBst1 | $isBst2") head.print() } } */ } }
0
Kotlin
0
0
ee06bebe0d3a7cd411d9ec7b7e317b48fe8c6d70
3,651
CodingChallenges
Apache License 2.0
src/Day13.kt
syncd010
324,790,559
false
null
import kotlin.math.sign class Day13: Day { private fun convert(input: List<String>) : List<Long> { return input[0].split(",").map { it.toLong() } } override fun solvePartOne(input: List<String>): Int { val output = Intcode(convert(input)) .execute() return output.slice(2 until output.size step 3).count { it == 2L } } private fun display(screen: List<Long>) { val maxX = screen.slice(0 until screen.size step 3).max()!!.toInt() val maxY = screen.slice(1 until screen.size step 3).max()!!.toInt() val map = mapOf(0L to " ", 1L to "#", 2L to "-", 3L to "_", 4L to "o") val disp = List(maxY + 1) { MutableList(maxX + 1) { " " } } for (idx in screen.indices step 3) { if (screen[idx] == -1L) continue disp[screen[idx + 1].toInt()][screen[idx].toInt()] = map[screen[idx + 2]] ?: "?" } println(disp.joinToString("\n") { it.joinToString("") }) } private fun findTile(screen: List<Long>, tile: Long): Position? { val idx = screen.slice(2 until screen.size step 3).indexOf(tile) return if (idx >= 0) Position(screen[idx * 3].toInt(), screen[idx * 3 + 1].toInt()) else null } override fun solvePartTwo(input: List<String>): Int { val arcade = Intcode(convert(input)) arcade.mem[0] = 2 var dir = 0L while (true) { val screen = arcade.execute(listOf(dir)) if (arcade.halted) { return screen[screen.indexOf(-1L) + 2].toInt() } val ballPos = findTile(screen, 4)!! val paddlePos = findTile(screen, 3)!! dir = (ballPos.x - paddlePos.x).sign.toLong() } } }
0
Kotlin
0
0
11c7c7d6ccd2488186dfc7841078d9db66beb01a
1,795
AoC2019
Apache License 2.0
2021/src/main/kotlin/com/github/afranken/aoc/Day202106.kt
afranken
434,026,010
false
{"Kotlin": 28937}
package com.github.afranken.aoc object Day202106 { fun part1(inputs: Array<String>): Long { val fish = fishMap(inputs.map { Integer.valueOf(it) }) val agedFish = age(fish, 80) return agedFish.values.sum() } fun part2(inputs: Array<String>): Long { val fish = fishMap(inputs.map { Integer.valueOf(it) }) val agedFish = age(fish, 256) return agedFish.values.sum() } private fun fishMap(inputs: List<Int>): MutableMap<Int, Long> { val fish = mutableMapOf<Int, Long>() inputs.forEach { fish.merge(it, 1, Long::plus) } return fish } private fun age(fish: MutableMap<Int, Long>, days: Int): Map<Int, Long> { repeat(days) { val eights = fish.getOrDefault(8, 0) val sevens = fish.getOrDefault(7, 0) val sixes = fish.getOrDefault(6, 0) val fives = fish.getOrDefault(5, 0) val fours = fish.getOrDefault(4, 0) val threes = fish.getOrDefault(3, 0) val twos = fish.getOrDefault(2, 0) val ones = fish.getOrDefault(1, 0) val zeroes = fish.getOrDefault(0, 0) //zeroes spawn new 8s fish[8] = zeroes fish[7] = eights //zeroes are set to 6s after spawning, 7s degrade to 6s fish[6] = zeroes + sevens fish[5] = sixes fish[4] = fives fish[3] = fours fish[2] = threes fish[1] = twos fish[0] = ones } return fish } }
0
Kotlin
0
0
0140f68e60fa7b37eb7060ade689bb6634ba722b
1,574
advent-of-code-kotlin
Apache License 2.0
src/Day02.kt
tristanrothman
572,898,348
false
null
fun main() { fun part1(input: List<String>): Int { return input.sumOf { val moveScore = (it.toCharArray().last() - 'X') + 1 val roundScore = when(it) { "A X", "B Y", "C Z" -> 3 "A Y", "B Z", "C X" -> 6 "A Z", "B X", "C Y" -> 0 else -> error("Input error") } moveScore + roundScore } } fun part2(input: List<String>): Int { return input.sumOf { val roundScore = (it.toCharArray().last() - 'X') * 3 val moveScore = when(it) { "A Y", "B X", "C Z" -> 1 "A Z", "B Y", "C X" -> 2 "A X", "B Z", "C Y" -> 3 else -> error("Input error") } moveScore + roundScore } } val input = readInput("Day02") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
e794ab7e0d50f22d250c65b20e13d9b5aeba23e2
919
advent-of-code-2022
Apache License 2.0
2023/14/Solution.kt
AdrianMiozga
588,519,359
false
{"Kotlin": 110785, "Python": 11275, "Assembly": 3369, "C": 2378, "Pawn": 1390, "Dart": 732}
import java.io.File private const val FILENAME = "2023/14/input.txt" fun main() { partOne() partTwo() } private fun partOne() { val file = File(FILENAME).readLines().toMutableList() moveUp(file) println(calculateLoad(file)) } private fun calculateLoad(file: MutableList<String>): Int { var result = 0 for ((index, line) in file.withIndex()) { val count = line.count { it == 'O' } result += (file.size - index) * count } return result } private fun moveUp(file: MutableList<String>) { repeat(file.size - 1) { for (row in 1 until file.size) { for ((column, character) in file[row].withIndex()) { if (character != 'O') { continue } if (file[row - 1][column] == '.') { file[row] = file[row].replaceRange(column, column + 1, ".") file[row - 1] = file[row - 1].replaceRange(column, column + 1, "O") } } } } } private fun partTwo() { var file = File(FILENAME).readLines().toMutableList() val cycles = 1_000_000_000 val values = HashMap<Int, Int>() val listValues = mutableListOf<Int>() for (cycle in 0 until cycles) { // North moveUp(file) // West file = transpose(file) moveUp(file) file = transpose(file) // South file = file.reversed().toMutableList() moveUp(file) file = file.reversed().toMutableList() // East file = transpose(file) file = file.reversed().toMutableList() moveUp(file) file = file.reversed().toMutableList() file = transpose(file) val load = calculateLoad(file) listValues.add(load) if (values.contains(load)) { values[load] = (values[load]!! + 1) } else { values[load] = 1 } // Wait for numbers to stabilize if (cycle == 250) { break } } // Find index where the sequence begins var smallest = Integer.MAX_VALUE for (key in values.filterValues { it > 2 }.keys) { for ((index, element) in listValues.withIndex()) { if (element == key) { if (index < smallest) { smallest = index } } } } val sequenceLength = values.filterValues { it > 2 }.size println(listValues[smallest + ((cycles - smallest - 1) % sequenceLength)]) } private fun transpose(list: List<String>): MutableList<String> { val result = mutableListOf<String>() for (column in list[0].indices) { var columnNew = "" for (row in list.indices) { columnNew += list[row][column] } result.add(columnNew) } return result }
0
Kotlin
0
0
c9cba875089d8d4fb145932c45c2d487ccc7e8e5
2,893
Advent-of-Code
MIT License
solution/#5 Longest Palindromic Substring/Solution.kt
enihsyou
116,918,868
false
{"Java": 179666, "Python": 36379, "Kotlin": 32431, "Shell": 367}
package leetcode.q5.kotlin; import org.junit.jupiter.api.Assertions import org.junit.jupiter.params.ParameterizedTest import org.junit.jupiter.params.provider.Arguments import org.junit.jupiter.params.provider.MethodSource class Solution { fun longestPalindrome(s: String): String { val T = preProcess(s) println(T) val P = IntArray(T.length) var C = 0 var R = 0 for (i in 1 until T.length - 1) { val i_mirror = 2 * C - i P[i] = if (R > i) minOf(R - i, P[i_mirror]) else 0 while (T[i + 1 + P[i]] == T[i - 1 - P[i]]) P[i]++ if (i + P[i] > R) { C = i R = i + P[i] } } var maxLen = 0 var centerIndex = 0 for (i in 1 until P.size - 1) { if (P[i] > maxLen) { maxLen = P[i] centerIndex = i } } println("maxLen = ${maxLen}") println("centerIndex = ${centerIndex}") return s.substring((centerIndex - 1 - maxLen) / 2, (centerIndex - 1 - maxLen) / 2 + maxLen) } private fun preProcess(s: String) = s.toCharArray().joinToString(separator = "#", prefix = "^#", postfix = "#$") } class SolutionTest { private val solution = Solution() @ParameterizedTest(name = "removeDuplicates({0}) = {1}") @MethodSource("provider") fun removeDuplicates(input: String, output: String) { Assertions.assertEquals(solution.longestPalindrome(input), output) } companion object { @JvmStatic fun provider(): List<Arguments> { return listOf( Arguments.of("babad", "bab"), Arguments.of("cbbd", "bb"), Arguments.of("", ""), Arguments.of("a", "a") ) } } }
1
Java
0
0
230325d1dfd666ee53f304edf74c9c0f60f81d75
1,873
LeetCode
MIT License
src/main/kotlin/extractors/MemExtractor.kt
Albaross
98,739,245
false
null
package org.albaross.agents4j.extraction.extractors import org.albaross.agents4j.extraction.* import org.albaross.agents4j.extraction.bases.TreeMapKB import org.albaross.agents4j.extraction.collections.Multiset import java.util.* typealias Triple<A> = kotlin.Triple<State, Collection<Pair<State, A>>, Collection<Rule<A>>> class MemExtractor<A>( private val new: () -> KnowledgeBase<A> = { TreeMapKB() }, private val order: Comparator<A>? = null, 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 val initial = create(emptySet(), input) kb.addAll(initial) var items = initialize(input, initial) for (k in 1..input.first().state.size) { if (k > 1) items = merge(items, input) if (items.isEmpty()) break for (i in 0 until items.size) { val (state, pairs, rules) = items[i] val created = create(state, pairs, rules) if (!created.isEmpty()) { items[i] = Triple(state, pairs, created) kb.addAll(created) } } } return kb } private fun create(state: State, supporting: Collection<Pair<State, A>>, existing: Collection<Rule<A>> = emptyList()): Collection<Rule<A>> { val grouped = supporting.groupBy { it.action } val maxCount = grouped.values.map { it.size }.max() val created = ArrayList<Rule<A>>() for ((action, pairs) in grouped) { if (maxCount == pairs.size) { val conf = pairs / supporting if (conf <= existing.weight(or = minconf)) continue if (!existing.isEmpty() && existing.all { action == it.action }) continue created.add(Rule(state, action, conf)) } } if (order != null && created.size > 1) { val minAction = created.map { it.action }.minWith(order) return created.filter { minAction == it.action } } return created } private fun initialize(input: Collection<Pair<State, A>>, initial: Collection<Rule<A>>): MutableList<Triple<A>> { val partitions = HashMap<String, Multiset<Pair<State, A>>>() for (pair in input) { for (s in pair.state) { val supporting = partitions.getOrPut(s) { Multiset() } supporting.add(pair) } } val items = ArrayList<Triple<A>>() for ((s, supporting) in partitions) { if (minsupp > 0.0 && supporting / input <= minsupp) continue items.add(Triple(setOf(s), supporting, initial)) } return items } private fun merge(items: Collection<Triple<A>>, input: Collection<Pair<State, A>>): MutableList<Triple<A>> { val merged = ArrayList<Triple<A>>() val list = items as List for (i in 0 until list.size) { for (k in (i + 1) until list.size) { val (state_i, pairs_i, rules_i) = list[i] val (state_k, pairs_k, rules_k) = list[k] val state = (state_i as SortedSet or state_k as SortedSet) ?: continue val pairs = (pairs_i as Multiset and pairs_k as Multiset) ?: continue if (minsupp > 0.0 && pairs / input <= minsupp) continue val rules = rules_i max rules_k merged.add(Triple(state, pairs, rules)) } } return merged } }
1
Kotlin
0
0
36bbbccd8ff9a88ea8745a329a446912d4de007d
3,755
agents4j-extraction
MIT License
solutions/cheating-detection/kotlin/cheating-detection.kt
cavesdev
418,595,190
true
{"Java": 85120, "Elixir": 51650, "Go": 50067, "Ruby": 24382, "Dart": 19382, "Scala": 18626, "JavaScript": 14831, "Python": 10246, "Rust": 6885, "Clojure": 5403, "Kotlin": 4945, "F#": 3328}
/****************** Qualification Round - Google Code Jam 2021 Problem #5: Cheating Detection. https://codingcompetitions.withgoogle.com/codejam/round/000000000043580a/00000000006d1155 Written by: <NAME> <@cavesdev> 18/10/21 for the Encora Apprentice Program The approach used here is taken from the Analysis section of the same problem: Estimate the players' and questions' skill and difficulty level, using number of correct answers. (probability) Sort by skill level Calculate the hardest questions and use the sigmoid function to estimate number of corrects. If estimated number of corrects is far from the actual results (results are much better), that player is the cheater. *******************/ import kotlin.math.floor import kotlin.math.exp val PLAYERS = 100 val QUESTIONS = 10000 // val EXTREME_QUESTIONS_RATE = floor(QUESTIONS * 0.05) val EXTREME_QUESTIONS_THRESHOLD = 2.0 fun getCorrectAnswersPerQuestion(answers: List<List<Int>>): List<Int> { var correctAnswersNum = mutableListOf<Int>() for(questionNumber in 0..(QUESTIONS - 1)){ var questionSum = 0 for(playerAnswers in answers) { if (playerAnswers[questionNumber] == 1) { questionSum++ } } correctAnswersNum.add(questionSum) } return correctAnswersNum } fun getCorrectAnswersPerPlayer(answers: List<List<Int>>): List<Int>{ var playerCorrectAnswers = mutableListOf<Int>() for (playerNum in 0..(PLAYERS - 1)) { val sum: Int = answers[playerNum].reduce { acc, num -> acc + num } playerCorrectAnswers.add(sum) } return playerCorrectAnswers } fun estimateQuestionsDifficulty(correctAnswersNum: List<Int>): List<Pair<Int,Double>> { var questionsDifficulty = mutableListOf<Pair<Int,Double>>() for (questionNum in 0..(QUESTIONS - 1)) { // x (si - qi) = ln(y/(1-y)) ?? // prob -> [-3, 3] val questionDifficulty: Double = (correctAnswersNum[questionNum] * -6.0 / PLAYERS) + 3.0 questionsDifficulty.add(Pair(questionNum, questionDifficulty)) } return questionsDifficulty } fun estimatePlayersSkill(playerCorrectAnswers: List<Int>): List<Double> { var playersSkill = mutableListOf<Double>() for (playerNum in 0..(PLAYERS - 1)) { // x (si - qi) = ln(y/(1-y)) ?? val playerSkill = (playerCorrectAnswers[playerNum] * 6.0 / QUESTIONS) - 3.0 playersSkill.add(playerSkill) } return playersSkill } fun calculateExtremeQuestions(questionsDifficulty: List<Pair<Int,Double>>): List<Int> { var extremeQuestions = mutableListOf<Int>() for ((questionNum, questionDifficulty) in questionsDifficulty) { if (questionDifficulty > EXTREME_QUESTIONS_THRESHOLD ) { extremeQuestions.add(questionNum) } } return extremeQuestions } fun calculateProbabilityVariation(answers: List<List<Int>>, playersSkill: List<Double>, extremeQuestions: List<Int>): MutableList<Pair<Int,Double>> { var correctAnswerProbabilityVariations = mutableListOf<Pair<Int,Double>>() for (playerNum in 0..(PLAYERS - 1)) { var playerCorrectExtreme = 0 val correctAnswerProbability = 1 / (1 + exp(-(playersSkill[playerNum] - EXTREME_QUESTIONS_THRESHOLD))) val playerCorrectAnswerProbability = extremeQuestions.size * correctAnswerProbability for (questionNum in extremeQuestions) { if (answers[playerNum][questionNum] == 1) { playerCorrectExtreme++ } } val probabilityVariation = playerCorrectExtreme - playerCorrectAnswerProbability correctAnswerProbabilityVariations.add(Pair(playerNum + 1, probabilityVariation)) } return correctAnswerProbabilityVariations } fun getCheater(): Int { // save every line from current test case (players' answers) var answers = mutableListOf<List<Int>>() for(`_` in 0..(PLAYERS - 1)){ val playerAnswers = readLine() val answerArray: List<Int> = playerAnswers!!.map { it.toString().toInt() } answers.add(answerArray) } var correctAnswersNum = getCorrectAnswersPerQuestion(answers) var playerCorrectAnswers = getCorrectAnswersPerPlayer(answers) var questionsDifficulty = estimateQuestionsDifficulty(correctAnswersNum) var playersSkill = estimatePlayersSkill(playerCorrectAnswers) var extremeQuestions = calculateExtremeQuestions(questionsDifficulty) var correctAnswerProbabilityVariations = calculateProbabilityVariation(answers, playersSkill, extremeQuestions) correctAnswerProbabilityVariations.sortByDescending { it.second } return correctAnswerProbabilityVariations[0].first } fun main() { var testCases: Int = readLine()!!.toInt() readLine() // get p percent of accuracy to pass test cases for(case in 1..testCases) { println("Case #${case}: ${getCheater()}") } }
0
Java
0
0
81e55cb08f410429187b802e8684bac3b54e3510
4,945
google-code-jam
MIT License
src/commonMain/kotlin/ai/Combinatorics.kt
KristiansKaneps
624,533,678
false
null
package ai import game.cards.* object Combinatorics { fun <T> permutations(from: Collection<T>): Collection<Collection<T>> { if (from.isEmpty()) return listOf(emptySet()) return from.flatMap { element -> permutations(from - element).map { setOf(element) + it } } } fun <T> variations(from: Collection<T>, k: Int): Collection<Collection<T>> = combinations(from, k).flatMap { combination -> permutations(combination) } fun <T> variationsUpToK(from: Collection<T>, k: Int): Collection<Collection<T>> = (1..k).flatMap { variations(from, it) } fun <T> combinations(from: Collection<T>, k: Int): Collection<Collection<T>> { if (k == 0) return listOf(emptySet()) if (from.isEmpty()) return emptySet() val head = from.first() val tail = from.drop(1) return combinations(tail, k - 1).map { setOf(head) + it } + combinations(tail, k) } fun <T> combinationsUpToK(from: Collection<T>, k: Int): Collection<Collection<T>> = (1..k).flatMap { combinations(from, it) } fun groupByCardType(cards: Collection<Card>): Collection<Collection<Card>> = cards.groupBy { it.type }.values fun groupByPossibleCardTypeMoves( cards: Collection<Card>, maxSize: Int = cards.size, ): Collection<Collection<Card>> { if (maxSize == 0) return emptyList() val groups = cards.groupBy { it.type }.values val result = mutableListOf<Collection<Card>>() @Suppress("NAME_SHADOWING") groups.forEach { cards -> if (cards.size > 1) { cards.forEach { card -> result.add(setOf(card)) } (2..maxSize).forEach { k -> combinations(cards, k).forEach { result.add(it) } } } else result.add(cards) } return result } }
0
Kotlin
0
0
0ef9c3fe3befdc11c8f55303fa3439fa26c3e80e
1,925
korge-test-card-game
MIT License
KotlinDeveloper/SeamCarving/VerticalSeamCalculator.kt
Tsyshnatiy
561,408,519
false
{"Kotlin": 64886, "JavaScript": 3306, "CSS": 1632, "HTML": 726}
package seamcarving data class Cell(val row: Int, val col: Int) typealias Seam = HashSet<Cell> class VerticalSeamCalculator(private val energies: Energies) { fun calculate() : Seam { val h = energies.size val w = energies[0].size val arrows = Array(h) { Array(w) { Cell(0, 0) } } for (j in arrows[0].indices) { arrows[0][j] = Cell(0, j) } val cumulativeEnergies = Array(h) { DoubleArray(w) } cumulativeEnergies[0] = energies.first() for (row in 1 until h) { for (col in 0 until w) { var cumEnergyValue = Double.POSITIVE_INFINITY val candidates = arrayOf(Cell(row - 1, col), Cell(row - 1, col - 1), Cell(row - 1, col + 1)) for (c in candidates) { if (c.col < 0 || c.col >= w) { continue } val potentialCumEnergy = cumulativeEnergies[c.row][c.col] + energies[row][col] if (cumEnergyValue > potentialCumEnergy) { cumEnergyValue = potentialCumEnergy arrows[row][col] = Cell(c.row, c.col) } } cumulativeEnergies[row][col] = cumEnergyValue } } return computeSeam(cumulativeEnergies, arrows) } private fun computeSeam(cumEnergies: Energies, arrows: Array<Array<Cell>>) : Seam { val result = HashSet<Cell>() val lastLineMin = cumEnergies.last().reduce { a, b -> a.coerceAtMost(b) } val lastLineMinIndex = cumEnergies.last().indexOfFirst { it.compareTo(lastLineMin) == 0 } val h = cumEnergies.size result.add(Cell(h - 1, lastLineMinIndex)) var lastArrow = result.last() for (row in h - 2 downTo 0) { val p = lastArrow val nextArrow = arrows[p.row][p.col] result.add(nextArrow) lastArrow = nextArrow } return result } }
0
Kotlin
0
0
5c3ef96cca79e51cc8bc3f65cad6086e0c99ea2d
2,134
JetBrainsCourses
Apache License 2.0
src/main/kotlin/day16/Day16.kt
cyril265
433,772,262
false
{"Kotlin": 39445, "Java": 4273}
package day16 import readToList import java.util.Stack private val input = readToList("day16.txt").first() fun main() { val map = input.map { char -> toBits(char) }.flatMap { it.toList() }.toMutableList() val packets = getPacket(map, null) println(packets) // println(packets.sumOf { it.version }) // // val stack = Stack<Node>() // packets.reversed().forEach { packet -> // if (packet.operation != null) { // val leaves = stack.popWhile { it.current.depth - 1 == packet.depth } // stack.push(Node(packet, leaves)) // } else { // stack.push(Node(packet)) // } // } // val message = evaluate(stack.first()) // println(message) } private fun evaluate(tree: Node): Long { if (tree.hasChildren()) { if (tree.current.operation != null) { println(tree.current.operation) val evaluate = tree.children.map { evaluate(it) }.reversed() return tree.current.operation.execute(evaluate) } } return tree.current.numericValue } private data class Node(val current: Packet, val children: List<Node> = emptyList()) { fun hasChildren(): Boolean { return children.isNotEmpty() } override fun toString(): String { if (current.operation != null) { return "operation=${current.operation}, children=$children, children=${ current.children.filterNotNull().map { it.operation ?: it.numericValue } }" } else { return "numeric=${current.numericValue}, children=$children, children=${ current.children.filterNotNull().map { it.operation ?: it.numericValue } }" } } } private fun getPacket(bits: MutableList<Char>, limit: Long? = null): List<Packet> { if (bits.all { it == '0' }) return emptyList() val (version, typeId) = getVersionType(bits) val opi = Operation.create(typeId) val result = mutableListOf<Packet>() while (bits.isNotEmpty()) { val packetSimple = getPacketSimple(bits) ?: break result.add(packetSimple) if (packetSimple.numberOfPackets != null) { packetSimple.children += (1..packetSimple.numberOfPackets).map { getPacketSimple(bits) } } } return result // if (typeId == 4L) { // return if (limit != null) { // (0 until limit).map { Packet(version, typeId, mapNumber(bits)) } // } else { // listOf(Packet(version, typeId, mapNumber(bits))) + getPacket(bits, null) // } // } else { // val (lengthType) = bits.consume(1) // // if (lengthType == '0') { // val totalLengthBits = bits.consume(15) // val totalLength = toLong(totalLengthBits) // // val newParent = Packet(version, typeId, totalLengthBits) // println(newParent.operation) // // if (limit != null) { // newParent.children += getPacket(bits.consume(totalLength)) // val newLimit = limit - 1 // newParent.children += (0 until newLimit).flatMap { getPacket(bits) } // } else { // newParent.children += getPacket(bits.consume(totalLength)) // newParent.children += getPacket(bits) // } // // return listOf(newParent) // } else { // val content = bits.consume(11) // val numberOfPackets = toLong(content) // val newParent = Packet(version, typeId, content) // println(newParent.operation) // newParent.children += newParent // newParent.children += getPacket(bits, numberOfPackets) // return listOf(newParent) // } // } } private fun getPacketSimple(bits: MutableList<Char>): Packet? { if (bits.all { it == '0' }) return null val (version, typeId) = getVersionType(bits) val opi = Operation.create(typeId) if (typeId == 4L) { Packet(version, typeId, mapNumber(bits)) } else { val (lengthType) = bits.consume(1) if (lengthType == '0') { val totalLengthBits = bits.consume(15) val totalLength = toLong(totalLengthBits) return Packet(version, typeId, totalLengthBits) } else { val content = bits.consume(11) val numberOfPackets = toLong(content) return Packet(version, typeId, content, numberOfPackets) } } return null } private fun getVersionType(bits: MutableList<Char>): Pair<Long, Long> { val version = toLong(bits.consume(3)) val typeId = toLong(bits.consume(3)) return Pair(version, typeId) } private fun mapNumber( bits: MutableList<Char> ): MutableList<Char> { val result = mutableListOf<Char>() do { val number = bits.consume(5) val (prefix) = number.consume(1) result.addAll(number) } while (prefix != '0') return result } private class Packet( val version: Long, typeId: Long, content: MutableList<Char>, val numberOfPackets: Long? = null ) { var children: MutableList<Packet?> = mutableListOf() val operation = Operation.create(typeId) val numericValue = toLong(content) override fun toString(): String { return "Packet(operation=$operation, numericValue=$numericValue, children=${ children.filterNotNull().map { it.operation ?: it.numericValue } })" } } private interface Operation { fun execute(numbers: List<Long>): Long companion object { fun create(typeId: Long): Operation? { return when (typeId) { 0L -> Sum() 1L -> Product() 2L -> Min() 3L -> Max() 5L -> GreaterThan() 6L -> LessThan() 7L -> EqualTo() 4L -> null else -> TODO() } } } } class Sum : Operation { override fun execute(numbers: List<Long>): Long { return numbers.sum() } } class Product : Operation { override fun execute(numbers: List<Long>): Long { return numbers.reduce { acc, num -> num * acc } } } class Min : Operation { override fun execute(numbers: List<Long>): Long { return numbers.minOf { it } } } class Max : Operation { override fun execute(numbers: List<Long>): Long { return numbers.maxOf { it } } } class GreaterThan : Operation { override fun execute(numbers: List<Long>): Long { val (a, b) = numbers return if (a > b) 1 else 0 } } class LessThan : Operation { override fun execute(numbers: List<Long>): Long { val (a, b) = numbers return if (a < b) 1 else 0 } } class EqualTo : Operation { override fun execute(numbers: List<Long>): Long { val (a, b) = numbers return if (a == b) 1 else 0 } } private fun toLong(bits: List<Char>): Long { return String(bits.toCharArray()).toLong(2) } private fun <T> MutableList<T>.consume(count: Long): MutableList<T> { return (0 until count).map { _ -> this.removeFirst() }.toMutableList() } private fun <T> Stack<T>.drain(): List<T> { val result = mutableListOf<T>() while (this.isNotEmpty()) { result.add(this.pop()) } return result } private fun <T> Stack<T>.popWhile(predicate: (T) -> Boolean): List<T> { val result = mutableListOf<T>() while (this.isNotEmpty() && predicate(this.peek())) { result.add(this.pop()) } return result } private fun toBits(char: Char) = when (char) { '0' -> "0000" '1' -> "0001" '2' -> "0010" '3' -> "0011" '4' -> "0100" '5' -> "0101" '6' -> "0110" '7' -> "0111" '8' -> "1000" '9' -> "1001" 'A' -> "1010" 'B' -> "1011" 'C' -> "1100" 'D' -> "1101" 'E' -> "1110" 'F' -> "1111" else -> TODO("yikes") }
0
Kotlin
0
0
1ceda91b8ef57b45ce4ac61541f7bc9d2eb17f7b
7,951
aoc2021
Apache License 2.0
src/Day01.kt
ranveeraggarwal
573,754,764
false
{"Kotlin": 12574}
fun main() { fun splitOnEmpty(input: List<String>): ArrayList<Int> { val allCalories = ArrayList<Int>() var current = 0 input.forEach { if (it.isEmpty()) { allCalories.add(current) current = 0 } else { current += Integer.parseInt(it) } } if (current > 0) allCalories.add(current) allCalories.sortDescending() return allCalories } fun part1(input: List<String>): Int { return splitOnEmpty(input).first() } fun part2(input: List<String>): Int { return splitOnEmpty(input).take(3).sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") check(part1(testInput) == 24000) check(part2(testInput) == 45000) val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
c8df23daf979404f3891cdc44f7899725b041863
950
advent-of-code-2022-kotlin
Apache License 2.0
kotlin/src/katas/kotlin/leetcode/bst_level_order_traversal/BstLevelOrderTraversal2.kt
dkandalov
2,517,870
false
{"Roff": 9263219, "JavaScript": 1513061, "Kotlin": 836347, "Scala": 475843, "Java": 475579, "Groovy": 414833, "Haskell": 148306, "HTML": 112989, "Ruby": 87169, "Python": 35433, "Rust": 32693, "C": 31069, "Clojure": 23648, "Lua": 19599, "C#": 12576, "q": 11524, "Scheme": 10734, "CSS": 8639, "R": 7235, "Racket": 6875, "C++": 5059, "Swift": 4500, "Elixir": 2877, "SuperCollider": 2822, "CMake": 1967, "Idris": 1741, "CoffeeScript": 1510, "Factor": 1428, "Makefile": 1379, "Gherkin": 221}
package katas.kotlin.leetcode.bst_level_order_traversal import katas.kotlin.leetcode.TreeNode import datsok.shouldEqual import org.junit.Test import java.util.* import kotlin.collections.ArrayList /** * https://leetcode.com/problems/binary-tree-level-order-traversal */ class BstLevelOrderTraversal2 { @Test fun `it works`() { levelOrder(TreeNode(1)) shouldEqual listOf(listOf(1)) levelOrder( TreeNode(1, TreeNode(2), TreeNode(3) ) ) shouldEqual listOf(listOf(1), listOf(2, 3)) levelOrder( TreeNode(3, TreeNode(9, TreeNode(6)), TreeNode(20, TreeNode(15), TreeNode(7)) ) ) shouldEqual listOf(listOf(3), listOf(9, 20), listOf(6, 15, 7)) } private fun levelOrder( node: TreeNode?, depth: Int = 0, result: ArrayList<ArrayList<Int>> = ArrayList() ): List<List<Int>> { if (node == null) return result if (result.size <= depth) result.add(ArrayList()) result[depth].add(node.value) levelOrder(node.left, depth + 1, result) levelOrder(node.right, depth + 1, result) return result } private fun levelOrder_(node: TreeNode?): List<List<Int>> { if (node == null) return emptyList() val queue = LinkedList<List<TreeNode>>() queue.addFirst(listOf(node)) val result = ArrayList<List<Int>>() while (queue.isNotEmpty()) { val nodesAtLevel = queue.removeLast() result.add(nodesAtLevel.map { it.value }) val nodesAtNextLevel = nodesAtLevel.flatMap { listOfNotNull(it.left, it.right) } if (nodesAtNextLevel.isNotEmpty()) { queue.add(nodesAtNextLevel) } } return result } }
7
Roff
3
5
0f169804fae2984b1a78fc25da2d7157a8c7a7be
1,878
katas
The Unlicense
src/Day04.kt
topr
572,937,822
false
{"Kotlin": 9662}
import kotlin.math.max import kotlin.math.min fun main() { operator fun ClosedRange<Int>.contains(other: ClosedRange<Int>) = this.start <= other.start && this.endInclusive >= other.endInclusive fun ClosedRange<Int>.overlaps(other: ClosedRange<Int>) = max(this.start, other.start) - min(this.endInclusive, other.endInclusive) <= 0 fun toRange(assignment: String) = assignment .split('-') .let { it.first().toInt()..it.last().toInt() } fun assignmentPairs(inputLine: String) = inputLine .split(',') .map(::toRange) .zipWithNext() .first() fun part1(input: List<String>) = input .map(::assignmentPairs) .count { it.run { first in second || second in first } } fun part2(input: List<String>) = input .map(::assignmentPairs) .count { it.first.overlaps(it.second) } val testInput = readInputLines("Day04_test") check(part1(testInput) == 2) check(part2(testInput) == 4) val input = readInputLines("Day04") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
8c653385c9a325f5efa2895e94830c83427e5d87
1,117
advent-of-code-kotlin-2022
Apache License 2.0
src/AOC2022/Day04/Day04.kt
kfbower
573,519,224
false
{"Kotlin": 44562}
package AOC2022.Day04 import AOC2022.readInput fun main() { fun part1(input: List<String>): Int { var encapsulatedcount = 0 input.forEachIndexed { i, s -> val parts = s.split(",","-") val min1= parts[0].toInt() val max1 = parts[1].toInt() val min2 = parts[2].toInt() val max2 = parts[3].toInt() if (min1 <= min2 && max1>=max2){ encapsulatedcount+=1 } else if (min2 <= min1 && max2>= max1){ encapsulatedcount+=1 } } return encapsulatedcount } fun part2(input: List<String>): Int { var noOverlap = 0 input.forEachIndexed { i, s -> val parts = s.split(",","-") val min1= parts[0].toInt() val max1 = parts[1].toInt() val min2 = parts[2].toInt() val max2 = parts[3].toInt() if (max1 < min2){ noOverlap +=1 println("No Overlap") } else if (max2 < min1){ noOverlap +=1 println("No Overlap") } } return input.size-noOverlap } val input = readInput("Day04") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
48a7c563ebee77e44685569d356a05e8695ae36c
1,322
advent-of-code-2022
Apache License 2.0
src/main/kotlin/P011_LargestProductInAGrid.kt
perihanmirkelam
291,833,878
false
null
/** * P11-Largest product in a grid * In the 20×20 grid below, four numbers along a diagonal line have been marked in red. * The product of these numbers is 26 × 63 × 78 × 14 = 1788696. * What is the greatest product of four adjacent numbers in the same direction * (up, down, left, right, or diagonally) in the 20×20 grid? */ fun p11() { val grid = "08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08" + "49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00" + "81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65" + "52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91" + "22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80" + "24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50" + "32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70" + "67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21" + "24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72" + "21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95" + "78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92" + "16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57" + "86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58" + "19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40" + "04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66" + "88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69" + "04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36" + "20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16" + "20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54" + "01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48" var greatest = 0 val rows: List<List<Int>> = grid.chunked(59).map { x -> x.split(" ").map { it.toInt() } } // vertical adjacent for (row in rows) for (i in 0..16) greatest = maxOf(greatest, row[i] * row[i + 1] * row[i + 2] * row[i + 3]) // horizontal adjacent for (j in 0..16) for (i in 0 until 20) greatest = maxOf(greatest, rows[j][i] * rows[j + 1][i] * rows[j + 2][i] * rows[j + 3][i]) // diagonal top left to bottom right adjacent for (j in 0..16) for (i in 0..16) greatest = maxOf(greatest, rows[j][i] * rows[j + 1][i + 1] * rows[j + 2][i + 2] * rows[j + 3][i + 3]) // diagonal top right to bottom left adjacent for (j in 19 downTo 3) for (i in 0..16) greatest = maxOf(greatest, rows[j][i] * rows[j - 1][i + 1] * rows[j - 2][i + 2] * rows[j - 3][i + 3]) println("A11: $greatest") }
0
Kotlin
1
3
a24ac440871220c87419bfd5938f80dc22a422b2
2,786
ProjectEuler
MIT License
src/main/kotlin/report/plain.kt
Tiofx
175,697,373
false
null
package report import algorithm.CPF import algorithm.Matrix import algorithm.Program import report.latex.toLatex fun List<CPF.Iteration>.description(namer: OperatorNamer) { forEach { it.description(it.program, namer) } } fun CPF.Iteration.description(program: Program, namer: OperatorNamer) { println("================== $number ===========================") println(namer.names(program).map(OperatorName::toPlainString)) // cpfCheck.map { it.canBeBringToCPF to it }.forEach(::println) println() if (parallelCheck != null) { println(parallelCheck.C.toLatex("S\n".repeat(40).split("\n"), "S\n".repeat(40).split("\n"))) println(parallelCheck.C.toMatrixString()) println(parallelCheck.copy(C = emptyList())) println(parallelCheck.maxChain) } if (sequentialCheck != null) { println(sequentialCheck) } println() } private fun List<CPF.Iteration>.shortDesription() { println("Description:") println("Iteration number: $size") forEachIndexed { i, it -> println( """ Iteration number: ${i + 1} Operator number: ${it.program.size} CPF check number: ${it.cpfCheck.size} """.trimIndent() ) } println("Total number of cpf check ${map { it.cpfCheck.size }.sum()}") } fun OperatorName.toPlainString() = when (this) { is OriginOperator -> "S$i" is GroupParallelOperator -> "||y$i" is GroupSequentialOperator -> "|y$i" UnknownName -> "Unknown" } fun Matrix.toMatrixString() = map { it.map { b -> if (b) 1 else 0 } } .map { it.toString() + "\n" } .reduce { acc, s -> acc + s } .replace("[\\[\\]]".toRegex(), "|") .replace(",", "")
0
Kotlin
0
0
32c1cc3e95940e377ed9a99293eccc871ce13864
1,815
CPF
The Unlicense
2021/kotlin/src/main/kotlin/com/pietromaggi/aoc2021/day18/Day18.kt
pfmaggi
438,378,048
false
{"Kotlin": 113883, "Zig": 18220, "C": 7779, "Go": 4059, "CMake": 386, "Awk": 184}
/* * 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 com.pietromaggi.aoc2021.day18 import com.pietromaggi.aoc2021.readInput // Source: https://github.com/elizarov/AdventOfCode2021/blob/main/src/Day18.kt sealed class SnailfishNumber { class Single(val value: Int) : SnailfishNumber() { override fun toString(): String = value.toString() } class Pair(val left: SnailfishNumber, val right: SnailfishNumber) : SnailfishNumber() { override fun toString(): String = "[$left,$right]" } } fun parseInput(input: String): SnailfishNumber { var pos = 0 fun parse(): SnailfishNumber { if (input[pos] == '[') { pos++ val left = parse() pos++ // skip ',' val right = parse() pos++ // skip ']' return SnailfishNumber.Pair(left, right) } val start = pos while (input[pos] in '0'..'9') pos++ return SnailfishNumber.Single(input.substring(start, pos).toInt()) } return parse() } fun SnailfishNumber.findPair(n: Int): SnailfishNumber.Pair? { if (n == 0) return this as? SnailfishNumber.Pair? if (this is SnailfishNumber.Pair) { left.findPair(n - 1)?.let { return it } right.findPair(n - 1)?.let { return it } } return null } fun SnailfishNumber.findReg(lim: Int): SnailfishNumber.Single? = when(this) { is SnailfishNumber.Single -> if (value >= lim) this else null is SnailfishNumber.Pair -> { left.findReg(lim)?.let { return it } right.findReg(lim)?.let { return it } null } } /* * Recursively construct a list of Snailfish numbers */ fun SnailfishNumber.traverse(keep: SnailfishNumber.Pair): List<SnailfishNumber> = when(this) { is SnailfishNumber.Single -> listOf(this) is SnailfishNumber.Pair -> if (this == keep) listOf(this) else left.traverse(keep) + right.traverse(keep) } fun SnailfishNumber.replace(op: Map<SnailfishNumber, SnailfishNumber>): SnailfishNumber { op[this]?.let { return it } return when(this) { is SnailfishNumber.Single -> this is SnailfishNumber.Pair -> SnailfishNumber.Pair(left.replace(op), right.replace(op)) } } fun SnailfishNumber.reduceOp(): Map<SnailfishNumber, SnailfishNumber>? { // Check for pairs to explode val pairToExplode = findPair(4) if ((pairToExplode != null) && (pairToExplode.left is SnailfishNumber.Single) && (pairToExplode.right is SnailfishNumber.Single)) { val updates = mutableMapOf<SnailfishNumber, SnailfishNumber>(pairToExplode to SnailfishNumber.Single(0)) val localListOfSnailfishNumber = traverse(pairToExplode) val indexOfPairToExplode = localListOfSnailfishNumber.indexOf(pairToExplode) (localListOfSnailfishNumber.getOrNull(indexOfPairToExplode - 1) as? SnailfishNumber.Single)?.let { left -> updates[left] = SnailfishNumber.Single(left.value + pairToExplode.left.value) } (localListOfSnailfishNumber.getOrNull(indexOfPairToExplode + 1) as? SnailfishNumber.Single)?.let { right -> updates[right] = SnailfishNumber.Single(right.value + pairToExplode.right.value) } return updates } // Check for numbers to split val valueToSplit = findReg(10) return if (valueToSplit != null) { mapOf(valueToSplit to SnailfishNumber.Pair( SnailfishNumber.Single(valueToSplit.value / 2), SnailfishNumber.Single((valueToSplit.value + 1) / 2))) } else { null } } fun add(a: SnailfishNumber, b: SnailfishNumber): SnailfishNumber = generateSequence<SnailfishNumber>(SnailfishNumber.Pair(a, b)) { snailfishNumber -> snailfishNumber.reduceOp()?.let { newValue -> snailfishNumber.replace(newValue) } }.last() fun SnailfishNumber.magnitude(): Int = when(this) { is SnailfishNumber.Single -> value is SnailfishNumber.Pair -> 3 * left.magnitude() + 2 * right.magnitude() } fun part1(numbers: List<SnailfishNumber>) = numbers.reduce(::add).magnitude() fun part2(numbers: List<SnailfishNumber>): Int { val result = buildList { for (i in numbers.indices) for (j in numbers.indices) if (i != j) add(add(numbers[i], numbers[j]).magnitude()) } return result.maxOrNull()!! } fun main() { val input = readInput("Day18") val numbers = input.map(::parseInput) println("What is the magnitude of the final sum?") println("My puzzle answer is: ${part1(numbers)}") println("What is the largest magnitude of any sum of two different snailfish numbers from the homework assignment?") println("My puzzle answer is: ${part2(numbers)}") }
0
Kotlin
0
0
7c4946b6a161fb08a02e10e99055a7168a3a795e
5,265
AdventOfCode
Apache License 2.0
src/Day01.kt
jfiorato
573,233,200
false
null
fun main() { fun accumulateElves(input: List<String>): MutableList<Int> { val elves = mutableListOf<Int>() var currentElf = 0 for (line in input) { if (line.isNotEmpty()) { currentElf += line.toInt() } else { elves.add(currentElf) currentElf = 0 } } if (currentElf > 0) elves.add(currentElf) elves.sortDescending() return elves } fun part1(input: List<String>): Int { val elves = accumulateElves(input) return elves.get(0) } fun part2(input: List<String>): Int { val elves = accumulateElves(input) return elves.take(3).sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") check(part1(testInput) == 24000) check(part2(testInput) == 45000) val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
4455a5e9c15cd067d2661438c680b3d7b5879a56
1,007
kotlin-aoc-2022
Apache License 2.0
src/Day03.kt
dustinlewis
572,792,391
false
{"Kotlin": 29162}
fun main() { fun part1(input: List<String>): Int { return input.fold(0) { acc, el -> val (firstHalf, secondHalf) = el.chunked(el.count()/2) acc + getIntersection(firstHalf, secondHalf).first().priority } } fun part2(input: List<String>): Int { return input.chunked(3).fold(0) { acc, el -> acc + getIntersection(*el.toTypedArray()).first().priority } } val input = readInput("Day03") println(part1(input)) println(part2(input)) } val priorityMap = ('a'..'z').zip(1..26).toMap() + ('A'..'Z').zip(27..52).toMap() val Char.priority: Int get() = priorityMap[this] ?: 0 //fun getIntersection(s1: String, s2: String): Set<Char> = // s1.toSet() intersect s2.toSet() // //fun getIntersection(strings: List<String>): Set<Char> = // strings.fold(strings.first().toSet()) { acc, s -> s.toSet() intersect acc } fun getIntersection(vararg strings: String): Set<Char> = strings.fold(strings.first().toSet()) { acc, s -> s.toSet() intersect acc }
0
Kotlin
0
0
c8d1c9f374c2013c49b449f41c7ee60c64ef6cff
1,065
aoc-2022-in-kotlin
Apache License 2.0
2023/src/main/kotlin/day16_fast.kt
madisp
434,510,913
false
{"Kotlin": 388138}
import utils.IntGrid import utils.MutableIntGrid import utils.Parser import utils.Solution import utils.Vec2i fun main() { Day16Fast.run() } object Day16Fast : Solution<IntGrid>() { override val name = "day16" override val parser = Parser.charGrid.map { IntGrid(it.width, it.height) { p -> when (it[p]) { '.' -> AIR '|' -> SPLITV '-' -> SPLITH '/' -> MIRROR_LR '\\' -> MIRROR_RL else -> throw IllegalArgumentException("Bad input char ${it[p]} at $p") } } } private val directions = listOf(Vec2i.UP, Vec2i.DOWN, Vec2i.LEFT, Vec2i.RIGHT) private const val AIR = 0 private const val SPLITV = 1 private const val SPLITH = 2 private const val MIRROR_LR = 3 private const val MIRROR_RL = 4 private const val UP = 0 private const val DOWN = 1 private const val LEFT = 2 private const val RIGHT = 3 private val cw = listOf(RIGHT, LEFT, UP, DOWN) private val ccw = listOf(LEFT, RIGHT, DOWN, UP) private fun solve(start: Int): Int { val beams = IntArray(128) beams[0] = start var beamsSize = 1 val seen = MutableIntGrid(IntArray(input.width * input.height), input.width, input.height) var energizedCount = 0 while (beamsSize > 0) { val beam = beams[--beamsSize] val direction = beam and 0b11 val x = (beam ushr 2 and 0xff) - 1 val y = (beam ushr 10 and 0xff) - 1 val location = Vec2i(x, y) val dir = directions[direction] val nextLocation = location + dir if (nextLocation.x !in 0 until input.width || nextLocation.y !in 0 until input.height) { // out of bounds continue } val seenAtNext = seen[nextLocation] if (seenAtNext == 0) { energizedCount++ } else if ((1 shl direction) and seenAtNext != 0) { // already tracked a beam going that way continue } val nextLocationPacked = ((nextLocation.x + 1) shl 2) or ((nextLocation.y + 1) shl 10) seen[nextLocation] = seen[nextLocation] or (1 shl direction) when (input[nextLocation]) { AIR -> beams[beamsSize++] = nextLocationPacked or direction SPLITH -> if (dir.y == 0) { beams[beamsSize++] = nextLocationPacked or direction } else { beams[beamsSize++] = nextLocationPacked or LEFT beams[beamsSize++] = nextLocationPacked or RIGHT } SPLITV -> if (dir.x == 0) { beams[beamsSize++] = nextLocationPacked or direction } else { beams[beamsSize++] = nextLocationPacked or UP beams[beamsSize++] = nextLocationPacked or DOWN } MIRROR_RL -> if (dir.y == 0) { beams[beamsSize++] = nextLocationPacked or cw[direction] } else { beams[beamsSize++] = nextLocationPacked or ccw[direction] } MIRROR_LR -> if (dir.y == 0) { beams[beamsSize++] = nextLocationPacked or ccw[direction] } else { beams[beamsSize++] = nextLocationPacked or cw[direction] } else -> throw IllegalStateException("Bad grid char ${input[location]}") } } return energizedCount } override fun part1(): Int { return solve((1 shl 10) or RIGHT) } override fun part2(): Int { val inputs = mutableListOf<Int>() for (y in 0 until input.height) { inputs += (y + 1 shl 10) or RIGHT inputs += (input.width + 1 shl 2) or (y + 1 shl 10) or LEFT } for (x in 0 until input.width) { inputs += (x + 1 shl 2) or DOWN inputs += (x + 1 shl 2) or (input.height + 1 shl 10) or UP } return inputs.maxOf { solve(it) } } }
0
Kotlin
0
1
3f106415eeded3abd0fb60bed64fb77b4ab87d76
3,657
aoc_kotlin
MIT License
src/main/kotlin/io/github/leandroborgesferreira/dagcommand/logic/NodeList.kt
leandroBorgesFerreira
268,720,218
false
{"Kotlin": 33555}
package io.github.leandroborgesferreira.dagcommand.logic import io.github.leandroborgesferreira.dagcommand.domain.AdjacencyList import io.github.leandroborgesferreira.dagcommand.domain.Node import java.util.* fun findRootNodes(adjacencyList: AdjacencyList) = adjacencyList.keys - adjacencyList.values.flatten().toSet() fun nodesData(adjacencyList: AdjacencyList): List<Node> { val totalModules = adjacencyList.keys.size val edges = createEdgeList(adjacencyList) val moduleToInstability = adjacencyList.keys.associateWith { module -> calculateInstability(module, edges, totalModules) } val phasesMap = compilePhases(adjacencyList).mapIndexed { i, modulesInPhase -> i to modulesInPhase }.toMap() val moduleToPhase = reversePhasesMap(phasesMap) val nodeList: List<Node> = adjacencyList.keys.map { module -> Node( name = module, buildStage = moduleToPhase[module] ?: -1, instability = moduleToInstability[module] ?: -1.0 ) } return nodeList } fun List<Node>.groupByStages(): Map<Int, List<String>> = groupBy { buildStage -> buildStage.buildStage }.mapValues { (_, stageList) -> stageList.map { it.name } }.toSortedMap() private fun reversePhasesMap(phasesMap: Map<Int, Set<String>>): Map<String, Int> = phasesMap .flatMap { (key, values) -> values.map { it to key } } .associateBy({ it.first }, { it.second })
8
Kotlin
10
38
1bb81d504593b997e43851d09fbdb6a47662909b
1,469
dag-command
Apache License 2.0
src/main/kotlin/days/Day9.kt
MaciejLipinski
317,582,924
true
{"Kotlin": 60261}
package days class Day9 : Day(9) { override fun partOne(): Any { val numbers = inputList.map { it.toLong() } for (i in numbers.indices) { if (i < PREAMBLE_LENGTH) { continue } if (!isSumOfPrevious(numbers[i], numbers.subList(i - PREAMBLE_LENGTH, i))) { return numbers[i] } } return -1 } override fun partTwo(): Any { val invalidNumber = partOne().toString().toLong() val numbers = inputList.map { it.toLong() } return numbers .mapNotNull { findContiguousList(it, numbers.subList(numbers.indexOf(it), numbers.lastIndex), invalidNumber) } .firstOrNull() ?.let { minPlusMaxOf(it) } ?: -1 } private fun isSumOfPrevious(num: Long, previous: List<Long>): Boolean { previous.forEach { a -> previous.forEach { b -> if (num == a + b) return true } } return false } private fun findContiguousList(number: Long, numbers: List<Long>, invalidNumber: Long): List<Long>? { var sum = 0L for (i in numbers.indices) { sum += numbers[i] if (sum == invalidNumber) { return numbers.subList(0, i+1) } if (sum > invalidNumber) { return null } } return null } private fun minPlusMaxOf(list: List<Long>): Long = (list.maxOrNull() ?: 0) + (list.minOrNull() ?: 0) companion object { const val PREAMBLE_LENGTH = 25 } }
0
Kotlin
0
0
1c3881e602e2f8b11999fa12b82204bc5c7c5b51
1,636
aoc-2020
Creative Commons Zero v1.0 Universal
kotlinLeetCode/src/main/kotlin/leetcode/editor/cn/[867]转置矩阵.kt
maoqitian
175,940,000
false
{"Kotlin": 354268, "Java": 297740, "C++": 634}
//给你一个二维整数数组 matrix, 返回 matrix 的 转置矩阵 。 // // 矩阵的 转置 是指将矩阵的主对角线翻转,交换矩阵的行索引与列索引。 // // // // // // 示例 1: // // //输入:matrix = [[1,2,3],[4,5,6],[7,8,9]] //输出:[[1,4,7],[2,5,8],[3,6,9]] // // // 示例 2: // // //输入:matrix = [[1,2,3],[4,5,6]] //输出:[[1,4],[2,5],[3,6]] // // // // // 提示: // // // m == matrix.length // n == matrix[i].length // 1 <= m, n <= 1000 // 1 <= m * n <= 105 // -109 <= matrix[i][j] <= 109 // // Related Topics 数组 // 👍 176 👎 0 //leetcode submit region begin(Prohibit modification and deletion) class Solution { fun transpose(matrix: Array<IntArray>): Array<IntArray> { //相当于把 M*N矩阵 转变成 N*M 矩阵 , res[j][i] = matrix[i][j] //时间复杂度 O(mn) var m = matrix.size var n = matrix[0].size val res = Array(n) { IntArray(m) } for (i in 0 until m){ for ( j in 0 until n){ res[j][i] = matrix[i][j] } } return res } } //leetcode submit region end(Prohibit modification and deletion)
0
Kotlin
0
1
8a85996352a88bb9a8a6a2712dce3eac2e1c3463
1,205
MyLeetCode
Apache License 2.0
src/day20/Code.kt
fcolasuonno
572,734,674
false
{"Kotlin": 63451, "Dockerfile": 1340}
package day20 import day06.main import readInput fun main() { fun part1(input: List<String>) = input.map { it.toLong() }.withIndex() .toMutableList().apply { for (originalIndex in indices) { val mixingIndex = indexOfFirst { it.index == originalIndex } val mixing = removeAt(mixingIndex) var finalIndex = (mixingIndex + mixing.value) % size while (finalIndex < 0) { finalIndex += size } add(finalIndex.toInt(), mixing) } }.run { val zero = indexOfFirst { it.value == 0L } (1000..3000 step 1000).sumOf { this[(zero + it) % size].value } } fun part2(input: List<String>) = input.map { it.toLong() * 811589153L }.withIndex() .toMutableList().apply { repeat(10) { for (originalIndex in indices) { val mixingIndex = indexOfFirst { it.index == originalIndex } val mixing = removeAt(mixingIndex) var finalIndex = (mixingIndex + mixing.value) % size while (finalIndex < 0) { finalIndex += size } add(finalIndex.toInt(), mixing) } } }.run { val zero = indexOfFirst { it.value == 0L } (1000..3000 step 1000).sumOf { this[(zero + it) % size].value } } val input = readInput(::main.javaClass.packageName) println("Part1=\n" + part1(input)) println("Part2=\n" + part2(input)) }
0
Kotlin
0
0
9cb653bd6a5abb214a9310f7cac3d0a5a478a71a
1,681
AOC2022
Apache License 2.0
src/main/kotlin/g1601_1700/s1627_graph_connectivity_with_threshold/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g1601_1700.s1627_graph_connectivity_with_threshold // #Hard #Array #Math #Union_Find #2023_06_16_Time_703_ms_(100.00%)_Space_87.8_MB_(100.00%) class Solution { fun areConnected(n: Int, threshold: Int, queries: Array<IntArray>): List<Boolean> { if (n < 1 || queries.isEmpty()) { return ArrayList() } var j: Int var k: Int var x: Int val set = DisjointSetUnion(n + 1) val edges = queries.size var i: Int = threshold + 1 while (i <= n) { k = n / i x = i j = 2 while (j <= k) { x += i set.union(i, x) j++ } i++ } val result: MutableList<Boolean> = ArrayList(edges) for (query in queries) { result.add(set.find(query[0]) == set.find(query[1])) } return result } private class DisjointSetUnion(n: Int) { private val rank: IntArray private val parent: IntArray init { rank = IntArray(n) parent = IntArray(n) for (i in 0 until n) { rank[i] = 1 parent[i] = i } } fun find(u: Int): Int { var x = u while (x != parent[x]) { x = parent[x] } parent[u] = x return x } fun union(u: Int, v: Int) { if (u != v) { val x = find(u) val y = find(v) if (x != y) { if (rank[x] > rank[y]) { rank[x] += rank[y] parent[y] = x } else { rank[y] += rank[x] parent[x] = y } } } } } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,904
LeetCode-in-Kotlin
MIT License
src/main/java/com/ncorti/aoc2021/Exercise11.kt
cortinico
433,486,684
false
{"Kotlin": 36975}
package com.ncorti.aoc2021 object Exercise11 { private fun getInput() = getInputAsTest("11") { split("\n") } .map { line -> line.toCharArray().map { it.digitToInt() }.toTypedArray() } .toTypedArray() private fun Array<Array<Int>>.letItFlash(): Int { var count = 0 for (i in this.indices) { for (j in this.indices) { if (this[i][j] == -1) { count++ this[i][j] = 0 } } } return count } private val steps = listOf(-1 to 0, -1 to -1, 0 to -1, 1 to 0, 1 to 1, 0 to 1, 1 to -1, -1 to 1) private fun Array<Array<Int>>.findFlashCandidates(): MutableSet<Pair<Int, Int>> { val toFlash = mutableSetOf<Pair<Int, Int>>() for (i in this.indices) { for (j in this.indices) { this[i][j] += 1 if (this[i][j] > 9) { toFlash.add(i to j) } } } return toFlash } private fun runSimulation(times: Int): Pair<Int, Int> { val world = getInput() var flashes = 0 val toFlash = mutableListOf<Pair<Int, Int>>() repeat(times) { time -> toFlash.addAll(world.findFlashCandidates()) while (toFlash.isNotEmpty()) { val (i, j) = toFlash.removeFirst() world[i][j] = -1 flashes++ steps.forEach { (modi, modj) -> val (newi, newj) = i + modi to j + modj if (newi in world.indices && newj in world.indices && world[newi][newj] != -1 && (newi to newj) !in toFlash) { world[newi][newj] += 1 if (world[newi][newj] > 9) { toFlash.add(newi to newj) } } } } val count = world.letItFlash() if (count == world.size * world.size) { return (flashes to time + 1) } } return (flashes to times) } fun part1(): Int = runSimulation(100).first fun part2(): Int = runSimulation(Int.MAX_VALUE).second } fun main() { println(Exercise11.part1()) println(Exercise11.part2()) }
0
Kotlin
0
4
af3df72d31b74857201c85f923a96f563c450996
2,406
adventofcode-2021
MIT License
src/chapter4/section4/ex25_ShortestPathsBetweenTwoSubsets.kt
w1374720640
265,536,015
false
{"Kotlin": 1373556}
package chapter4.section4 import chapter3.section5.LinearProbingHashSET import chapter3.section5.SET /** * 两个顶点集合之间的最短路径 * 给定一幅边的权重均为正的有向图和两个没有交集的顶点集S和T, * 找到从S中的任意顶点到达T中的任意顶点的最短路径。 * 你的算法在最坏情况下所需的时间应该与ElogV成正比。 * * 解:根据练习4.4.24中的算法,将集合S中的所有顶点作为起点,生成最短路径森林, * 遍历集合T,找到到达每个顶点的最短路径,最短的最短路径必定只含有一条边 */ fun ex25_ShortestPathsBetweenTwoSubsets(digraph: EdgeWeightedDigraph, S: SET<Int>, T: SET<Int>): DirectedEdge? { val startingPoints = Array(S.size()) { 0 } S.forEachIndexed { i, v -> check(!T.contains(v)) startingPoints[i] = v } T.forEach { check(!S.contains(it)) } val sp = MultisourceShortestPaths(digraph, startingPoints) var minEdge: DirectedEdge? = null T.forEach { v -> if (sp.hasPathTo(v)) { if (minEdge == null || minEdge!!.weight > sp.distTo(v)) { val path = sp.pathTo(v)!!.iterator() val edge = path.next() // 连接两个集合顶点的最短路径必定只包含一条边 if (!path.hasNext()) { minEdge = edge } } } } return minEdge } fun main() { val digraph = getTinyEWD() val S = LinearProbingHashSET<Int>() val T = LinearProbingHashSET<Int>() S.add(0) S.add(1) S.add(2) S.add(3) T.add(4) T.add(5) T.add(6) T.add(7) println(ex25_ShortestPathsBetweenTwoSubsets(digraph, S, T)) println(ex25_ShortestPathsBetweenTwoSubsets(digraph, T, S)) }
0
Kotlin
1
6
879885b82ef51d58efe578c9391f04bc54c2531d
1,827
Algorithms-4th-Edition-in-Kotlin
MIT License
src/main/kotlin/biz/koziolek/adventofcode/year2022/day04/day4.kt
pkoziol
434,913,366
false
{"Kotlin": 715025, "Shell": 1892}
package biz.koziolek.adventofcode.year2022.day04 import biz.koziolek.adventofcode.findInput fun main() { val inputFile = findInput(object {}) val assignments = parseAssignments(inputFile.bufferedReader().readLines()) println("Fully contained assignment pairs: ${assignments.count { it.isAnyFullyContainedInOther() }}") println("Overlapping assignment pairs: ${assignments.count { it.areOverlapping() }}") } data class Assignment(val beginning: Int, val end: Int) data class AssignmentPair(val first: Assignment, val second: Assignment) { fun isAnyFullyContainedInOther(): Boolean = (first.beginning >= second.beginning && first.end <= second.end) || (second.beginning >= first.beginning && second.end <= first.end) fun areOverlapping(): Boolean = (first.beginning <= second.end && first.end >= second.beginning) } fun parseAssignments(lines: Iterable<String>): List<AssignmentPair> = lines.map { line -> val parts = line.split(',', '-') AssignmentPair( first = Assignment( beginning = parts[0].toInt(), end = parts[1].toInt(), ), second = Assignment( beginning = parts[2].toInt(), end = parts[3].toInt(), ) ) }
0
Kotlin
0
0
1b1c6971bf45b89fd76bbcc503444d0d86617e95
1,318
advent-of-code
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/MinDepth.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2023 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import java.util.LinkedList import java.util.Queue import kotlin.math.min /** * 111. Minimum Depth of Binary Tree * @see <a href="https://leetcode.com/problems/minimum-depth-of-binary-tree/">Source</a> */ fun interface MinDepth { operator fun invoke(root: TreeNode?): Int } /** * Approach 1: Depth-First Search (DFS) */ class MinDepthDFS : MinDepth { override operator fun invoke(root: TreeNode?): Int { return dfs(root) } private fun dfs(root: TreeNode?): Int { if (root == null) { return 0 } // If only one of child is non-null, then go into that recursion. if (root.left == null) { return 1 + dfs(root.right) } else if (root.right == null) { return 1 + dfs(root.left) } // Both children are non-null, hence call for both childs. return 1 + min(dfs(root.left), dfs(root.right)) } } /** * Approach 2: Breadth-First Search (BFS) */ class MinDepthBFS : MinDepth { override operator fun invoke(root: TreeNode?): Int { if (root == null) { return 0 } val q: Queue<TreeNode> = LinkedList() q.add(root) var depth = 1 while (q.isNotEmpty()) { var qSize: Int = q.size while (qSize > 0) { qSize-- val node: TreeNode = q.remove() ?: continue // Since we added nodes without checking null, we need to skip them here. // The first leaf would be at minimum depth, hence return it. if (node.left == null && node.right == null) { return depth } q.add(node.left) q.add(node.right) } depth++ } return -1 } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
2,457
kotlab
Apache License 2.0
src/Day16.kt
jrmacgill
573,065,109
false
{"Kotlin": 76362}
class Day16 { val inputLineRegex = """Valve ([A-Z]*) has flow rate=(\d+); tunnel[s]? lead[s]? to valve[s]? (.*)""".toRegex() val data = mutableMapOf<String, Room>() val maxTicks = 30 var best = 0 class Room(val id : String, val flow : Int, val links : List<String>) { } fun maxRemain(open : List<String>, tick : Int) : Int { var remain = 0 data.forEach { v -> if (!open.contains(v.key)) { remain += v.value.flow * (maxTicks-tick) } } return remain } fun step(room : Room , tick : Int, open : List<String>, score:Int) { if (tick == maxTicks) { println("Done with: " + score) if (score > best) { best = score } return } if (open.size == data.size) { println("All open with " + score) return } if (maxRemain(open, tick)+score < best) { //println("Crap, giveup") return } if (!open.contains(room.id)) { var next = open.toMutableList() next.add(room.id) step(room, tick+1,next, score + (room.flow*(maxTicks-(tick+1)))) } room.links.forEach{ // println("step to " + it.trim()) step(data[it.trim()]!!, tick+1, open, score) } } fun parse(line : String) { val match = inputLineRegex .find(line)!! println(match) val (code, flow, links) = match.destructured data[code] = Room(code, flow.toInt(), links.split(",")) /* val (code : String , flow : Int, links : String) = inputLineRegex .matchEntire(line) ?.destructured ?: throw IllegalArgumentException("Incorrect input line $line")*/ } fun go() { var lines =readInput("day16") lines.forEach(::parse) step(data["AA"]!!, 0, listOf<String>(), 0) println(best) } } fun main() { Day16().go() }
0
Kotlin
0
1
3dcd590f971b6e9c064b444139d6442df034355b
2,061
aoc-2022-kotlin
Apache License 2.0
src/main/kotlin/io/github/kmakma/adventofcode/y2019/Y2019Day10.kt
kmakma
225,714,388
false
null
package io.github.kmakma.adventofcode.y2019 import io.github.kmakma.adventofcode.y2019.utils.Vector2D import kotlin.math.abs internal class Y2019Day10 : Y2019Day(10, "Monitoring Station") { private lateinit var asteroidList: List<Vector2D> private lateinit var detectedAsteroids: List<Int> override fun initializeDay() { val asteroidMapLines = inputInStringLines() val asteroidMutList = mutableListOf<Vector2D>() // parse asteroid map to list of asteroids for (y in asteroidMapLines.indices) { for (x in asteroidMapLines[y].indices) { if (asteroidMapLines[y][x] == '#') { asteroidMutList.add(Vector2D(x, y)) } } } asteroidList = asteroidMutList // calculate detected asteroids val detected = mutableListOf<Int>() for (asteroid in asteroidList) { detected.add(numberOfDetectedAsteroids(asteroid)) } detectedAsteroids = detected } override suspend fun solveTask1(): Int { return detectedAsteroids.maxOrNull() ?: 0 } override suspend fun solveTask2(): Int? { val stationAsteroid = asteroidList[detectedAsteroids.indexOf(detectedAsteroids.maxOrNull() ?: 0)] // map of vectors grouped by shortest vector; e.g. ((1,2),(2,4),(3,6)..) at index (1,2) val vectorsToAsteroids: MutableMap<Vector2D, MutableList<Vector2D>> = (asteroidList - stationAsteroid) .map { (it - stationAsteroid) } .groupBy { it.shortest() } .mapValues { it.value.sortedWith { a, b -> clockwiseCompare(a, b) }.toMutableList() } .toMutableMap() // sort keys clockwise (actually not clockwise, since it starts at (0,-1) and goes counter-clockwise) val sortedKeys = (vectorsToAsteroids.keys) .sortedWith { a, b -> clockwiseCompare(a, b) } .toMutableSet() // laser show, until 200 destroyed var destroyed = 0 while (sortedKeys.isNotEmpty()) { val iterator = sortedKeys.iterator() while (iterator.hasNext()) { val direction = iterator.next() val vecsInDir: MutableList<Vector2D> = vectorsToAsteroids[direction]!! var destroyedV = vecsInDir.removeAt(0) destroyed++ if (destroyed == 200) { destroyedV += stationAsteroid return destroyedV.x * 100 + destroyedV.y } if (vecsInDir.size < 1) { iterator.remove() } } } return null } /** * compare function to sort vectors around (0,0) clockwise starting at 12 o'clock (0,-1). don't use (0,0), might not work * * compliments to manipulated work of https://stackoverflow.com/a/6989383 */ private fun clockwiseCompare(a: Vector2D, b: Vector2D): Int { // a and b on opposing sites (left/right) if (a.x >= 0 && b.x < 0) return -1 if (a.x < 0 && b.x >= 0) return 1 // a and b on y-axis if (a.x == 0 && b.x == 0) { return when { (a.y > 0 && b.y > 0) || (a.y <= 0 && b.y <= 0) -> abs(a.y) - abs(b.y) a.y <= 0 && b.y > 0 -> -1 a.y > 0 && b.y <= 0 -> 1 else -> error("impossible state") } } // a and b both on one site (left/right); cross product of vectors b x a val det = b.x * a.y - a.x * b.y if (det != 0) return det // points a and b are on the same line from the center // check which point is closer to the center return (a.length - b.length).toInt() } private fun numberOfDetectedAsteroids(asteroid: Vector2D): Int { return (asteroidList - asteroid) .map { (it - asteroid).shortest() } .toSet() .size } }
0
Kotlin
0
0
7e6241173959b9d838fa00f81fdeb39fdb3ef6fe
3,996
adventofcode-kotlin
MIT License
modules/fathom/src/main/kotlin/silentorb/mythic/fathom/surfacing/EdgeUnification.kt
silentorb
227,508,449
false
null
package silentorb.mythic.fathom.surfacing import silentorb.mythic.spatial.Vector3 import kotlin.math.abs data class BrokenLine( val middle: Vector3, val first: Edge, val second: Edge ) { val edges = listOf(first, second) } typealias BrokenLines = List<BrokenLine> tailrec fun accumulateNeighborLines(edge: Edge, endpoint: Vector3, lines: BrokenLines, accumulator: BrokenLines): Pair<BrokenLines, Vector3> = if (lines.none()) Pair(accumulator, endpoint) else { val matches = lines.filter { line -> line.edges.contains(edge) } if (matches.none()) Pair(accumulator, endpoint) else { assert(matches.size == 1) val match = matches.first() val nextEdge = match.edges.minus(edge).first() accumulateNeighborLines(nextEdge, getOtherVertex(nextEdge, match.middle), lines - match, accumulator + match) } } tailrec fun groupLines(brokenLines: BrokenLines, accumulator: List<Edge>): List<Edge> = if (brokenLines.none()) accumulator else { val next = brokenLines.first() val remaining = brokenLines.drop(1) val a = next.first val b = next.second val (firstNeighbors, start) = accumulateNeighborLines(a, getOtherVertex(a, next.middle), remaining, listOf()) val (secondNeighbors, end) = accumulateNeighborLines(b, getOtherVertex(b, next.middle), remaining, listOf()) val neighbors = firstNeighbors + secondNeighbors groupLines(remaining - neighbors, accumulator + Edge(start, end)) } fun unifyLinearEdges(allEdges: Edges): Edges { val vertices = getVerticesFromEdges(allEdges) val vertexEdgeMap = vertices .map { vertex -> Pair(vertex, allEdges.filter { edgeContains(it, vertex) }) } val lines = vertexEdgeMap .filter { (_, edges) -> edges.size == 2 } val edgesNeedingUnifying = lines .mapNotNull { (vertex, edges) -> val a = edges[0] val b = edges[1] val firstVector = getEdgeVector(a) val secondVector = getEdgeVector(b) val dot = firstVector.dot(secondVector) if (abs(dot) > 0.8f) BrokenLine(vertex, a, b) else null } val unifiedEdges = groupLines(edgesNeedingUnifying, listOf()) val oldEdges = edgesNeedingUnifying.flatMap { listOf(it.first, it.second) } return allEdges .minus(oldEdges) .plus(unifiedEdges) }
0
Kotlin
0
2
74462fcba9e7805dddec1bfcb3431665df7d0dee
2,411
mythic-kotlin
MIT License
src/commonMain/kotlin/rtree/Context.kt
seisuke
509,360,379
false
{"Kotlin": 165567, "HTML": 268}
package rtree /** * Configures an RTree prior to instantiation of an [RTree]. * * @constructor * @param minChildren minimum number of children per node (at least 1) * @param maxChildren max number of children per node (minimum is 3) * @param selector algorithm to select search path * @param splitter algorithm to split the children across two new nodes * @param factory node creation factory */ data class Context<T, GEOMETRY : Geometry>( val minChildren: Int, val maxChildren: Int, val selector: Selector<T, GEOMETRY>, val splitter: Splitter, val factory: Factory<T, GEOMETRY>, ) { init { require(minChildren >= 1) require(maxChildren > 2) require(minChildren < maxChildren) } } /** * The heuristic used on insert to select which node to add an Entry to. * */ interface Selector<T, GEOMETRY : Geometry> { /** * Returns the node from a list of nodes that an object with the given * geometry would be added to. * * @param geometry * geometry * @param nodes * nodes to select from * @return one of the given nodes */ fun select( geometry: Geometry, nodes: List<Node<T, GEOMETRY>> ): Node<T, GEOMETRY> } interface Splitter { /** * Splits a list of items into two lists of at least minSize. * * @param items list of items to split * @param minSize min size of each list * @return two lists */ fun <T : HasGeometry> split(items: List<T>, minSize: Int): ListPair<T> } /** * Uses minimal area increase to select a node from a list. * */ class SelectorMinimalAreaIncrease<T, S : Geometry> : Selector<T, S> { override fun select( geometry: Geometry, nodes: List<Node<T, S>> ): Node<T, S> { return nodes.minWithOrNull(areaIncreaseThenAreaComparator(geometry.mbr())) ?: nodes.first() } private fun areaIncreaseThenAreaComparator( rectangle: Rectangle ): Comparator<HasGeometry> = Comparator { g1, g2 -> val value = areaIncrease(rectangle, g1).compareTo(areaIncrease(rectangle, g2)) if (value == 0) { area(rectangle, g1).compareTo(area(rectangle, g2)) } else { value } } private fun area(rectangle: Rectangle, hasGeometry: HasGeometry): Int { return hasGeometry.geometry().mbr().add(rectangle).area() } private fun areaIncrease(rectangle: Rectangle, hasGeometry: HasGeometry): Int { val gPlusR = hasGeometry.geometry().mbr().add(rectangle) return gPlusR.area() - hasGeometry.geometry().mbr().area() } } /** * according to * http://en.wikipedia.org/wiki/R-tree#Splitting_an_overflowing_node */ class SplitterQuadratic : Splitter { override fun <T : HasGeometry> split(items: List<T>, minSize: Int): ListPair<T> { // find the worst combination pairwise in the list and use them to start // the two groups val (worstCombination1, worstCombination2) = worstCombination(items) // worst combination to have in the same node is now e1,e2. // establish a group around e1 and another group around e2 val remaining: List<T> = items - listOf( worstCombination1, worstCombination2 ) val minGroupSize = items.size / 2 // now add the remainder to the groups using least mbr area increase // except in the case where minimumSize would be contradicted val (group1Result, group2Result) = assignRemaining( listOf(worstCombination1), listOf(worstCombination2), remaining, minGroupSize ) return ListPair(group1Result, group2Result) } private tailrec fun <T : HasGeometry> assignRemaining( group1: List<T>, group2: List<T>, remaining: List<T>, minGroupSize: Int ): Pair<List<T>, List<T>> = if (remaining.isEmpty()) { group1 to group2 } else { val mbr1 = group1.mbr() val mbr2 = group2.mbr() val item1 = getBestCandidateForGroup(remaining, mbr1) val item2 = getBestCandidateForGroup(remaining, mbr2) val area1LessThanArea2 = item1.geometry().mbr().add(mbr1).area() <= item2.geometry().mbr().add(mbr2).area() if ( area1LessThanArea2 && group2.size + remaining.size - 1 >= minGroupSize || !area1LessThanArea2 && group1.size + remaining.size == minGroupSize ) { assignRemaining( group1 + item1, group2, remaining - item1, minGroupSize ) } else { assignRemaining( group1, group2 + item2, remaining - item2, minGroupSize ) } } private fun <T : HasGeometry> getBestCandidateForGroup( list: List<T>, groupMbr: Rectangle ): T { val minEntry = list.minByOrNull { entry -> groupMbr.add(entry.geometry().mbr()).area() } ?: list.first() return minEntry } private fun <T : HasGeometry> worstCombination(items: List<T>): Pair<T, T> { val mbrList: List<Pair<T, Rectangle>> = items.map { it to it.geometry().mbr() } val combination = mbrList.flatMap { mbr -> List(mbrList.size) { mbr }.zip(mbrList) } val maxCombination = combination.maxByOrNull { (a, b) -> a.second.add(b.second).area() }?.let { (a, b) -> a.first to b.first } ?: (items[0] to items[0]) return maxCombination } }
0
Kotlin
0
4
fe6480c744dabcdcf532d6733a089b500f229c80
5,690
ksn-draw
Apache License 2.0
src/Day14.kt
Totwart123
573,119,178
false
null
enum class Materials{ AIR, ROCK, SAND } fun main() { fun printGround(ground: List<List<Materials>>){ var xOffset = Int.MAX_VALUE ground.forEach { line -> line.forEachIndexed { index, materials -> if(index > xOffset){ return@forEachIndexed } if(materials != Materials.AIR){ xOffset = index } } } ground.map { line -> line.map{ when(it){ Materials.AIR -> "." Materials.ROCK -> "#" Materials.SAND -> "o" } } }.forEach { println(it.takeLast(it.size-xOffset).joinToString("")) } } fun drawLines(ground: MutableList<MutableList<Materials>>, lines: List<Pair<Int, Int>>){ for(i in 0 until lines.size - 1){ val from = lines[i] val to = lines[i+1] if(from.first == to.first){ val fromy = if(from.second > to.second)to.second else from.second val toy = if(from.second < to.second)to.second else from.second for(j in fromy..toy){ ground[j][from.first] = Materials.ROCK } } if(from.second == to.second){ val fromx = if(from.first > to.first)to.first else from.first val tox = if(from.first < to.first)to.first else from.first for(j in fromx..tox){ ground[from.second][j] = Materials.ROCK } } } } fun part2(input: List<String>): Int { val coords = input.map {line -> line.split("->").map { it.trim() }.map { val coords = it.split(",") val x = coords[0].toInt() val y = coords[1].toInt() Pair(x, y) } } val xOffset = coords.flatten().minOf { it.first } val ground = mutableListOf<MutableList<Materials>>() for(i in 0 until coords.flatten().maxOf { it.second } + 3){ ground.add(mutableListOf()) for(j in 0 until coords.flatten().maxOf { it.first } + 1){ ground[i].add(Materials.AIR) } } coords.forEach { drawLines(ground, it) } var currentSandTile = Pair(500,0) var currentSandTileCount = 1 val maxY = coords.flatten().maxOf { it.second } var oldSandTile: Pair<Int, Int>? = null while(oldSandTile != currentSandTile){ oldSandTile = currentSandTile if(ground.first().size == currentSandTile.first + 1){ ground.forEach { line -> line.add(Materials.AIR) } } when (Materials.AIR) { ground[currentSandTile.second + 1][currentSandTile.first] -> { currentSandTile = Pair(currentSandTile.first, currentSandTile.second + 1) } ground[currentSandTile.second + 1][currentSandTile.first - 1] -> { currentSandTile = Pair(currentSandTile.first - 1, currentSandTile.second + 1) } ground[currentSandTile.second + 1][currentSandTile.first + 1] -> { currentSandTile = Pair(currentSandTile.first + 1, currentSandTile.second + 1) } else -> { if(currentSandTile == Pair(500, 0)) break; currentSandTile = Pair(500, 0) oldSandTile = null currentSandTileCount ++ //printGround(ground) } } if(currentSandTile.second == maxY + 2){ currentSandTile = Pair(500, 0) oldSandTile = null currentSandTileCount ++ //printGround(ground) } oldSandTile?.let { ground[it.second][it.first] = Materials.AIR } ground[currentSandTile.second][currentSandTile.first] = Materials.SAND } return currentSandTileCount } fun part1(input: List<String>): Int { val coords = input.map {line -> line.split("->").map { it.trim() }.map { val coords = it.split(",") val x = coords[0].toInt() val y = coords[1].toInt() Pair(x, y) } } val xOffset = coords.flatten().minOf { it.first } val ground = mutableListOf<MutableList<Materials>>() for(i in 0 until coords.flatten().maxOf { it.second } + 1){ ground.add(mutableListOf()) for(j in 0 until coords.flatten().maxOf { it.first } + 1){ ground[i].add(Materials.AIR) } } coords.forEach { drawLines(ground, it) } var currentSandTile = Pair(500,0) var currentSandTileCount = 1 val maxY = coords.flatten().maxOf { it.second } while(currentSandTile.second < maxY){ var oldSandTile = currentSandTile when (Materials.AIR) { ground[currentSandTile.second + 1][currentSandTile.first] -> { currentSandTile = Pair(currentSandTile.first, currentSandTile.second + 1) } ground[currentSandTile.second + 1][currentSandTile.first - 1] -> { currentSandTile = Pair(currentSandTile.first - 1, currentSandTile.second + 1) } ground[currentSandTile.second + 1][currentSandTile.first + 1] -> { currentSandTile = Pair(currentSandTile.first + 1, currentSandTile.second + 1) } else -> { currentSandTile = Pair(500, 0) oldSandTile = currentSandTile currentSandTileCount ++ printGround(ground) } } ground[oldSandTile.second][oldSandTile.first] = Materials.AIR ground[currentSandTile.second][currentSandTile.first] = Materials.SAND } return currentSandTileCount-1 } val testInput = readInput("Day14_test") check(part1(testInput) == 24) check(part2(testInput) == 93) val input = readInput("Day14") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
33e912156d3dd4244c0a3dc9c328c26f1455b6fb
6,486
AoC
Apache License 2.0
library/src/main/kotlin/com/yt8492/indikate/RoutingPath.kt
yt8492
295,082,472
false
null
package com.yt8492.indikate class RoutingPath(val parts: List<RoutingPathSegment>) { fun evaluate(path: String): PathEvaluationResult { val pathParts = path.splitToSequence("/") .filter { it.isNotBlank() } .toList() if (pathParts.size != parts.size) { return PathEvaluationResult( false, PathEvaluationResult.QUALITY_FAILED, emptyMap() ) } var quality = PathEvaluationResult.QUALITY_CONSTANT val parameters = mutableMapOf<String, String>() pathParts.zip(parts).forEach { (pathPart, part) -> when (part) { is RoutingPathSegment.Constant -> { if (part.value != pathPart) { return PathEvaluationResult( false, PathEvaluationResult.QUALITY_FAILED, emptyMap() ) } } is RoutingPathSegment.Parameter -> { quality *= PathEvaluationResult.QUALITY_PARAMETER parameters[part.value] = pathPart } is RoutingPathSegment.WildCard -> { quality *= PathEvaluationResult.QUALITY_WILDCARD } } } return PathEvaluationResult( true, quality, parameters ) } companion object { private val ROOT: RoutingPath = RoutingPath(listOf()) fun parse(path: String): RoutingPath { if (path == "/") return ROOT val parts = path.splitToSequence("/") .filter { it.isNotBlank() } .map { when { it == "*" -> RoutingPathSegment.WildCard it.startsWith(":") -> RoutingPathSegment.Parameter(it.drop(1)) else -> RoutingPathSegment.Constant(it) } } .toList() return RoutingPath(parts) } } override fun toString(): String = parts.joinToString("/", "/") { it.value } } sealed class RoutingPathSegment { abstract val value: String data class Constant(override val value: String) : RoutingPathSegment() data class Parameter(override val value: String) : RoutingPathSegment() object WildCard : RoutingPathSegment() { override val value: String = "*" } } data class PathEvaluationResult( val succeeded: Boolean, val quality: Double, val parameters: Map<String, String> ) { companion object { const val QUALITY_CONSTANT = 1.0 const val QUALITY_PARAMETER = 0.8 const val QUALITY_WILDCARD = 0.5 const val QUALITY_FAILED = 0.0 } }
0
Kotlin
0
8
4f86715b99e48120f700cab957c55066ac0f7d66
2,875
indikate
MIT License
graph/MaximumFlow.kt
wangchaohui
737,511,233
false
{"Kotlin": 36737}
class MaximumFlow(vertexSize: Int, private val s: Int, private val t: Int) { data class Edge( val u: Int, val v: Int, var capacity: Int, var flow: Int = 0, ) { lateinit var reverse: Edge } private val level = IntArray(vertexSize) private val edges = Array(vertexSize) { mutableListOf<Edge>() } private val currentEdges = IntArray(vertexSize) fun addEdge(u: Int, v: Int, capacity: Int, reversedCapacity: Int = 0): Edge { val edge = Edge(u, v, capacity).also { edges[u] += it } edge.reverse = Edge(v, u, reversedCapacity).apply { reverse = edge }.also { edges[v] += it } return edge } fun dinic(): Long { var f = 0L while (bfs()) { currentEdges.fill(0) f += dfs(s, Int.MAX_VALUE) } return f } private fun bfs(): Boolean { level.fill(-1) level[s] = 0 val q = ArrayDeque<Int>() q.add(s) while (q.isNotEmpty()) { val u = q.removeFirst() for (edge in edges[u]) { val v = edge.v if (level[v] == -1 && edge.capacity > edge.flow) { level[v] = level[u] + 1 q.add(v) } } } return level[t] >= 0 } private fun dfs(u: Int, flowLimit: Int): Int { if (u == t || flowLimit == 0) return flowLimit var pushedFlow = 0 while (pushedFlow < flowLimit) { val edge = edges[u].getOrNull(currentEdges[u]++) ?: break val v = edge.v if (level[v] != level[u] + 1) continue val pathFlow = dfs(v, min(flowLimit - pushedFlow, edge.capacity - edge.flow)) pushedFlow += pathFlow edge.flow += pathFlow edge.reverse.flow -= pathFlow } return pushedFlow } }
0
Kotlin
0
0
241841f86fdefa9624e2fcae2af014899a959cbe
1,905
kotlin-lib
Apache License 2.0
백준/문제 추천 시스템 Version 1.kt
jisungbin
382,889,087
false
null
import java.io.BufferedReader import java.io.BufferedWriter import java.io.InputStreamReader import java.io.OutputStreamWriter import java.util.TreeMap private enum class ProblemType { EASY, HARD } private val solvedProblemNumbers = mutableListOf<Int>() private val problemsTree = TreeMap<Int, TreeMap<Int, Int>>() // 난이도 - <문제 번호, 아무값> fun main() { val br = BufferedReader(InputStreamReader(System.`in`)) val bw = BufferedWriter(OutputStreamWriter(System.out)) repeat(br.readLine()!!.toInt()) { val (problemNumber, problemLevel) = br.readLine()!!.split(" ").map { it.toInt() } problemsTree[problemLevel] = problemsTree.getOrDefault(problemLevel, TreeMap<Int, Int>()).apply { put(problemNumber, 0) } } repeat(br.readLine()!!.toInt()) { val commands = br.readLine().split(" ") val command = commands[0] when (command) { "add" -> { val problemNumber = commands[1].toInt() val problemLevel = commands[2].toInt() problemsTree[problemLevel] = problemsTree.getOrDefault(problemLevel, TreeMap<Int, Int>()).apply { put(problemNumber, 0) } } "solved" -> { val problemNumber = commands[1].toInt() solvedProblemNumbers.add(problemNumber) } "recommend" -> { val type = commands[1] val recommandProblemNumber = if (type == "1") { // 가장 어려운 문제 recommendProblemNumber(ProblemType.HARD) } else { // 가장 쉬운 문제 recommendProblemNumber(ProblemType.EASY) } bw.write("$recommandProblemNumber\n") } } } br.close() bw.flush() bw.close() } private fun recommendProblemNumber(type: ProblemType): Int { val problemLevel = if (type == ProblemType.HARD) { problemsTree.lastKey() } else { problemsTree.firstKey() } val problems = problemsTree[problemLevel]!! if (problems.isEmpty()) { problemsTree.remove(problemLevel) return recommendProblemNumber(type) } val problemNumber = if (type == ProblemType.HARD) { problems.lastKey() } else { problems.firstKey() } return if (solvedProblemNumbers.contains(problemNumber)) { // 이미 풀린 문제 problems.remove(problemNumber) solvedProblemNumbers.remove(problemNumber) recommendProblemNumber(type) } else { problemNumber } }
0
Kotlin
1
10
ee43375828ca7e748e7c79fbed63a3b4d27a7a2c
2,638
algorithm-code
MIT License
src/day04/Day04.kt
daniilsjb
726,047,752
false
{"Kotlin": 66638, "Python": 1161}
package day04 import java.io.File import kotlin.math.pow fun main() { val data = parse("src/day04/Day04.txt") println("🎄 Day 04 🎄") println() println("[Part 1]") println("Answer: ${part1(data)}") println() println("[Part 2]") println("Answer: ${part2(data)}") } private fun String.toMatches(): Int { val (_, winningPart, playerPart) = split(": ", " | ") val winningNumbers = winningPart .split(" ") .mapNotNull(String::toIntOrNull) .toSet() val playerNumbers = playerPart .split(" ") .mapNotNull(String::toIntOrNull) return playerNumbers.count { it in winningNumbers } } private fun parse(path: String): List<Int> = File(path) .readLines() .map(String::toMatches) private fun part1(data: List<Int>): Int = data.sumOf { 2.0.pow(it).toInt() / 2 } private fun part2(data: List<Int>): Int { val pile = MutableList(data.size) { 1 } for ((i, matches) in data.withIndex()) { for (offset in 1..matches) { pile[i + offset] += pile[i] } } return pile.sum() }
0
Kotlin
0
0
46a837603e739b8646a1f2e7966543e552eb0e20
1,178
advent-of-code-2023
MIT License
src/Day05.kt
ChrisCrisis
575,611,028
false
{"Kotlin": 31591}
import java.io.File data class MovementOperation( val from: Int, val to: Int, val amount: Int, ) data class StorageSlot( //val slotId: Int, val currentContainer: List<Char>, ) data class InputData( val craneSlots: List<StorageSlot>, val moves: List<MovementOperation>, ) const val CRANE_START_OFFSET = 1 const val CRANE_MOVE_OFFSET = 4 fun <E> List<List<E>>.transpose(): List<List<E>> { val result : List<MutableList<E>> = List(this.maxOf { it.size }){ mutableListOf() } this.forEach { it.forEachIndexed { index, e -> result[index].add(e) } } return result } fun main() { fun parseCraneSlots(craneData: List<String>): List<StorageSlot>{ val cleanData = craneData.take(craneData.size - 1) val some = cleanData.reversed().map { it.substring(CRANE_START_OFFSET,it.length-1) .slice(it.indices step CRANE_MOVE_OFFSET) .toList() }.transpose().map { containerInfo -> StorageSlot(containerInfo.filter { it != ' ' }) } return some } fun parseMovementOperations(operations: List<String>): List<MovementOperation> { return operations.map { val split = it.split(" ") MovementOperation( split[3].toInt(), split[5].toInt(), split[1].toInt(), ) } } fun parseInputToData(path: String): InputData{ val sections = File(path).readText() .split("\n\n") val craneSlots = parseCraneSlots(sections[0].split("\n")) val moves = parseMovementOperations(sections[1].split("\n")) return InputData( craneSlots, moves, ) } fun getLastItemFromCranes(craneSlots: List<StorageSlot>): String { return craneSlots.map { it.currentContainer.last() }.joinToString("") } fun InputData.getCraneSlotsAfterMoves9000(): List<StorageSlot>{ val initData = this.craneSlots.map { it.currentContainer.toMutableList() } this.moves.forEach { move -> val from = initData[move.from-1] val to = initData[move.to-1] from.takeLast(move.amount).reversed().forEach { to.add(it) from.removeLast() } } return initData.map { StorageSlot(it) } } fun InputData.getCraneSlotsAfterMoves9001(): List<StorageSlot> { val initData = this.craneSlots.map { it.currentContainer.toMutableList() } this.moves.forEach { move -> val from = initData[move.from - 1] val to = initData[move.to - 1] from.takeLast(move.amount).forEach { to.add(it) from.removeLast() } } return initData.map { StorageSlot(it) } } fun part1(data: InputData): String { val slotsAfterMoves = data.getCraneSlotsAfterMoves9000() return getLastItemFromCranes(slotsAfterMoves) } fun part2(data: InputData): String { val slotsAfterMoves = data.getCraneSlotsAfterMoves9001() return getLastItemFromCranes(slotsAfterMoves) } val testInput = parseInputToData("src/Day05_test.txt") check(part1(testInput) == "CMZ") check(part2(testInput) == "MCD") val input = parseInputToData("src/Day05.txt") println(part1(input)) println(part2(input)) }
1
Kotlin
0
0
732b29551d987f246e12b0fa7b26692666bf0e24
3,574
aoc2022-kotlin
Apache License 2.0
src/main/kotlin/io/github/pshegger/aoc/y2020/Y2020D23.kt
PsHegger
325,498,299
false
null
package io.github.pshegger.aoc.y2020 import io.github.pshegger.aoc.common.BaseSolver import io.github.pshegger.aoc.common.TaskVisualizer import io.github.pshegger.aoc.y2020.visualization.Y2020D23Visualizer class Y2020D23 : BaseSolver() { override val year = 2020 override val day = 23 override fun getVisualizer(): TaskVisualizer = Y2020D23Visualizer(parseInput()) override fun part1(): String { val inputNumbers = parseInput() val index1 = inputNumbers.indexOf(1) val cups = simulateGame(inputNumbers, 100) return buildString { var currentNode = cups[index1].next while (currentNode.value != 1) { append(currentNode.value) currentNode = currentNode.next } } } override fun part2(): Long { val inputNumbers = parseInput() val startingNumbers = inputNumbers + (inputNumbers.maxOf { it } + 1..1_000_000) val index1 = inputNumbers.indexOf(1) val cups = simulateGame(startingNumbers, 10_000_000) val nextVal = cups[index1].next.value val next2Val = cups[index1].next.next.value return next2Val.toLong() * nextVal } private fun simulateGame(startingNumbers: List<Int>, roundCount: Int): List<Node<Int>> { val (cups, minCup, maxCup, indices) = computeStart(startingNumbers) var currentCupIndex = 0 repeat(roundCount) { val pickUp = listOf( cups[currentCupIndex].next, cups[currentCupIndex].next.next, cups[currentCupIndex].next.next.next, ) cups[currentCupIndex].next = pickUp.last().next pickUp.last().next.prev = cups[currentCupIndex] var destination = cups[currentCupIndex].value - 1 if (destination < minCup) destination = maxCup while (pickUp.any { it.value == destination }) { destination-- if (destination < minCup) destination = maxCup } val destinationIndex = indices[destination] ?: error("WTF") val n0 = cups[destinationIndex] val n1 = cups[destinationIndex].next n1.prev = pickUp.last() pickUp.last().next = n1 n0.next = pickUp.first() pickUp.first().prev = n0 currentCupIndex = indices[cups[currentCupIndex].next.value] ?: error("WTF") } return cups } private fun parseInput() = readInput { readLines().first().trim().map { "$it".toInt() } } data class Node<T>(val value: T) { lateinit var prev: Node<T> lateinit var next: Node<T> } data class StartData(val cups: List<Node<Int>>, val minCup: Int, val maxCup: Int, val indices: Map<Int, Int>) companion object { fun computeStart(startingNumbers: List<Int>): StartData { val cups = startingNumbers.map { Node(it) } val minCup = startingNumbers.minOf { it } val maxCup = startingNumbers.maxOf { it } val indices = startingNumbers.mapIndexed { index, value -> Pair(value, index) }.toMap() cups.forEachIndexed { index, node -> if (index == 0) { node.prev = cups.last() } else { node.prev = cups[index - 1] } if (index == cups.lastIndex) { node.next = cups.first() } else { node.next = cups[index + 1] } } return StartData(cups, minCup, maxCup, indices) } } }
0
Kotlin
0
0
346a8994246775023686c10f3bde90642d681474
3,650
advent-of-code
MIT License
src/Day04.kt
faragogergo
573,451,927
false
{"Kotlin": 4406}
fun main() { fun String.range(): IntRange { val (start, end) = split("-") return IntRange(start.toInt(), end.toInt()) } fun String.rangePair(): Pair<IntRange, IntRange> { val (first, second) = split(",") return Pair(first.range(), second.range()) } fun IntRange.contains(other: IntRange) = first <= other.first && last >= other.last fun part1(input: List<String>) = input.count { val (first, second) = it.rangePair() first.contains(second) || second.contains(first) } fun part2(input: List<String>) = input.count { val (first, second) = it.rangePair() first.intersect(second).isNotEmpty() } val input = readInput("Day04") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
47dce5333f3c3e74d02ac3aaf51501069ff615bc
791
Advent_of_Code_2022
Apache License 2.0
src/main/kotlin/com/jacobhyphenated/day18/Day18.kt
jacobhyphenated
572,119,677
false
{"Kotlin": 157591}
package com.jacobhyphenated.day18 import com.jacobhyphenated.Day import com.jacobhyphenated.day15.PathCost import java.io.File import java.util.* // Many Worlds Interpretation class Day18: Day<List<List<Char>>> { override fun getInput(): List<List<Char>> { return createGrid( this.javaClass.classLoader.getResource("day18/input.txt")!!.readText() ) } /** * You are in a cave with keys (lower case letters) and locked doors (upper case letters). * When you find the key, you can pass through the corresponding doors. * Your robot's location is signified with an @ (. means open space, # means wall) * * What is the fewest number of moves necessary to find all the keys (runs in 1.5 seconds) * */ override fun part1(input: List<List<Char>>): Number { // start at @ symbol val initialPosition = initialStartingLocation(input) val grid = deepCopy(input) val lowestCostPath = mutableSetOf<Int>() return recursePath(grid, setOf(initialPosition), 0, lowestCostPath, mutableMapOf())!! } /** * The pattern around the initial robot looks like * ... * .@. * ... * * But instead, there are 4 robots, and the pattern should look like: * @#@ * ### * @#@ * * Each robot can move independently (but only one can move at a time) * Using all 4 robots, what is the fewest number of total moves needed to collect all keys? * * Runs in 45 seconds. Obviously not ideal and needs further optimizations */ override fun part2(input: List<List<Char>>): Number { val (r,c) = initialStartingLocation(input) val grid = deepCopy(input) // replace the starting initial robot pattern with the part 2 pattern for (row in r-1..r+1) { for (col in c-1..c+1) { grid[row][col] = '#' } } val robots = setOf(Pair(r-1,c-1), Pair(r-1, c+1), Pair(r+1, c-1), Pair(r+1, c+1)) robots.forEach { (row, col) -> grid[row][col] = '@' } val lowestCostPath = mutableSetOf<Int>() // re-use the part 1 logic but with a set of 4 robot positions rather than 1 position return recursePath(grid, robots, 0, lowestCostPath, mutableMapOf())!! } fun createGrid(input: String): List<List<Char>> { return input.lines() .map { it.toCharArray().map { c -> c } } } /** * Use a Depth First recursive search to find the shortest path to collect all keys. * * @param grid state of the map * @param robots current position(s) of the robot(s). Part 1 has one robot while part 2 has four * @param currentCost the cost to get the robot to its current position * @param lowestCostPath The final costs found so far to solve the problem * @param memo Memoization map that tracks the set of keys remaining + the robot positions to the cost to solve that map state * * @return The cost of getting from this current state to a solved state (null if this branch is not valid) */ private fun recursePath(grid: List<List<Char>>, robots: Set<Pair<Int,Int>>, currentCost: Int, lowestCostPath: MutableSet<Int>, memo: MutableMap<Pair<Set<Char>, Set<Pair<Int,Int>>>, Int>): Int? { val remainingKeys: Map<Char, Pair<Int,Int>> = grid .flatMapIndexed { r, row -> row.mapIndexed{ c, space -> Pair(Pair(r,c), space)}} .fold(mutableMapOf()){ acc, (position, space) -> if (space != '.' && space != '#' && space != '@' && space == space.lowercaseChar()) { acc[space] = position } acc } // There are no keys left, so we can stop - the total cost to get all keys is the cost to get here if (remainingKeys.isEmpty()) { lowestCostPath.add(currentCost) return 0 } // If we have previously solved this map state, use that memoized value memo[Pair(remainingKeys.keys, robots)]?.let { return it } val nextMove = robots.mapNotNull { robot -> val distances = validPathsForPosition(grid, robot) // If the cost of getting to a key from here is greater than an already solved cost, this branch // of the DFS is dead and can be pruned val currentMinCost = lowestCostPath.minOrNull() ?: Int.MAX_VALUE if (remainingKeys.any { (_,position) -> (distances[position] ?: 0) + currentCost > currentMinCost}) { return null } // for each key to find, do a recursive DFS // remove the key and corresponding door from the grid, then re-calculate position movement costs remainingKeys.entries.mapNotNull keyMap@{ (key, nextPosition) -> // no path to this key yet val costToPosition = distances[nextPosition] ?: return@keyMap null val (row, col) = nextPosition val newGrid = deepCopy(grid) newGrid[row][col] = '@' newGrid[robot.first][robot.second] = '.' clearDoor(newGrid, key) val nextRobots = robots.toMutableSet() nextRobots.remove(robot) nextRobots.add(nextPosition) recursePath(newGrid, nextRobots, costToPosition + currentCost, lowestCostPath, memo) ?.let { it + costToPosition } }.minOrNull() }.minOrNull() if (nextMove != null) { // Memoize the solved value for the given grid state memo[Pair(remainingKeys.keys, robots)] = nextMove } return nextMove } /** * Dijkstra's algorithm implementation for the grid * Finds the lowest movement cost to each space from the given location * Does not pass through walls, doors, keys, or other robots */ private fun validPathsForPosition(grid:List<List<Char>>, position: Pair<Int,Int>): Map<Pair<Int,Int>, Int> { val distances: MutableMap<Pair<Int,Int>, Int> = mutableMapOf() // Use a priority queue implementation - min queue sorted by lowest "cost" val queue = PriorityQueue<PathCost> { a, b -> a.cost - b.cost } queue.add(PathCost(position, 0)) distances[position] = 0 var current: PathCost do { current = queue.remove() // If we already found a less expensive way to reach this position if (current.cost > (distances[current.position] ?: Int.MAX_VALUE)) { continue } val (r,c) = current.position // if this position is a key or a door or a robot, we won't look further as the path is essentially blocked if (current.position != position && grid[r][c] != '.') { continue } // From the current position, look in each direction for a valid move // (the outside border is always walls, so we don't need to worry about index out of bounds issues) listOf(Pair(r-1,c), Pair(r+1,c), Pair(r,c-1), Pair(r,c+1)) .filter { (row,col) -> grid[row][col] != '#' } .forEach { val cost = distances.getValue(current.position) + 1 // If the cost to this space is less than what was previously known, put this on the queue if (cost < (distances[it] ?: Int.MAX_VALUE)) { distances[it] = cost queue.add(PathCost(it, cost)) } } } while (queue.size > 0) return distances } private fun clearDoor(grid: MutableList<MutableList<Char>>, key: Char) { for (r in grid.indices) { for (c in grid[r].indices) { if (grid[r][c] == key.uppercaseChar()) { grid[r][c] = '.' return } } } } private fun initialStartingLocation(grid: List<List<Char>>): Pair<Int,Int> { for (r in grid.indices) { for (c in grid[r].indices) { if (grid[r][c] == '@') { return Pair(r,c) } } } throw IllegalStateException("No valid starting character") } private fun deepCopy(grid: List<List<Char>>): MutableList<MutableList<Char>> { val newGrid = mutableListOf<MutableList<Char>>() for (row in grid) { newGrid.add(row.toMutableList()) } return newGrid } }
0
Kotlin
0
0
1a0b9cb6e9a11750c5b3b5a9e6b3d63649bf78e4
8,796
advent2019
The Unlicense
src/main/kotlin/dev/bogwalk/batch0/Problem7.kt
bog-walk
381,459,475
false
null
package dev.bogwalk.batch0 import dev.bogwalk.util.maths.isPrime /** * Problem 7: The 10001st Prime * * https://projecteuler.net/problem=7 * * Goal: Find the Nth prime number. * * Constraints: 1 <= N <= 10_001 * * e.g.: N = 6 * primes = {2,3,5,7,11,13,...} * 6th prime = 13 */ class The10001stPrime { /** * Solution iterates over all numbers & checks for primality using an optimised helper function, * until the [n]th prime is found. * * Odd numbers are not excluded from this iteration as this solution ran on average 7.80ms * for N = 10_001, compared to 8.21ms when the number starts at 1 and increments by 2. */ fun getNthPrime(n: Int): Int { var count = n var number = 1 while (count > 0) { if ((++number).isPrime()) count-- } return number } /** * Solution generates a list of primes of size [count] for quick-draw access. The dynamic * list itself is used to test primality of every number based on the prime factorisation * principle. * * The same rules for primes apply, namely that every prime after 2 is odd and the only * factor greater than sqrt(x) would be x itself if x is prime. * * @return list of primes with the nth prime at index n-1. */ fun getAllPrimes(count: Int): List<Int> { val primes = mutableListOf(2) var number = 1 nextNum@while (primes.size < count) { number += 2 for (p in primes) { if (p * p > number) break if (number % p == 0) continue@nextNum } primes.add(number) } return primes } }
0
Kotlin
0
0
62b33367e3d1e15f7ea872d151c3512f8c606ce7
1,718
project-euler-kotlin
MIT License
src/test/kotlin/Day04.kt
christof-vollrath
317,635,262
false
null
import io.kotest.core.datatest.forAll import io.kotest.core.spec.style.FunSpec import io.kotest.matchers.shouldBe /* --- Day 4: Passport Processing --- See https://adventofcode.com/2020/day/4 */ fun parsePassportStrings(passportsString: String): List<String> = passportsString.split("""\n\s*\n""".toRegex()) fun countCheckedPassports(passportStrings: List<String>) = passportStrings.map { parsePassport(it) } .filter { it.check() } .count() fun countValidPassports(passportStrings: List<String>) = passportStrings.map { parsePassport(it) } .filter { it.check() && it.validate() } .count() fun Map<String, String>.check() = keys.toSet().intersect(setOf( "byr", "iyr", "eyr", "hgt", "hcl", "ecl", "pid" )).size == 7 fun Map<String, String>.validate() = keys.subtract(setOf("cid")).all { key -> val validator = validators[key] ?: { false } val value = this[key] if (value == null) { println("Error: no validator for $key") return false } val result = validator(value) if (!result) println("Error: validator $key could not validate $value") result } fun parsePassport(input: String): Map<String, String> { val pattern = """\s*([a-z]+):\s*(\S+)""".toPattern() val matcher = pattern.matcher(input) return sequence { while(matcher.find()) { yield(matcher.group(1) to matcher.group(2)) } }.toMap() } val validators: Map<String, (String)->Boolean> = mapOf( "byr" to { input -> val n = input.toIntOrNull() n != null && 1920 <= n && n <= 2002 }, "iyr" to { input -> val n = input.toIntOrNull() n != null && 2010 <= n && n <= 2020 }, "eyr" to { input -> val n = input.toIntOrNull() n != null && 2020 <= n && n <= 2030 }, "hgt" to { input -> when { input.endsWith("cm") -> { val n = input.removeSuffix("cm").toIntOrNull() n != null && 150 <= n && n <= 193 } input.endsWith("in") -> { val n = input.removeSuffix("in").toIntOrNull() n != null && 59 <= n && n <= 76 } else -> false } }, "hcl" to { input -> val regex = """^#[0-9a-f]{6}$""".toRegex() regex.find(input) != null }, "ecl" to { input -> input in setOf("amb", "blu", "brn", "gry", "grn", "hzl", "oth") }, "pid" to { input -> val regex = """^[0-9]{9}$""".toRegex() regex.matches(input) }, ) class Day04_Part1 : FunSpec({ context("parse passport") { val passportString = """ ecl:gry pid:860033327 eyr:2020 hcl:#fffffd byr:1937 iyr:2017 cid:147 hgt:183cm """.trimIndent() test("should be parsed correctly") { val passport = parsePassport(passportString) passport["ecl"] shouldBe "gry" passport["hcl"] shouldBe "#fffffd" } } context("check passport") { data class CheckPassportTestCase(val passportString: String, val expected: Boolean) forAll( CheckPassportTestCase(""" ecl:gry pid:860033327 eyr:2020 hcl:#fffffd byr:1937 iyr:2017 cid:147 hgt:183cm """.trimIndent(), true), CheckPassportTestCase(""" iyr:2013 ecl:amb cid:350 eyr:2023 pid:028048884 hcl:#cfa07d byr:1929 """.trimIndent(), false), CheckPassportTestCase(""" hcl:#ae17e1 iyr:2013 eyr:2024 ecl:brn pid:760753108 byr:1931 hgt:179cm """.trimIndent(), true), CheckPassportTestCase(""" hcl:#cfa07d eyr:2025 pid:166559648 iyr:2011 ecl:brn hgt:59in """.trimIndent(), false), ) { (passportString, expected) -> val result = parsePassport(passportString).check() result shouldBe expected } } context("count valid passports") { val passportsString = """ ecl:gry pid:860033327 eyr:2020 hcl:#fffffd byr:1937 iyr:2017 cid:147 hgt:183cm iyr:2013 ecl:amb cid:350 eyr:2023 pid:028048884 hcl:#cfa07d byr:1929 hcl:#ae17e1 iyr:2013 eyr:2024 ecl:brn pid:760753108 byr:1931 hgt:179cm hcl:#cfa07d eyr:2025 pid:166559648 iyr:2011 ecl:brn hgt:59in """.trimIndent() context("parse passports") { val passportStrings = parsePassportStrings(passportsString) test("should have found four passport strings") { passportStrings.size shouldBe 4 } } context("count valid passports") { val count = countCheckedPassports(parsePassportStrings(passportsString)) count shouldBe 2 } } }) class Day04_Part1_Exercise: FunSpec({ val input = readResource("day04Input.txt")!! val count = countCheckedPassports(parsePassportStrings(input)) test("solution") { count shouldBe 230 } }) class Day04_Part2 : FunSpec({ context("validators") { validators["byr"]!!("1920") shouldBe true validators["byr"]!!("1900") shouldBe false validators["iyr"]!!("2010") shouldBe true validators["iyr"]!!("2009") shouldBe false validators["eyr"]!!("2030") shouldBe true validators["eyr"]!!("2031") shouldBe false validators["hgt"]!!("150cm") shouldBe true validators["hgt"]!!("149cm") shouldBe false validators["hgt"]!!("76in") shouldBe true validators["hgt"]!!("77in") shouldBe false validators["hcl"]!!("#0123ef") shouldBe true validators["hcl"]!!("#0123ex") shouldBe false validators["hcl"]!!("#0123efX") shouldBe false validators["ecl"]!!("amb") shouldBe true validators["ecl"]!!("xyz") shouldBe false validators["pid"]!!("000000001") shouldBe true validators["pid"]!!("0123456789") shouldBe false } context("validate passports") { val invalidPassportsString = """ eyr:1972 cid:100 hcl:#18171d ecl:amb hgt:170 pid:186cm iyr:2018 byr:1926 iyr:2019 hcl:#602927 eyr:1967 hgt:170cm ecl:grn pid:012533040 byr:1946 hcl:dab227 iyr:2012 ecl:brn hgt:182cm pid:021572410 eyr:2020 byr:1992 cid:277 hgt:59cm ecl:zzz eyr:2038 hcl:74454a iyr:2023 pid:3556412378 byr:2007 """.trimIndent() test("all passports should be invalid") { val invalidPassportStrings = parsePassportStrings(invalidPassportsString) invalidPassportStrings.size shouldBe 4 countValidPassports(invalidPassportStrings) shouldBe 0 } val validPassportsString = """ pid:087499704 hgt:74in ecl:grn iyr:2012 eyr:2030 byr:1980 hcl:#623a2f eyr:2029 ecl:blu cid:129 byr:1989 iyr:2014 pid:896056539 hcl:#a97842 hgt:165cm hcl:#888785 hgt:164cm byr:2001 iyr:2015 cid:88 pid:545766238 ecl:hzl eyr:2022 iyr:2010 hgt:158cm hcl:#b6652a ecl:blu byr:1944 eyr:2021 pid:093154719 """.trimIndent() test("all passports should be valid") { val validPassportStrings = parsePassportStrings(validPassportsString) validPassportStrings.size shouldBe 4 countValidPassports(validPassportStrings) shouldBe 4 } } }) class Day04_Part2_Exercise: FunSpec({ val input = readResource("day04Input.txt")!! val count = countValidPassports(parsePassportStrings(input)) test("solution") { count shouldBe 156 } })
1
Kotlin
0
0
8ad08350aa4bd1a29b7e18765fc7a2d6de8021e8
8,018
advent_of_code_2020
Apache License 2.0
src/day4/day4.kt
bienenjakob
573,125,960
false
{"Kotlin": 53763}
package day4 import inputTextOfDay import testTextOfDay val input = inputTextOfDay(4) fun getInput(input: String): List<Pair<Set<Int>, Set<Int>>> { return input.lines().map { it.split(',','-').map(String::toInt) .let{ (a,b,c,d) -> (a..b).toSet() to (c..d).toSet() } } } fun part1(text: String): Int { return getInput(text).count { (a, b) -> a intersect b == a || a intersect b == b } } fun part2(text: String): Int { return getInput(text).count { (a, b) -> (a intersect b).isNotEmpty() } } fun main() { val day = 4 val testInput = testTextOfDay(day) check(part1(testInput) == 2) check(part2(testInput) == 4) check(part1(input) == 602) check(part2(input) == 891) println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
6ff34edab6f7b4b0630fb2760120725bed725daa
801
aoc-2022-in-kotlin
Apache License 2.0
day21/kotlin/corneil/src/main/kotlin/solution.kt
jensnerche
317,661,818
true
{"HTML": 2739009, "Java": 348790, "Kotlin": 271602, "TypeScript": 262310, "Python": 198318, "JetBrains MPS": 191916, "Groovy": 125347, "Jupyter Notebook": 116902, "C++": 101742, "Dart": 47762, "Haskell": 43633, "CSS": 35030, "Ruby": 27091, "JavaScript": 13242, "Scala": 11409, "Dockerfile": 10370, "PHP": 4152, "Go": 2838, "Shell": 2651, "Rust": 2082, "Clojure": 567, "Cypher": 515, "Tcl": 46}
package com.github.corneil.aoc2019.day21 import com.github.corneil.aoc2019.intcode.Program import com.github.corneil.aoc2019.intcode.readProgram import java.io.File fun makeInput(input: String): List<Long> { val lines = input.trim().split('\n') return lines.map { it.trim().map { it.toLong() } + 10L }.flatten() } fun printOutput(output: List<Long>): String { return output.map { if (it.toInt() < 256) it.toChar().toString() else it.toString() }.joinToString("") } fun reportHullDamage(code: List<Long>, springCode:String): Int { val program = Program(code) val state = program.createProgram() val input = mutableListOf<Long>() input.addAll(makeInput(springCode)) var result = 0 do { state.executeUntilInput(input) input.clear() val output = state.extractOutput() result += output.filter { it > 256 }.sum().toInt() println(output) val str = printOutput(output) println(str) } while (!state.isHalted()) return result; } fun main() { val code = readProgram(File("input.txt")) val springCode1 = """ NOT A J NOT B T AND D T OR T J NOT C T OR T J AND D J WALK """.trimIndent() val damage1 = reportHullDamage(code, springCode1) println("Damage:$damage1") val springCode2 = """ NOT A J NOT B T AND D T OR T J NOT C T OR T J NOT A T OR T J AND H J OR E J AND D J RUN """.trimIndent() val damage2 = reportHullDamage(code, springCode2) println("Damage:$damage2") }
0
HTML
0
0
a84c00ddbeb7f9114291125e93871d54699da887
1,658
aoc-2019
MIT License
src/Day24.kt
underwindfall
573,471,357
false
{"Kotlin": 42718}
fun main() { day24Part(1) day24Part(2) } fun day24Part(part: Int) { val dayId = "24" val input = readInput("Day${dayId}") val a = input.toCharArray2() val (n, m) = a.size2() val (di, dj) = RDLU_DIRS data class B(val i: Int, val j: Int, val d: Int) val bs = a.mapIndexed2NotNull { i, j, c -> val d = when (c) { '>' -> 0 'v' -> 1 '<' -> 2 '^' -> 3 '#', '.' -> -1 else -> error(a[i][j]) } if (d >= 0) B(i, j, d) else null } var pc = HashSet<P2>() var pn = HashSet<P2>() var s = P2(0, 1) var f = P2(n - 1, m - 2) pc += s val totalPhases = if (part == 1) 0 else 2 var phase = 0 var t = 0 while (phase < totalPhases || f !in pc) { if (f in pc) { phase++ pc.clear() f = s.also { s = f } pc += s } val bn = bs.map { b -> P2( (b.i + di[b.d] * (t + 1) - 1).mod(n - 2) + 1, (b.j + dj[b.d] * (t + 1) - 1).mod(m - 2) + 1 ) }.toSet() for (p in pc) { for (d in 0..3) { val p1 = P2(p.i + di[d], p.j + dj[d]) if (p1 in bn) continue if (p1.i in 0 until n && p1.j in 0 until m && a[p1.i][p1.j] != '#') { pn += p1 } } if (p !in bn) pn += p } pc = pn.also { pn = pc } pn.clear() t++ } println("part$part = $t") }
0
Kotlin
0
0
0e7caf00319ce99c6772add017c6dd3c933b96f0
1,568
aoc-2022
Apache License 2.0
src/main/kotlin/com/hj/leetcode/kotlin/problem1146/Solution.kt
hj-core
534,054,064
false
{"Kotlin": 619841}
package com.hj.leetcode.kotlin.problem1146 /** * LeetCode page: [1146. Snapshot Array](https://leetcode.com/problems/snapshot-array/); */ class SnapshotArray(length: Int) { private var latestSnapId = -1 private val snapshots = Array(length) { mutableListOf(Record(latestSnapId, 0)) } private val pendingChanges = hashMapOf<Int, Int>() // entry = (index, value) private data class Record(val snapId: Int, val value: Int) /* Complexity of N calls: * Time O(N) and Space O(N); */ fun set(index: Int, `val`: Int) { pendingChanges[index] = `val` } /* Complexity: * Time O(N) and Space O(N) where N is the size of pendingChanges; */ fun snap(): Int { latestSnapId++ for ((index, value) in pendingChanges) { val hasValueChanged = value != snapshots[index].last().value if (hasValueChanged) { snapshots[index].add(Record(latestSnapId, value)) } } pendingChanges.clear() return latestSnapId } /* Complexity: * Time O(Log(latestSnapId)) and Space O(1); */ fun get(index: Int, snap_id: Int): Int { require(snap_id in 0..latestSnapId) return equivalentRecord(index, snap_id).value } private fun equivalentRecord(index: Int, snapId: Int): Record { require(snapId >= snapshots[index][0].snapId) if (snapId >= snapshots[index].last().snapId) { return snapshots[index].last() } // Binary search on the index of record in snapshots[index] var lowerBound = 0 var upperBound = snapshots[index].lastIndex while (lowerBound <= upperBound) { val guessIndex = lowerBound + (upperBound - lowerBound) / 2 val guessSnapId = snapshots[index][guessIndex].snapId when { guessSnapId < snapId -> lowerBound = guessIndex + 1 guessSnapId > snapId -> upperBound = guessIndex - 1 else -> return snapshots[index][guessIndex] } } return snapshots[index][upperBound] } }
1
Kotlin
0
1
14c033f2bf43d1c4148633a222c133d76986029c
2,129
hj-leetcode-kotlin
Apache License 2.0
app/src/main/kotlin/com/github/ilikeyourhat/kudoku/model/dividers/RegionDivider.kt
ILikeYourHat
139,063,649
false
{"Kotlin": 166134}
package com.github.ilikeyourhat.kudoku.model.dividers import com.github.ilikeyourhat.kudoku.model.Board import com.github.ilikeyourhat.kudoku.model.Field import com.github.ilikeyourhat.kudoku.model.Region import com.github.ilikeyourhat.kudoku.model.SudokuType class RegionDivider { private val dividers = mutableListOf<DivideCommand>() fun divideByRows() = apply { dividers.add { board -> (0 until board.sizeY()).map { indexY -> board.region(0, indexY, board.sizeX() - 1, indexY) } } } fun divideByColumns() = apply { dividers.add { board -> (0 until board.sizeX()).map { indexX -> board.region(indexX, 0, indexX, board.sizeY() - 1) } } } fun divideByBlocks(blockSize: Int) = divideByBlocks(blockSize, blockSize) fun divideByBlocks(blockSizeX: Int, blockSizeY: Int) = apply { dividers.add { board -> require(board.sizeX() % blockSizeX == 0) { "blockSizeX is $blockSizeX, sizeX is ${board.sizeX()}" } require(board.sizeY() % blockSizeY == 0) { "blockSizeY is $blockSizeY, sizeY is ${board.sizeY()}" } val regions = mutableListOf<Region>() for (x in 0 until board.sizeX() step blockSizeX) { for (y in 0 until board.sizeY() step blockSizeY) { regions += board.region(x, y, x + blockSizeX - 1, y + blockSizeY - 1) } } regions } } fun allFields() = apply { dividers.add { board -> listOf(Region(board.fields().filterNotNull())) } } fun primaryDiagonal() = apply { dividers.add { board -> require(board.sizeX() == board.sizeY()) val fields = mutableListOf<Field>() for (x in 0 until board.sizeX()) { fields += board.at(x, x)!! } listOf(Region(fields)) } } fun antiDiagonal() = apply { dividers.add { board -> require(board.sizeX() == board.sizeY()) val fields = mutableListOf<Field>() for (x in 0 until board.sizeX()) { fields += board.at(x, board.sizeY() - x - 1)!! } listOf(Region(fields)) } } fun applySubSudoku(x: Int, y: Int, type: SudokuType) = apply { dividers.add { board -> val subBoard = board.fragment(x, y, x + type.sizeX, y + type.sizeY) type.divider().divide(subBoard) } } fun divide(board: Board): List<Region> { return dividers.flatMap { it.divide(board) } .distinct() } } fun interface DivideCommand{ fun divide(board: Board): List<Region> }
1
Kotlin
0
0
b234b2de2edb753844c88ea3cd573444675fc1cf
2,767
Kudoku
Apache License 2.0
2021/src/main/kotlin/day7_fast.kt
madisp
434,510,913
false
{"Kotlin": 388138}
import utils.Parser import utils.Solution import kotlin.math.abs fun main() { Day7Fast.run() } object Day7All { @JvmStatic fun main(args: Array<String>) { mapOf("func" to Day7Func, "imp" to Day7Imp, "fast" to Day7Fast).forEach { (header, solution) -> solution.run(header = header, skipPart1 = true, skipTest = true, printParseTime = false) } } } object Day7Fast : Solution<List<Int>>() { override val name = "day7" override val parser = Parser.ints override fun part1(crabs: List<Int>): Int { return solve(crabs, this::identity) } override fun part2(crabs: List<Int>): Int { return solve(crabs, this::cost) } private fun solve(crabs: List<Int>, costFn: (Int) -> Int): Int { fun totalFuel(target: Int): Int { return crabs.sumOf { costFn(abs(it - target)) } } var lower = 0 var upper = crabs.maxOrNull()!! while (lower != upper) { val mid = (lower + upper) / 2 if (mid > lower && totalFuel(mid) < totalFuel(mid - 1)) { lower = mid } else { upper = mid } } return totalFuel(lower) } private fun identity(distance: Int) = distance private fun cost(distance: Int) = distance * (distance + 1) / 2 }
0
Kotlin
0
1
3f106415eeded3abd0fb60bed64fb77b4ab87d76
1,225
aoc_kotlin
MIT License
day04/src/Day04.kt
simonrules
491,302,880
false
{"Kotlin": 68645}
import java.io.File class Day04(path: String) { private var numbers: List<Int> private val boards = mutableListOf<MutableList<Int>>() private val won: MutableList<Boolean> init { val lines = File(path).readLines() numbers = lines[0].split(',').map { it.toInt() } val numBoards = (lines.size - 1) / 6 won = MutableList(numBoards) { false } var start = 2 // start at line 2 for (b in 0 until numBoards) { // read boards val board = mutableListOf<Int>() for (i in 0..4) { val row = lines[start + i].trim().split("\\s+".toRegex()).map { it.toInt() } board.addAll(row) } boards.add(board) start += 6 } } private fun isWinningBoard(b: Int): Boolean { val board = boards[b] // check rows for (r in 0..4) { var count = 0 for (c in 0..4) { if (board[r * 5 + c] == -1) { count++ } } if (count == 5) { return true } } // check cols for (c in 0..4) { var count = 0 for (r in 0..4) { if (board[r * 5 + c] == -1) { count++ } } if (count == 5) { return true } } return false } private fun findWinningBoard(): Int { for (b in boards.indices) { // skip any already winning boards if (won[b]) { continue } if (isWinningBoard(b)) { return b } } return -1 } private fun boardScore(b: Int): Int { var score = 0 val board = boards[b] for (i in board.indices) { if (board[i] != -1) { score += board[i] } } return score } fun part1(): Int { numbers.forEach { n -> boards.forEach { b -> // doesn't work :( //b.replaceAll { elem -> if (elem == n) -1 else n } for (i in b.indices) { if (b[i] == n) { b[i] = -1 } } val winning = findWinningBoard() if (winning != -1) { return n * boardScore(winning) } } } return 0 } fun part2(): Int { var winning = 0 numbers.forEach { n -> boards.forEachIndexed { i, b -> // doesn't work :( //b.replaceAll { elem -> if (elem == n) -1 else n } for (i in b.indices) { if (b[i] == n) { b[i] = -1 } } winning = findWinningBoard() if (winning != -1) { won[i] = true } if (won.all { it }) { return n * boardScore(winning) } } } return 0 } } fun main(args: Array<String>) { val aoc = Day04("day04/input.txt") //println(aoc.part1()) println(aoc.part2()) }
0
Kotlin
0
0
d9e4ae66e546f174bcf66b8bf3e7145bfab2f498
3,374
aoc2021
Apache License 2.0
kotlin/sort/NthElement.kt
polydisc
281,633,906
true
{"Java": 540473, "Kotlin": 515759, "C++": 265630, "CMake": 571}
package sort import java.util.stream.IntStream object NthElement { // See: http://www.cplusplus.com/reference/algorithm/nth_element // O(n) on average fun nth_element(a: IntArray, low: Int, high: Int, n: Int, rnd: Random) { var low = low var high = high while (true) { val k = partition(a, low, high, low + rnd.nextInt(high - low)) if (n < k) high = k else if (n > k) low = k + 1 else return } } fun partition(a: IntArray, fromInclusive: Int, toExclusive: Int, separatorIndex: Int): Int { var i = fromInclusive var j = toExclusive - 1 val separator = a[separatorIndex] swap(a, i++, separatorIndex) while (i <= j) { while (i <= j && a[i] < separator) ++i while (i <= j && a[j] > separator) --j if (i >= j) break swap(a, i++, j--) } swap(a, j, fromInclusive) return j } fun swap(a: IntArray, i: Int, j: Int) { val t = a[j] a[j] = a[i] a[i] = t } // O(n) worst case. See Cormen et al fun nth_element2(a: IntArray, low: Int, high: Int, n: Int) { var low = low var high = high if (high - low <= 1) return while (true) { val a5 = IntArray((high - low + 4) / 5) var i = low var cnt = 0 while (i < high) { val j: Int = Math.min(i + 5, high) for (iteration in 0..2) { var k = i while (k + 1 < j) { if (a[k] > a[k + 1]) { val t = a[k] a[k] = a[k + 1] a[k + 1] = t } k++ } } a5[cnt++] = a[i + j ushr 1] i += 5 } nth_element2(a5, 0, a5.size, a5.size / 2) val separatorIndex: Int = IntStream.range(low, high).filter { i -> a[i] == a5[a5.size / 2] }.findFirst().getAsInt() val k = partition(a, low, high, separatorIndex) if (n < k) high = k else if (n > k) low = k + 1 else return } } // Random test fun main(args: Array<String?>?) { val rnd = Random(1) val len = 1000000 nth_element(IntArray(len), 0, len, 0, rnd) nth_element2(IntArray(len), 0, len, 0) for (step in 0..99999) { val n: Int = rnd.nextInt(10) + 1 val a: IntArray = rnd.ints(n, 0, 10).toArray() val b: IntArray = a.clone() val k: Int = rnd.nextInt(n) nth_element(a, 0, n, k, rnd) nth_element2(b, 0, n, k) val sa: IntArray = a.clone() Arrays.sort(sa) val sb: IntArray = b.clone() Arrays.sort(sb) if (!Arrays.equals(sa, sb)) throw RuntimeException() if (a[k] != sa[k] || b[k] != sb[k]) throw RuntimeException() for (i in 0 until n) { if (i < k && a[i] > a[k] || i > k && a[i] < a[k]) throw RuntimeException() if (i < k && b[i] > b[k] || i > k && b[i] < b[k]) throw RuntimeException() } } } }
1
Java
0
0
4566f3145be72827d72cb93abca8bfd93f1c58df
3,302
codelibrary
The Unlicense
src/main/kotlin/day06/Day6.kt
limelier
725,979,709
false
{"Kotlin": 48112}
package day06 import common.InputReader import kotlin.math.ceil import kotlin.math.floor import kotlin.math.sqrt private fun waysToBeat(time: Long, recordDistance: Long): Long { // terms of a quadratic inequality: timePressed^2 - time * timePressed + recordDistance >= 0 val a = 1L val b = -time val c = recordDistance val delta = sqrt((b*b - 4*a*c).toDouble()) val firstRoot = (-b - delta) / (2*a) val secondRoot = (-b + delta) / (2*a) // roots are floats, find all the integers between them val solutions = ceil(firstRoot).toLong()..floor(secondRoot).toLong() return solutions.last - solutions.first + 1 } public fun main() { val lines = InputReader("day06/input.txt").lines() val whitespace = "\\s+".toRegex() val times = lines[0].split(whitespace).drop(1).map { it.toLong() } val records = lines[1].split(whitespace).drop(1).map { it.toLong() } val product = times.zip(records).map { (time, record) -> waysToBeat(time, record)}.reduce(Long::times) println("Part 1: $product") val realTime = lines[0].filter { it.isDigit() }.toLong() val realRecord = lines[1].filter { it.isDigit() }.toLong() val waysToBeat = waysToBeat(realTime, realRecord) println("Part 2: $waysToBeat") }
0
Kotlin
0
0
0edcde7c96440b0a59e23ec25677f44ae2cfd20c
1,266
advent-of-code-2023-kotlin
MIT License
src/main/kotlin/01.kts
reitzig
318,492,753
false
null
fun matchingPair(entries: List<Int>, target: Int): Pair<Int, Int>? { val sortedEntries = entries.sorted(); var left = 0 var right = entries.lastIndex while (left < right ) { val sum = sortedEntries[left] + sortedEntries[right] if (sum < target) { left += 1 } else if ( sum > target ) { right -= 1 } else { assert(sum == target) return Pair(sortedEntries[left], sortedEntries[right]) } } return null } fun matchingTriplet(entries: List<Int>, target: Int): Triple<Int, Int, Int>? { return entries.mapIndexed { index, entry -> // ^_^ val matchingPair = matchingPair( entries.filterIndexed { i, _ -> i != index }, target - entry) if ( matchingPair != null ) { return@mapIndexed Triple(entry, matchingPair.first, matchingPair.second) } else { return@mapIndexed null } }.filterNotNull().firstOrNull() } // --- val entries = args.map(String::toInt) val pair = matchingPair(entries, 2020) if ( pair != null ) { assert(pair.first + pair.second == 2020) println(pair.first * pair.second) } else { println("No matching pair!") } val triplet = matchingTriplet(entries, 2020) if ( triplet != null ) { assert(triplet.first + triplet.second + triplet.third == 2020) println(triplet.first * triplet.second * triplet.third) } else { println("No matching triplet!") } // --> kscript 01.kts $(cat 01_input)
0
Kotlin
0
0
f17184fe55dfe06ac8897c2ecfe329a1efbf6a09
1,536
advent-of-code-2020
The Unlicense
leetcode2/src/leetcode/n-queens.kt
hewking
68,515,222
false
null
package leetcode import java.lang.StringBuilder import java.util.* /** * 51. N皇后 * https://leetcode-cn.com/problems/n-queens/ * Created by test * Date 2019/12/22 20:30 * Description * n 皇后问题研究的是如何将 n 个皇后放置在 n×n 的棋盘上,并且使皇后彼此之间不能相互攻击。 上图为 8 皇后问题的一种解法。 给定一个整数 n,返回所有不同的 n 皇后问题的解决方案。 每一种解法包含一个明确的 n 皇后问题的棋子放置方案,该方案中 'Q' 和 '.' 分别代表了皇后和空位。 示例: 输入: 4 输出: [ [".Q..", // 解法 1 "...Q", "Q...", "..Q."], ["..Q.", // 解法 2 "Q...", "...Q", ".Q.."] ] 解释: 4 皇后问题存在两个不同的解法。 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/n-queens 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 */ object NQueue { class Solution { /** * 存放答案 */ val ans = mutableListOf<List<String>>() /** * 思路: * https://leetcode-cn.com/problems/n-queens/solution/javahui-su-fa-si-lu-jian-dan-qing-xi-qing-kan-dai-/ * 回溯法 * 大佬讲解 * https://leetcode-cn.com/problems/n-queens/solution/hui-su-suan-fa-xiang-jie-by-labuladong/ */ fun solveNQueens(n: Int): List<List<String>> { var res = "" for (i in 0 until n) { res += '.' } val queens = mutableListOf<String>() for (j in 0 until n) { queens.add((res)) } backTrack(0,queens) return ans } /** * 回溯法框架 * res = [] * backTrack(路径,选择列表){ * if 满足条件 * res.add(路径) * return * for(选择 in 选择列表) { * 做选择 * backTrack(路径,选择列表) * 撤销选择 * } */ fun backTrack(row: Int ,queens: MutableList<String>) { if (queens.size == row) { ans.add(queens) return } val n = queens[row].length for (col in 0 until n) { if (!isValid(queens,row,col)) { continue } val sb = StringBuilder(queens[row]) sb[col] = 'Q' queens[row] = sb.toString() backTrack(row + 1,queens) sb[col] = '.' queens[row] = sb.toString() } } fun isValid(queens: MutableList<String>,row: Int,col: Int):Boolean { val n = queens.size // 检查列上是否有冲突 for (i in 0 until n) { if (queens[i][col] == 'Q'){ return false } } // 检查右上方是否有皇后冲突 var j = col + 1 for (i in row - 1 .. 0) { if (j <= n) { if (queens[i][j] == 'Q') { return false } } j ++ } // 检查左上方是否有皇后冲突 var k = col - 1 for (i in row - 1 .. 0) { if (k>=0){ if (queens[i][k] == 'Q') { return false } } k-- } return true } } }
0
Kotlin
0
0
a00a7aeff74e6beb67483d9a8ece9c1deae0267d
3,649
leetcode
MIT License
src/main/kotlin/Problem34.kt
jimmymorales
496,703,114
false
{"Kotlin": 67323}
/** * Digit factorials * * 145 is a curious number, as 1! + 4! + 5! = 1 + 24 + 120 = 145. * * Find the sum of all numbers which are equal to the sum of the factorial of their digits. * * Note: As 1! = 1 and 2! = 2 are not sums they are not included. * * https://projecteuler.net/problem=34 */ fun main() { check(145.isDigitFactorial()) println(sumOfDigitFactorials()) } private fun sumOfDigitFactorials(from: Int = 10, to: Int = 99999): Int = (from..to).filter(Int::isDigitFactorial).sum() private fun Int.isDigitFactorial(): Boolean = digits().sumOf(Int::factorial) == this private fun Int.factorial(): Int = (1..this).fold(1) { x, y -> x * y }
0
Kotlin
0
0
e881cadf85377374e544af0a75cb073c6b496998
662
project-euler
MIT License
src/main/kotlin/Day13.kt
clechasseur
264,758,910
false
null
object Day13 { private val input = """ 0: 3 1: 2 2: 4 4: 4 6: 5 8: 6 10: 6 12: 6 14: 6 16: 8 18: 8 20: 8 22: 8 24: 10 26: 8 28: 8 30: 12 32: 14 34: 12 36: 10 38: 12 40: 12 42: 9 44: 12 46: 12 48: 12 50: 12 52: 14 54: 14 56: 14 58: 12 60: 14 62: 14 64: 12 66: 14 70: 14 72: 14 74: 14 76: 14 80: 18 88: 20 90: 14 98: 17 """.trimIndent() private val inputRegex = Regex("""^(\d+): (\d+)$""") fun part1() = tripSeverity(0).first fun part2() = generateSequence(0) { it + 1 }.map { tripSeverity(it) }.takeWhile { it.second }.count() private fun tripSeverity(delay: Int): Pair<Int, Boolean> { val layers = input.lineSequence().map { it.toLayer() }.map { it.depth to it }.toMap() val lastLayer = layers.keys.max()!! layers.values.forEach { it.picomove(delay) } var packet = 0 var severity = 0 var caught = false while (packet <= lastLayer) { val layer = layers[packet] if (layer != null && layer.position == 0) { severity += layer.severity caught = true } layers.forEach { (_, l) -> l.picomove(1) } packet++ } return severity to caught } private class Layer(val depth: Int, val range: Int) { private var offset = 1 var position = 0 private set val severity: Int get() = depth * range fun picomove(by: Int) { (0 until (by % (range * 2 - 2))).forEach { _ -> position += offset if (position == 0 || position == (range - 1)) { offset = -offset } } } override fun toString() = "{$depth} [$range] -> $position" } private fun String.toLayer(): Layer { val match = inputRegex.matchEntire(this) ?: error("Wrong layer format: $this") return Layer(match.groupValues[1].toInt(), match.groupValues[2].toInt()) } }
0
Kotlin
0
0
f3e8840700e4c71e59d34fb22850f152f4e6e739
2,334
adventofcode2017
MIT License
2015/src/main/kotlin/day2_func.kt
madisp
434,510,913
false
{"Kotlin": 388138}
import utils.Parser import utils.Solution import utils.mapItems fun main() { Day2Func.run() } data class Box(val l: Int, val w: Int, val h: Int) { val area: Int get() = 2*l*w + 2*w*h + 2*h*l val slack: Int get() = minOf(l*w, w*h, h*l) val smallestPerimeter: Int get() = minOf(2*(l+w), 2*(w+h), 2*(h+l)) val volume: Int get() = l * w * h } object Day2Func : Solution<List<Box>>() { override val name = "day2" override val parser = Parser.lines.mapItems { line -> val (l, w, h) = line.split('x', limit = 3).map { it.toInt() } Box(l, w, h) } override fun part1(): Int { return input.sumOf { it.area + it.slack} } override fun part2(): Number { return input.sumOf { it.smallestPerimeter + it.volume } } }
0
Kotlin
0
1
3f106415eeded3abd0fb60bed64fb77b4ab87d76
749
aoc_kotlin
MIT License
src/main/kotlin/g0201_0300/s0273_integer_to_english_words/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g0201_0300.s0273_integer_to_english_words // #Hard #String #Math #Recursion #Udemy_Strings // #2022_11_03_Time_273_ms_(82.93%)_Space_35.5_MB_(87.80%) import java.util.StringJoiner class Solution { private val ones = arrayOf( "One ", "Two ", "Three ", "Four ", "Five ", "Six ", "Seven ", "Eight ", "Nine " ) private val teens = arrayOf( "Ten ", "Eleven ", "Twelve ", "Thirteen ", "Fourteen ", "Fifteen ", "Sixteen ", "Seventeen ", "Eighteen ", "Nineteen " ) private val twenties = arrayOf( "Twenty ", "Thirty ", "Forty ", "Fifty ", "Sixty ", "Seventy ", "Eighty ", "Ninety " ) fun numberToWords(num: Int): String { if (num == 0) { return "Zero" } val joiner = StringJoiner("") processThreeDigits(joiner, num / 1000000000, "Billion ") processThreeDigits(joiner, num / 1000000, "Million ") processThreeDigits(joiner, num / 1000, "Thousand ") processThreeDigits(joiner, num, null) return joiner.toString().trim { it <= ' ' } } private fun processThreeDigits(joiner: StringJoiner, input: Int, name: String?) { val threeDigit = input % 1000 if (threeDigit > 0) { if (threeDigit / 100 > 0) { joiner.add(ones[threeDigit / 100 - 1]) val hundred = "Hundred " joiner.add(hundred) } if (threeDigit % 100 >= 20) { joiner.add(twenties[threeDigit % 100 / 10 - 2]) if (threeDigit % 10 > 0) { joiner.add(ones[threeDigit % 10 - 1]) } } else if (threeDigit % 100 >= 10 && threeDigit % 100 < 20) { joiner.add(teens[threeDigit % 10]) } else if (threeDigit % 100 > 0 && threeDigit % 100 < 10) { joiner.add(ones[threeDigit % 10 - 1]) } if (name != null) { joiner.add(name) } } } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
2,067
LeetCode-in-Kotlin
MIT License
src/day22/b/day22b.kt
pghj
577,868,985
false
{"Kotlin": 94937}
package day22.b import readInputLines import shouldBe import util.IntVector import vec import java.util.regex.Pattern import kotlin.math.sqrt fun main() { val input = read() val c = input.cube var s = c.faces[vec(0, 0, 1)]!! var p = vec(0, c.size - 1) var d = vec(1, 0) val valid = 0 until c.size for (i in input.move) { when (i) { is Int -> { for (k in 1..i) { val q = p + d if (!(q[0] in valid && q[1] in valid)) { val (s2, q2, d2) = s.changeEdge(p, d) val v = s2.map[q2] if (v == '#') break s = s2 p = q2 d = d2 } else { val v = s.map[q] if (v == '#') break p = q } s.map[p] = directionIcon(d) } } is Char -> { s.map[p] = rotationIcon(d, i) when (i) { 'L' -> d = d.rotate(0, 1) 'R' -> d = d.rotate(1, 0) } } } } s.map[p] = '╳' c.print() p = input.faceToUnfoldedTransform[s.normal]!!(p) shouldBe(15426, score(p, d)) } fun score(p: IntVector, d: IntVector): Long { return when (d) { vec(1,0) -> 0L vec(0,-1) -> 1L vec(-1,0) -> 2L vec(0,1) -> 3L else -> throw RuntimeException() } + 1000 * p[1] + 4 * p[0] } class Cube( val size: Int ) { val faces = HashMap<IntVector, Face>() inner class Face( val normal: IntVector, val xAxis: IntVector, ) { val yAxis: IntVector get() = normal cross xAxis val origin: IntVector get() = normal - xAxis - yAxis val map = HashMap<IntVector, Char>() fun edge(idx :Int) : IntVector { check(idx >= 0) val i = idx % 4 val a = if (i % 2 == 0) xAxis else normal cross xAxis return if (idx > 1) -a else a } fun changeEdge(pos: IntVector, dir: IntVector): Triple<Face, IntVector, IntVector> { check(pos[0] in 0 until size && pos[1] in 0 until size) check(dir dot dir == 1) val normal0 = normal val normal1 = xAxis * dir[0] + yAxis * dir[1] val face1 = faces[normal1]!! var q = pos + dir q = vec((q[0]+size) % size, (q[1]+size) % size) var d = dir // Partially unfold: // Rotate xAxis of face0, so it will lie in the plane of face1. // Now we can test whether the local coordinates // of these faces are rotated relative to each other. val xAxis0rot = xAxis.rotate(normal0, normal1) when (xAxis0rot dot face1.xAxis) { 1 -> { // local coordinates of faces are already aligned } -1 -> { // rotate 180 q = q.rotate2(0,1) + vec(size-1,size-1) d = d.rotate2(0,1) } 0 -> { // need to rotate 90 degrees, but in which direction... when ((xAxis0rot cross face1.xAxis) dot normal1) { 1 -> { // rotate 90 cw q = q.rotate(1, 0) + vec(0, size-1) d = d.rotate(1, 0) } -1 -> { // rotate 90 ccw q = q.rotate(0, 1) + vec(size-1, 0) d = d.rotate(0, 1) } else -> throw RuntimeException() } } else -> throw RuntimeException() } return Triple(face1, q, d) } fun print() { println("Face: normal: $normal / origin: $origin / xAxis: $xAxis / yAxis: $yAxis") for (y in size-1 downTo 0) { for (x in 0 until size) { val c = map[vec(x,y)]!! print(c) } print("\n") } } } fun addFace(normal: IntVector, xAxis: IntVector): Face { val s = Face(normal, xAxis) faces[normal] = s return s } fun print() { for (s in faces.values) { s.print() print("\n") } } } class Input( val cube: Cube, val move: ArrayList<Any>, val faceToUnfoldedTransform: HashMap<IntVector, (IntVector)->IntVector>, ) fun read(): Input { val size : Int val lines = readInputLines(22) val instr = lines.last() val map = HashMap<IntVector, Char>() run { var p = vec(0, 0) val m = lines.subList(0, lines.size-1).filter { it.isNotBlank() } size = sqrt(m.sumOf { it.trim().length } / 6.0).toInt() m.forEach { row -> var q = p for (c in row) { if (c == '.' || c == '#') map[q] = c q += vec(1,0) } p += vec(0,1) } } val moves = ArrayList<Any>() run { val t = instr.split(Pattern.compile("[0-9]+")).filter { it.isNotBlank() }.map { it[0] } val n = instr.split(Pattern.compile("[RL]")).map { it.toInt() } for (i in t.indices) { moves.add(n[i]) moves.add(t[i]) } moves.add(n.last()) } // Note: for all coordinates during calculation we switch to positive/standard/right-handed orientation (y-axis is UP) // Fold map into a cube val cube = Cube(size) // We need these later to transform coordinates on the face of the cube back to the coordinates // in the unfolded input data. val faceToUnfoldedTransform = HashMap<IntVector, (IntVector)->IntVector >() fun addSide(pUnfolded: IntVector, sideNormal: IntVector, xAxis: IntVector): Cube.Face { faceToUnfoldedTransform[sideNormal] = { p -> pUnfolded + vec(0, size) + vec(p[0] + 1, -p[1]) } val side = cube.addFace(sideNormal, xAxis) for (x in 0 until size) { for (y in 0 until size) side.map[vec(x,y)] = map[vec(pUnfolded[0] + x, pUnfolded[1] + size - y - 1)]!! } return side } // Search on the four sides of a face we already have. fun findAllSides(pUnfolded: IntVector, face0: Cube.Face) { if (cube.faces.size == 6) return var d = vec(1, 0) for(edgeIdx in 0..3) { val q = pUnfolded + d*size val normal1 = face0.edge(edgeIdx) if (map.containsKey(q) && !cube.faces.containsKey(normal1)) { val xAxis1 = face0.xAxis.rotate(face0.normal, normal1) val s = addSide(q, normal1, xAxis1) findAllSides(q, s) } if (cube.faces.size == 6) break d = d.rotate(1,0) } } val p = vec(map.keys.filter { it[1] == 0 }.minOf { it[0] }, 0) val s = addSide(p, vec(0,0,1), vec(1,0,0)) findAllSides(p, s) return Input(cube, moves, faceToUnfoldedTransform) } fun directionIcon(d: IntVector) : Char = if (d[0] == 0) '┃' else '━' fun rotationIcon(d: IntVector, t: Char) : Char { return when (if (t == 'R') d.rotate(0, 1) else d) { vec(1, 0) -> '┛' vec(-1, 0) -> '┏' vec(0, 1) -> '┓' vec(0, -1) -> '┗' else -> '?' } }
0
Kotlin
0
0
4b6911ee7dfc7c731610a0514d664143525b0954
7,705
advent-of-code-2022
Apache License 2.0
src/Day08.kt
karloti
573,006,513
false
{"Kotlin": 25606}
fun part1(a: Array<IntArray>): Int { val n = a.size val m = a[0].size val b = Array(n) { BooleanArray(m) } var hIndex: Int var h1: Int var h2: Int for (i in 0 until n) { hIndex = 0 h1 = -1 for (j in 0 until m) { if (a[i][j] > h1) { h1 = a[i][j] hIndex = j b[i][j] = true } else if (h1 == 9) break } h2 = -1 for (j in m - 1 downTo hIndex) { if (a[i][j] > h2) { if (h1 == h2) break h2 = a[i][j] b[i][j] = true } } } for (j in 0 until m) { hIndex = 0 h1 = -1 for (i in 0 until n) { if (a[i][j] > h1) { h1 = a[i][j] hIndex = i b[i][j] = true } else if (h1 == 9) break } h2 = -1 for (i in n - 1 downTo hIndex) { if (a[i][j] > h2) { if (h1 == h2) break h2 = a[i][j] b[i][j] = true } } } var count = 2 * m + 2 * n - 4 for (i in 1 until n - 1) for (j in 1 until m - 1) if (b[i][j]) count++ return count } fun part2(a: Array<IntArray>): Int { val n = a.size val m = a[0].size var result = 0 for (i in 0 until n) { for (j in 0 until m) { var d1 = j for (k in j - 1 downTo 0) { if (a[i][k] >= a[i][j]) { d1 = j - k break } } var d2 = m - j - 1 for (k in j + 1 until m) { if (a[i][k] >= a[i][j]) { d2 = k - j break } } var d3 = i for (k in i - 1 downTo 0) { if (a[k][j] >= a[i][j]) { d3 = i - k break } } var d4 = n - i - 1 for (k in i + 1 until n) { if (a[k][j] >= a[i][j]) { d4 = k - i break } } val f = d1 * d2 * d3 * d4 if (f > result) result = f } } return result } fun main() { val aTest = readInput("Day08_test").map { it.map(Char::digitToInt).toIntArray() }.toTypedArray() check(part1(aTest).also(::println) == 21) check(part2(aTest).also(::println) == 8) val a = readInput("Day08").map { it.map(Char::digitToInt).toIntArray() }.toTypedArray() check(part1(a).also(::println) == 1719) check(part2(a).also(::println) == 590824) }
0
Kotlin
1
2
39ac1df5542d9cb07a2f2d3448066e6e8896fdc1
2,717
advent-of-code-2022-kotlin
Apache License 2.0
src/Day06.kt
max-zhilin
573,066,300
false
{"Kotlin": 114003}
fun main() { fun part1(input: List<String>): Int { var buf = "" input[0].forEachIndexed() { pos, c -> buf += c val set = mutableSetOf<Char>() buf.forEach { b -> set.add(b) if (set.size == 4) { return pos + 1 } } if (buf.length == 4) buf = buf.substring(1) } // println(tail) // var sum = "" // stacks.forEach { // val c = it.peek() // if (c.isLetter()) sum += c // } return 0 } fun part2(input: List<String>): Int { var buf = "" input[0].forEachIndexed() { pos, c -> buf += c val set = mutableSetOf<Char>() buf.forEach { b -> set.add(b) if (set.size == 14) { return pos + 1 } } if (buf.length == 14) buf = buf.substring(1) } // println(tail) // var sum = "" // stacks.forEach { // val c = it.peek() // if (c.isLetter()) sum += c // } return 0 } // test if implementation meets criteria from the description, like: val testInput = readInput("Day06_test") // println(part1(testInput)) check(part1(testInput) == 7) // println(part2(testInput)) check(part2(testInput) == 19) val input = readInput("Day06") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
d9dd7a33b404dc0d43576dfddbc9d066036f7326
1,531
AoC-2022
Apache License 2.0
src/main/kotlin/algorithms/NumUtils.kt
xmmmmmovo
280,634,710
false
null
/* * Copyright (c) 2020. xmmmmmovo */ package algorithms import ds.LinkedList import edu.princeton.cs.algs4.StdRandom import ext.compareTo /** * 蛮力法求三数之和 * @author xmmmmmovo * @date 2020/7/28 16:09 * @param list 数字列表 * @param num 所求的数字 * @return 满足条件的个数 * @since version-1.0 */ fun threeSumForce(list: List<Int>, num: Int): List<List<Int>> { val res = LinkedList<List<Int>>() val sl = list.sorted().run { if (containsDuplicatesInSorted(this)) distinct() else this } for (a in sl.indices) for (b in a + 1 until sl.size) for (c in b + 1 until sl.size) if (sl[a] + sl[b] + sl[c] == num) { res.add(listOf(sl[a], sl[b], sl[c])) } return res } /** * 二分法[binarySearch]求三数之和 * @author xmmmmmovo * @date 2020/7/28 16:09 * @param list 数字列表 * @return 满足和为0的所有组合的列表 * @throws IllegalArgumentException 数组元素小于3个时抛出异常 * @since version-1.0 */ fun threeSumBinaryFast(list: List<Int>, num: Int): List<List<Int>> { val res = LinkedList<List<Int>>() val sl = list.sorted().run { if (containsDuplicatesInSorted(this)) distinct() else this } if (list.size < 3) throw IllegalArgumentException("数组非重复元素小于3个!") for (i in sl.indices) { for (j in i + 1 until sl.size) { val k = binarySearch(sl, num - (sl[i] + sl[j]), j + 1) if (k != -1) { res.add(listOf(sl[i], sl[j], sl[k])) } } } return res } /** * 矩阵局部最小元素 * @author xmmmmmovo * @date 2020/7/30 19:36 * @param matrix 矩阵 * @return 最小元素数字 * @throws IllegalArgumentException 矩阵为空的时候抛出异常 * @since version-1.0 */ fun <T : Comparable<T>> matrixPartialMinElem(matrix: List<List<T>>): Pair<Int, Int> { if (matrix.isEmpty()) throw IllegalArgumentException("矩阵不能为空!") var lor = 0 var hir = matrix.size - 1 while (lor <= hir) { val mr = lor + (hir - lor) / 2 val kc = partialMinElem(matrix[mr]) when { kc == -1 -> { lor++ } mr == 0 -> if (matrix[mr + 1][kc] > matrix[mr][kc]) return Pair(mr, kc) else lor = mr + 1 mr == matrix.size - 1 -> if (matrix[mr][kc] < matrix[mr - 1][kc]) return Pair(mr, kc) else hir = mr - 1 matrix[mr - 1][kc] > matrix[mr][kc] && matrix[mr][kc] < matrix[mr + 1][kc] -> return Pair(mr, kc) matrix[mr - 1][kc] < matrix[mr][kc] && matrix[mr][kc] < matrix[mr + 1][kc] -> hir = mr - 1 matrix[mr - 1][kc] < matrix[mr][kc] && matrix[mr][kc] > matrix[mr + 1][kc] -> if (matrix[mr - 1][kc] >= matrix[mr + 1][kc]) lor = mr + 1 else hir = mr - 1 else -> lor = mr + 1 } } return Pair(-1, -1) } /** * 生日问题 * 验证第一个重复随机数之前生成的整数数量为(ΠN/2)^(1/2) * 具体测试查看Test文件 * @author xmmmmmovo * @date 2020/7/30 12:24 * @param N 生成的数量 * @return 返回第一个重复的随机数时生成的数字数量 * @since version-1.0 */ fun firstRandomDuplicate(N: Int): Int { val m = mutableSetOf<Int>() var i = 0 while (true) { val rn = StdRandom.uniform(N) if (m.contains(rn)) return i m.add(rn) i++ } }
0
Kotlin
0
0
94da0519cf2b8d8a9b42b4aea09caf50d9732599
3,724
Algorithms4thEditionKotlinSolutions
Apache License 2.0
src/Day06.kt
iownthegame
573,926,504
false
{"Kotlin": 68002}
fun main() { fun findFirstMessage(n: Int, input: String): Int { val length = input.length for (i in 0 until length) { val string = input.substring(i, i + n) if (string.toSet().size == n) { return i + n } } return 0 } fun part1(input: String): Int { return findFirstMessage(4, input) } fun part2(input: String): Int { return findFirstMessage(14, input) } // test if implementation meets criteria from the description, like: check(part1("mjqjpqmgbljsphdztnvjfqwrcgsmlb") == 7) check(part1("bvwbjplbgvbhsrlpgdmjqwftvncz") == 5) check(part1("nppdvjthqldpwncqszvftbrmjlhg") == 6) check(part1("nznrnfrfntjfmvfwmzdfjlvtqnbhcprsg") == 10) check(part1("zcfzfwzzqfrljwzlrfnpqdbhtmscgvjw") == 11) check(part2("mjqjpqmgbljsphdztnvjfqwrcgsmlb") == 19) check(part2("bvwbjplbgvbhsrlpgdmjqwftvncz") == 23) check(part2("nppdvjthqldpwncqszvftbrmjlhg") == 23) check(part2("nznrnfrfntjfmvfwmzdfjlvtqnbhcprsg") == 29) check(part2("zcfzfwzzqfrljwzlrfnpqdbhtmscgvjw") == 26) val input = readTestInput("Day06")[0] println("part 1 result: ${part1(input)}") println("part 2 result: ${part2(input)}") }
0
Kotlin
0
0
4e3d0d698669b598c639ca504d43cf8a62e30b5c
1,261
advent-of-code-2022
Apache License 2.0
src/main/kotlin/icu/trub/aoc/day12/SpringRegistry.kt
dtruebin
728,432,747
false
{"Kotlin": 76202}
package icu.trub.aoc.day12 import kotlin.time.measureTimedValue internal class SpringRegistry(val records: List<Record>) { fun countPossibleArrangements(debug: Boolean = false) = records.map { val (arrangements, duration) = measureTimedValue { it.countPossibleArrangements() } if (debug && duration.inWholeMilliseconds > 500) println("$duration to process $it") arrangements }.sumOf { it } fun unfold(factor: Int = 5): SpringRegistry = SpringRegistry(records.map { it.unfold(factor) }) companion object { fun parse(input: Sequence<String>): SpringRegistry = input .map { Record.parse(it) } .toList() .let { records -> SpringRegistry(records) } } internal data class Record(val conditions: String, val damagedGroupSizes: List<Int>) { fun countPossibleArrangements(): Long = countPossibleArrangements(conditions, damagedGroupSizes) private fun countPossibleArrangements(conditions: String, groups: List<Int>): Long { val args = conditions to groups with(getCachedArrangementCount(args)) { if (this != null) return this } if (conditions.isEmpty()) { return when (groups.isEmpty()) { true -> cache(args, 1) else -> cache(args, 0) } } if (conditions.startsWith(WORKING_SPRING)) { val remainingConditions = conditions.drop(1) return cache(remainingConditions to groups, countPossibleArrangements(remainingConditions, groups)) } else if (conditions.startsWith(UNKNOWN_SPRING)) { val uncoveredWorking = conditions.replaceFirstChar { WORKING_SPRING } val uncoveredDamaged = conditions.replaceFirstChar { DAMAGED_SPRING } return cache(uncoveredWorking to groups, countPossibleArrangements(uncoveredWorking, groups)) + cache(uncoveredDamaged to groups, countPossibleArrangements(uncoveredDamaged, groups)) } else if (conditions.startsWith(DAMAGED_SPRING)) { val firstGroup = when (groups.isNotEmpty()) { true -> groups.first() else -> return cache(args, 0) } val canFitFirstGroup = conditions.take(firstGroup).all { it != WORKING_SPRING } && !conditions.drop(firstGroup).startsWith(DAMAGED_SPRING) val canFitAllRemainingGroups = groups.sum() + groups.size - 1 <= conditions.length if (!canFitFirstGroup || !canFitAllRemainingGroups) { return cache(args, 0) } val remainingConditions: String = conditions.drop(firstGroup).replaceFirstChar { WORKING_SPRING } val remainingGroups: List<Int> = groups.drop(1) return cache( remainingConditions to remainingGroups, countPossibleArrangements(remainingConditions, remainingGroups) ) } throw IllegalStateException() } fun unfold(factor: Int): Record = Record( List(factor) { conditions }.joinToString("?"), buildList { repeat(factor) { addAll(damagedGroupSizes) } } ) companion object { const val WORKING_SPRING = '.' const val DAMAGED_SPRING = '#' const val UNKNOWN_SPRING = '?' private val arrangementCountCache = mutableMapOf<Pair<String, List<Int>>, Long>() fun cache(key: Pair<String, List<Int>>, arrangementCount: Long): Long = arrangementCountCache.computeIfAbsent(key) { arrangementCount } fun getCachedArrangementCount(key: Pair<String, List<Int>>): Long? = arrangementCountCache[key] fun parse(line: String): Record = line.split(" ") .let { (conditions, groupStr) -> conditions to groupStr.split(",").map { it.toInt() } } .let { (conditions, groups) -> Record(conditions, groups) } } } }
0
Kotlin
0
0
1753629bb13573145a9781f984a97e9bafc34b6d
4,121
advent-of-code
MIT License
src/Day25.kt
Kietyo
573,293,671
false
{"Kotlin": 147083}
import kotlin.math.absoluteValue fun Long.pow(num: Int): Long { var curr = 1L repeat(num) { curr *= this } return curr } fun calculateMaxSnafu(n: Int): Long { var sum = 0L for (i in 0 until n) { val currPosition = i val fiveOrder = 5L.pow(currPosition) sum += fiveOrder * 2 } return sum } fun calculateMinSnafu(n: Int): Long { var sum = 0L for (i in 0 until n) { val currPosition = i val fiveOrder = 5L.pow(currPosition) if (i == n - 1) { sum += fiveOrder } else { sum += fiveOrder * (-2) } } return sum } fun String.convertFromSnafu(): Long { val chars = this.toCharArray() println("Processing: " + this) println("chars.indices: " + chars.indices) var sum = 0L for (i in 0 until chars.size) { val currPosition = chars.size - i - 1 val fiveOrder = 5L.pow(currPosition) val currChar = chars[i] val num = when { currChar == '-' -> -1 currChar == '=' -> -2 currChar == '0' -> 0 currChar == '1' -> 1 currChar == '2' -> 2 else -> TODO("Unsupported char: $currChar") }.toLong() println("currChar:$currChar, currPosition: $currPosition, fiveOrder: $fiveOrder, calc: ${fiveOrder * num}") sum += fiveOrder * num } return sum } data class SnafuConfig( val n: Int, val minSnafu: Long, val maxSnafu: Long, ) { val fiverOrder get() = 5L.pow(n) val fiverOrderTimesTwo get() = 5L.pow(n) * 2 } fun getSnafuConfigForNum(num: Long): SnafuConfig { var n = 0 while (true) { val min = calculateMinSnafu(n) val max = calculateMaxSnafu(n) if (num >= min && num <= max) { val fiveOrder = 5L.pow(n) return SnafuConfig(n, min, max) } n++ } } fun Long.convertToSnafu2(): String { val snafuConfig = getSnafuConfigForNum(this) var currentSnafuLength = snafuConfig.n - 1 if (currentSnafuLength == -1) return "0" println("snafuLength: $currentSnafuLength") val sb = StringBuilder() var currNum = this while (currentSnafuLength >= 0) { val minSnafuAbove = calculateMinSnafu(currentSnafuLength + 1) val maxSnafuAbove = calculateMaxSnafu(currentSnafuLength + 1) val abs = currNum.absoluteValue val minSnafu = calculateMinSnafu(currentSnafuLength) val maxSnafu = calculateMaxSnafu(currentSnafuLength) val withinRange = abs == 0L || abs in minSnafuAbove..maxSnafuAbove || abs in minSnafu..maxSnafu // if (!withinRange) { // // } // require(withinRange) { // "Error when processing: $this" // } val fiveOrder = 5L.pow(currentSnafuLength) val fiveOrderTimes2 = fiveOrder * 2 val chosenNumber = when { !withinRange -> 0 currNum < 0 -> { when { abs >= fiveOrderTimes2 -> -2 (abs + maxSnafu) >= fiveOrderTimes2 -> -2 (abs + maxSnafu) >= fiveOrder -> -1 abs >= fiveOrder -> -1 else -> 0 } } currNum > 0 -> when { currNum >= fiveOrderTimes2 -> 2 (currNum + maxSnafu) >= fiveOrderTimes2 -> 2 currNum >= fiveOrder -> 1 (currNum + maxSnafu) >= fiveOrder -> 1 else -> 0 } else -> 0 } when (chosenNumber) { 2 -> sb.append('2') 1 -> sb.append('1') 0 -> sb.append('0') -1 -> sb.append('-') -2 -> sb.append('=') else -> TODO() } val currNumBefore = currNum currNum -= fiveOrder * chosenNumber println("currentSnafuLength: $currentSnafuLength, chosenNumber: $chosenNumber, currNumBefore: $currNumBefore, currNumAfter: $currNum") currentSnafuLength-- } return sb.toString() } fun main() { fun part1(input: List<String>): Unit { val line = input.first() println(line) println(line.convertFromSnafu()) val snafus = input.map { it.convertFromSnafu() } println(snafus.joinToString("\n")) println("sum:") println(snafus.sum()) println(snafus.sum().convertToSnafu2()) // 2=0=== is wrong println() } fun part2(input: List<String>): Unit { } val dayString = "day25" // test if implementation meets criteria from the description, like: val testInput = readInput("${dayString}_test") // part1(testInput) // part2(testInput) val input = readInput("${dayString}_input") // 33658310202841 - didn't work // part1(input) // part2(input) repeat(22) { println("n: $it") println("min snafu: " + calculateMinSnafu(it)) println("max snafu: " + calculateMaxSnafu(it)) } // for (it in 122..256) { println("it: $it") println(it.toLong().convertToSnafu2()) println() } // println("2=-01".convertFromSnafu()) println(33658310202841.convertToSnafu2()) }
0
Kotlin
0
0
dd5deef8fa48011aeb3834efec9a0a1826328f2e
5,279
advent-of-code-2022-kietyo
Apache License 2.0
src/commonMain/kotlin/org/parserkt/pat/complex/TriePattern.kt
ParserKt
242,278,819
false
null
package org.parserkt.pat.complex import org.parserkt.* import org.parserkt.util.* import org.parserkt.pat.* // File: pat/complex/TriePattern class MapPattern<K, V>(val map: Map<K, V>, private val noKey: Feed<K>.(K) -> V? = {notParsed}): PreetyPattern<K, V>() { override fun read(s: Feed<K>): V? { val key = s.peek; val value = map[key] return if (value == null) s.noKey(key) else if (s.isStickyEnd()) notParsed else value } override fun show(s: Output<K>, value: V?) { if (value != null) reverseMap[value]?.let(s) } private val reverseMap = map.reversedMap() override fun toPreetyDoc() = listOf("map", map).preety().colonParens() } /* val dict = KeywordPattern<String>().apply { mergeStrings("hello" to "你好", "world" to "世界") } val noun = Repeat(asList(), dict) */ typealias KeywordPattern<V> = TriePattern<Char, V> typealias PairedKeywordPattern<V> = PairedTriePattern<Char, V> open class TriePattern<K, V>: Trie<K, V>(), Pattern<K, V> { override fun read(s: Feed<K>): V? { var point: Trie<K, V> = this while (true) try { point = point.routes[s.peek]?.also { onItem(s.consume()) } ?: break } catch (_: Feed.End) { onEOS(); break } return point.value?.also(::onSuccess) ?: onFail() } override fun show(s: Output<K>, value: V?) { if (value == null) return reverseMap[value]?.let { it.forEach(s) } } private val reverseMap by lazy { toMap().reversedMap() } override fun toPreetyDoc() = super.toString().preety() protected open fun onItem(value: K) {} protected open fun onSuccess(value: V) {} protected open fun onFail(): V? = notParsed protected open fun onEOS() {} override fun toString() = toPreetyDoc().toString() } open class PairedTriePattern<K, V>: TriePattern<K, V>() { val map: Map<Iterable<K>, V> get() = pairedMap val reverseMap: Map<V, Iterable<K>> get() = pairedReverseMap private val pairedMap: MutableMap<Iterable<K>, V> = mutableMapOf() private val pairedReverseMap: MutableMap<V, Iterable<K>> = mutableMapOf() override fun set(key: Iterable<K>, value: V) { pairedMap[key] = value; pairedReverseMap[value] = key return super.set(key, value) } override fun show(s: Output<K>, value: V?) { if (value == null) return super.show(s, value) reverseMap[value]?.let { it.forEach(s) } } }
1
Kotlin
0
11
37599098dc9aafef7b509536e6d17ceca370d6cf
2,318
ParserKt
MIT License
advent-of-code-2021/src/main/kotlin/eu/janvdb/aoc2021/day24/Transform.kt
janvdbergh
318,992,922
false
{"Java": 1000798, "Kotlin": 284065, "Shell": 452, "C": 335}
package eu.janvdb.aoc2021.day24 import eu.janvdb.aocutil.kotlin.readLines const val FILENAME = "input24.txt" val LINE_PATTERN = Regex("([a-z]{3}) ([a-z]) ?(.+)?") fun main() { var input = 0 val variables = mutableMapOf( Pair("x", 0), Pair("y", 0), Pair("z", 0), Pair("w", 0) ) fun transform(line: String): String { val match = LINE_PATTERN.matchEntire(line)!! val (_, instruction, arg1, arg2) = match.groupValues val var1 = arg1 + (variables[arg1]!! + 1) val var2 = arg1 + variables[arg1]!! val var3 = if (variables.containsKey(arg2)) arg2 + variables.get(arg2) else arg2 variables[arg1] = variables[arg1]!! + 1 return when (instruction) { "inp" -> "val $var1 = i${input++}" "add" -> "val $var1 = $var2 + $var3" "mul" -> "val $var1 = $var2 * $var3" "div" -> "val $var1 = $var2 / $var3" "mod" -> "val $var1 = $var2 % $var3" "eql" -> "val $var1 = if ($var2 == $var3) 1 else 0" else -> throw IllegalArgumentException() } } println("val x0 = 0") println("val y0 = 0") println("val z0 = 0") println("val w0 = 0") readLines(2021, FILENAME) .asSequence() .map { line -> transform(line) } .forEach(::println) println("return z${variables["z"]}") }
0
Java
0
0
78ce266dbc41d1821342edca484768167f261752
1,213
advent-of-code
Apache License 2.0
solutions/aockt/y2023/Y2023D16.kt
Jadarma
624,153,848
false
{"Kotlin": 435090}
package aockt.y2023 import aockt.util.parse import aockt.util.spacial.Area import aockt.util.spacial.Direction import aockt.util.spacial.Direction.* import aockt.util.spacial.Point import aockt.util.spacial.move import aockt.y2023.Y2023D16.Element.* import io.github.jadarma.aockt.core.Solution object Y2023D16 : Solution { /** The type of element a beam of light can encounter. */ private enum class Element { LeftMirror, RightMirror, HorizontalSplitter, VerticalSplitter } /** * A mirror maze that can focus lasers. * @param content The elements in the maze and their location. */ private class MirrorMaze(content: Iterable<Pair<Point, Element>>) { private val grid: MutableMap<Point, Element> = content .associate { it.first to it.second } .toMutableMap() /** The area of the maze. */ val area: Area = Area(grid.keys) /** Get the element at the given [point], if it exists. */ operator fun get(point: Point): Element? = grid[point] /** * Propagate a laser beam starting from a [source] location and [heading] into a direction. * * @param source Where this beam starts from. * @param heading The direction of the beam. * @return All points in the maze that the beam and all its splits energize at least once. * The points are not given in order, as the beam can split multiple times. */ fun beam(source: Point, heading: Direction): Set<Point> = buildSet { // The laser might be split into a loop, this acts like a circuit breaker. // Direction also is a factor, since it's valid for beams to cross each other. val seen = mutableSetOf<Pair<Point, Direction>>() fun beamBranch(source: Point, heading: Direction) { var point = source var direction = heading while (point in area) { if (point to direction in seen) return seen.add(point to direction) add(point) direction = when (get(point)) { null -> direction LeftMirror -> when (direction) { Left -> Up Right -> Down Down -> Right Up -> Left } RightMirror -> when (direction) { Left -> Down Right -> Up Up -> Right Down -> Left } HorizontalSplitter -> when (direction) { Left, Right -> direction Up, Down -> Left.also { beamBranch(point.move(Right), Right) } } VerticalSplitter -> when (direction) { Up, Down -> direction Left, Right -> Up.also { beamBranch(point.move(Down), Down) } } } point = point.move(direction) } } beamBranch(source, heading) } } /** Parse the [input] and return the [MirrorMaze]. */ private fun parseInput(input: String): MirrorMaze = parse { fun parseElement(char: Char): Element? = when (char) { '\\' -> LeftMirror '/' -> RightMirror '|' -> VerticalSplitter '-' -> HorizontalSplitter '.' -> null else -> error("Unknown char: $char.") } input .lines() .asReversed() .flatMapIndexed { y, line -> line.mapIndexed { x, c -> parseElement(c)?.let { Point(x, y) to it } } } .filterNotNull() .let(::MirrorMaze) } override fun partOne(input: String): Any { val maze = parseInput(input) return with(maze.area) { Point(xRange.first, yRange.last) } .let { source -> maze.beam(source, Right) } .count() } override fun partTwo(input: String): Any { val maze = parseInput(input) return buildList { with(maze.area) { for (y in yRange) add(maze.beam(Point(xRange.first, y), Right)) for (x in xRange) add(maze.beam(Point(x, yRange.last), Down)) for (y in yRange) add(maze.beam(Point(xRange.last, y), Left)) for (x in xRange) add(maze.beam(Point(x, yRange.first), Up)) } }.maxOf { beam -> beam.count() } } }
0
Kotlin
0
3
19773317d665dcb29c84e44fa1b35a6f6122a5fa
4,740
advent-of-code-kotlin-solutions
The Unlicense
src/main/kotlin/days/aoc2022/Day23.kt
bjdupuis
435,570,912
false
{"Kotlin": 537037}
package days.aoc2022 import days.Day import util.Point2d class Day23 : Day(2022, 23) { override fun partOne(): Any { return calculateEmptyLandOnMinimalRectangleAfterRounds(inputList, 10) } override fun partTwo(): Any { return calculateRoundWithNoMovingElves(inputList) } fun calculateRoundWithNoMovingElves(input: List<String>): Int { val map = mutableMapOf<Point2d, Char>() for (y in input.indices) { val line = input[y] for (x in line.indices) { map[Point2d(x, y)] = line[x] } } val proposals = mutableMapOf<Point2d, Point2d>() var start = 0 var elvesMoving = true while (elvesMoving) { map.filter { it.value == '#' }.keys.forEach { elf -> if (neighbors(elf).any { '#' == map[it] }) { var proposal: Point2d? = null var i = 1 // reset considerations val considerations = considerations(elf, start) while (i++ <= 4 && proposal == null) { val direction = considerations.next() if (direction.none { '#' == map[it] }) { proposal = direction.first() } } if (proposal != null) { proposals[elf] = proposal } } } val validProposals = proposals.filter { proposal -> proposals.count { it.value == proposal.value } == 1 } if (validProposals.isEmpty()) { elvesMoving = false } else { validProposals.forEach { proposal -> map[proposal.value] = '#' map[proposal.key] = '.' } proposals.clear() } start++ } return start } fun calculateEmptyLandOnMinimalRectangleAfterRounds(input: List<String>, rounds: Int): Int { val map = mutableMapOf<Point2d, Char>() for (y in input.indices) { val line = input[y] for (x in line.indices) { map[Point2d(x, y)] = line[x] } } val proposals = mutableMapOf<Point2d, Point2d>() var start = 0 repeat(rounds) { map.filter { it.value == '#' }.keys.forEach { elf -> if (neighbors(elf).any { '#' == map[it] }) { var proposal: Point2d? = null var i = 1 // reset considerations val considerations = considerations(elf, start) while (i++ <= 4 && proposal == null) { val direction = considerations.next() if (direction.none { '#' == map[it] }) { proposal = direction.first() } } if (proposal != null) { proposals[elf] = proposal } } } proposals.filter { proposal -> proposals.count { it.value == proposal.value } == 1 }.forEach { proposal -> map[proposal.value] = '#' map[proposal.key] = '.' } proposals.clear() start++ val elves = map.filter { it.value == '#' } val min = Point2d(elves.keys.minOf { it.x }, elves.keys.minOf { it.y }) val max = Point2d(elves.keys.maxOf { it.x }, elves.keys.maxOf { it.y }) for (y in min.y..max.y) { for (x in min.x..max.x) { print(map[Point2d(x, y)] ?: ".") } println() } println() } val elves = map.filter { it.value == '#' } val min = Point2d(elves.keys.minOf { it.x }, elves.keys.minOf { it.y }) val max = Point2d(elves.keys.maxOf { it.x }, elves.keys.maxOf { it.y }) var count = 0 for (x in min.x..max.x) { for (y in min.y..max.y) { if ('.' == (map[Point2d(x, y)] ?: '.')) { count++ } } } return count } private fun considerNorth(fromLocation: Point2d): List<Point2d> { return listOf( fromLocation.copy(y = fromLocation.y - 1), fromLocation.copy(x = fromLocation.x - 1, y = fromLocation.y - 1), fromLocation.copy(x = fromLocation.x + 1, y = fromLocation.y - 1)) } private fun considerSouth(fromLocation: Point2d): List<Point2d> { return listOf( fromLocation.copy(y = fromLocation.y + 1), fromLocation.copy(x = fromLocation.x - 1, y = fromLocation.y + 1), fromLocation.copy(x = fromLocation.x + 1, y = fromLocation.y + 1)) } private fun considerWest(fromLocation: Point2d): List<Point2d> { return listOf( fromLocation.copy(x = fromLocation.x - 1), fromLocation.copy(x = fromLocation.x - 1, y = fromLocation.y - 1), fromLocation.copy(x = fromLocation.x - 1, y = fromLocation.y + 1)) } private fun considerEast(fromLocation: Point2d): List<Point2d> { return listOf( fromLocation.copy(x = fromLocation.x + 1), fromLocation.copy(x = fromLocation.x + 1, y = fromLocation.y - 1), fromLocation.copy(x = fromLocation.x + 1, y = fromLocation.y + 1)) } private fun neighbors(fromLocation: Point2d): List<Point2d> { val result = mutableSetOf<Point2d>() result.addAll(considerEast(fromLocation)) result.addAll(considerNorth(fromLocation)) result.addAll(considerSouth(fromLocation)) result.addAll(considerWest(fromLocation)) return result.toList() } private fun considerations(fromLocation: Point2d, start: Int) = sequence { val list = listOf( considerNorth(fromLocation), considerSouth(fromLocation), considerWest(fromLocation), considerEast(fromLocation)) var i = 0 while(true) { yield(list[(start + i++) % 4]) } }.iterator() }
0
Kotlin
0
1
c692fb71811055c79d53f9b510fe58a6153a1397
6,326
Advent-Of-Code
Creative Commons Zero v1.0 Universal
src/day01/Day01.kt
hamerlinski
572,951,914
false
{"Kotlin": 25910}
package day01 import readInput fun main() { fun prepareElves(input: List<String>): Elves { val inputIterator = input.iterator(); val elvesList = mutableListOf<Elf>() val temporaryList = mutableListOf<Int>() inputIterator.forEach { if (it == "") { val tempElf = Elf(temporaryList) elvesList.add(tempElf) temporaryList.clear() } else temporaryList.add(it.toInt()) } return Elves(elvesList) } fun part1(elves: Elves): Int { return elves.maxCalories } fun part2(elves: Elves): Int { return elves.top3ElvesMaxCalories } val day01input = readInput("Day01", "day01") val allElves = prepareElves(day01input) println(part1(allElves)) println(part2(allElves)) } class Elf(caloriesList: List<Int>) { val sumOfCalories = caloriesList.sum() } class Elves(elves: List<Elf>) { val maxCalories = elves.maxOf { it.sumOfCalories } val top3ElvesMaxCalories = elves.sortedByDescending { it.sumOfCalories }.subList(0, 3).sumOf { it.sumOfCalories } }
0
Kotlin
0
0
bbe47c5ae0577f72f8c220b49d4958ae625241b0
1,132
advent-of-code-kotlin-2022
Apache License 2.0
src/Day05/Day05.kt
brhliluk
572,914,305
false
{"Kotlin": 16006}
fun main() { val matcher = Regex("move (\\d.*) from (\\d) to (\\d)") fun parseInput(input: List<String>, inputLinesLen: Int = 7, step: Int = 4, crateTowers: Int = 9): List<MutableList<Char>> { val dock = Array(crateTowers) { Array<Char?>(inputLinesLen + 1) { null } } for (i in 0..inputLinesLen) { for (j in 1 until inputLinesLen * step + crateTowers step step) { with(input[i][j]) { if (this.isLetter()) dock[j / step][inputLinesLen - i] = this } } } return dock.map { it.filterNotNull().toMutableList() } } fun part1(input: List<String>): CharArray { val dock = parseInput(input) input.takeLast(input.size - 10).forEach { val (count, from, to) = matcher.matchEntire(it)!!.destructured repeat(count.toInt()) { dock[to.toInt() - 1].add(dock[from.toInt() - 1].removeLast()) } } return dock.map { it.last() }.toCharArray() } fun part2(input: List<String>): CharArray { val dock = parseInput(input) input.takeLast(input.size - 10).forEach { val (count, from, to) = matcher.matchEntire(it)!!.destructured dock[to.toInt() - 1] += dock[from.toInt() - 1].takeLast(count.toInt()) repeat(count.toInt()) { dock[from.toInt() - 1].removeLast() } } return dock.mapNotNull { it.lastOrNull() }.toCharArray() } val input = readInput("Day05") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
96ac4fe0c021edaead8595336aad73ef2f1e0d06
1,567
kotlin-aoc
Apache License 2.0
src/main/kotlin/com/groundsfam/advent/y2022/d09/Day09.kt
agrounds
573,140,808
false
{"Kotlin": 281620, "Shell": 742}
package com.groundsfam.advent.y2022.d09 import com.groundsfam.advent.DATAPATH import com.groundsfam.advent.timed import kotlin.io.path.div import kotlin.io.path.useLines import kotlin.math.abs data class Move(val direction: Char, val times: Int) fun trackTail(moves: List<Move>, numKnots: Int): Int { val knotsX = IntArray(numKnots) val knotsY = IntArray(numKnots) val tailVisited = mutableSetOf(knotsX.last() to knotsY.last()) moves.forEach { move -> repeat(move.times) { when (move.direction) { 'U' -> knotsY[0]++ 'D' -> knotsY[0]-- 'R' -> knotsX[0]++ 'L' -> knotsX[0]-- else -> throw RuntimeException("Illegal direction ${move.direction}") } (1 until numKnots).forEach { i -> val headX = knotsX[i-1] val headY = knotsY[i-1] val tailX = knotsX[i] val tailY = knotsY[i] if (abs(headX - tailX) > 1 || abs(headY - tailY) > 1) { knotsX[i] = when { tailX < headX -> tailX + 1 tailX > headX -> tailX - 1 else -> tailX } knotsY[i] = when { tailY < headY -> tailY + 1 tailY > headY -> tailY - 1 else -> tailY } } } tailVisited.add(knotsX.last() to knotsY.last()) } } return tailVisited.size } fun main() = timed { val moves = (DATAPATH / "2022/day09.txt").useLines { lines -> lines.toList().map { line -> Move(line.first(), line.substring(2).toInt()) } } trackTail(moves, 2) .also { println("Part one: $it") } trackTail(moves, 10) .also { println("Part two: $it") } }
0
Kotlin
0
1
c20e339e887b20ae6c209ab8360f24fb8d38bd2c
1,928
advent-of-code
MIT License
src/main/kotlin/com/hj/leetcode/kotlin/problem1234/Solution.kt
hj-core
534,054,064
false
{"Kotlin": 619841}
package com.hj.leetcode.kotlin.problem1234 /** * LeetCode page: [1234. Replace the Substring for Balanced String](https://leetcode.com/problems/replace-the-substring-for-balanced-string/); */ class Solution { /* Complexity: * Time O(N) and Space O(1) where N is the length of s; */ fun balancedString(s: String): Int { val chars = charArrayOf('Q', 'W', 'E', 'R') val charFrequency = getFrequencyPerChar(s) fun readFrequency(uppercase: Char) = charFrequency[uppercase - 'A'] fun increaseFrequency(uppercase: Char) = charFrequency[uppercase - 'A']++ fun decreaseFrequency(uppercase: Char) = charFrequency[uppercase - 'A']-- val balance = s.length shr 2 fun canBeBalanced() = chars.all { char -> readFrequency(char) <= balance } if (canBeBalanced()) return 0 var minLength = s.length var leftIndex = 0 for (rightIndex in s.indices) { val char = s[rightIndex] decreaseFrequency(char) while (canBeBalanced()) { val currLength = rightIndex - leftIndex + 1 minLength = minOf(minLength, currLength) increaseFrequency(s[leftIndex]) leftIndex++ } } return minLength } private fun getFrequencyPerChar(uppercaseOnly: String): IntArray { val frequency = IntArray(26) for (char in uppercaseOnly) { frequency[char - 'A']++ } return frequency } }
1
Kotlin
0
1
14c033f2bf43d1c4148633a222c133d76986029c
1,528
hj-leetcode-kotlin
Apache License 2.0
Round 1C - B. Parenting Partnering/src/app.kt
amirkhanyana
110,548,909
false
{"Kotlin": 20514}
import java.util.* data class TimeInterval(val from: Int, val to: Int) : Comparable<TimeInterval> { val size: Int get() = if (from > to) 24 * 60 - from + to else to - from override fun compareTo(other: TimeInterval): Int = from.compareTo(other.from) } data class ParentActivity(val parentId: Int, val interval: TimeInterval) : Comparable<ParentActivity> { override fun compareTo(other: ParentActivity): Int = interval.compareTo(other.interval) } data class FreeInterval(val leftParentActivity: ParentActivity, val rightParentActivity: ParentActivity) : Comparable<FreeInterval> { val interval = TimeInterval(leftParentActivity.interval.to, rightParentActivity.interval.from) override fun compareTo(other: FreeInterval): Int = interval.size.compareTo(other.interval.size) } fun main(args: Array<String>) { val input = Scanner(System.`in`) val T = input.nextInt() var Ti = 1 while (Ti <= T) { val parentsCount = 2 val parentsActivitiesCount = IntArray(parentsCount, { input.nextInt() }) val activitiesByParent = Array(parentsCount, { parentId -> Array(parentsActivitiesCount[parentId], { ParentActivity(parentId, TimeInterval(input.nextInt(), input.nextInt())) }) }) val parentActivities = activitiesByParent.flatten().toTypedArray() parentActivities.sort() val intervalsCount = parentActivities.size var prevParentActivity = parentActivities.last() val parentActivitiesIterator = parentActivities.iterator() val freeIntervals = Array(intervalsCount, { val activity = parentActivitiesIterator.next() val freeInterval = FreeInterval(prevParentActivity, activity) prevParentActivity = activity freeInterval }) freeIntervals.sort() val parentBusyness = IntArray(parentsCount) for (parentActivity in parentActivities) { parentBusyness[parentActivity.parentId] += parentActivity.interval.size } val parentsDone = BooleanArray(parentsCount) var switches = 0 for (freeInterval in freeIntervals) { if (freeInterval.leftParentActivity.parentId != freeInterval.rightParentActivity.parentId) { ++switches continue } switches += 2 val parentId = freeInterval.leftParentActivity.parentId if (parentsDone[parentId]) continue parentBusyness[parentId] += freeInterval.interval.size if (parentBusyness[parentId] > 720) { parentsDone[parentId] = true } else { switches -= 2 } } println("Case #$Ti: $switches") ++Ti } }
0
Kotlin
0
0
25a8e6dbd5843e9d4a054d316acc9d726995fffe
2,765
Google-Code-Jam-2017-Problem-Kotlin-Solutions
The Unlicense
src/Day04.kt
LauwiMeara
572,498,129
false
{"Kotlin": 109923}
fun main() { fun part1(input: List<List<IntRange>>): Int { var count = 0 for (pair in input) { val intersection = pair.first().intersect(pair.last()) if (intersection == pair.first().toSet() || intersection == pair.last().toSet()) { count++ } } return count } fun part2(input: List<List<IntRange>>): Int { var count = 0 for (pair in input) { val intersection = pair.first().intersect(pair.last()) if (intersection.isNotEmpty()) { count++ } } return count } val input = readInputAsStrings("Day04") .map{pair -> pair.split(",") .map{elf -> elf.substringBefore("-").toInt()..elf.substringAfter("-").toInt()}} println(part1(input)) println(part2(input)) }
0
Kotlin
0
1
34b4d4fa7e562551cb892c272fe7ad406a28fb69
871
AoC2022
Apache License 2.0
app/src/main/java/de/kauker/unofficial/grocy/utils/StringUtils.kt
aimok04
556,343,801
false
{"Kotlin": 114124}
package de.kauker.unofficial.grocy.utils import java.util.* fun String.distanceTo(c: String): Double { return similarity(this, c) } fun similarity(s1: String, s2: String): Double { var longer = s1 var shorter = s2 if (s1.length < s2.length) { // longer should always have greater length longer = s2 shorter = s1 } val longerLength = longer.length return if (longerLength == 0) { 1.0 /* both strings are zero length */ } else (longerLength - editDistance(longer, shorter)) / longerLength.toDouble() } fun editDistance(is1: String, is2: String): Int { var s1 = is1 var s2 = is2 s1 = s1.lowercase(Locale.getDefault()) s2 = s2.lowercase(Locale.getDefault()) val costs = IntArray(s2.length + 1) for (i in 0..s1.length) { var lastValue = i for (j in 0..s2.length) { if (i == 0) costs[j] = j else { if (j > 0) { var newValue = costs[j - 1] if (s1[i - 1] != s2[j - 1]) newValue = Math.min( Math.min(newValue, lastValue), costs[j] ) + 1 costs[j - 1] = lastValue lastValue = newValue } } } if (i > 0) costs[s2.length] = lastValue } return costs[s2.length] }
0
Kotlin
0
3
9796c5ec845d32a38b7833ef62197112a775d578
1,376
grocy-for-wear-os
Apache License 2.0