path
stringlengths
5
169
owner
stringlengths
2
34
repo_id
int64
1.49M
755M
is_fork
bool
2 classes
languages_distribution
stringlengths
16
1.68k
content
stringlengths
446
72k
issues
float64
0
1.84k
main_language
stringclasses
37 values
forks
int64
0
5.77k
stars
int64
0
46.8k
commit_sha
stringlengths
40
40
size
int64
446
72.6k
name
stringlengths
2
64
license
stringclasses
15 values
src/year2015/day03/Day03.kt
lukaslebo
573,423,392
false
{"Kotlin": 222221}
package year2015.day03 import check import readInput fun main() { // test if implementation meets criteria from the description, like: val testInput = readInput("2015", "Day03_test") check(part1(testInput), 4) check(part2(testInput), 3) val input = readInput("2015", "Day03") println(part1(input)) println(part2(input)) } private fun part1(input: List<String>): Int { var santasPosition = Pos(0, 0) val houses = mutableSetOf(santasPosition) for (dir in input.first()) { santasPosition = santasPosition.move(dir) houses += santasPosition } return houses.size } private fun part2(input: List<String>): Int { var santasPosition = Pos(0, 0) var roboPosition = Pos(0, 0) val houses = mutableSetOf(santasPosition) var index = 0 for (dir in input.first()) { if (index++ % 2 == 0) { santasPosition = santasPosition.move(dir) houses += santasPosition } else { roboPosition = roboPosition.move(dir) houses += roboPosition } } return houses.size } private data class Pos(val x: Int, val y: Int) { fun move(dir: Char) = when (dir) { '>' -> Pos(x + 1, y) '<' -> Pos(x - 1, y) '^' -> Pos(x, y - 1) 'v' -> Pos(x, y + 1) else -> error("direction $dir not supported") } }
0
Kotlin
0
1
f3cc3e935bfb49b6e121713dd558e11824b9465b
1,372
AdventOfCode
Apache License 2.0
src/y2022/Day17.kt
gaetjen
572,857,330
false
{"Kotlin": 325874, "Mermaid": 571}
package y2022 import util.Direction import util.PosL import util.readInput import java.lang.Long.max object Day17 { const val CHAMBER_WIDTH = 7 enum class Shape(grid: List<String>) { FLOOR(listOf("████")), PLUS(listOf(" █ ", "███", " █ ")), CORNER(listOf("███", " █", " █")), // ! reverse order 0, 0 is bottom left COLUMN(listOf("█", "█", "█", "█")), SQUARE(listOf("██", "██")); val width = grid.first().length val height = grid.size.toLong() val blockPositions = grid.mapIndexed { colIdx, line -> line.mapIndexed { rowIdx, chr -> if (chr == ' ') null else rowIdx.toLong() to colIdx.toLong() } }.flatten().filterNotNull().toSet() } class FallingShape(var pos: PosL, val shape: Shape) { fun blockPositions() : Set<PosL> { return shape.blockPositions.map { it + pos }.toSet() } fun overlaps(blocks: Set<PosL>): Boolean { if (pos.second < 0) { return true } if (pos.first < 0) { return true } if (pos.first + shape.width > CHAMBER_WIDTH) { return true } return blockPositions().intersect(blocks).isNotEmpty() } fun move(dir: Direction) { pos = dir.moveL(pos) } fun moved(dir: Direction): FallingShape { return FallingShape(dir.moveL(pos), shape) } } class Chamber(val blocks: MutableSet<PosL>, val jets: List<Direction>) { fun addRock(numRocks: Long) { val rock = FallingShape(2L to maxHeight + 3, Shape.values()[(numRocks % 5).toInt()]) while (true) { val jetDir = jets[numSteps] numSteps = (numSteps + 1) % jets.size if (!rock.moved(jetDir).overlaps(blocks)) { rock.move(jetDir) } if (rock.moved(Direction.DOWN).overlaps(blocks)) { blocks.addAll(rock.blockPositions()) maxHeight = max(maxHeight, rock.pos.second + rock.shape.height) return } else { rock.move(Direction.DOWN) } } } var numSteps = 0 var maxHeight = 0L } private fun parse(input: String): List<Direction> { return input.map { if (it == '>') Direction.RIGHT else Direction.LEFT } } fun part2(input: String, maxRocks: Long): Long { val jets = parse(input) val chamber = Chamber(mutableSetOf(), jets) var numRocks = 0L val steps = mutableListOf(0) val heights = mutableListOf(0L) var heightSkip = 0L var numRepeats = 0L while (numRocks < maxRocks) { chamber.addRock(numRocks) numRocks++ steps.add(chamber.numSteps) heights.add(chamber.maxHeight) if (heightSkip == 0L) { val repeatingLength = getDuplicateLength(steps.reversed()) if (repeatingLength != -1) { println("found repeat of length after $numRocks: $repeatingLength") heightSkip = checkHeights(heights.reversed(), repeatingLength) numRepeats = (maxRocks - numRocks) / repeatingLength numRocks += numRepeats * repeatingLength println("same pattern will repeat $numRepeats times, for a total of $numRocks rocks and a height of ${chamber.maxHeight + numRepeats * heightSkip}") } } } return chamber.maxHeight + (numRepeats * heightSkip) } private fun checkHeights(heights: List<Long>, length: Int) : Long{ val first = heights.subList(0, length).map { it - heights[0] } val second = heights.subList(length, length * 2).map { it - heights[length] } if (first == second) { println("height differences are matching! height difference: ${-first.last()}") return heights.first() - heights[length] } else { error("diffs don't match") } } private fun getDuplicateLength(steps: List<Int>): Int { val start = steps.first() val secondIdx = steps .mapIndexed { idx, i -> idx to i } .slice(steps.indices step 5) .firstOrNull { it.second == start && it.first != 0 }?.first return if (secondIdx != null && secondIdx * 2 < steps.size && steps.subList(0, secondIdx) == steps.subList(secondIdx, secondIdx * 2)) { secondIdx } else { -1 } } } private operator fun PosL.plus(pos: PosL) = this.first + pos.first to this.second + pos.second fun main() { val testInput = """ >>><<><>><<<>><>>><<<>>><<<><<<>><>><<>> """.trimIndent() println(Day17.Shape.values().joinToString("\n")) println(Day17.Shape.values().joinToString("\n") {it.blockPositions.toString()}) println(testInput.length) println("------Tests------") println(Day17.part2(testInput, 2022)) println(Day17.part2(testInput, 1_000_000_000_000)) println("------Real------") val input = readInput("resources/2022/day17").first() println(Day17.part2(input, 2022)) // wrong: 1536416184990 (too low) println(Day17.part2(input, 1_000_000_000_000)) }
0
Kotlin
0
0
d0b9b5e16cf50025bd9c1ea1df02a308ac1cb66a
5,508
advent-of-code
Apache License 2.0
src/Day05.kt
vladislav-og
573,326,483
false
{"Kotlin": 27072}
fun main() { fun extractData(row: String, stacks: ArrayList<ArrayDeque<String>>) { val regex = Regex("\\d+") val (n, stackFrom, stackTo) = regex.findAll(row).map { c -> c.value.toInt() - 1 }.toList() for (i in 0..n) { val removeFirst = stacks[stackFrom].removeFirst() stacks[stackTo].addFirst(removeFirst) } } fun part1(input: List<String>): String { val stacks = arrayListOf<ArrayDeque<String>>() var evaluateMoves = false for (row in input) { if (evaluateMoves) { extractData(row, stacks) } else { if (row.trim().isBlank()) { evaluateMoves = true } var pointer = 0 var stackNumber = 0 for (char in row) { if (stacks.size <= stackNumber){ stacks.add(ArrayDeque()) } if (char.isLetter()) { stacks[stackNumber].add(char.toString()) } if (pointer == 3) { stackNumber++ pointer = 0 } else { pointer++ } } } } return stacks.stream().map { q -> q.first() }.toList().joinToString("") } fun part2(input: List<String>): String { val stacks = arrayListOf<ArrayDeque<String>>() var evaluateMoves = false for (row in input) { if (evaluateMoves) { extractData(row, stacks) } else { if (row.trim().isBlank()) { evaluateMoves = true } var pointer = 0 var stackNumber = 0 for (char in row) { if (stacks.size <= stackNumber){ stacks.add(ArrayDeque()) } if (char.isLetter()) { stacks[stackNumber].add(char.toString()) } if (pointer == 3) { stackNumber++ pointer = 0 } else { pointer++ } } } } return stacks.stream().map { q -> q.first() }.toList().joinToString("") } // test if implementation meets criteria from the description, like: val testInput = readInput("Day05_test") println(part1(testInput)) check(part1(testInput).equals("CMZ")) println(part2(testInput)) check(part2(testInput) == "MCD") val input = readInput("Day05") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
b230ebcb5705786af4c7867ef5f09ab2262297b6
2,819
advent-of-code-2022
Apache License 2.0
src/Day20.kt
IvanChadin
576,061,081
false
{"Kotlin": 26282}
import java.util.* import kotlin.math.abs fun main() { val inputName = "Day20_test" fun part1(): Long { val list = readInput(inputName).mapIndexed { i, s -> Pair(i, s.toLong()) } val indexes = ArrayList(list.indices.toList()) for (i in list.indices) { var j = indexes[i] var steps = abs(list[j].second) % (list.size - 1) val step = if (list[j].second > 0) 1 else -1 while (steps > 0) { steps-- val next = (j + step + list.size) % list.size Collections.swap(list, j, next) indexes[list[j].first] = j indexes[list[next].first] = next j = next } } var ans = 0L for (i in list.indices) { if (list[i].second == 0L) { ans += list[(i + 1000) % list.size].second + list[(i + 2000) % list.size].second + list[(i + 3000) % list.size].second } } return ans } fun part2(): Long { val list = readInput(inputName).mapIndexed { i, s -> Pair(i, s.toLong() * 811589153) } val indexes = ArrayList(list.indices.toList()) repeat(10) { for (i in list.indices) { var j = indexes[i] var steps = abs(list[j].second) % (list.size - 1) val step = if (list[j].second > 0) 1 else -1 while (steps > 0) { steps-- val next = (j + step + list.size) % list.size Collections.swap(list, j, next) indexes[list[j].first] = j indexes[list[next].first] = next j = next } } } var ans = 0L for (i in list.indices) { if (list[i].second == 0L) { ans += list[(i + 1000) % list.size].second + list[(i + 2000) % list.size].second + list[(i + 3000) % list.size].second } } return ans } val result = part2() println(result) }
0
Kotlin
0
0
2241437e6c3a20de70306a0cb37b6fe2ed8f9e3a
2,195
aoc-2022
Apache License 2.0
src/Day01.kt
Derrick-Mwendwa
573,947,669
false
{"Kotlin": 8707}
fun main() { fun part1(input: List<String>): Int { val calories = input.joinToString("\n").split("\n\n").map { it.lines().sumOf { line -> line.toInt() } } return calories.max() } fun part2(input: List<String>): Int { val calories = input.joinToString("\n").split("\n\n").map { it.lines().sumOf { line -> line.toInt() } }.sortedDescending() return calories[0] + calories[1] + calories[2] } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") check(part2(testInput) == 45000) val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
1
7870800afa54c831c143b5cec84af97e079612a3
779
advent-of-code-kotlin-2022
Apache License 2.0
src/hongwei/leetcode/playground/leetcodecba/M54SpiralMatrix.kt
hongwei-bai
201,601,468
false
{"Java": 143669, "Kotlin": 38875}
package hongwei.leetcode.playground.leetcodecba class M54SpiralMatrix { companion object { const val OFF = 444 } fun test() { val input = arrayOf(intArrayOf(1, 2, 3), intArrayOf(4, 5, 6), intArrayOf(7, 8, 9)) val answer = listOf(1, 2, 3, 6, 9, 8, 7, 4, 5) val result = spiralOrder(input) print("pass: ${result == answer}, result: $result") } enum class Direction { RIGHT, DOWN, LEFT, UP; fun getNext(): Direction = when (this) { RIGHT -> DOWN DOWN -> LEFT LEFT -> UP UP -> RIGHT } fun getXAfterMove(x: Int): Int = when (this) { RIGHT -> x + 1 LEFT -> x - 1 else -> x } fun getYAfterMove(y: Int): Int = when (this) { DOWN -> y + 1 UP -> y - 1 else -> y } } fun spiralOrder(matrix: Array<IntArray>): List<Int> { var direction = Direction.RIGHT val sizeX = matrix[0].size val sizeY = matrix.size val maxCount = sizeX * sizeY val list = mutableListOf<Int>() var x = 0 var y = 0 list.add(matrix[0][0]) matrix[y][x] = OFF while (list.size < maxCount) { while (direction.getXAfterMove(x) in 0 until sizeX && direction.getYAfterMove(y) in 0 until sizeY && matrix[direction.getYAfterMove(y)][direction.getXAfterMove(x)] != OFF ) { x = direction.getXAfterMove(x) y = direction.getYAfterMove(y) list.add(matrix[y][x]) matrix[y][x] = OFF } direction = direction.getNext() } return list } fun spiralOrder2(matrix: Array<IntArray>): List<Int> { var i = 0 var j = 0 val list = mutableListOf<Int>() var x0 = 0 var y0 = 0 var x1 = matrix[0].size - 1 var y1 = matrix.size - 1 while (x0 <= x1 && y0 <= y1) { y0++ while (i <= x1) { // println("d1-- p($i,$j) is ${matrix[j][i]}, boundary: x[$x0~$x1], y[$y0~$y1]") list.add(matrix[j][i++]) } i = x1 j++ x1-- while (j <= y1) { // println("d2-- p($i,$j) is ${matrix[j][i]}, boundary: x[$x0~$x1], y[$y0~$y1]") list.add(matrix[j++][i]) } j = y1 i-- y1-- while (i >= x0) { // println("d3-- p($i,$j) is ${matrix[j][i]}, boundary: x[$x0~$x1], y[$y0~$y1]") list.add(matrix[j][i--]) } i = x0 j-- x0++ while (j >= y0) { // println("d4-- p($i,$j) is ${matrix[j][i]}, boundary: x[$x0~$x1], y[$y0~$y1]") list.add(matrix[j--][i]) } j = y0 i++ } return list } } /* https://leetcode.com/problems/spiral-matrix/ Given an m x n matrix, return all elements of the matrix in spiral order. Example 1: Input: matrix = [[1,2,3],[4,5,6],[7,8,9]] Output: [1,2,3,6,9,8,7,4,5] Example 2: Input: matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]] Output: [1,2,3,4,8,12,11,10,9,5,6,7] Constraints: m == matrix.length n == matrix[i].length 1 <= m, n <= 10 -100 <= matrix[i][j] <= 100 */
0
Java
0
1
9d871de96e6b19292582b0df2d60bbba0c9a895c
3,445
leetcode-exercise-playground
Apache License 2.0
src/main/kotlin/string/MinimumWindowSubstring.kt
ghonix
88,671,637
false
null
package string /* https://leetcode.com/problems/minimum-window-substring/ */ class MinimumWindowSubstring { val tMap = HashMap<Char, Int>() private fun isAcceptable(map: HashMap<Char, Int>): Boolean { for (key in map.keys) { if (map[key]!! > 0) { return false } } return true } private fun shouldShrinkWindow(map: java.util.HashMap<Char, Int>): Boolean { if (isAcceptable(map)) { return true } for (key in map.keys) { if (map[key]!! > 0) { return false } } return true } fun minWindow(src: String, t: String): String { for (char in t) { // hash the count of chars in t if (tMap.containsKey(char)) { tMap[char] = tMap[char]!!.inc() } else { tMap[char] = 1 } } var l = 0 var r = l var minLength = Int.MAX_VALUE var rangeStart = 0 var rangeEnd = 0 while (r < src.length) { val end = src[r] if (tMap.containsKey(end)) { tMap[end] = tMap[end]!!.dec() r++ } else { r++ } while (l <= r && shouldShrinkWindow(map = tMap)) { if ((r - l) < minLength) { minLength = r - l rangeStart = l rangeEnd = r } // try to shrink the window val start = src[l] if (tMap.containsKey(start)) { if (tMap[start]!!.inc() <= 0) { tMap[start] = tMap[start]!!.inc() l++ continue } else { break } } else { l++ } } } return src.substring(startIndex = rangeStart, endIndex = rangeEnd) } } fun main() { println( MinimumWindowSubstring().minWindow("ADOBECODEBANC", "ABC") ) } /* 1- Hour debug (java, js, python) * Code with issues * Find the bugs and fix them 2- 2 hours take home * Algorithm coding problem * Data infra (schema design) * System design proposal */
0
Kotlin
0
2
25d4ba029e4223ad88a2c353a56c966316dd577e
2,451
Problems
Apache License 2.0
src/main/kotlin/dp/LargestPattern.kt
yx-z
106,589,674
false
null
package dp import math.isPrime import util.* // given a bitmap as a 2d array, identify the largest rectangular pattern that appear more than once // the copies of a pattern may overlap but cannot coincide // report its size fun main(args: Array<String>) { val bitmap = arrayOf( intArrayOf(0, 1, 0, 0, 0), intArrayOf(1, 0, 1, 0, 0), intArrayOf(0, 1, 0, 1, 0), intArrayOf(0, 0, 1, 0, 1), intArrayOf(0, 0, 0, 1, 0)) // println(bitmap.largestPattern()) println(bitmap.map { it.toOneArray() }.toOneArray().largestPattern()) } fun OneArray<OneArray<Int>>.largestPattern(): Int { val M = this val n = size // dp(i, j, p, q, h): max width w : h * w subarrays are identical // memoization structure: 5d array dp[1..n, 1..n, 1..n, 1..n, 1..n] val dp = OneArray(n + 1) { OneArray(n + 1) { OneArray(n + 1) { OneArray(n + 1) { OneArray(n) { 0 } } } } } // space complexity: O(n^5) var max = 0 // evaluation order: h has to be 1 to n since entries in h - 1 are required // there is no specific evaluation order for i, j, p, q for (h in 1..n) { for (i in 1..n) { for (j in 1..n + 1) { for (p in 1..n) { for (q in 1..n + 1) { // different cases val curr = when { i == p && j == q -> N_INF j > n || q > n -> 0 M[i, j] != M[p, q] -> 0 h == 1 -> 1 + dp[i, j + 1, p, q + 1, 1] else -> min(dp[i, j, p, q, 1], dp[i + 1, j, p + 1, q, h - 1]) } dp[i, j, p, q, h] = curr // maintain a max here if (curr > 0) { max = max(max, curr * h) } } } } } } // time complexity: O(n^5) return max } fun Array<IntArray>.largestPattern(): Int { val rows = size val cols = this[0].size val primes = Array(rows) { IntArray(cols) } val primesFlat = primes(rows * cols) for (row in 0 until rows) { for (col in 0 until cols) { primes[row, col] = primesFlat[cols * row + col] } } val dp = Array(rows) { Array(cols) { Array(rows) { IntArray(cols) { 1 } } } } val dpFlat = Array(rows * rows * cols * cols) { 0 to (0 to (0 to (0 to 1))) } var dpFlatIdx = 0 for (i in 0 until rows) { for (j in 0 until cols) { for (p in i until rows) { for (q in j until cols) { dp[i, j, p, q] = if (this[p, q] == 1) { primes[p - i, q - j] } else { 1 } if (p - 1 >= 0 && q - 1 >= 0) { dp[i, j, p, q] *= dp[i, j, p - 1, q] * dp[i, j, p, q - 1] / dp[i, j, p - 1, q - 1] } else if (p - 1 >= 0) { dp[i, j, p, q] *= dp[i, j, p - 1, q] } else if (q - 1 >= 0) { dp[i, j, p, q] *= dp[i, j, p, q - 1] } dpFlat[dpFlatIdx] = i to (j to (p to (q to dp[i, j, p, q]))) dpFlatIdx++ } } } } dpFlat.sortBy { it.second.second.second.second } var maxSize = Int.MIN_VALUE (1 until dpFlat.size).asSequence() .filter { dpFlat[it].second.second.second.second == dpFlat[it - 1].second.second.second.second } .forEach { maxSize = max(maxSize, (dpFlat[it].second.second.first - dpFlat[it].first + 1) * (dpFlat[it].second.second.second.first - dpFlat[it].second.first + 1)) } return maxSize } // return the first `n` prime numbers fun primes(n: Int): IntArray { val ans = IntArray(n) var num = 2 for (i in 0 until n) { while (!num.isPrime()) { num++ } ans[i] = num num++ } return ans }
0
Kotlin
0
1
15494d3dba5e5aa825ffa760107d60c297fb5206
3,286
AlgoKt
MIT License
src/main/kotlin/se/saidaspen/aoc/aoc2015/Day18.kt
saidaspen
354,930,478
false
{"Kotlin": 301372, "CSS": 530}
package se.saidaspen.aoc.aoc2015 import se.saidaspen.aoc.util.* fun main() = Day18.run() object Day18 : Day(2015, 18) { override fun part1(): Any { var lMap = toMap(input) val alwaysOn = listOf<P<Int, Int>>() repeat(100) {lMap = switchLights(lMap, alwaysOn)} return lMap.values.count { it == '#' } } override fun part2(): Any { var lMap = toMap(input) val alwaysOn = listOf(P(0,0), P(0,99), P(99,99), P(99,0)) repeat(100) {lMap = switchLights(lMap, alwaysOn)} return lMap.values.count { it == '#' } } private fun switchLights(lmap: MutableMap<Pair<Int, Int>, Char>, alwaysOn: List<P<Int, Int>>): MutableMap<Pair<Int, Int>, Char> { val map = lmap.toMutableMap() val maxVal = 99 for (col in 0..maxVal) { for (row in 0..maxVal) { val thisLight = P(col, row) if (alwaysOn.contains(thisLight)){ map[thisLight] = '#' continue } val litNeighbors = neighbors(thisLight).filter { it.first in 0..maxVal && it.second in 0..maxVal }.count { lmap[it]!! == '#' } if (lmap[thisLight] == '#') { if (litNeighbors == 2 || litNeighbors == 3) { map[thisLight] = '#' } else map[thisLight] = '.' } else { if (litNeighbors == 3) { map[thisLight] = '#' } } } } return map } }
0
Kotlin
0
1
be120257fbce5eda9b51d3d7b63b121824c6e877
1,592
adventofkotlin
MIT License
src/main/kotlin/th/in/jamievl/adventofcode/d2/Day2.kt
jamievlin
578,295,680
false
{"Kotlin": 8145, "Starlark": 4278}
package th.`in`.jamievl.adventofcode.d2 import th.`in`.jamievl.adventofcode.common.readFromResource import java.lang.IllegalArgumentException enum class WinState { LOSE, WIN, DRAW } enum class RpsPlay { ROCK, PAPER, SCISSORS; fun calculateOutcomePartScore() = when (this) { ROCK -> 1 SCISSORS -> 3 PAPER -> 2 } companion object { private fun calculateOutcome(yourPlay: RpsPlay, opponent: RpsPlay): Int = when (yourPlay) { ROCK -> when (opponent) { SCISSORS -> 6 PAPER -> 0 ROCK -> 3 } PAPER -> when (opponent) { SCISSORS -> 0 PAPER -> 3 ROCK -> 6 } SCISSORS -> when (opponent) { SCISSORS -> 3 PAPER -> 6 ROCK -> 0 } } private fun calculateFromDesiredOutcome(theirPlay: RpsPlay, result: WinState): RpsPlay = when (theirPlay) { ROCK -> when (result) { WinState.DRAW -> ROCK WinState.WIN -> PAPER WinState.LOSE -> SCISSORS } PAPER -> when (result) { WinState.DRAW -> PAPER WinState.WIN -> SCISSORS WinState.LOSE -> ROCK } SCISSORS -> when (result) { WinState.DRAW -> SCISSORS WinState.WIN -> ROCK WinState.LOSE -> PAPER } } fun calculateScore(yourPlay: RpsPlay, opponent: RpsPlay): Int = calculateOutcome(yourPlay, opponent) + yourPlay.calculateOutcomePartScore() fun calculateScoreFromDesiredOutcome(theirPlay: RpsPlay, result: WinState): Int { val yourPlay = calculateFromDesiredOutcome(theirPlay, result) val resultScore = when (result) { WinState.WIN -> 6 WinState.LOSE -> 0 WinState.DRAW -> 3 } return resultScore + yourPlay.calculateOutcomePartScore() } } } fun main() { var totalScore = 0 var secondPartScore = 0 readFromResource("d2/d2_input.txt") { val yourPlay = it[2] val desiredOutcomeLine = it[2] // part 2 val theirPlay = it[0] val yourEnum = when (yourPlay) { 'X' -> RpsPlay.ROCK 'Y' -> RpsPlay.PAPER 'Z' -> RpsPlay.SCISSORS else -> throw IllegalArgumentException() } val desiredOutcome = when (desiredOutcomeLine) { 'X' -> WinState.LOSE 'Y' -> WinState.DRAW 'Z' -> WinState.WIN else -> throw IllegalArgumentException() } val theirEnum = when (theirPlay) { 'A' -> RpsPlay.ROCK 'B' -> RpsPlay.PAPER 'C' -> RpsPlay.SCISSORS else -> throw IllegalArgumentException() } // 1st part totalScore += RpsPlay.calculateScore(yourEnum, theirEnum) secondPartScore += RpsPlay.calculateScoreFromDesiredOutcome(theirEnum, desiredOutcome) } println("total score: $totalScore") println("part 2 total score: $secondPartScore") }
0
Kotlin
0
0
4b0f5a8e6bcc411f1a76cfcd6d099872cf220e46
3,249
adventofcode-2022
MIT License
src/main/kotlin/com/colinodell/advent2022/Day25.kt
colinodell
572,710,708
false
{"Kotlin": 105421}
package com.colinodell.advent2022 import kotlin.math.pow class Day25(private val input: List<String>) { fun solvePart1() = input.sumOf { snafuToDecimal(it) }.toSnafu() companion object { private val digitMap = mapOf( '=' to -2L, '-' to -1L, '0' to 0L, '1' to 1L, '2' to 2L ) private val reverseMap = digitMap.entries.associate { (k, v) -> v to k } fun snafuToDecimal(snafu: String) = snafu .toCharArray() .reversed() .withIndex() .fold(0L) { acc, (i: Int, c) -> acc + 5.0.pow(i.toDouble()).toLong() * digitMap[c]!! } fun decimalToSnafu(decimal: Long) = when (decimal) { 0L -> "0" else -> decimal.toSnafu() } private fun Long.toSnafu(): String { if (this == 0L) return "" return when (val next = this % 5L) { 0L, 1L, 2L -> (this / 5L).toSnafu() + reverseMap[next] 3L, 4L -> (this / 5L + 1L).toSnafu() + reverseMap[next - 5L] else -> error("$this is not a valid snafu num") } } } }
0
Kotlin
0
1
32da24a888ddb8e8da122fa3e3a08fc2d4829180
1,208
advent-2022
MIT License
src/Day08.kt
ChristianNavolskyi
573,154,881
false
{"Kotlin": 29804}
class Day08 : Challenge<Int> { override val name: String get() = "Day 08" override fun inputName(): String = "Day08" override fun testInputName(): String = "Day08_test" override fun testResult1(): Int = 21 override fun testResult2(): Int = 8 override fun part1(input: String): Int { val forest = input.parseForest() val visibilityMap = forest.lookup(::visibility) // println("Visible Trees") // visibilityMap.print() return visibilityMap.sum() } override fun part2(input: String): Int { val forest = input.parseForest() val sight = forest.lookup(::sight) // println("Sight Map") // sight.print() return sight.max() } private fun String.parseForest(): List<List<Int>> = trim().split("\n").map { it.map { char -> char.digitToInt() }.toList() }.toList() private fun List<List<Int>>.transpose(): List<List<Int>> = List(first().size) { column -> List(size) { row -> get(row)[column] } } private fun List<List<Int>>.lookup(determinant: (rowIndex: Int, columnIndex: Int, row: List<Int>, column: List<Int>) -> Int): List<List<Int>> { val transposed = transpose() // println("Forest") // print() // println("Transposed Forest") // transposed.print() return mapIndexed { rowIndex, row -> List(row.size) { columnIndex -> determinant(rowIndex, columnIndex, row, transposed[columnIndex]) } }.toList() } private fun visibility(rowIndex: Int, columnIndex: Int, row: List<Int>, column: List<Int>): Int { val width = row.size val height = column.size val treeHeight = row[columnIndex] return if (rowIndex == 0 || columnIndex == 0 || rowIndex == width - 1 || columnIndex == height - 1) { 1 } else { val maxLeft = row.subList(0, columnIndex).maxOrNull() ?: 0 val maxRight = row.subList(columnIndex + 1, width).maxOrNull() ?: 0 val maxTop = column.subList(0, rowIndex).maxOrNull() ?: 0 val maxBottom = column.subList(rowIndex + 1, height).maxOrNull() ?: 0 if (treeHeight > maxLeft || treeHeight > maxRight || treeHeight > maxTop || treeHeight > maxBottom) { 1 } else { 0 } } } private fun sight(rowIndex: Int, columnIndex: Int, row: List<Int>, column: List<Int>): Int { val width = row.size val height = column.size val treeHeight = row[columnIndex] return if (rowIndex == 0 || columnIndex == 0 || rowIndex == width - 1 || columnIndex == height - 1) { 0 } else { val sightLeft = row.subList(0, columnIndex).reversed().indexOfFirstOrNull { it >= treeHeight }?.inc() ?: columnIndex val sightRight = row.subList(columnIndex + 1, width).indexOfFirstOrNull { it >= treeHeight }?.inc() ?: (width - columnIndex - 1) val sightTop = column.subList(0, rowIndex).reversed().indexOfFirstOrNull { it >= treeHeight }?.inc() ?: rowIndex val sightBottom = column.subList(rowIndex + 1, height).indexOfFirstOrNull { it >= treeHeight }?.inc() ?: (height - rowIndex - 1) return sightLeft * sightRight * sightTop * sightBottom } } private fun <T> List<T>.indexOfFirstOrNull(predicate: (it: T) -> Boolean): Int? { val index = indexOfFirst(predicate) return if (index == -1) null else index } private fun List<List<Int>>.print() { forEach { it.forEach { visible -> print("$visible\t") } println() } } private fun List<List<Int>>.sum(): Int = sumOf { it.sum() } private fun List<List<Int>>.max(): Int = maxOf { it.max() } }
0
Kotlin
0
0
222e25771039bdc5b447bf90583214bf26ced417
3,864
advent-of-code-2022
Apache License 2.0
src/main/kotlin/com/groundsfam/advent/y2023/d11/Day11.kt
agrounds
573,140,808
false
{"Kotlin": 281620, "Shell": 742}
package com.groundsfam.advent.y2023.d11 import com.groundsfam.advent.DATAPATH import com.groundsfam.advent.points.Point import com.groundsfam.advent.timed import kotlin.io.path.div import kotlin.io.path.useLines import kotlin.math.exp import kotlin.math.max import kotlin.math.min val galaxies = mutableListOf<Point>() // values of x val nonemptyCols = mutableSetOf<Int>() // values of y val nonemptyRows = mutableSetOf<Int>() fun dist(galaxy1: Point, galaxy2: Point, expansion: Long): Long { val minX = min(galaxy1.x, galaxy2.x) val maxX = max(galaxy1.x, galaxy2.x) val minY = min(galaxy1.y, galaxy2.y) val maxY = max(galaxy1.y, galaxy2.y) return maxX - minX + (expansion - 1) * (minX..maxX).filterNot(nonemptyCols::contains).size + maxY - minY + (expansion - 1) * (minY..maxY).filterNot(nonemptyRows::contains).size } fun totalGalaxyDistance(expansion: Long): Long = galaxies.indices.sumOf { i -> galaxies.indices.filter { it > i }.sumOf { j -> dist(galaxies[i], galaxies[j], expansion) } } fun main() = timed { (DATAPATH / "2023/day11.txt").useLines { lines -> lines.forEachIndexed { y, line -> line.forEachIndexed { x, c -> if (c == '#') { galaxies.add(Point(x, y)) nonemptyCols.add(x) nonemptyRows.add(y) } } } } println("Part one: ${totalGalaxyDistance(2)}") println("Part two: ${totalGalaxyDistance(1_000_000)}") }
0
Kotlin
0
1
c20e339e887b20ae6c209ab8360f24fb8d38bd2c
1,542
advent-of-code
MIT License
src/cn/leetcode/codes/simple20/Simple20_2.kt
shishoufengwise1234
258,793,407
false
{"Java": 771296, "Kotlin": 68641}
package cn.leetcode.codes.simple20 import cn.leetcode.codes.out import java.util.HashMap /* 给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。 有效字符串需满足: 左括号必须用相同类型的右括号闭合。 左括号必须以正确的顺序闭合。 注意空字符串可被认为是有效字符串。 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/valid-parentheses 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 */ fun isValid(s: String): Boolean { if (s.isEmpty()) { return false } val hashMap = HashMap<String,String>() hashMap.put("(", ")") hashMap.put("{", "}") hashMap.put("[", "23") out(" get ${hashMap.get("[")}") out(" get2 ${hashMap.getValue("[")}") // val map = hashMapOf(Pair("(", ")"), Pair("{", "}"), Pair("[", "]")) // out("map = $map") val chars = s.toCharArray() for (i in chars.indices) { val left = chars[i] out(" left = $left") val right = hashMap.getOrDefault( left ?: "","") out(" left = $left , right = $right") var isVa = false for (j in i + 1 until chars.size) { if ((chars[j] ?: "") == right) { isVa = true out("达到条件") break } } out(" isVa = $isVa") if (!isVa) { return false } } return true }
0
Java
0
0
f917a262bcfae8cd973be83c427944deb5352575
1,516
LeetCodeSimple
Apache License 2.0
src/Day01.kt
Vincentvibe3
573,202,573
false
{"Kotlin": 8454}
fun main() { fun part1(input: List<String>): Int { var max = -1 var currentElf = 0 for (line in input) { if (line.isBlank()){ if (currentElf>max){ max = currentElf } currentElf = 0 } else{ currentElf+=line.toInt() } } return max } fun part2(input: List<String>): Int { val elves = mutableListOf(0) for (line in input) { if (line.isBlank()){ elves.add(0) } else{ elves[elves.lastIndex]+=line.toInt() } } return elves.sorted().reversed().subList(0, 3).sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") check(part1(testInput) == 24000) check(part2(testInput) == 45000) val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
246c8c43a416023343b3ef518ae3e21dd826ee81
1,017
advent-of-code-2022
Apache License 2.0
src/net/sheltem/aoc/y2021/Day03.kt
jtheegarten
572,901,679
false
{"Kotlin": 178521}
package net.sheltem.aoc.y2021 suspend fun main() { Day03().run() } class Day03 : Day<Long>(198, 230) { override suspend fun part1(input: List<String>): Long = input .toBits() .let { it.first.toDecimal() to it.second.toDecimal() } .let { it.first * it.second } override suspend fun part2(input: List<String>): Long = input .let { it.filterBits() * it.filterBits(false) } } private fun List<String>.filterBits(mostCommon: Boolean = true): Long { var resultList = this for(index in resultList[0].indices) { resultList = resultList.partition { it[index] == '1' } .let { if (mostCommon && (it.first.size >= it.second.size) || !mostCommon && (it.first.size < it.second.size)) it.first else it.second } if (resultList.size == 1) return resultList.single().toDecimal() } return 0L } private fun List<String>.toBits(): Pair<String, String> { return (0 until this[0].length) .map { digit -> this.sumOf { row -> row[digit].digitToInt() }.let { if (it > size / 2) 1 else 0 } }.joinToString("") .let { it to it.flip() } } private fun String.toDecimal(): Long { var result = 0L indices.forEach { result = result.shl(1) if (this[it] == '1') result++ } return result } private fun String.flip() = map { if (it == '0') '1' else '0' }.joinToString("")
0
Kotlin
0
0
ac280f156c284c23565fba5810483dd1cd8a931f
1,502
aoc
Apache License 2.0
src/main/kotlin/Day4.kt
ueneid
575,213,613
false
null
class Day4(val inputs: List<String>) { fun solve1(): Int { return inputs.asSequence() .map { line -> line.split(",") .flatMap { it.split("-") } .map { it.toInt() } } .count { it[0] <= it[2] && it[3] <= it[1] || it[2] <= it[0] && it[1] <= it[3] } } fun solve2(): Int { return inputs.asSequence() .map { line -> line.split(",") .map { it.split("-").map { s -> s.toInt() } } .map { (it[0]..it[1]).toSet() } } .map { it[0].intersect(it[1]) } .count { it.isNotEmpty() } } } fun main() { val obj = Day4(Resource.resourceAsListOfString("day4/input.txt")) println(obj.solve1()) println(obj.solve2()) }
0
Kotlin
0
0
743c0a7adadf2d4cae13a0e873a7df16ddd1577c
836
adventcode2022
MIT License
src/day18/b/day18b.kt
pghj
577,868,985
false
{"Kotlin": 94937}
package day18.b import day18.a.Side import day18.a.read import inBounds import repeatUntilEmpty import shouldBe import util.IntVector import vec fun main() { val dir = listOf( vec(1,0,0), vec(0,1,0), vec(0,0,1), ) val cubes = read() // Bounding box with an added margin of 1 on all sides val min = IntVector(3) { i -> cubes.minOf { it[i] }-1 } val max = IntVector(3) { i -> cubes.maxOf { it[i] }+1 } val outsideAir = HashSet<IntVector>() for (x in min[0] .. max[0]) { for (y in min[1]..max[1]) { for (z in min[2]..max[2]) { if ( x == min[0] || x == max[0] || y == min[1] || y == max[1] || z == min[2] || z == max[2] ) { // There are no cubes on the surface of the bounding box, so it must be air. outsideAir.add(vec(x, y, z)) } } } } // Find all air in contact with outside air, that is not blocked by cubes. val w = HashSet(outsideAir) repeatUntilEmpty(w) { p -> dir.forEach { d -> listOf(-1,1) .map { s -> d*s + p } // all neighbouring cells .filter { inBounds(min, max, it) } // that are within bounds .filter { !cubes.contains(it) } // and not already occupied by cube .filter { !outsideAir.contains(it) } // and not already found .forEach { outsideAir.add(it) // add w.add(it) // and use as starting point to continue search } } } // Collect all cell sides of the outside air. val outsideAirSides = HashSet<Side>() outsideAir.forEach { p -> (0..2).forEach { i -> listOf( Side(p, i), Side(p + dir[i], i) ).forEach { airSide -> outsideAirSides.add(airSide) } } } // Count all cube sides in contact with outside air sides. var n = 0 cubes.forEach { p -> (0..2).forEach { i -> listOf( Side(p, i), Side(p + dir[i], i) ).forEach { cubeSide -> if (outsideAirSides.contains(cubeSide)) n++ } } } shouldBe(2652, n) }
0
Kotlin
0
0
4b6911ee7dfc7c731610a0514d664143525b0954
2,300
advent-of-code-2022
Apache License 2.0
src/Day01.kt
hadiamin
572,509,248
false
null
fun main() { fun part1(input: List<String>): Int { val sumedList = mutableListOf<Int>() var sum = 0 for (item in input) { if (item != "") { sum += item.toInt() } else { sumedList.add(sum) sum = 0 } } return sumedList.max() } fun part2(input: List<String>): Int { val sumedList = mutableListOf<Int>() var sum = 0 for (item in input) { if (item != "") { sum += item.toInt() } else { sumedList.add(sum) sum = 0 } } return sumedList.sorted().reversed().subList(0, 3).sum() } // test if implementation meets criteria from the description, like: // val testInput = readInput("Day01.txt") // check(part1(testInput) == 1) val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
e63aea2a55b629b9ac3202cdab2a59b334fb7041
982
advent-of-code-2022-kotlin
Apache License 2.0
kotlin/src/com/daily/algothrim/leetcode/NumEquivDominoPairs.kt
idisfkj
291,855,545
false
null
package com.daily.algothrim.leetcode /** * 1128. 等价多米诺骨牌对的数量 * * 给你一个由一些多米诺骨牌组成的列表 dominoes。 * * 如果其中某一张多米诺骨牌可以通过旋转 0 度或 180 度得到另一张多米诺骨牌,我们就认为这两张牌是等价的。 * * 形式上,dominoes[i] = [a, b] 和 dominoes[j] = [c, d] 等价的前提是 a==c 且 b==d,或是 a==d 且 b==c。 * * 在 0 <= i < j < dominoes.length 的前提下,找出满足 dominoes[i] 和 dominoes[j] 等价的骨牌对 (i, j) 的数量。 * */ class NumEquivDominoPairs { companion object { @JvmStatic fun main(args: Array<String>) { println(NumEquivDominoPairs().solution(arrayOf( intArrayOf(1, 2), intArrayOf(2, 1), intArrayOf(3, 4), intArrayOf(5, 6) ))) } } // dominoes[i].size 最大为两位 // O(n) fun solution(dominoes: Array<IntArray>): Int { // 组成两位数的正数 val a = IntArray(100) var count = 0 for (item in dominoes) { if (item[0] > item[1]) { val temp = item[0] item[0] = item[1] item[1] = temp } count += a[item[0] * 10 + item[1]]++ } return count } }
0
Kotlin
9
59
9de2b21d3bcd41cd03f0f7dd19136db93824a0fa
1,406
daily_algorithm
Apache License 2.0
src/day14/day14.kt
diesieben07
572,879,498
false
{"Kotlin": 44432}
package day14 import streamInput //val file = "Day14Example" val file = "Day14" data class Point(val x: Int, val y: Int) fun Sequence<String>.parseInput(): Sequence<List<Point>> { return map { line -> line.split(" -> ").map { it.split(',') }.map { (x, y) -> Point(x.toInt(), y.toInt()) } } } enum class Contents(val display: String) { AIR("."), ROCK("#"), SAND("*") } private fun part(fakeBottom: Boolean) { streamInput(file) { input -> val lines = input.parseInput().toMutableList() val allPoints = lines.flatten() var maxX = allPoints.maxBy { it.x }.x var maxY = allPoints.maxBy { it.y }.y if (fakeBottom) { lines.add(listOf(Point(0, y = maxY + 2), Point(maxX + 300, y = maxY + 2))) maxX += 300 maxY += 2 } val grid = MutableList(maxY + 1) { MutableList(maxX + 1) { Contents.AIR } } for (line in lines) { for ((start, end) in line.windowed(2)) { if (start.x == end.x) { for (y in minOf(start.y, end.y)..maxOf(start.y, end.y)) { grid[y][start.x] = Contents.ROCK } } else { for (x in minOf(start.x, end.x)..maxOf(start.x, end.x)) { grid[start.y][x] = Contents.ROCK } } } } fun printGrid() { println( grid.joinToString(separator = "\n") { row -> row.subList(494, row.size).joinToString(separator = "") { it.display } } ) } fun tryMove(current: Point, dx: Int = 0, dy: Int = 0): Point { val n = current.copy(x = current.x + dx, y = current.y + dy) return if (n.y in grid.indices && n.x in grid[n.y].indices && grid[n.y][n.x] == Contents.AIR) { n } else { current } } fun oneSandMovement(from: Point): Point? { var newPosition = from newPosition = tryMove(newPosition, dy = 1) if (newPosition == from) { newPosition = tryMove(newPosition, dy = 1, dx = -1) } if (newPosition == from) { newPosition = tryMove(newPosition, dy = 1, dx = 1) } val changed = from != newPosition return when { changed -> newPosition else -> null } } fun simulateSand(from: Point): Point? { var currentPosition = from do { currentPosition = oneSandMovement(currentPosition) ?: break } while (true) return when { currentPosition == from && grid[from.y][from.x] == Contents.AIR -> { grid[from.y][from.x] = Contents.SAND from } currentPosition != from && currentPosition.y != grid.lastIndex && currentPosition.x != grid[currentPosition.y].lastIndex -> { grid[currentPosition.y][currentPosition.x] = Contents.SAND currentPosition } else -> null } } val sandStart = Point(500, 0) var sandCount = 0 while (true) { val restPosition = simulateSand(sandStart) ?: break sandCount++ // println(sandCount) // println(restPosition) // printGrid() // println() } println(sandCount) } } fun main() { part(false) part(true) }
0
Kotlin
0
0
0b9993ef2f96166b3d3e8a6653b1cbf9ef8e82e6
3,680
aoc-2022
Apache License 2.0
src/day3/Solution.kt
Zlate87
572,858,682
false
{"Kotlin": 12960}
package day3 import readInput fun main() { fun getIntValue(it: Char) = if (it.isLowerCase()) it.toInt() - 96 else it.toInt() - 38 fun getValue1(line: String): Int { val substring1 = line.substring(0, line.length / 2) val substring2 = line.substring(line.length / 2) substring1.forEach { if (substring2.contains(it)) return getIntValue(it) } throw java.lang.RuntimeException() } fun part1(input: List<String>): Int { return input.sumOf { getValue1(it) } } fun getValue2(strings: List<String>): Int { strings[0].forEach { if (strings[1].contains(it) && strings[2].contains(it)) return getIntValue(it) } throw java.lang.RuntimeException() } fun part2(input: List<String>): Int { return input.chunked(3).sumOf { getValue2(it) } } // test if implementation meets criteria from the description, like: val testInput = readInput("day3/Input_test") check(part1(testInput) == 157) check(part2(testInput) == 70) val input = readInput("day3/Input") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
57acf4ede18b72df129ea932258ad2d0e2f1b6c3
1,120
advent-of-code-2022
Apache License 2.0
src/main/kotlin/g2201_2300/s2209_minimum_white_tiles_after_covering_with_carpets/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g2201_2300.s2209_minimum_white_tiles_after_covering_with_carpets // #Hard #String #Dynamic_Programming #Prefix_Sum // #2023_06_27_Time_373_ms_(100.00%)_Space_40_MB_(100.00%) class Solution { fun minimumWhiteTiles(floor: String, numCarpets: Int, carpetLen: Int): Int { val len = floor.length val dp = Array(numCarpets + 1) { IntArray(len + 1) } val prefix = IntArray(len) var tiles = 0 var total = 0 for (i in 0 until len) { // calculate total no of Tiles within the Carpet Length Window tiles += floor[i].code - '0'.code // start excluding tiles which are not in the Range anymore of the Carpet Length given if (i - carpetLen >= 0) { tiles -= floor[i - carpetLen].code - '0'.code } // the total no of tiles covered within the Carpet Length range for current index prefix[i] = tiles total += floor[i].code - '0'.code } for (i in 1..numCarpets) { for (j in 0 until len) { // if we do not wish to cover current Tile val doNot = dp[i][j] // if we do wish to cover current tile val doTake = dp[i - 1][Math.max(0, j - carpetLen + 1)] + prefix[j] // we should go back the Carpet length & check for tiles not covered before j - // carpet Length distance dp[i][j + 1] = Math.max(doTake, doNot) } } return total - dp[numCarpets][len] } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,574
LeetCode-in-Kotlin
MIT License
solver/src/main/kotlin/dev/mrichter/mapf/solver/CTSolver.kt
matyasrichter
493,165,334
false
{"Kotlin": 51082}
package dev.mrichter.mapf.solver import dev.mrichter.mapf.graph.Agent import java.util.* class ConstraintTreeNode<CT>( val parent: ConstraintTreeNode<CT>?, val vertexConstraint: VertexConstraint<CT>?, val edgeConstraint: EdgeConstraint<CT>?, val agentId: UUID, val solution: List<List<CT>>, val cost: Int, ) { /** * Traverse the tree and collect vertex constraints for an agent. */ fun getVertexConstraints(id: UUID): Sequence<VertexConstraint<CT>> = sequence { if (agentId == id && vertexConstraint != null) { yield(vertexConstraint) } parent?.let { yieldAll(it.getVertexConstraints(id)) } } /** * Traverse the tree and collect edge constraints for an agent. */ fun getEdgeConstraints(id: UUID): Sequence<EdgeConstraint<CT>> = sequence { if (agentId == id && edgeConstraint != null) { yield(edgeConstraint) } parent?.let { yieldAll(it.getEdgeConstraints(id)) } } val depth: Int = parent?.depth?.inc() ?: 0 } fun <E> Iterable<E>.updated(index: Int, elem: E) = mapIndexed { i, existing -> if (i == index) elem else existing } class CTSolver<CT>( private val singleAgentSolver: SingleAgentSolver<CT>, ) { fun solve(agents: List<Agent<CT>>): Result<ConstraintTreeNode<CT>> { val open = PriorityQueue(compareBy<ConstraintTreeNode<CT>> { it.cost }.thenBy { it.depth }) val root = createRootNode(agents) root.onSuccess { open.add(it) } var totalNodes = 0 while (!open.isEmpty()) { val curr = open.remove() totalNodes++ var final = true createChildren(curr, agents).forEach { open.add(it); final = false } if (final) return Result.success(curr) } return Result.failure(NotSolvable("Instance is not solvable")) } private fun createNode( agents: List<Agent<CT>>, parent: ConstraintTreeNode<CT>, index: Int, vertexConstraint: VertexConstraint<CT>?, edgeConstraint: EdgeConstraint<CT>?, ): Result<ConstraintTreeNode<CT>> { return singleAgentSolver.solve( agents[index], 0, parent.getVertexConstraints(agents[index].id).toHashSet() .also { set -> vertexConstraint?.let { set.add(it) } }, parent.getEdgeConstraints(agents[index].id).toHashSet().also { set -> edgeConstraint?.let { set.add(it) } }, ).map { val newSolutionSet = parent.solution.updated(index, it) ConstraintTreeNode(parent, vertexConstraint, edgeConstraint, agents[index].id, newSolutionSet, newSolutionSet.fold(0) { prev, path -> prev + path.size }) } } private fun createRootNode(agents: List<Agent<CT>>): Result<ConstraintTreeNode<CT>> { val solution: List<List<CT>> try { val raw = agents.map { singleAgentSolver.solve(it, 0, setOf(), setOf()).getOrThrow() } val solutionLength = raw.maxOf { it.size } solution = raw.map { it + generateSequence { it.last() }.take(solutionLength - it.size) } } catch (e: NotSolvable) { return Result.failure(NotSolvable("Not solvable")) } return Result.success( ConstraintTreeNode(parent = null, vertexConstraint = null, edgeConstraint = null, agentId = agents[0].id, solution = solution, cost = solution.fold(0) { prev, path -> prev + path.size }) ) } /** * Find conflicts by iterating through all paths and create child nodes for them. */ private fun createChildren( node: ConstraintTreeNode<CT>, agents: List<Agent<CT>> ): Sequence<ConstraintTreeNode<CT>> { val iterators = node.solution.map { it.iterator() }.withIndex() val mapNextOrLast = { its: Iterable<IndexedValue<Iterator<CT>>> -> its.map { (index, it) -> if (it.hasNext()) it.next() else node.solution[index].last() } } var n0 = mapNextOrLast(iterators) var step = 0 while (iterators.any { (_, it) -> it.hasNext() }) { val n1 = mapNextOrLast(iterators) for (indexA in n0.indices) { for (indexB in indexA + 1 until node.solution.size) { // check for vertex conflict if (n0[indexA] == n0[indexB]) { return sequence { // check if we're not creating a constraint for a finished agent // because the child node would never reach it if (step < node.solution[indexA].size) { createNode(agents, node, indexA, Pair(n0[indexA], step), null) .onSuccess { yield(it) } } if (step < node.solution[indexB].size) { createNode(agents, node, indexB, Pair(n0[indexB], step), null) .onSuccess { yield(it) } } } } // check for edge conflict if (n0[indexA] == n1[indexB] && n0[indexB] == n1[indexA]) { return sequence { if (step < node.solution[indexA].size) { createNode( agents, node, indexA, null, Pair(Pair(n0[indexA], n1[indexA]), step), ).onSuccess { yield(it) } } if (step < node.solution[indexB].size) { createNode( agents, node, indexB, null, Pair(Pair(n0[indexB], n1[indexB]), step), ).onSuccess { yield(it) } } } } } } n0 = n1 step++ } return emptySequence() } }
0
Kotlin
0
0
2ef0b766ab91087fb2b51d01e058c9fb2f6abbaf
6,930
mapf-cbs
MIT License
src/main/kotlin/heap/top_k_frequent/TopKFrequentElements.kt
Pawlllosss
526,668,214
false
{"Kotlin": 61939}
package heap.top_k_frequent import java.util.* fun topKFrequent(nums: IntArray, k: Int): IntArray { val frequencyByNumber = getFrequencyByNumber(nums) val numbersSortedByFrequency = PriorityQueue<Pair<Int, Int>> { pair1, pair2 -> pair2.first - pair1.first } frequencyByNumber.forEach { (key, value) -> numbersSortedByFrequency.add(value to key) } return (1..k).map { numbersSortedByFrequency.poll() } .map { it.second } .toIntArray() } fun topKFrequentWithMap(nums: IntArray, k: Int): IntArray { val frequencyByNumber = getFrequencyByNumber(nums) val numbersByFrequencySorted = frequencyByNumber.entries.groupBy({ it.value }, { it.key }).toSortedMap( compareByDescending { it }) return numbersByFrequencySorted.entries.take(k).flatMap { it.value }.take(k).toIntArray() } private fun getFrequencyByNumber(nums: IntArray): MutableMap<Int, Int> { val frequencyByNumber = mutableMapOf<Int, Int>() nums.forEach { if (frequencyByNumber.containsKey(it)) { frequencyByNumber.compute(it) { _, value -> value!! + 1 } } else { frequencyByNumber[it] = 1 } } return frequencyByNumber }
0
Kotlin
0
0
94ad00ca3e3e8ab7a2cb46f8846196ae7c55c8b4
1,197
Kotlin-algorithms
MIT License
kotlin/structures/FenwickTree2D.kt
polydisc
281,633,906
true
{"Java": 540473, "Kotlin": 515759, "C++": 265630, "CMake": 571}
package structures object FenwickTree2D { fun add(t: Array<IntArray>, r: Int, c: Int, value: Int) { var i = r while (i < t.size) { var j = c while (j < t[0].length) { t[i][j] += value j = j or j + 1 } i = i or i + 1 } } // sum[(0, 0), (r, c)] fun sum(t: Array<IntArray>, r: Int, c: Int): Int { var res = 0 var i = r while (i >= 0) { var j = c while (j >= 0) { res += t[i][j] j = (j and j + 1) - 1 } i = (i and i + 1) - 1 } return res } // sum[(r1, c1), (r2, c2)] fun sum(t: Array<IntArray>, r1: Int, c1: Int, r2: Int, c2: Int): Int { return sum(t, r2, c2) - sum(t, r1 - 1, c2) - sum(t, r2, c1 - 1) + sum(t, r1 - 1, c1 - 1) } operator fun get(t: Array<IntArray>, r: Int, c: Int): Int { return sum(t, r, c, r, c) } operator fun set(t: Array<IntArray>, r: Int, c: Int, value: Int) { add(t, r, c, -FenwickTree2D[t, r, c] + value) } // Usage example fun main(args: Array<String?>?) { val t = Array(10) { IntArray(20) } add(t, 0, 0, 1) add(t, 9, 19, -2) System.out.println(-1 == sum(t, 0, 0, 9, 19)) } }
1
Java
0
0
4566f3145be72827d72cb93abca8bfd93f1c58df
1,344
codelibrary
The Unlicense
2021/src/main/kotlin/Day03.kt
eduellery
433,983,584
false
{"Kotlin": 97092}
class Day03(private val input: List<String>) { private fun List<String>.bitwiseFilter(keepMostCommon: Boolean, width: Int): String = (0 until width).fold(this) { inputs, column -> if (inputs.size == 1) inputs else { val split = inputs.partition { it[column] == '1' } if (keepMostCommon) split.longest() else split.shortest() } }.first() fun solve1(): Int { val width = input.first().length val gamma = (0 until width).sumOf { column -> val columnValue = (width - column - 1).binaryColumnValue() if (input.count { it[column] == '1' } > input.size / 2) columnValue else 0 } val epsilon = width.maxBinaryValue() - gamma return gamma * epsilon } fun solve2(): Int { val width = input.first().length val o2 = input.bitwiseFilter(true, width).toInt(2) val c02 = input.bitwiseFilter(false, width).toInt(2) return o2 * c02 } }
0
Kotlin
0
1
3e279dd04bbcaa9fd4b3c226d39700ef70b031fc
1,010
adventofcode-2021-2025
MIT License
src/main/kotlin/com/github/ferinagy/adventOfCode/aoc2021/2021-24.kt
ferinagy
432,170,488
false
{"Kotlin": 787586}
package com.github.ferinagy.adventOfCode.aoc2021 import com.github.ferinagy.adventOfCode.println import com.github.ferinagy.adventOfCode.readInputLines import java.util.* fun main() { val input = readInputLines(2021, "24-input") println("Part1:") part1(input).println() println() println("Part2:") part2(input).println() } private fun part1(input: List<String>): Long { val opposites = getOpposites(input) val result = Array(14) { 0 } opposites.forEach { (index1, val1, index2, val2) -> if (val1 < val2) { result[index1] = 9 result[index2] = 9 - (val2 - val1) } else { result[index2] = 9 result[index1] = 9 - (val1 - val2) } } return result.joinToString(separator = "").toLong() } private fun part2(input: List<String>): Long { val opposites = getOpposites(input) val result = Array(14) { 0 } opposites.forEach { (index1, val1, index2, val2) -> if (val1 < val2) { result[index1] = 1 + (val2 - val1) result[index2] = 1 } else { result[index2] = 1 + (val1 - val2) result[index1] = 1 } } return result.joinToString(separator = "").toLong() } private fun getOpposites(input: List<String>): MutableList<Opposites> { val ops = input.windowed(18, step = 18).map { val willAdd = it[4].endsWith('1') val previousDiff = it[5].split(' ')[2].toInt() val thisDiff = it[15].split(' ')[2].toInt() InputOp(willAdd, if (willAdd) thisDiff else -previousDiff) } val stack = LinkedList<IndexedValue<InputOp>>() val opposites = mutableListOf<Opposites>() ops.withIndex().forEach { if (it.value.add) { stack.addFirst(it) } else { val other = stack.removeFirst() opposites += Opposites(it.index, it.value.value, other.index, other.value.value) } } return opposites } private data class InputOp(val add: Boolean, val value: Int) private data class Opposites(val index1: Int, val diff1: Int, val index2: Int, val diff2: Int)
0
Kotlin
0
1
f4890c25841c78784b308db0c814d88cf2de384b
2,143
advent-of-code
MIT License
gcj/y2020/kickstart_b/d.kt
mikhail-dvorkin
93,438,157
false
{"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408}
package gcj.y2020.kickstart_b import kotlin.math.pow private fun solve(): Double { val (w, h, x1, y1, x2, y2) = readInts() return solve(x1 - 1, y2 - 1, h) + solve(y1 - 1, x2 - 1, w) } private fun solve(x: Int, y: Int, h: Int): Double { if (y + 1 >= h) return 0.0 var res = 0.0 var c = 1.0 var p = x + y for (i in 0 until x) { res += c * (2.0).pow(-p) c *= x + y - i c /= i + 1 while (c < 1) { p++; c *= 2 } while (c > 1) { p--; c /= 2 } } return res } fun main() = repeat(readInt()) { println("Case #${it + 1}: ${solve()}") } private fun readLn() = readLine()!! private fun readInt() = readLn().toInt() private fun readStrings() = readLn().split(" ") private fun readInts() = readStrings().map { it.toInt() } operator fun <T> List<T>.component6(): T = get(5)
0
Java
1
9
30953122834fcaee817fe21fb108a374946f8c7c
784
competitions
The Unlicense
src/main/kotlin/com/github/solairerove/algs4/leprosorium/dynamic_programming/EditDistance.kt
solairerove
282,922,172
false
{"Kotlin": 251919}
package com.github.solairerove.algs4.leprosorium.dynamic_programming import kotlin.math.min fun main() { println(minDistance("horse", "ros")) // 3 println(minDistance("abc", "zabd")) // 2 } // O(nm) time | O(nm) space private fun minDistance(word1: String, word2: String): Int { val n1 = word1.length val n2 = word2.length val distance = List(n2 + 1) { MutableList(n1 + 1) { el -> el } } for (i in 0 until n2 + 1) { for (j in 0 until n1 + 1) { distance[i][j] = j } distance[i][0] = i } for (i in 1 until n2 + 1) { for (j in 1 until n1 + 1) { distance[i][j] = if (word2[i - 1] == word1[j - 1]) { distance[i - 1][j - 1] } else { 1 + min( distance[i - 1][j - 1], min( distance[i - 1][j], distance[i][j - 1] ) ) } } } return distance[n2][n1] }
1
Kotlin
0
3
64c1acb0c0d54b031e4b2e539b3bc70710137578
1,030
algs4-leprosorium
MIT License
src/main/kotlin/helpthebookseller/StockList.kt
borisskert
492,139,934
false
{"Kotlin": 11866}
package solution /** * https://www.codewars.com/kata/54dc6f5a224c26032800005c/train/kotlin */ object StockList { fun stockSummary(lstOfArt: Array<String>, lstOfCat: Array<String>): String { if (lstOfArt.isEmpty()) { return "" } val stock = lstOfArt .map(::readOne) .groupBy { it.category } .map { (key, value) -> StockItem(key, value.sumOf { it.quantity }) } .associateBy { it.category } return lstOfCat .map { stock[it] ?: StockItem(it, 0) } .joinToString(" - ") { "(${it.category} : ${it.quantity})" } } } data class StockItem(val category: String, val quantity: Int) { } val stockItemPattern = """([A-Z][A-Z0-9]+) ([0-9]+)""".toRegex() fun readOne(input: String): StockItem { val match = stockItemPattern.matchEntire(input) val groups = match!!.groups val category = groups[1]!!.value val quantity = groups[2]!!.value return StockItem(category.take(1), quantity.toInt()) }
0
Kotlin
0
0
0659b332819751d7d89a7cf5f8239d17b7245c28
1,114
kotlin-katas
MIT License
src/test/kotlin/ch/ranil/aoc/aoc2022/Day20.kt
stravag
572,872,641
false
{"Kotlin": 234222}
package ch.ranil.aoc.aoc2022 import ch.ranil.aoc.AbstractDay import org.junit.jupiter.api.Test import kotlin.math.abs import kotlin.test.assertEquals class Day20 : AbstractDay() { @Test fun part1Test() { assertEquals(3, compute1(testInput)) } @Test fun part1Puzzle() { assertEquals(11123, compute1(puzzleInput)) } @Test fun part2Test() { assertEquals(1623178306, compute2(testInput)) } @Test fun part2Puzzle() { assertEquals(4248669215955, compute2(puzzleInput)) } private fun compute1(input: List<String>): Int { val sequence = parse(input) sequence.mix() return listOf(1000, 2000, 3000).sumOf { sequence.getAfterZero(it) } } private fun compute2(input: List<String>): Long { val sequence = parse(input) val decryptionKey = 811589153L repeat(10) { sequence.mix(decryptionKey) } return listOf(1000, 2000, 3000).sumOf { sequence.getAfterZero(it) * decryptionKey } } private fun parse(input: List<String>): Sequence { return input.map { it.toInt() }.let { Sequence.build(it) } } private data class Sequence( val sequence: MutableList<Element>, val unprocessed: List<Element>, ) { fun mix(decryptionKey: Long = 1) { unprocessed.forEach { elementToMix -> val index = sequence.indexOf(elementToMix) mix(index, decryptionKey) } } private fun mix(index: Int, decryptionKey: Long = 1) { val endIndex = sequence.size - 1 val elementToMix = sequence[index] val numberToMix = (elementToMix.number * decryptionKey % endIndex).toInt() val newIndex = if (numberToMix < 0 && abs(numberToMix) >= index) { // wrap around left endIndex - abs(index - abs(numberToMix)) } else if (numberToMix > 0 && (index + numberToMix) >= endIndex) { // wrap around right index + numberToMix - endIndex } else { index + numberToMix } sequence.removeAt(index) sequence.add(newIndex, elementToMix) } fun getAfterZero(n: Int): Int { val zeroIndex = sequence.indexOfFirst { it.number == 0 } val index = (zeroIndex + n) % sequence.size return sequence[index].number } companion object { fun build(numbers: List<Int>): Sequence { val nodes = numbers.mapIndexed { index, i -> Element(i, index) } return Sequence( sequence = ArrayList(nodes), unprocessed = ArrayList(nodes), ) } } } private data class Element( val number: Int, private val id: Int, // ensures uniqueness ) }
0
Kotlin
1
0
dbd25877071cbb015f8da161afb30cf1968249a8
2,985
aoc
Apache License 2.0
src/Day06.kt
fasfsfgs
573,562,215
false
{"Kotlin": 52546}
fun String.findMarker(markerSize: Int) = windowed(markerSize) .first { window -> val repeatedChar = window.find { testedChar -> window.count { testedChar == it } > 1 } repeatedChar == null } fun main() { fun part1(input: String): Int { val marker = input.findMarker(4) return input.indexOf(marker) + marker.length } fun part2(input: String): Int { val marker = input.findMarker(14) return input.indexOf(marker) + marker.length } val testInput = readInputAsString("Day06_test") check(part1(testInput) == 7) check(part2(testInput) == 19) check(part1("bvwbjplbgvbhsrlpgdmjqwftvncz") == 5) check(part1("nppdvjthqldpwncqszvftbrmjlhg") == 6) check(part1("nznrnfrfntjfmvfwmzdfjlvtqnbhcprsg") == 10) check(part1("zcfzfwzzqfrljwzlrfnpqdbhtmscgvjw") == 11) check(part2("bvwbjplbgvbhsrlpgdmjqwftvncz") == 23) check(part2("nppdvjthqldpwncqszvftbrmjlhg") == 23) check(part2("nznrnfrfntjfmvfwmzdfjlvtqnbhcprsg") == 29) check(part2("zcfzfwzzqfrljwzlrfnpqdbhtmscgvjw") == 26) val input = readInputAsString("Day06") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
17cfd7ff4c1c48295021213e5a53cf09607b7144
1,199
advent-of-code-2022
Apache License 2.0
src/Day03.kt
tomoki1207
572,815,543
false
{"Kotlin": 28654}
fun main() { val types = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" fun part1(input: List<String>) = input.map { line -> val items = line.chunked(line.length / 2) items[0].toCharArray().intersect(items[1].toCharArray().toSet()) }.sumOf { shared -> shared.sumOf { types.indexOf(it) + 1 } } fun part2(input: List<String>) = input.chunked(3) .map { lines -> lines.map { it.toCharArray() }.fold(types.toCharArray().toSet()) { a, b -> a.intersect(b.toSet()) } }.sumOf { shared -> shared.sumOf { types.indexOf(it) + 1 } } val testInput = readInput("Day03_test") check(part1(testInput) == 157) check(part2(testInput) == 70) val input = readInput("Day03") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
2ecd45f48d9d2504874f7ff40d7c21975bc074ec
855
advent-of-code-kotlin-2022
Apache License 2.0
advent-of-code-2023/src/test/kotlin/Day8Test.kt
yuriykulikov
159,951,728
false
{"Kotlin": 1666784, "Rust": 33275}
import io.kotest.matchers.shouldBe import org.junit.jupiter.api.Test class Day8Test { private val testInput2 = """RL AAA = (BBB, CCC) BBB = (DDD, EEE) CCC = (ZZZ, GGG) DDD = (DDD, DDD) EEE = (EEE, EEE) GGG = (GGG, GGG) ZZZ = (ZZZ, ZZZ) """ private val testInput6 = """LLR AAA = (BBB, BBB) BBB = (AAA, ZZZ) ZZZ = (ZZZ, ZZZ) """ data class Node(val name: String, val left: String, val right: String) @Test fun `silver test (example)`() { countSteps(testInput2).shouldBe(2) countSteps(testInput6).shouldBe(6) } @Test fun `silver test`() { countSteps(loadResource("Day8")).shouldBe(12361) } @Test fun `gold test (example)`() { countStepsGhost( """LR 11A = (11B, XXX) 11B = (XXX, 11Z) 11Z = (11B, XXX) 22A = (22B, XXX) 22B = (22C, 22C) 22C = (22Z, 22Z) 22Z = (22B, 22B) XXX = (XXX, XXX)""") .shouldBe(6) } @Test fun `gold test`() { countStepsGhost(loadResource("Day8")).shouldBe(18215611419223) } private fun countSteps(input: String): Int { val (rl, map) = parseInput(input) return generateSequence { rl.toCharArray().asSequence() } .flatten() .scan(map.getValue("AAA")) { node, c -> if (c == 'L') map.getValue(node.left) else map.getValue(node.right) } .takeWhile { it.name != "ZZZ" } .count() } private fun countStepsGhost(input: String): Long { val (rl, map) = parseInput(input) val starts = map.values.filter { it.name.endsWith("A") } return starts .map { start -> generateSequence { rl.toCharArray().asSequence() } .flatten() .scan(start) { node, c -> if (c == 'L') map.getValue(node.left) else map.getValue(node.right) } .takeWhile { !it.name.endsWith("Z") } .count() .toLong() } .fold(1L) { acc, i -> lcm(acc, i) } } private fun lcm(a: Long, b: Long): Long { return a * b / gcd(a, b) } private fun gcd(a: Long, b: Long): Long { return if (b == 0L) a else gcd(b, a % b) } private fun parseInput(input: String): Pair<String, Map<String, Node>> { val rl = input.lines().first() val map = input .lines() .asSequence() .drop(2) .filterNot { it.isEmpty() } .map { val (name, children) = it.split(" = ") val (l, r) = children.replace("(", "").replace(")", "").split(", ") Node(name.trim(), l, r) } .associateBy { it.name } return Pair(rl, map) } }
0
Kotlin
0
1
f5efe2f0b6b09b0e41045dc7fda3a7565cb21db3
2,614
advent-of-code
MIT License
2020/src/main/kotlin/Day2.kt
osipxd
388,214,845
false
null
/** * # Day 2: Password Philosophy * * Your flight departs in a few days from the coastal airport; the easiest way down to the coast from here * is via [toboggan](https://en.wikipedia.org/wiki/Toboggan). * * The shopkeeper at the North Pole Toboggan Rental Shop is having a bad day. "Something's wrong with * our computers; we can't log in!" You ask if you can take a look. * * Their password database seems to be a little corrupted: some of the passwords wouldn't have been * allowed by the Official Toboggan Corporate Policy that was in effect when they were chosen. * * To try to debug the problem, they have created a list (your puzzle input) of **passwords** (according to the * corrupted database) and **the corporate policy when that password was set**. * * For example, suppose you have the following list: * ``` * 1-3 a: abcde * 1-3 b: cdefg * 2-9 c: ccccccccc * ``` * Each line gives the password policy and then the password. The password policy indicates the lowest * and highest number of times a given letter must appear for the password to be valid. For example, `1-3 a` * means that the password must contain `a` at least `1` time and at most `3` times. * * In the above example, `2` passwords are valid. The middle password, `<PASSWORD>`, is not; it contains no * instances of `b`, but needs at least `1`. The first and third passwords are valid: they contain one `a` or nine `c`, * both within the limits of their respective policies. * * **How many passwords are valid** according to their policies? * * --- Part Two --- * * While it appears you validated the passwords correctly, they don't seem to be what the Official * Toboggan Corporate Authentication System is expecting. * * The shopkeeper suddenly realizes that he just accidentally explained the password policy rules from his * old job at the sled rental place down the street! The Official Toboggan Corporate Policy actually works a * little differently. * * Each policy actually describes two **positions in the password**, where `1` means the first character, `2` * means the second character, and so on. (Be careful; Toboggan Corporate Policies have no concept of * "index zero"!) **Exactly one of these positions** must contain the given letter. Other occurrences of the * letter are irrelevant for the purposes of policy enforcement. * * Given the same example list from above: * - `1-3 a: abcde` is **valid**: position `1` contains `a` and position `3` does not. * - `1-3 b: cdefg` is **invalid**: neither position `1` nor position `3` contains `b`. * - `2-9 c: ccccccccc` is **invalid**: both position `2` and position `9` contain `c`. * * **How many passwords are valid** according to the new interpretation of the policies? * * *[Open in browser](https://adventofcode.com/2020/day/2)* */ object Day2 { // Complexity: O(n) fun part1(input: Sequence<Pair<Policy, String>>): Int { return input.count { (policy, password) -> password.count { it == policy.char } in policy.range } } // Complexity: O(n) fun part2(input: Sequence<Pair<Policy, String>>): Int { return input.count { (policy, password) -> val firstMatch = password[policy.num1 - 1] == policy.char val secondMatch = password[policy.num2 - 1] == policy.char firstMatch xor secondMatch } } fun parsePolicyAndPassword(line: String): Pair<Policy, String> { val (num1, num2, char, password) = line.split("-", " ", ": ") return Policy(num1.toInt(), num2.toInt(), char.single()) to password } data class Policy( val num1: Int, val num2: Int, val char: Char, ) { val range: IntRange get() = num1..num2 } }
0
Kotlin
0
0
66553923d8d221bcd1bd108f701fceb41f4d1cbf
3,781
advent-of-code
MIT License
kotlin/src/com/s13g/aoc/aoc2015/Day13.kt
shaeberling
50,704,971
false
{"Kotlin": 300158, "Go": 140763, "Java": 107355, "Rust": 2314, "Starlark": 245}
package com.s13g.aoc.aoc2015 import com.s13g.aoc.Result import com.s13g.aoc.Solver import com.s13g.aoc.resultFrom /** * --- Day 13: Knights of the Dinner Table --- * https://adventofcode.com/2015/day/13 */ class Day13 : Solver { override fun solve(lines: List<String>): Result { val diffs = mutableMapOf<Set<String>, Int>() val allNames = mutableSetOf<String>() for (splitLine in lines.map { it.split(" ") }) { val name = splitLine[0] val gain = splitLine[2] == "gain" val amount = splitLine[3].toInt() * if (gain) 1 else -1 val nextTo = splitLine[10].substring(0, splitLine[10].length - 1) val pair = setOf(name, nextTo) if (pair !in diffs) { diffs[pair] = amount } else { diffs[pair] = diffs[pair]!! + amount } allNames.add(name) } val scoreA = generateAllCombos(allNames).maxOf { getScore(it, diffs) } val scoreB = generateAllCombos(allNames.plus("Sascha")).maxOf { getScore(it, diffs) } return resultFrom(scoreA, scoreB) } private fun getScore(order: List<String>, diffs: Map<Set<String>, Int>): Int { return order.plusElement(order.first()).windowed(2, 1) .sumOf { diffs[setOf(it[0], it[1])] ?: 0 } } private fun generateAllCombos(names: Set<String>): List<List<String>> { val result = mutableListOf<List<String>>() if (names.size == 1) { return result.plusElement(listOf(names.first())) } for (name in names) { val remaining = names.minus(name) for (combo in generateAllCombos(remaining)) { result.add(combo.plusElement(name)) } } return result } }
0
Kotlin
1
2
7e5806f288e87d26cd22eca44e5c695faf62a0d7
1,643
euler
Apache License 2.0
src/main/kotlin/com/groundsfam/advent/y2023/d22/Day22.kt
agrounds
573,140,808
false
{"Kotlin": 281620, "Shell": 742}
package com.groundsfam.advent.y2023.d22 import com.groundsfam.advent.DATAPATH import com.groundsfam.advent.mapWithPutDefault import com.groundsfam.advent.rangeIntersect import com.groundsfam.advent.timed import java.util.TreeSet import kotlin.io.path.div import kotlin.io.path.useLines private data class Brick(val x: IntRange, val y: IntRange, val z: IntRange) private fun Brick.intersect(that: Brick): Brick? { val x = this.x.rangeIntersect(that.x) ?: return null val y = this.y.rangeIntersect(that.y) ?: return null val z = this.z.rangeIntersect(that.z) ?: return null return Brick(x, y, z) } private fun Brick.fall(): Brick = copy(z = z.first - 1..<z.last) private class Solution(bricks: List<Brick>) { private val settledBricks = TreeSet<Brick> { a, b -> fun Brick.attrList() = listOf(z.last, z.first, y.last, y.first, x.last, x.first) a.attrList() .zip(b.attrList()) .map { (a1, b1) -> a1 - b1 } .firstOrNull { it != 0 } ?: 0 } private val restsOn: Map<Brick, Set<Brick>> private val supports: Map<Brick, Set<Brick>> init { val _restsOn = mutableMapOf<Brick, MutableSet<Brick>>() val _supports: MutableMap<Brick, MutableSet<Brick>> by mapWithPutDefault { mutableSetOf() } bricks .sortedBy { it.z.first } .forEach { brick -> var prevStep: Brick? = null var fallingBrick = brick val hitBricks = mutableSetOf<Brick>() while (fallingBrick.z.first > 0 && hitBricks.isEmpty()) { prevStep = fallingBrick fallingBrick = fallingBrick.fall() // iterate through settled bricks in sorted order, highest to lowest val settledBricksIter = settledBricks.descendingIterator() var settledBrick = if (settledBricksIter.hasNext()) settledBricksIter.next() else null // stop iteration when the bricks are below the falling brick while (settledBrick != null && settledBrick.z.last >= fallingBrick.z.first) { if (settledBrick.intersect(fallingBrick) != null) { hitBricks.add(settledBrick) } settledBrick = if (settledBricksIter.hasNext()) settledBricksIter.next() else null } } if (prevStep == null) { throw RuntimeException("Brick $brick is in impossible position and cannot fall") } settledBricks.add(prevStep) _restsOn[prevStep] = hitBricks hitBricks.forEach { hitBrick -> _supports.getValue(hitBrick).add(prevStep) } } restsOn = _restsOn supports = _supports } fun safeBricks(): Int { val unsafeBricks = restsOn .values .mapNotNullTo(mutableSetOf()) { if (it.size == 1) it.first() else null } return settledBricks.size - unsafeBricks.size } fun chainReaction(): Int { var sum = 0 settledBricks.forEach { brick -> val removedBricks = mutableSetOf(brick) val queue = ArrayDeque<Brick>() queue.addAll(supports.getValue(brick)) while (queue.isNotEmpty()) { val nextBrick = queue.removeFirst() if (nextBrick !in removedBricks && restsOn[nextBrick]!!.all { it in removedBricks }) { sum++ removedBricks.add(nextBrick) queue.addAll(supports.getValue(nextBrick)) } } } return sum } } fun main() = timed { val solution = (DATAPATH / "2023/day22.txt").useLines { lines -> lines .mapTo(mutableListOf()) { line -> val (from, to) = line.split("~") val (fromX, fromY, fromZ) = from.split(",").map(String::toInt) val (toX, toY, toZ) = to.split(",").map(String::toInt) Brick(fromX..toX, fromY..toY, fromZ..toZ) } .let(::Solution) } println("Part one: ${solution.safeBricks()}") println("Part two: ${solution.chainReaction()}") }
0
Kotlin
0
1
c20e339e887b20ae6c209ab8360f24fb8d38bd2c
4,399
advent-of-code
MIT License
kotlin/src/com/s13g/aoc/aoc2022/Day2.kt
shaeberling
50,704,971
false
{"Kotlin": 300158, "Go": 140763, "Java": 107355, "Rust": 2314, "Starlark": 245}
package com.s13g.aoc.aoc2022 import com.s13g.aoc.Result import com.s13g.aoc.Solver import com.s13g.aoc.resultFrom /** * --- Day 2: Rock Paper Scissors --- * https://adventofcode.com/2022/day/2 */ class Day2 : Solver { override fun solve(lines: List<String>): Result { val beats = mapOf(1 to 3, 2 to 1, 3 to 2) val m1 = lines.sumBy { score1(it, beats) } val m2 = lines.sumBy { score2(it, beats) } return resultFrom(m1, m2) } private fun score1(play: String, beats: Map<Int, Int>): Int { val p1 = play[0].toInt() - 'A'.toInt() + 1 val p2 = play[2].toInt() - 'X'.toInt() + 1 return score(p1, p2, beats) } private fun score2(play: String, beats: Map<Int, Int>): Int { val p1 = play[0].toInt() - 'A'.toInt() + 1 val p2 = if (play[2] == 'Y') p1 else if (play[2] == 'X') beats[p1]!! else beats.filter { it.value == p1 }.map { it.key }.first() return score(p1, p2, beats) } private fun score(p1: Int, p2: Int, beats: Map<Int, Int>): Int = if (p1 == p2) 3 + p2 else if (beats[p1] == p2) p2 else 6 + p2 }
0
Kotlin
1
2
7e5806f288e87d26cd22eca44e5c695faf62a0d7
1,078
euler
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/LongestIncreasingPath.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2021 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import kotlin.math.max fun interface LongestIncreasingPath { operator fun invoke(grid: Array<IntArray>): Int } class LongestIncreasingPathDFS : LongestIncreasingPath { private val dirs = arrayOf(intArrayOf(0, 1), intArrayOf(1, 0), intArrayOf(0, -1), intArrayOf(-1, 0)) private var m = 0 private var n = 0 override operator fun invoke(grid: Array<IntArray>): Int { if (grid.isEmpty()) return 0 m = grid.size n = grid[0].size val cache = Array(m) { IntArray(n) } var ans = 0 for (i in 0 until m) for (j in 0 until n) ans = Math.max(ans, dfs(grid, i, j, cache)) return ans } private fun dfs(matrix: Array<IntArray>, i: Int, j: Int, cache: Array<IntArray>): Int { if (cache[i][j] != 0) return cache[i][j] for (d in dirs) { val x = i + d[0] val y = j + d[1] if (x in 0 until m && 0 <= y && y < n && matrix[x][y] > matrix[i][j]) { cache[i][j] = max(cache[i][j], dfs(matrix, x, y, cache)) } } return ++cache[i][j] } } class LongestIncreasingPathPeelingOnion : LongestIncreasingPath { private val dir = arrayOf(intArrayOf(0, 1), intArrayOf(1, 0), intArrayOf(0, -1), intArrayOf(-1, 0)) override operator fun invoke(grid: Array<IntArray>): Int { var m: Int = grid.size if (m == 0) return 0 var n: Int = grid[0].size val matrix = Array(m + 2) { IntArray(n + 2) } for (i in 0 until m) System.arraycopy(grid[i], 0, matrix[i + 1], 1, n) val outdegree = Array(m + 2) { IntArray(n + 2) } for (i in 1..m) { for (j in 1..n) { for (d in dir) { if (matrix[i][j] < matrix[i + d[0]][j + d[1]]) { outdegree[i][j]++ } } } } n += 2 m += 2 var leaves: MutableList<IntArray> = ArrayList() for (i in 1 until m - 1) { for (j in 1 until n - 1) { if (outdegree[i][j] == 0) { leaves.add(intArrayOf(i, j)) } } } var height = 0 while (leaves.isNotEmpty()) { height++ val newLeaves: MutableList<IntArray> = ArrayList() for (node in leaves) { for (d in dir) { val x = node[0] + d[0] val y = node[1] + d[1] if (matrix[node[0]][node[1]] > matrix[x][y] && --outdegree[x][y] == 0) { newLeaves.add(intArrayOf(x, y)) } } } leaves = newLeaves } return height } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
3,393
kotlab
Apache License 2.0
day12/src/main/kotlin/ver_b.kt
jabbalaci
115,397,721
false
null
package b import java.io.File object Groups { /* A feltárt csoportokat egy listában tároljuk. A lista elemei halmazok, ezek a halmazok az egyes csoportok. */ private val groups = mutableListOf<Set<Int>>() /* Ha a start pl. 0, akkor elindul a 0-tól, s feltárja, hogy a linkeket követve mely csúcsokhoz lehet eljutni. Az eredményt egy halmazban adja vissza. */ fun findGroupOf(start: Int, map: Map<Int, List<Int>>): Set<Int> { val bag = mutableSetOf(start) // init val li = mutableListOf(start) // init var i = 0 while (i < li.size) { val currValue = li[i] for (n in map[currValue]!!) { if (n !in bag) { li.add(n) bag.add(n) } } ++i } return bag.toSet() // immutable } /* Hány db csoportot találtunk. */ fun numberOfGroups() = this.groups.size /* Kapunk egy kulcsot, ami egy kezdőpozíció. Ha ez a kulcs már szerepel vmelyik feltárt coportban, akkor nem foglalkozunk vele. Ha még nem szerepel, akkor feltárjuk a hozzá tartozó csoportot. */ fun exploreGroupOf(key: Int, map: Map<Int, List<Int>>) { if (this.isKeyInAnyGroup(key) == false) { val group = this.findGroupOf(key, map) this.groups.add(group) } } /* Az adott kulcs szerepel-e már vmelyik feltárt csoportban? */ private fun isKeyInAnyGroup(key: Int): Boolean { for (group in this.groups) { if (key in group) { return true } } return false } } fun main(args: Array<String>) { // val fname = "example.txt" val fname = "input.txt" val map = readFile(fname) /* Megyünk végig a kulcsokon, s feltárjuk (és letároljuk) a csoportokat. */ for (key in map.keys) { Groups.exploreGroupOf(key, map) } println(Groups.numberOfGroups()) } fun readFile(fname: String): Map<Int, List<Int>> { val map = mutableMapOf<Int, List<Int>>() File(fname).forEachLine { line -> val parts = line.split("<->") val key = parts[0].trim().toInt() val value = parts[1].split(",").map { it.trim().toInt() } map[key] = value } return map }
0
Kotlin
0
0
bce7c57fbedb78d61390366539cd3ba32b7726da
2,410
aoc2017
MIT License
src/year2022/day23/Day23.kt
lukaslebo
573,423,392
false
{"Kotlin": 222221}
package year2022.day23 import check import readInput fun main() { // test if implementation meets criteria from the description, like: val testInput = readInput("2022", "Day23_test") check(part1(testInput), 110) check(part2(testInput), 20) val input = readInput("2022", "Day23") println(part1(input)) println(part2(input)) } private fun part1(input: List<String>): Int { val (positions, _) = getPositionsAndRoundsAfterStableDiffusion(input, 10) val minX = positions.minOf { it.x } val maxX = positions.maxOf { it.x } val minY = positions.minOf { it.y } val maxY = positions.maxOf { it.y } return (maxX - minX + 1) * (maxY - minY + 1) - positions.size } private fun part2(input: List<String>): Int { val (_, rounds) = getPositionsAndRoundsAfterStableDiffusion(input) return rounds } private fun getPositionsAndRoundsAfterStableDiffusion( input: List<String>, maxRounds: Int = Int.MAX_VALUE ): Pair<Set<Pos>, Int> { val positions = parseElfPositions(input).toMutableSet() var round = 1 while (round <= maxRounds) { val nextByElf = positions.associateWith { elf -> when (round % 4) { 1 -> when { elf.surroundingPositions.none { it in positions } -> elf elf.northernPositions.none { it in positions } -> Pos(elf.x, elf.y - 1) elf.southernPositions.none { it in positions } -> Pos(elf.x, elf.y + 1) elf.westernPositions.none { it in positions } -> Pos(elf.x - 1, elf.y) elf.easternPositions.none { it in positions } -> Pos(elf.x + 1, elf.y) else -> elf } 2 -> when { elf.surroundingPositions.none { it in positions } -> elf elf.southernPositions.none { it in positions } -> Pos(elf.x, elf.y + 1) elf.westernPositions.none { it in positions } -> Pos(elf.x - 1, elf.y) elf.easternPositions.none { it in positions } -> Pos(elf.x + 1, elf.y) elf.northernPositions.none { it in positions } -> Pos(elf.x, elf.y - 1) else -> elf } 3 -> when { elf.surroundingPositions.none { it in positions } -> elf elf.westernPositions.none { it in positions } -> Pos(elf.x - 1, elf.y) elf.easternPositions.none { it in positions } -> Pos(elf.x + 1, elf.y) elf.northernPositions.none { it in positions } -> Pos(elf.x, elf.y - 1) elf.southernPositions.none { it in positions } -> Pos(elf.x, elf.y + 1) else -> elf } 0 -> when { elf.surroundingPositions.none { it in positions } -> elf elf.easternPositions.none { it in positions } -> Pos(elf.x + 1, elf.y) elf.northernPositions.none { it in positions } -> Pos(elf.x, elf.y - 1) elf.southernPositions.none { it in positions } -> Pos(elf.x, elf.y + 1) elf.westernPositions.none { it in positions } -> Pos(elf.x - 1, elf.y) else -> elf } else -> error("!") } } val moves = nextByElf.entries.groupBy { it.value }.entries .filter { it.value.size == 1 } .map { it.value.first() } .filter { it.key != it.value } if (moves.isEmpty()) break moves.forEach { move -> val (from, to) = move positions -= from positions += to } round++ } return positions to round } private data class Pos(val x: Int, val y: Int) { val surroundingPositions get() = setOf( Pos(x - 1, y - 1), Pos(x, y - 1), Pos(x + 1, y - 1), Pos(x + 1, y), Pos(x + 1, y + 1), Pos(x, y + 1), Pos(x - 1, y + 1), Pos(x - 1, y), ) val northernPositions get() = setOf(Pos(x - 1, y - 1), Pos(x, y - 1), Pos(x + 1, y - 1)) val southernPositions get() = setOf(Pos(x - 1, y + 1), Pos(x, y + 1), Pos(x + 1, y + 1)) val westernPositions get() = setOf(Pos(x - 1, y - 1), Pos(x - 1, y), Pos(x - 1, y + 1)) val easternPositions get() = setOf(Pos(x + 1, y - 1), Pos(x + 1, y), Pos(x + 1, y + 1)) } private fun parseElfPositions(input: List<String>): Set<Pos> { val positions = mutableSetOf<Pos>() input.forEachIndexed { y, line -> line.forEachIndexed { x, c -> if (c == '#') positions += Pos(x, y) } } return positions }
0
Kotlin
0
1
f3cc3e935bfb49b6e121713dd558e11824b9465b
4,767
AdventOfCode
Apache License 2.0
app/src/main/java/com/softaai/dsa_kotlin/graph/dijkstra/Dijkstra.kt
amoljp19
537,774,597
false
{"Kotlin": 139041}
package com.softaai.dsa_kotlin.graph.dijkstra import com.softaai.dsa_kotlin.graph.Edge import com.softaai.dsa_kotlin.graph.Graph import com.softaai.dsa_kotlin.graph.Vertex import com.softaai.dsa_kotlin.graph.adjacencylist.AdjacencyListGraph import com.softaai.dsa_kotlin.priorityqueue.ComparatorPriorityQueueImpl /** * Created by amoljp19 on 12/3/2022. * softAai Apps. */ class Dijkstra(){ // to back track path fun <T> route(destination : Vertex<T>, paths : HashMap<Vertex<T>, Visit<T>>) : ArrayList<Edge<T>>{ var vertex = destination val path = arrayListOf<Edge<T>>() loop@ while (true){ val visit = paths[vertex] ?: break when(visit.visitType){ VisitType.EDGE -> visit.edge?.let{ path.add(it) vertex = it.source } VisitType.START -> break@loop } } return path } fun <T> distance(destination : Vertex<T>, paths : HashMap<Vertex<T>, Visit<T>>) : Double{ val path = route(destination, paths) return path.sumOf { it.weight ?: 0.0 } } fun <T> shortestPath(start : Vertex<T>, graph : AdjacencyListGraph<T>) : HashMap<Vertex<T>, Visit<T>> { val paths = HashMap<Vertex<T>, Visit<T>>() paths[start] = Visit(VisitType.START) val distanceComparator = Comparator<Vertex<T>>(){first, second -> (distance(second, paths) - distance(first, paths)).toInt() } val priorityQueue = ComparatorPriorityQueueImpl<Vertex<T>>(distanceComparator) priorityQueue.enqueue(start) while (true){ val vertex = priorityQueue.dequeue() ?: break val edges = graph.edges(vertex) edges.forEach { val weight = it.weight ?: return@forEach if (paths[it.destination] == null || distance(vertex, paths) + weight < distance(it.destination, paths)){ paths[it.destination] = Visit(VisitType.EDGE, it) priorityQueue.enqueue(it.destination) } } } return paths } fun <T> shortestPath(destination: Vertex<T>, paths: HashMap<Vertex<T>, Visit<T>>) : ArrayList<Edge<T>>{ return route(destination, paths) } // Challenge 1 - Add a method to class Dijkstra that returns a dictionary of all the shortest paths to //all vertices given a starting vertex. fun <T> getAllShortestPath(source: Vertex<T>, graph : AdjacencyListGraph<T>): HashMap<Vertex<T>, ArrayList<Edge<T>>> { val paths = HashMap<Vertex<T>, ArrayList<Edge<T>>>() val pathsFromSource = shortestPath(source, graph) graph.allVertices.forEach { val path = shortestPath(it, pathsFromSource) paths[it] = path } return paths } } class Visit<T>(val visitType : VisitType, val edge : Edge<T>? = null) enum class VisitType{ START, EDGE }
0
Kotlin
0
1
3dabfbb1e506bec741aed3aa13607a585b26ac4c
3,016
DSA_KOTLIN
Apache License 2.0
aoc_2023/src/main/kotlin/problems/day22/SandBrickSimulator.kt
Cavitedev
725,682,393
false
{"Kotlin": 228779}
package problems.day22 class SandBrickSimulator(lines: List<String>) { var bricks = lines.map { line -> val (coord1, coord2) = line.split("~").map { coordStr -> val splitCoord = coordStr.split(",").map { it.toLong() } Coordinate(splitCoord[0], splitCoord[1], splitCoord[2]) } return@map Brick(coord1, coord2) } fun fallBricks() { val reorderedBricks = bricks.sortedBy { it.minZ() } val minX = reorderedBricks.minOf { it.minX() } val minY = reorderedBricks.minOf { it.minY() } val maxX = reorderedBricks.maxOf { it.maxX() } val maxY = reorderedBricks.maxOf { it.maxY() } val floorMap = mutableMapOf<Pair<Long, Long>, Floor>() for (x in minX..maxX) { for (y in minY..maxY) { floorMap[Pair(x, y)] = Floor(0, null) } } for (brick in reorderedBricks) { if (brick.isVertical()) { val floor = floorMap[Pair(brick.startCord.x, brick.startCord.y)]!! val difToFloor = brick.minZ() - floor.z - 1 brick.startCord.z -= difToFloor brick.endCoordinate.z -= difToFloor floor.addBrick(brick) floor.brick = brick floor.z = brick.maxZ() } else { val positions = brick.positions() val floors = positions.map { pos -> floorMap[Pair(pos.x, pos.y)]!! } val maxZFloor = floors.maxOf { it.z } // val touchingFloors = floors.filter { it.z == maxZFloor } val brickZ = maxZFloor + 1 brick.startCord.z = brickZ brick.endCoordinate.z = brickZ // for (floor in touchingFloors) { // // } for (floor in floors) { if (floor.z == maxZFloor) { floor.addBrick(brick) } floor.brick = brick floor.z = brickZ } } } this.bricks = reorderedBricks } fun countBricksCanBeDisintegrated(): Int { return this.bricks.count { it.canBeDisintegrated() } } fun sumFallIfDisintegrate(): Int { return this.bricks.sumOf { it.amountThatWouldFallIfDisintegrate() } } }
0
Kotlin
0
1
aa7af2d5aa0eb30df4563c513956ed41f18791d5
2,415
advent-of-code-2023
MIT License
src/main/kotlin/dev/bogwalk/batch3/Problem40.kt
bog-walk
381,459,475
false
null
package dev.bogwalk.batch3 import kotlin.math.pow /** * Problem 40: Champernowne's Constant * * https://projecteuler.net/problem=40 * * Goal: Calculate the value of the expression d_i1 * d_i2 * .. d_i7 if d_in represents the nth * digit of the fractional part of Champernowne's Constant. * * Constraints: 1 <= i1..i7 <= 1e18 * * Champernowne's Constant: The irrational decimal fraction created by concatenating all positive * integers to the right of a decimal point, such that: * * C = 0.123456789101112131415161718192021... * * e.g.: i1..i7 = 1 2 3 4 5 6 7 * expression = 1 * 2 * 3 * 4 * 5 * 6 * 7 * result = 5040 */ class ChampernownesConstant { // increase efficiency by pre-computing magnitudes & amount of digits in all series private val magnitudes = List(17) { e -> (10.0).pow(e).toLong() } private val kDigits = List(17) { k -> (k + 1) * 9 * magnitudes[k] } /** * N.B. At upper constraints, using a classic for-loop resulted in a better speed performance * of 1.4e5ns compared to a speed of 2.59ms when map() & fold() are called on [digits]. */ fun champernownesProduct(digits: List<Long>): Int { var product = 1 for (digit in digits) { product *= getConstant(digit) } return product } /** * Assuming that the positive integers of Champernowne's Constant are separated into series * representing the number of digits of each successive integer, k, and the range of each * series is calculated by [10^(k-1), (10^k) - 1], then each series will have 9 * 10^(k-1) * terms and, thereby, a total of k * 9 * 10^(k-1) digits. * * The cumulative total digits per series can be used to determine in which series range the * requested [index] sits as well as its position in the series. * * e.g. Searching for the 2000th digit in Champernowne's Constant (C): * * - 2000 - 180 - 9 = 1811 < 2700. * * - Therefore, it is found in the 1811th digit in series 3. * * - 1811 is first zero-indexed (as C does not start with 0). * * - As series 3 has 3 digits in every term, 1810 / 3 gives the location of the 1810th digit * as being in the 603rd term -> 100 + 603 = 703. * * - 1810 % 3 = 1, so the 1810th digit is at index 1 of 703. * * - Therefore, the 2000th digit in C is 0. */ fun getConstant(index: Long): Int { var k = 1 var i = index while (i > kDigits[k - 1]) { // final reduced i represents the ith digit in the kth series i -= kDigits[k - 1] k++ } i -= 1 // zero-indexed // kTerm represents the ordinal position in the series // termI represents the index of the digit within the term found below val kTerm = i / k val termI = (i % (1L * k)).toInt() val term = (magnitudes[k - 1] + kTerm).toString() return term[termI].digitToInt() } }
0
Kotlin
0
0
62b33367e3d1e15f7ea872d151c3512f8c606ce7
3,016
project-euler-kotlin
MIT License
src/algorithmsinanutshell/networkflow/FordFulkersonAlgorithm.kt
realpacific
234,499,820
false
null
package algorithmsinanutshell.networkflow import kotlin.test.assertEquals /** * Algorithm to find the max flow to the sink in a given [network] * * https://brilliant.org/wiki/ford-fulkerson-algorithm/ * * https://www.youtube.com/watch?v=NwenwITjMys * * O(E*mf) where E=edge, mf=value of max flow */ class FordFulkersonAlgorithm(private val network: Network) { init { network.validate() } private fun getPath(from: NVertex, to: NVertex, visitedEdge: MutableSet<Pair<NEdge, Int>>): Set<Pair<NEdge, Int>>? { if (from == to) { return visitedEdge } val edges = from.edges for (edge in edges) { val residualCapacity = edge.capacity - edge.flow // Ignore path if residual capacity is not remaining if (residualCapacity > 0 && !visitedEdge.contains(Pair(edge, residualCapacity))) { // Record the current edge along with residual capacity. The minimum residual capacity is added to flow of whole path visitedEdge.add(Pair(edge, residualCapacity)) val result = getPath(edge.end, to, visitedEdge) if (result != null) { // The minimum residual capacity of all edges in current path is added to flow of whole path // Increment flow in current edge edge.flow += visitedEdge.minOf { it.second } return result } } } return null } fun calculateMaxFlow(): Int { val source = network.source val sink = network.sink var path: Set<Pair<NEdge, Int>>? // Keep looping since the path may have remaining residual capacity even after visiting it do { path = getPath(source, sink, mutableSetOf()) } while (path != null) network.vertices.forEach(::println) var totalFlow = 0 network.vertices.forEach { vertex -> totalFlow += vertex.edges.filter { it.end == network.sink }.sumBy { it.flow } } return totalFlow } } fun main() { network1() network2() } private fun network1() { val network = Network() val s = network.add('S') val a = network.add('A') val b = network.add('B') val c = network.add('C') val d = network.add('D') val t = network.add('T') network.source = s network.sink = t s.connect(a, 4) s.connect(c, 3) a.connect(b, 4) b.connect(c, 3) b.connect(t, 2) c.connect(d, 6) d.connect(t, 6) assertEquals(7, FordFulkersonAlgorithm(network).calculateMaxFlow()) } private fun network2() { val network = Network() val s = network.add('S') val a = network.add('A') val b = network.add('B') val c = network.add('C') val d = network.add('D') val t = network.add('T') network.source = s network.sink = t s.connect(a, 3) s.connect(b, 2) a.connect(c, 2) a.connect(d, 2) b.connect(c, 2) b.connect(d, 3) c.connect(t, 3) d.connect(t, 2) assertEquals(5, FordFulkersonAlgorithm(network).calculateMaxFlow()) }
4
Kotlin
5
93
22eef528ef1bea9b9831178b64ff2f5b1f61a51f
3,190
algorithms
MIT License
src/main/java/com/booknara/problem/union/NumberOfProvincesKt.kt
booknara
226,968,158
false
{"Java": 1128390, "Kotlin": 177761}
package com.booknara.problem.union /** * 547. Number of Provinces (Medium) * https://leetcode.com/problems/number-of-provinces/ */ class NumberOfProvincesKt { // T:O(n*n*logn), S:O(n) fun findCircleNum(isConnected: Array<IntArray>): Int { // input check val n = isConnected.size val roots = IntArray(n) { i -> i } val weights = IntArray(n) { 1 } // can be better using negative value of roots var count = isConnected.size for (i in isConnected.indices) { for (j in isConnected[i].indices) { if (i < j && isConnected[i][j] == 1) { val root1 = findRoot(roots, i) // i -> root1 val root2 = findRoot(roots, j) // j -> root2 if (root1 != root2) { // point smaller sized tree to root of larger, update size if (weights[root1] < weights[root2]) { roots[root1] = root2 weights[j] += weights[i] } else { roots[root2] = root1 weights[i] += weights[j] } count-- } } } } return count } fun findRoot(roots: IntArray, idx: Int): Int { var index = idx while (roots[index] != index) { roots[index] = roots[roots[index]] // path compression index = roots[index] } return index } }
0
Java
1
1
04dcf500ee9789cf10c488a25647f25359b37a53
1,329
playground
MIT License
Kotlin/src/main/kotlin/org/algorithm/problems/0011_evaluate_division.kt
raulhsant
213,479,201
true
{"C++": 1035543, "Kotlin": 114509, "Java": 27177, "Python": 16568, "Shell": 999, "Makefile": 187}
//Problem Statement // Equations are given in the format A / B = k, where A and B are variables // represented as strings, and k is a real number (floating point number). // Given some queries, return the answers. If the answer does not exist, return -1.0. // // Example: // Given a / b = 2.0, b / c = 3.0. // queries are: a / c = ?, b / a = ?, a / e = ?, a / a = ?, x / x = ? . // return [6.0, 0.5, -1.0, 1.0, -1.0 ]. package org.algorithm.problems import java.util.ArrayDeque; class `0011_evaluate_division` { fun calcEquation(equations: Array<Array<String>>, values: DoubleArray, queries: Array<Array<String>>): DoubleArray { val graph = HashMap<String, ArrayList<Pair<String, Double>>>(); val result: MutableList<Double> = mutableListOf<Double>(); var numerator: String = ""; var denominator: String = ""; var value: Double = 1.0; for (i in equations.indices) { numerator = equations[i][0]; denominator = equations[i][1]; value = values[i]; if (!graph.contains(numerator)) { graph.put(numerator, arrayListOf<Pair<String, Double>>()); } graph[numerator]!!.add(Pair(denominator, value)); if (!graph.contains(denominator)) { graph.put(denominator, arrayListOf<Pair<String, Double>>()); } graph[denominator]!!.add(Pair(numerator, 1 / value)); } for (querie in queries) { numerator = querie[0]; denominator = querie[1]; if (!graph.contains(numerator) || !graph.contains(denominator)) { result.add(-1.0); } else if (numerator == denominator) { result.add(1.0); } else { val bfs = ArrayDeque<Pair<String, Double>>(); val visited = HashSet<String>(); var found: Boolean = false; bfs.add(Pair(numerator, 1.0)); while (!bfs.isEmpty() && !found) { val vertex: Pair<String, Double> = bfs.pollFirst(); if (!visited.contains(vertex.first)) { visited.add(vertex.first); for (connections in graph[vertex.first].orEmpty()) { if (connections.first == denominator) { result.add(connections.second * vertex.second); found = true; break; } else { bfs.add(Pair(connections.first, vertex.second * connections.second)); } } } } if (!found) { result.add(-1.0); } } } return result.toDoubleArray(); } }
0
C++
0
0
1578a0dc0a34d63c74c28dd87b0873e0b725a0bd
2,919
algorithms
MIT License
src/main/kotlin/wk271/Problem3.kt
yvelianyk
405,919,452
false
{"Kotlin": 147854, "Java": 610}
package wk271 fun main() { // val res = Problem3().minimumRefill(intArrayOf(2,2,3,3), 5 ,5) // val res = Problem3().minimumRefill(intArrayOf(2,2,3,3), 3 ,4) val res = Problem3().minimumRefill(intArrayOf(2, 2, 5, 2, 2), 5, 5) println(res) } class Problem3 { fun minimumRefill(plants: IntArray, capacityA: Int, capacityB: Int): Int { var aliceCur = 0 var bobCur = plants.size - 1 var aliceCurCapacity = capacityA var bobCurCapacity = capacityB var result = 0 while (aliceCur <= bobCur) { if (aliceCur == bobCur) { if (bobCurCapacity > aliceCurCapacity) { if (plants[bobCur] <= bobCurCapacity) { bobCurCapacity -= plants[bobCur] } else { result++ } } else { if (plants[aliceCur] <= aliceCurCapacity) { aliceCurCapacity -= plants[aliceCur] } else { result++ } } return result } if (plants[aliceCur] <= aliceCurCapacity) { aliceCurCapacity -= plants[aliceCur] } else { result++ aliceCurCapacity = capacityA aliceCurCapacity -= plants[aliceCur] } if (plants[bobCur] <= bobCurCapacity) { bobCurCapacity -= plants[bobCur] } else { result++ bobCurCapacity = capacityB bobCurCapacity -= plants[bobCur] } aliceCur++ bobCur-- } return result } }
0
Kotlin
0
0
780d6597d0f29154b3c2fb7850a8b1b8c7ee4bcd
1,752
leetcode-kotlin
MIT License
src/main/kotlin/com/hj/leetcode/kotlin/problem148/Solution2.kt
hj-core
534,054,064
false
{"Kotlin": 619841}
package com.hj.leetcode.kotlin.problem148 import com.hj.leetcode.kotlin.common.model.ListNode /** * LeetCode page: [148. Sort List](https://leetcode.com/problems/sort-list/); */ class Solution2 { /* Complexity: * Time O(NLogN) and Space O(1) where N is the number of nodes in head; */ fun sortList(head: ListNode?): ListNode? { val dummyHead = ListNode(-1).also { it.next = head } var currSplitSize = 1 var mergeSortNotDone = true while (mergeSortNotDone) { val numSubListPairs = performSubMergeSortAndReturnNumSubListPairs(dummyHead, currSplitSize) mergeSortNotDone = numSubListPairs > 1 currSplitSize = currSplitSize shl 1 } return dummyHead.next } private fun performSubMergeSortAndReturnNumSubListPairs( listWithDummyHead: ListNode, splitSize: Int ): Int { var numSubListPairs = 0 var currTail = listWithDummyHead var headOfNextSubListPair = currTail.next while (headOfNextSubListPair != null) { val head1 = headOfNextSubListPair val tail1 = head1.getNthNode(splitSize) val head2 = tail1?.next val tail2 = head2.getNthNode(splitSize) headOfNextSubListPair = tail2?.next tail1?.next = null tail2?.next = null currTail = addMergedSortedToTailAndReturnNewTail(head1, head2, currTail) numSubListPairs++ } return numSubListPairs } private fun ListNode?.getNthNode(n: Int): ListNode? { require(n > 0) { "Require n to start at 1, i.e. head is the first node." } var currNode = this var count = 1 while (count < n && currNode != null) { currNode = currNode.next count++ } return currNode } private fun addMergedSortedToTailAndReturnNewTail( sorted1: ListNode?, sorted2: ListNode?, tail: ListNode ): ListNode { var currTail = tail var ptr1 = sorted1 var ptr2 = sorted2 while (ptr1 != null && ptr2 != null) { if (ptr1.`val` < ptr2.`val`) { currTail.next = ptr1 ptr1 = ptr1.next } else { currTail.next = ptr2 ptr2 = ptr2.next } currTail = checkNotNull(currTail.next) } currTail.next = ptr1 ?: ptr2 return currTail.last() } private fun ListNode.last(): ListNode { var currNode = this while (currNode.next != null) { currNode = checkNotNull(currNode.next) } return currNode } }
1
Kotlin
0
1
14c033f2bf43d1c4148633a222c133d76986029c
2,730
hj-leetcode-kotlin
Apache License 2.0
src/main/day16/State.kt
ollehagner
572,141,655
false
{"Kotlin": 80353}
package day16 import java.lang.IllegalArgumentException import java.lang.IllegalStateException data class State(val openers: List<ValveOpener>, val valves: List<Valve>) { fun potentialMax(timeLimit: Int, distances: Map<Pair<String, String>, Int>): Int { var remainingTime = (timeLimit * openers.size) - openers.sumOf { it.elapsedTime } return releasedPressure(timeLimit) + valves .filter { it.closed() } .sortedByDescending { it.flowRate } .map { it to (openers.minOfOrNull { opener -> distances[opener.position to it.id]!! } ?: throw IllegalStateException( "Invalid distance map" )) } .takeWhile { (_, distance) -> remainingTime -= distance remainingTime > 0 } .sumOf { (valve, distance) -> valve.open(openers.first().elapsedTime + distance).releasedPressure(timeLimit) } } fun openedValves(): Set<String> { return this.valves.filter { it.opened }.map { it.id }.toSet() } fun openerAtValve(id: String): ValveOpener { return openers.firstOrNull { it.position == id } ?: throw IllegalArgumentException("No opener at valve $id") } fun valve(id: String): Valve { return valves.firstOrNull { it.id == id } ?: throw IllegalArgumentException("No valve at valve $id") } fun score(): Int { return currentRelease() / openers.sumOf { it.elapsedTime } } fun releasedPressure(timeLimit: Int): Int { return valves .filter { it.opened } .sumOf { it.releasedPressure(timeLimit) } } fun currentRelease(): Int { return valves.filter { it.opened } .sumOf { it.flowRate } } fun openValves(actions: List<OpenValveAction>): State { return actions.toSet() .fold(this) { acc, action -> acc.openValve(action) } } private fun openValve(action: OpenValveAction): State { val opener = openerAtValve(action.from) val newOpener = opener.openValve(action.to, action.time + 1) val openedValve = valves.first { it.id == action.to }.open(newOpener.elapsedTime) val newValves = valves .filter { it.id != openedValve.id } .fold(mutableListOf(openedValve)) { acc, valve -> acc.add(valve) acc } return copy( openers = openers.filter { it != opener } + newOpener, valves = newValves ) } }
0
Kotlin
0
0
6e12af1ff2609f6ef5b1bfb2a970d0e1aec578a1
2,581
aoc2022
Apache License 2.0
src/day10/Day10.kt
IThinkIGottaGo
572,833,474
false
{"Kotlin": 72162}
package day10 import addOrSet import getOrAdd import readInput fun main() { val testInput = readInput("day10_test") check(resolve(testInput, true, 20, 60, 100, 140, 180, 220) == 13140) println() val input = readInput("day10") println(resolve(input, true, 20, 60, 100, 140, 180, 220)) // FBURHZCH } fun resolve(input: List<String>, printMode: Boolean, vararg cycles: Int): Int { var register = 1 var currentCycles = 0 var remainCycles: Int var result = 0 val drawPoints = mutableListOf<String>() input.forEach { line -> val (inst, args) = line.split(" ").run { Pair(this[0], this.getOrNull(1)?.toInt() ?: 0) } remainCycles = getRemainCycles(inst) while (remainCycles != 0) { ++currentCycles printPreProcess(currentCycles, register, drawPoints) // register process part --remainCycles if (currentCycles in cycles) { result += register * currentCycles } if (remainCycles == 0 && inst == "addx") register += args } } doPrint(printMode, drawPoints) return result } private fun getRemainCycles(inst: String) = when (inst) { "addx" -> 2 "noop" -> 1 else -> error("unknown instructions.") } private fun printPreProcess(currentCycles: Int, register: Int, drawPoints: MutableList<String>) { val drawPosition = currentCycles - 1 if ((drawPosition % 40) in (register - 1..register + 1)) { drawPoints.addOrSet(drawPosition, "#") } else { drawPoints.getOrAdd(drawPosition) { "." } } } private fun doPrint(mode: Boolean, drawPoints: List<String>) { if (mode) { drawPoints.forEachIndexed { i, s -> print(s) if ((i + 1) % 40 == 0) println() } } }
0
Kotlin
0
0
967812138a7ee110a63e1950cae9a799166a6ba8
1,839
advent-of-code-2022
Apache License 2.0
src/main/kotlin/de/pgebert/aoc/days/Day04.kt
pgebert
724,032,034
false
{"Kotlin": 65831}
package de.pgebert.aoc.days import de.pgebert.aoc.Day import kotlin.math.pow class Day04(input: String? = null) : Day(4, "Scratchcards", input) { private val scratchcard = ".*:(.*)\\|(.*)".toRegex() override fun partOne() = inputList.sumOf { line -> scratchcard.find(line) ?.destructured ?.map { it.split(" ").filter { it.isNotBlank() }.toSet() } ?.let { (winning, all) -> winning.intersect(all).powTwoMinusOne() } ?: 0 } override fun partTwo(): Int { val cardCount = inputList.indices.associateWith { 1 }.toMutableMap() inputList.mapIndexedNotNull { card, line -> scratchcard.find(line) ?.destructured ?.map { it.split(" ").filter { it.isNotBlank() }.toSet() } ?.let { (winning, all) -> Pair(card, winning.intersect(all)) } }.forEach { (card, wins) -> wins.indices.forEach { i -> cardCount[card + i + 1] = cardCount[card + i + 1]!! + cardCount[card]!! } } return cardCount.values.sum() } private fun Set<String>.powTwoMinusOne(): Int = if (isNotEmpty()) (2.0).pow(size - 1).toInt() else 0 private fun <R> MatchResult.Destructured.map(transform: (String) -> R) = toList().map(transform) }
0
Kotlin
1
0
a30d3987f1976889b8d143f0843bbf95ff51bad2
1,322
advent-of-code-2023
MIT License
src/Day20.kt
simonbirt
574,137,905
false
{"Kotlin": 45762}
fun main() { Day20.printSolutionIfTest(3, 1623178306) } object Day20 : Day<Long, Long>(20) { override fun part1(lines: List<String>) = solve(lines,1,1) override fun part2(lines: List<String>) = solve(lines, 10, 811589153L) private fun solve(lines: List<String>, reps: Int, key: Long): Long { val initial = lines.map {it.toLong() * key}.withIndex() val size = initial.count() val final = initial.toMutableList() for(cycle in 1..reps) { initial.filter { it.value != 0L }.forEach { val pos = final.indexOf(it) val newPos = (pos + it.value).mod(size - 1) final.removeAt(pos) final.add(newPos, it) } } val indexZero = final.indexOfFirst { it.value == 0L } return listOf(1000,2000,3000).map{final[(indexZero + it).mod(size)]}.map {it.value}.reduce(Long::plus) } }
0
Kotlin
0
0
962eccac0ab5fc11c86396fc5427e9a30c7cd5fd
930
advent-of-code-2022
Apache License 2.0
aoc_2023/src/main/kotlin/problems/day4/Scratchcards.kt
Cavitedev
725,682,393
false
{"Kotlin": 228779}
package problems.day4 import kotlin.math.pow class Scratchcards(val scratchcards: Array<Scratchcard>) { companion object { fun fromLines(lines: List<String>): Scratchcards { val scratchcards: Array<Scratchcard> = lines.map { line -> val (card, numbers) = line.split(':') val cardIndex = card.split(" ").last().toInt() val (winningNumbersStr, playedNumbersStr) = numbers.split('|') val numbersRegex = Regex("""(\d+)""") val winningNumbers: IntArray = numbersRegex.findAll(winningNumbersStr).map { numberStr -> numberStr.value.toInt() }.toList().toIntArray() val playedNumbers: IntArray = numbersRegex.findAll(playedNumbersStr).map { numberStr -> numberStr.value.toInt() }.toList().toIntArray() Scratchcard(cardIndex, winningNumbers, playedNumbers) }.toTypedArray() return Scratchcards(scratchcards) } } fun sumWinningPoints(): Int { return scratchcards.map { 2.0.pow(it.playedNumbersWon().count() - 1.0).toInt() }.fold(0) { acc, points -> acc + points } } fun sumNumberOfCopies(): Int { val timesToPlayEachCard = IntArray(this.scratchcards.count()) { 1 } for (timePlayCardIndex in timesToPlayEachCard.indices) { val timePlayCard = timesToPlayEachCard[timePlayCardIndex] val card = scratchcards[timePlayCardIndex] val wonNumbers = card.playedNumbersWon() for (i in wonNumbers.indices) { timesToPlayEachCard[timePlayCardIndex + i + 1] += timePlayCard } } return timesToPlayEachCard.reduce { pre, cur -> pre + cur } } }
0
Kotlin
0
1
aa7af2d5aa0eb30df4563c513956ed41f18791d5
1,848
advent-of-code-2023
MIT License
2022/kotlin-lang/src/main/kotlin/mmxxii/days/Day14.kt
Delni
317,500,911
false
{"Kotlin": 66017, "Dart": 53066, "Go": 28200, "TypeScript": 7238, "Rust": 7104, "JavaScript": 2873}
package mmxxii.days import java.awt.Point import kotlin.math.sign class Day14 : Abstract2022<Int>("14", "Regolith Reservoir") { override fun part1(input: List<String>): Int = input .map(String::toPath) .let { paths -> val grid = mutableSetOf<Point>() grid.addPaths(paths) val bounds = Point( grid.minOf { it.x }.toInt(), 0, ) to Point( grid.maxOf { it.x }.toInt(), grid.maxOf { it.y }.toInt(), ) var grain = Point(500, 0) var grains = 0 while (grain inside bounds) { val formerPosition = Point(grain.x, grain.y) grain.moveOn(grid, floor = Int.MAX_VALUE) if (formerPosition == grain) { grid.add(grain) grain = Point(500, 0) grains++ } } grains } override fun part2(input: List<String>): Int = input .map(String::toPath) .let { paths -> val grid = mutableSetOf<Point>() grid.addPaths(paths) val floor = grid.maxOf { it.y }.toInt() + 2 var grain = Point(500, 0) var grains = 0 while (true) { val formerPosition = Point(grain.x, grain.y) grain.moveOn(grid, floor = floor) if (formerPosition == grain) { grains++ grid.add(grain) if (grain == Point(500, 0)) { break } else { grain = Point(500, 0) } } } grains } } infix fun Point.inside(bounds: Pair<Point, Point>) = (bounds.first.x <= x && x <= bounds.second.x) && (bounds.first.y <= y && y <= bounds.second.y) fun Point.moveOn(grid: Iterable<Point>, floor: Int) { val down = Point(x, y + 1) val left = Point(x - 1, y + 1) val right = Point(x + 1, y + 1) when { !grid.contains(down) && y + 1 < floor -> move(x, y + 1) !grid.contains(left) && y + 1 < floor -> move(x - 1, y + 1) !grid.contains(right) && y + 1 < floor -> move(x + 1, y + 1) } } fun MutableSet<Point>.addPaths(paths: List<List<Pair<Point, Point>>>) = paths.forEach { path -> path.forEach { add(it.first) var currentPoint = it.first while (currentPoint != it.second) { add(currentPoint) currentPoint = Point( currentPoint.x + (it.second.x - it.first.x).sign, currentPoint.y + (it.second.y - it.first.y).sign ) } add(it.second) } } fun String.toPath(): List<Pair<Point, Point>> = split("->") .windowed(2) .map { it.first().toPoint() to it.last().toPoint() } fun String.toPoint(): Point = split(',') .map(String::trim) .map(String::toInt) .run { Point(first(), last()) }
0
Kotlin
0
1
d8cce76d15117777740c839d2ac2e74a38b0cb58
3,059
advent-of-code
MIT License
advent-of-code-2021/src/main/kotlin/eu/janvdb/aoc2021/day10/Day10.kt
janvdbergh
318,992,922
false
{"Java": 1000798, "Kotlin": 284065, "Shell": 452, "C": 335}
package eu.janvdb.aoc2021.day10 import eu.janvdb.aocutil.kotlin.readLines import java.util.* const val FILENAME = "input10.txt" val MATCHING_CHARS = mapOf(Pair('(', ')'), Pair('{', '}'), Pair('[', ']'), Pair('<', '>')) val SCORES1 = mapOf(Pair(')', 3L), Pair(']', 57L), Pair('}', 1197L), Pair('>', 25137L)) val SCORES2 = mapOf(Pair(')', 1L), Pair(']', 2L), Pair('}', 3L), Pair('>', 4L)) fun main() { val scores = readLines(2021, FILENAME).map(::getSyntaxScoreForPattern) val result1 = scores.filter { !it.first }.sumOf { it.second } println(result1) val scores2 = scores.filter { it.first }.map { it.second }.sorted() val result2 = scores2[scores2.size/2] println(result2) } // First element indicates if correct, second element the score fun getSyntaxScoreForPattern(line: String): Pair<Boolean, Long> { val openingCharactersFound = LinkedList<Char>() for(ch in line.toCharArray()) { when(ch) { '(', '{', '[', '<' -> openingCharactersFound.addLast(MATCHING_CHARS[ch]!!) ')', '}', ']', '>' -> { val matchingChar = openingCharactersFound.removeLast() if (ch != matchingChar) { return Pair(false, SCORES1[ch]!!) } } } } val score = openingCharactersFound.foldRight(0L) { ch, acc -> acc * 5 + SCORES2[ch]!! } return Pair(true, score) }
0
Java
0
0
78ce266dbc41d1821342edca484768167f261752
1,282
advent-of-code
Apache License 2.0
src/Day09.kt
ChristianNavolskyi
573,154,881
false
{"Kotlin": 29804}
import kotlin.math.absoluteValue import kotlin.math.ceil import kotlin.math.sign class Day09 : Challenge<Int> { override val name: String get() = "Day 09" override fun inputName(): String = "Day09" override fun testInputName(): String = "Day09_test" override fun testInputName2(): String = "Day09_test2" override fun testResult1(): Int = 13 override fun testResult2(): Int = 36 override fun part1(input: String): Int { val moves = input.trim().split("\n").map { Move.fromInput(it) } val traceMap = mutableSetOf<Pair<Int, Int>>() val rope = Rope(listOf(RopeSegment("H", null), RopeSegment("T", traceMap))) moves.forEach { rope.apply(it) } return traceMap.count() } override fun part2(input: String): Int { val moves = input.trim().split("\n").map { Move.fromInput(it) } val traceMap = mutableSetOf<Pair<Int, Int>>() val rope = Rope(listOf(RopeSegment("H", null)) + List(8) { RopeSegment((it + 1).toString(), null) } + listOf(RopeSegment("T", traceMap))) moves.forEach { rope.apply(it) } return traceMap.count() } } enum class Direction(private val shortHand: Char) { UP('U'), LEFT('L'), RIGHT('R'), DOWN('D'); companion object { fun getByShortHand(shortHand: Char) = Direction.values().first { it.shortHand == shortHand } } } abstract class Move(val steps: Int) { abstract override fun toString(): String abstract fun step(position: Pair<Int, Int>): Pair<Int, Int> companion object { fun fromInput(input: String): Move { val inputPart = input.split(" ") val direction = Direction.getByShortHand(inputPart[0].first()) val steps = inputPart[1].toInt() return when (direction) { Direction.UP -> MoveUp(steps) Direction.LEFT -> MoveLeft(steps) Direction.RIGHT -> MoveRight(steps) Direction.DOWN -> MoveDown(steps) } } } } class MoveUp(steps: Int) : Move(steps) { override fun toString(): String = "Up $steps" override fun step(position: Pair<Int, Int>): Pair<Int, Int> = Pair(position.first, position.second + 1) } class MoveDown(steps: Int) : Move(steps) { override fun toString(): String = "Down $steps" override fun step(position: Pair<Int, Int>): Pair<Int, Int> = Pair(position.first, position.second - 1) } class MoveLeft(steps: Int) : Move(steps) { override fun toString(): String = "Left $steps" override fun step(position: Pair<Int, Int>): Pair<Int, Int> = Pair(position.first - 1, position.second) } class MoveRight(steps: Int) : Move(steps) { override fun toString(): String = "Right $steps" override fun step(position: Pair<Int, Int>): Pair<Int, Int> = Pair(position.first + 1, position.second) } class Rope(private val segments: List<RopeSegment>) { fun apply(move: Move) { repeat((0 until move.steps).count()) { val first = segments.first() first.position = move.step(first.position) segments.subList(1, segments.size).fold(first.position) { previousPosition, ropeSegment -> ropeSegment.updatedLeading(previousPosition) ropeSegment.position } } } } class RopeSegment(private val segmentName: String, private val trace: MutableSet<Pair<Int, Int>>?) { var position: Pair<Int, Int> = Pair(0, 0) set(value) { // println("moving segment $segmentName: ${field.toStringPrint()} -> ${value.toStringPrint()}") field = value trace?.add(value) } init { trace?.add(position) } fun updatedLeading(newLeading: Pair<Int, Int>) { val totalDistance = newLeading - position if (shouldMoveTail(totalDistance)) { val differenceVector = totalDistance / 2 val newTail = position + differenceVector position = newTail } } private fun shouldMoveTail(totalDistance: Pair<Int, Int>): Boolean = totalDistance.abs().max() > 1 private operator fun Pair<Int, Int>.minus(other: Pair<Int, Int>): Pair<Int, Int> = Pair(first - other.first, second - other.second) private operator fun Pair<Int, Int>.plus(other: Pair<Int, Int>): Pair<Int, Int> = Pair(first + other.first, second + other.second) private operator fun Pair<Int, Int>.div(divider: Int): Pair<Int, Int> = Pair(first.sign * ceil(first.absoluteValue / divider.toDouble()).toInt(), second.sign * ceil(second.absoluteValue / divider.toDouble()).toInt()) private fun Pair<Int, Int>.abs(): Pair<Int, Int> = Pair(first.absoluteValue, second.absoluteValue) private fun Pair<Int, Int>.max(): Int = kotlin.math.max(first, second) private fun Pair<Int, Int>.toStringPrint() = "($first,$second)" }
0
Kotlin
0
0
222e25771039bdc5b447bf90583214bf26ced417
4,884
advent-of-code-2022
Apache License 2.0
Kotlin-Knn/src/main/kotlin/dataKNN.kt
JUSTNic3
739,087,623
false
{"Kotlin": 11542}
import kotlin.math.* import com.github.doyaaaaaken.kotlincsv.dsl.csvReader data class KNNMovie( val name: String, val genre: String, val crew: String, val language: String ) class KNNAlgorithm( private val movies: List<KNNMovie>, private val k: Int = 5 ) { fun findNearestNeighbors(input: KNNMovie): List<KNNMovie> { // Compute similarities val similarities = movies.map { movie -> Pair(movie, computeKNNSimilarity(movie, input)) } return similarities .sortedByDescending { it.second } .take(k) .map { it.first } } private fun computeKNNSimilarity(movie1: KNNMovie, movie2: KNNMovie): Double { val genreWeight = 0.5 // Adjust val crewWeight = 0.4 val languageWeight = 0.3 val genreSimilarity = jaccardIndex(movie1.genre.toGenreSet(), movie2.genre.toGenreSet()) val crewSimilarity = jaccardIndex(movie1.crew.toCrewSet(), movie2.crew.toCrewSet()) val languageMatch = if (movie1.language == movie2.language) 1.0 else 0.0 return (genreSimilarity * genreWeight) + (crewSimilarity * crewWeight) + (languageMatch * languageWeight) } private fun String.toGenreSet(): Set<String> = this.split(", ").map { it.trim() }.toSet() private fun String.toCrewSet(): Set<String> = this.split(", ").map { it.trim() }.toSet() private fun jaccardIndex(set1: Set<String>, set2: Set<String>): Double { val intersection = set1.intersect(set2).size.toDouble() val union = set1.union(set2).size.toDouble() return if (union == 0.0) 0.0 else intersection / union } } fun KNN() { val movies = loadKNNCsvData("database/imdb_movies.csv") println("Enter your favorite movie genre (Drama, Action):") val favoriteGenre = readLine()!! println("Enter your favorite crew member (director, actor):") val favoriteCrew = readLine()!! println("Enter your favorite language (English, Spanish):") val favoriteLanguage = readLine()!! val knnAlgorithm = KNNAlgorithm(movies, k = 10) val preferredMovie = KNNMovie("",favoriteGenre, favoriteCrew, favoriteLanguage) val recommendations = knnAlgorithm.findNearestNeighbors(preferredMovie) println("\u001B[32mRecommended movies:\u001B[0m") // Green color for header recommendations.forEach { movie -> println("\u001B[35mName:\u001B[0m ${movie.name}") println("\u001B[36mGenre:\u001B[0m ${movie.genre}") println("\u001B[33mCrew:\u001B[0m ${movie.crew}") println("\u001B[34mLanguage:\u001B[0m ${movie.language}\n") } } fun loadKNNCsvData(relativePath: String): List<KNNMovie> { val inputStream = object {}.javaClass.classLoader.getResourceAsStream(relativePath) ?: throw IllegalArgumentException("File not found at $relativePath") val knnMovies = mutableListOf<KNNMovie>() csvReader().open(inputStream) { readAllWithHeaderAsSequence().forEach { row -> val name = row["names"] ?: "" val genre = row["genre"] ?: "" val crew = row["crew"] ?: "" val language = row["orig_lang"] ?: "" knnMovies.add(KNNMovie(name, genre, crew, language)) } } return knnMovies }
0
Kotlin
0
0
2c74d4e143d082a61c8a72de9b1c8469fdf82b30
3,258
Kotlin-Knn
MIT License
src/adventofcode/Day12.kt
Timo-Noordzee
573,147,284
false
{"Kotlin": 80936}
package adventofcode import org.openjdk.jmh.annotations.* import java.util.* import java.util.concurrent.TimeUnit import kotlin.collections.ArrayDeque private typealias Grid = Array<IntArray> private operator fun Array<IntArray>.get(point: Point): Int = this[point.y][point.x] private class Terrain( val start: Point, val end: Point, private val m: Int, private val n: Int, private val grid: Grid, ) { // Solve using BFS fun solve(isDestination: Terrain.(point: Point) -> Boolean): Int { val queue = ArrayDeque<Point>().apply { add(end) } val visited = BooleanArray(m * n).apply { this[end.getIndex(n)] = true } val steps = IntArray(m * n).apply { this[end.getIndex(n)] = 0 } while (queue.isNotEmpty()) { val current = queue.removeFirst() if (this.isDestination(current)) return steps[current.getIndex(n)] current.getNeighbors().forEach { point -> val index = point.getIndex(n) if (point in this && !visited[index] && grid[current] - grid[point] < 2) { visited[index] = true steps[index] = steps[current.getIndex(n)] + 1 queue.add(point) } } } error("no path found, check your input") } operator fun contains(point: Point) = point.y in grid.indices && point.x in grid[0].indices operator fun get(y: Int) = grid[y] companion object { fun fromInput(input: List<String>): Terrain { var start = Point(0, 0) var end = Point(0, 0) val m = input.size val n = input[0].length val grid: Grid = Array(m) { IntArray(n) } for (i in input.indices) { for (j in 0 until n) { when (val char = input[i][j]) { 'S' -> { start = Point(j, i) grid[i][j] = 0 } 'E' -> { end = Point(j, i) grid[i][j] = 'z' - 'a' } else -> grid[i][j] = char - 'a' } } } return Terrain(start, end, m, n, grid) } } } @State(Scope.Benchmark) @Fork(1) @Warmup(iterations = 0) @Measurement(iterations = 10, time = 2, timeUnit = TimeUnit.SECONDS) class Day12 { var input: List<String> = emptyList() @Setup fun setup() { input = readInput("Day12") } @Benchmark fun part1() = Terrain.fromInput(input).solve { point -> point atSamePositionAs start } @Benchmark fun part2() = Terrain.fromInput(input).solve { point -> this[point.y][point.x] == 0 } } fun main() { val day12 = Day12() // test if implementation meets criteria from the description, like: day12.input = readInput("Day12_test") check(day12.part1() == 31) check(day12.part2() == 29) day12.input = readInput("Day12") println(day12.part1()) println(day12.part2()) }
0
Kotlin
0
2
10c3ab966f9520a2c453a2160b143e50c4c4581f
3,133
advent-of-code-2022-kotlin
Apache License 2.0
src/day1/Day01.kt
kongminghan
573,466,303
false
{"Kotlin": 7118}
package day1 import readInput fun main() { fun highestSumCalories(input: List<String>, limit: Int): Int { return input .foldIndexed(mutableListOf<MutableList<Int>>(mutableListOf())) { _, acc, item -> if (item == "") { acc.add(mutableListOf()) } else { acc.last().add(item.toInt()) } acc } .asSequence() .map { it.sum() } .sortedDescending() .take(limit) .sum() } fun part1(input: List<String>): Int { return highestSumCalories(input, limit = 1) } fun part2(input: List<String>): Int { return highestSumCalories(input = input, limit = 3) } // test if implementation meets criteria from the description, like: val testInput = readInput(day = 1, name = "Day01_test") check(part1(testInput) == 9) check(part2(testInput) == 21) val input = readInput(day = 1, name = "Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
f602900209712090778c161d407ded8c013ae581
1,086
advent-of-code-kotlin
Apache License 2.0
advent-of-code-2022/src/main/kotlin/year_2022/Day16.kt
rudii1410
575,662,325
false
{"Kotlin": 37749}
package year_2022 import util.Runner import java.util.Stack import kotlin.math.min data class Node1(val label: String, val rate: Int, val child: MutableList<Node1>) fun main() { /* Part 1 */ fun part1(input: List<String>): Int { val map = mutableMapOf<String, Pair<Int, List<String>>>() val visited = mutableMapOf<String, Boolean>() val valve = mutableMapOf<String, Boolean>() input.forEach { row -> row.split("; ", "=", "valve").let { d -> // println(d[3].split(", ").map { it.replace("s ", "").trim() }) // println() val idx = d[0].split(" ")[1] val w = d[1].toInt() map[idx] = Pair(w, d[3].split(", ").map { it.replace("s ", "").trim() }) visited[idx] = false valve[idx] = w == 0 } } val stack = Stack<String>().apply { add("AA") } var minutes = 1 var result = 0 var tmp = 0 while(stack.isNotEmpty() && minutes <= 6) { val v = stack.peek() println("valve: $v, minute: $minutes, isValveOpen: ${valve[v]}") println(stack) if (valve[v] == false && map[v]!!.first > 0) { minutes += 1 valve[v] = true result += tmp continue } if (visited[v] == true) { stack.pop() continue } visited[v] = true tmp += map[v]!!.first println("$tmp - $result") stack.pop() map[v]!!.second.reversed().forEach { stack.push(it) } minutes += 1 println("next: ${stack.peek()}") } println(result) return result } Runner.run(::part1, 1651) /* Part 2 */ fun part2(input: List<String>): Int { return input.size } Runner.run(::part2, 0) }
1
Kotlin
0
0
ab63e6cd53746e68713ddfffd65dd25408d5d488
1,959
advent-of-code
Apache License 2.0
src/util/algorithms/LineSimplification.kt
JBWills
291,822,812
false
null
package util.algorithms import coordinate.Point import coordinate.Segment import util.numbers.times import util.polylines.PolyLine import util.polylines.iterators.mapBySegment import util.tuple.map import java.util.LinkedList import java.util.Queue fun PolyLine.douglassPeucker(epsilon: Double): PolyLine { // Find the point with the maximum distance var dmax = 0.0 var index = 0 if (size < 2) return this val startToEnd = Segment(first(), last()) forEachIndexed { i, point -> if (i == 0 || i == size - 1) return@forEachIndexed val d = point.perpendicularDistanceTo(startToEnd) if (d > dmax) { index = i dmax = d } } // If max distance is greater than epsilon, recursively simplify return if (dmax > epsilon) { (0 until index to (index until size)).map { slice(it).douglassPeucker(epsilon) }.toList().flatten() } else { listOf(first(), last()) } } /** * From https://keithmaggio.wordpress.com/2018/05/29/math-magician-path-smoothing-with-chaikin/ * * @param path * @return */ fun PolyLine.chaikin(): PolyLine { if (this.isEmpty()) return listOf() val ret = mutableListOf(first()) val procPath: Queue<Point> = LinkedList(this) var prevPoint: Point = procPath.remove() while (procPath.size > 1) { val curPoint = procPath.remove() val nextPoint = procPath.peek() val currentHeading = (curPoint - prevPoint).normalized val nextHeading = (nextPoint - curPoint).normalized val angle = Segment(currentHeading, nextHeading).slope.value if (angle >= 30) { if (angle >= 90) { procPath.remove() prevPoint = curPoint continue } val pointQ = curPoint * 0.75 + nextPoint * 0.25 val pointR = curPoint * 0.25 + nextPoint * 0.75 ret.add(pointQ) ret.add(pointR) prevPoint = pointR } else { ret.add(curPoint) prevPoint = curPoint } } // Make sure we get home. if (!ret.contains(last())) ret.add(last()) return ret } fun PolyLine.chaikin2(): PolyLine { if (size < 2) return this val chaikinPoints = mapBySegment { segment -> listOf(segment.getPointAtPercent(0.25), segment.getPointAtPercent(0.75)) }.flatten() return first() + chaikinPoints + last() } fun PolyLine.chaikin(times: Int): PolyLine { var res = this times.times { res = res.chaikin2() } return res }
0
Kotlin
0
0
569b27c1cb1dc6b2c37e79dfa527b9396c7a2f88
2,380
processing-sketches
MIT License
Collections/Sum/src/Task.kt
diskostu
554,658,487
false
{"Kotlin": 36179}
// Return the sum of prices for all the products ordered by a given customer fun moneySpentBy(customer: Customer): Double = customer.orders.flatMap { it.products }.sumOf { it.price } fun main() { // demo code to find the solutions val shop = createSampleShop() val customer = shop.customers[0] val flatMap = customer.orders.flatMap { it.products } println("flatMap = $flatMap") val sumOf = flatMap.sumOf { it.price } println("sumOf = $sumOf") } fun createSampleShop(): Shop { // create some sample entities val product1 = Product("product 1", 1.0) val product2 = Product("product 2", 2.0) val product3 = Product("product 3", 3.0) val product4 = Product("product 4", 4.0) val product5 = Product("product 4", 5.0) val order1 = Order(listOf(product1), false) val order2 = Order(listOf(product2, product3), false) val order3 = Order(listOf(product1, product3, product4), false) val customer1 = Customer( name = "custumer1", city = City("Berlin"), orders = listOf(order1, order3) ) val customer2 = Customer( name = "custumer2", city = City("Hamburg"), orders = listOf(order2) ) return Shop("myShop", listOf(customer1, customer2)) }
0
Kotlin
0
0
3cad6559e1add8d202e15501165e2aca0ee82168
1,271
Kotlin_Koans
MIT License
samples/camera/camera2/src/main/java/com/example/platform/camera/common/CameraSizes.kt
Anglemmj7
652,373,352
false
null
/* * Copyright 2023 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 * * https://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.platform.camera.common import android.graphics.Point import android.hardware.camera2.CameraCharacteristics import android.hardware.camera2.params.StreamConfigurationMap import android.util.Size import android.view.Display import kotlin.math.max import kotlin.math.min /** Helper class used to pre-compute shortest and longest sides of a [Size] */ class SmartSize(width: Int, height: Int) { var size = Size(width, height) var long = max(size.width, size.height) var short = min(size.width, size.height) override fun toString() = "SmartSize(${long}x${short})" } /** Standard FHD size for pictures and video */ val SIZE_1080P: SmartSize = SmartSize(1920, 1080) /** Standard HD size for pictures and video */ val SIZE_720P: SmartSize = SmartSize(1280, 720) /** Returns a [SmartSize] object for the given [Display] */ fun getDisplaySmartSize(display: Display): SmartSize { val outPoint = Point() display.getRealSize(outPoint) return SmartSize(outPoint.x, outPoint.y) } /** * Returns the largest available PREVIEW size. For more information, see: * https://d.android.com/reference/android/hardware/camera2/CameraDevice and * https://developer.android.com/reference/android/hardware/camera2/params/StreamConfigurationMap */ fun <T> getPreviewOutputSize( display: Display, characteristics: CameraCharacteristics, targetClass: Class<T>, format: Int? = null, ): Size? { // Find which is smaller: screen or 1080p val screenSize = getDisplaySmartSize(display) val fhdScreen = screenSize.long >= SIZE_1080P.long || screenSize.short >= SIZE_1080P.short val maxSize = if (fhdScreen) SIZE_1080P else screenSize // If image format is provided, use it to determine supported sizes; else use target class val config = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP) if (format == null) assert(StreamConfigurationMap.isOutputSupportedFor(targetClass)) else config?.isOutputSupportedFor(format)?.let { assert(it) } val allSizes = if (format == null) config?.getOutputSizes(targetClass) else config?.getOutputSizes(format) // Get available sizes and sort them by area from largest to smallest. val validSizes = allSizes ?.sortedWith(compareBy { it.height * it.width }) ?.map { SmartSize(it.width, it.height) } ?.reversed() // Then, get the largest output size that is smaller or equal than our max size. return validSizes?.first { it.long <= maxSize.long && it.short <= maxSize.short }?.size }
0
Kotlin
0
0
f4e8993b7052082f03f0d8f787ecea862e7b8c3a
3,174
Android-
Apache License 2.0
src/Day05.kt
rounakdatta
540,743,612
false
{"Kotlin": 19962}
fun parseLine(input: String): Pair<Pair<Int, Int>, Pair<Int, Int>> { return input.split(" -> ") .map { it -> it.split(",") } .map { it -> Pair(it.first().toInt(), it.last().toInt()) } .let { Pair(it.first(), it.last()) } } fun drawStraightLineOnChart(chart: MutableList<MutableList<Int>>, straightLine: Pair<Pair<Int, Int>, Pair<Int, Int>>): MutableList<MutableList<Int>> { // 7,0 -> 7,4 // 7,0 7,1 7,2 7,3, 7,4 return when(Pair(straightLine.first.first == straightLine.second.first, straightLine.first.second == straightLine.second.second)) { // when the line is vertical i.e. x is fixed Pair(true, false) -> { (straightLine.first.second until straightLine.second.second + 1) .forEach { it -> chart[straightLine.first.first][it] += 1 } (straightLine.second.second until straightLine.first.second + 1) .forEach { it -> chart[straightLine.first.first][it] += 1 } chart } // when the line is horizontal else -> { (straightLine.first.first until straightLine.second.first + 1) .forEach { it -> chart[it][straightLine.first.second] += 1 } (straightLine.second.first until straightLine.first.first + 1) .forEach { it -> chart[it][straightLine.first.second] += 1 } chart } } } fun drawDiagonalLineOnChart(chart: MutableList<MutableList<Int>>, diagonalLine: Pair<Pair<Int, Int>, Pair<Int, Int>>): MutableList<MutableList<Int>> { // (4,8) (5,7) (6,6) (7,5) (8,4), (9,3) // directed towards fourth quadrant e.g. 4,8 -> 9,3 return if (diagonalLine.first.first < diagonalLine.second.first && diagonalLine.first.second > diagonalLine.second.second) { (diagonalLine.first.first until diagonalLine.second.first + 1).map { xCoordinate -> chart[xCoordinate][diagonalLine.first.second - (xCoordinate - diagonalLine.first.first)] += 1 } .let { chart } // directed towards the third quadrant e.g. 4,8 -> 2,6 } else if (diagonalLine.second.first < diagonalLine.first.first && diagonalLine.first.second > diagonalLine.second.second) { (diagonalLine.second.first until diagonalLine.first.first + 1).map { xCoordinate -> chart[xCoordinate][diagonalLine.second.second + (xCoordinate - diagonalLine.second.first)] += 1 } .let { chart } // directed towards the second quadrant e.g. 4,8 -> 2,10 } else if (diagonalLine.second.first < diagonalLine.first.first && diagonalLine.second.second > diagonalLine.first.second) { (diagonalLine.second.first until diagonalLine.first.first + 1).map { xCoordinate -> chart[xCoordinate][diagonalLine.second.second - (xCoordinate - diagonalLine.second.first)] += 1 } .let { chart } // directed towards the first quadrant i.e. 4,8 -> 7,11 } else if (diagonalLine.first.first < diagonalLine.second.first && diagonalLine.second.second > diagonalLine.first.second) { (diagonalLine.first.first until diagonalLine.second.first + 1).map { xCoordinate -> chart[xCoordinate][diagonalLine.first.second + (xCoordinate - diagonalLine.first.first)] += 1 } .let { chart } } else { // unlikely case, never to be reached chart } } fun countOverlaps(chart: MutableList<MutableList<Int>>): Int { return chart .map { it -> it.filter { itx -> itx > 1 }.size } .sum() } fun checkIfStraightOrDiagonal(pointPair: Pair<Pair<Int, Int>, Pair<Int, Int>>): String { return if (pointPair.first.first == pointPair.second.first || pointPair.first.second == pointPair.second.second) { "straight" } else if ((pointPair.first.first == pointPair.first.second && pointPair.second.first == pointPair.second.second) || ((pointPair.first.first - pointPair.first.second) % 2 == 0 && (pointPair.second.first - pointPair.second.second) % 2 == 0)) { "diagonal" } else { "invalid" } } fun main() { val maxBoardSize = 1000 fun part1(input: List<String>): Int { return input.map { parseLine(it) } // filter out those lying in a straight line .filter { it.first.first == it.second.first || it.first.second == it.second.second } .fold(MutableList(maxBoardSize) {MutableList(maxBoardSize) {0}}) { chart, straightLine -> chart.apply { drawStraightLineOnChart(chart, straightLine) } } .let { countOverlaps(it) } } fun part2(input: List<String>): Int { return input.map { parseLine(it) } // .filter { it.first.first == it.second.first || it.first.second == it.second.second || (it.first.first == it.first.second && it.second.first == it.second.second) } .map { it -> Pair(it, checkIfStraightOrDiagonal(it)) } .filter { it -> it.second == "straight" || it.second == "diagonal" } .fold(MutableList(maxBoardSize) {MutableList(maxBoardSize) {0}}) { chart, typeOfLine -> chart.apply { if (typeOfLine.second == "straight") { drawStraightLineOnChart(chart, typeOfLine.first) } else { drawDiagonalLineOnChart(chart, typeOfLine.first) } } } // .also { // it.forEach { itx -> println(itx) } // } .let { countOverlaps(it) } } val input = readInput("Day05") println(part1(input)) println(part2(input)) }
0
Kotlin
0
1
130d340aa4c6824b7192d533df68fc7e15e7e910
5,671
aoc-2021
Apache License 2.0
src/main/kotlin/Day23.kt
clechasseur
258,279,622
false
null
import org.clechasseur.adventofcode2019.Day23Data import org.clechasseur.adventofcode2019.IntcodeComputer object Day23 { private val input = Day23Data.input fun part1(): Long { val computers = List(50) { idx -> IntcodeComputer(input, idx.toLong()) } val queues = List(50) { mutableListOf<Packet>() } var nat = emptyList<Packet>() while (nat.isEmpty()) { nat = readComputerInputs(computers, queues) writeQueuesToOutputs(computers, queues) } return nat.first().y } fun part2(): Long { val computers = List(50) { idx -> IntcodeComputer(input, idx.toLong()) } val queues = List(50) { mutableListOf<Packet>() } var natRam: Packet? = null val prevNatPackets = mutableListOf<Packet>() while (true) { val nat = readComputerInputs(computers, queues) if (nat.isNotEmpty()) { natRam = nat.last() } if (natRam != null && computers.none { it.done } && queues.all { it.isEmpty() }) { if (prevNatPackets.indexOfFirst { it.y == natRam!!.y } != -1) { return natRam.y } prevNatPackets.add(natRam) computers[0].addInput(natRam.x, natRam.y) natRam = null } writeQueuesToOutputs(computers, queues) } } private data class Packet(val target: Int, val x: Long, val y: Long) private fun readComputerInputs(computers: List<IntcodeComputer>, queues: List<MutableList<Packet>>): List<Packet> { val nat = mutableListOf<Packet>() computers.forEachIndexed { idx, computer -> val output = computer.readAllOutput() require(output.size % 3 == 0) { "Output size of computer $idx is not divisible by 3" } output.chunked(3) { Packet(it[0].toInt(), it[1], it[2]) }.forEach { packet -> when { packet.target == 255 -> nat.add(packet) packet.target in queues.indices -> queues[packet.target].add(packet) else -> error("Packet destination ${packet.target} unknown") } } } return nat } private fun writeQueuesToOutputs(computers: List<IntcodeComputer>, queues: List<MutableList<Packet>>) { queues.forEachIndexed { idx, queue -> if (queue.isEmpty()) { computers[idx].addInput(-1L) } else { queue.forEach { packet -> computers[idx].addInput(packet.x, packet.y) } queue.clear() } } } }
0
Kotlin
0
0
187acc910eccb7dcb97ff534e5f93786f0341818
2,658
adventofcode2019
MIT License
src/main/kotlin/days/aoc2020/Day14.kt
bjdupuis
435,570,912
false
{"Kotlin": 537037}
package days.aoc2020 import days.Day class Day14: Day(2020, 14) { override fun partOne(): Any { val memory = mutableMapOf<Long,Long>() var bitMaskClear = 0L var bitMaskSet = 0L inputList.forEach { instruction -> when { instruction.startsWith("mask") -> { Regex("mask = ([01X]+)").matchEntire(instruction)?.destructured?.let { (mask) -> bitMaskClear = 0L bitMaskSet = 0L var current = 1L mask.reversed().forEach { when(it) { '1' -> bitMaskSet += current '0' -> bitMaskClear += current } current = current shl 1 } bitMaskClear = bitMaskClear.inv() } } instruction.startsWith("mem") -> { Regex("mem\\[(\\d+)\\] = (\\d+)").matchEntire(instruction)?.destructured?.let { (address, value) -> value.toLong().apply { memory[address.toLong()] = (this or bitMaskSet) and bitMaskClear } } } } } return memory.filterNot { it.value == 0L }?.map { it.value }?.sum() ?: 0 } override fun partTwo(): Any { return calculatePartTwo(inputList) } fun calculatePartTwo(list: List<String>): Long { val memory = mutableMapOf<Long,Long>() var currentMask = "" list.forEach { instruction -> when { instruction.startsWith("mask") -> { Regex("mask = ([01X]+)").matchEntire(instruction)?.destructured?.let { (mask) -> currentMask = mask } } instruction.startsWith("mem") -> { Regex("mem\\[(\\d+)\\] = (\\d+)").matchEntire(instruction)?.destructured?.let { (address, value) -> value.toLong().apply { addressSequence(currentMask, address.toLong()).forEach { memory[it] = value.toLong() } } } } } } return memory.filterNot { it.value == 0L }?.map { it.value }?.sum() ?: 0 } private fun addressSequence(mask: String, address: Long) = sequence { var bitMaskSet = 0L var bitMaskClear = 0L var current = 1L val floaters = mutableListOf<Long>() mask.reversed().forEach { when(it) { '1' -> bitMaskSet += current 'X' -> { bitMaskClear += current floaters.add(current) } } current = current shl 1 } bitMaskClear = bitMaskClear.inv() val masksAppliedToAddress = (address or bitMaskSet) and bitMaskClear permute(masksAppliedToAddress, floaters).forEach { address -> yield(address) } } private fun permute(currentMask: Long, floaters: List<Long>): List<Long> { if (floaters.size == 1) { return listOf(currentMask, currentMask + floaters[0]) } val permutations = mutableListOf<Long>() val first = floaters.first() permute(currentMask, floaters.drop(1)).forEach { l -> permutations.add(l) permutations.add(first + l) } return permutations } }
0
Kotlin
0
1
c692fb71811055c79d53f9b510fe58a6153a1397
3,720
Advent-Of-Code
Creative Commons Zero v1.0 Universal
src/Day11.kt
Misano9699
572,108,457
false
null
var monkeys: MutableList<Monkey> = mutableListOf() var reliefModifier = 0L var keepInCheck = 1L fun main() { fun reset() { monkeys = mutableListOf() keepInCheck = 1L } fun listOfItems(line: String): MutableList<Long> = line.replace(" ", "").split(",").map { it.toLong() }.toMutableList() fun parseInput(input: List<String>) { var monkey = Monkey(0) input.forEach { line -> when { line.startsWith("Monkey ") -> monkey = Monkey(line.split(" ")[1].replace(":", "").toInt()) line.startsWith(" Starting items:") -> monkey.items = listOfItems(line.substring(18)) line.startsWith(" Operation: new = old ") -> { monkey.operation = line.substring(23).split(" ")[0] monkey.operand = line.substring(23).split(" ")[1] } line.startsWith(" Test: divisible by ") -> monkey.test = line.substring(21).toInt() line.startsWith(" If true: throw to monkey ") -> monkey.toMonkey.add(line.substring(29).toInt()) line.startsWith(" If false: throw to monkey ") -> monkey.toMonkey.add(line.substring(30).toInt()) line.startsWith("") -> monkeys.add(monkey) } } monkeys.add(monkey) } fun play() { monkeys.forEach { println("Monkey ${it.number}") it.play() } } // To keep the worry level within range, we need to find a way to let all the tests still work. // Reducing the worry level to the modulo of all test numbers multiplied should do that, // without disrupting the test fun determineKeepInCheckLevels() { monkeys.forEach { keepInCheck *= it.test } } fun part1(input: List<String>): Long { reliefModifier = 3L reset() parseInput(input) determineKeepInCheckLevels() (1..20).forEach { println("Round $it") play() } val maxActive = monkeys.map { it.active }.sortedDescending().take(2) return maxActive[0] * maxActive[1] } fun part2(input: List<String>): Long { reliefModifier = 1L // no more relieved after inspection reset() parseInput(input) determineKeepInCheckLevels() println("Keep in check $keepInCheck") (1..10000).forEach { println("Round $it") play() } val maxActive = monkeys.sortedByDescending { it.active }.take(2) println("Most active monkeys: ${maxActive[0].active}, ${maxActive[1].active}") return maxActive[0].active * maxActive[1].active } // test if implementation meets criteria from the description, like: val testInput = readInput("Day11_test") val input = readInput("Day11") println("---- PART 1 ----") check(part1(testInput).also { println("Answer test input part1: $it") } == 10605L) println("Answer part1: " + part1(input)) println("---- PART 2 ----") check(part2(testInput).also { println("Answer test input part2: $it") } == 2713310158) println("Answer part2: " + part2(input)) } class Monkey(val number: Int) { var items = mutableListOf<Long>() var operation: String = "" var operand: String = "" var test: Int = 0 var toMonkey = mutableListOf<Int>() var active = 0L fun play() { (0 until items.size).forEach { _ -> active++ // take item var worryLevel = items.removeFirst() // inspect worryLevel = operate(worryLevel, operation, when(operand) { "old" -> worryLevel else -> operand.toLong() }) worryLevel /= reliefModifier worryLevel %= keepInCheck // test worry level and throw when (worryLevel % test == 0L) { true -> monkeys[toMonkey[0]].items.add(worryLevel) false -> monkeys[toMonkey[1]].items.add(worryLevel) } } } private fun operate(worrylevel: Long, operation: String, operand: Long) = when (operation) { "+" -> worrylevel + operand "-" -> worrylevel - operand "/" -> worrylevel / operand "*" -> worrylevel * operand else -> worrylevel } }
0
Kotlin
0
0
adb8c5e5098fde01a4438eb2a437840922fb8ae6
4,369
advent-of-code-2022
Apache License 2.0
src/main/kotlin/leetcode/Problem2231.kt
fredyw
28,460,187
false
{"Java": 1280840, "Rust": 363472, "Kotlin": 148898, "Shell": 604}
package leetcode /** * https://leetcode.com/problems/largest-number-after-digit-swaps-by-parity/ */ class Problem2231 { fun largestInteger(num: Int): Int { val oddIndexes = mutableListOf<Int>() val evenIndexes = mutableListOf<Int>() val numString = num.toString() for ((i, n) in numString.withIndex()) { if (n.toInt() % 2 != 0) { oddIndexes += i } else { evenIndexes += i } } var answer = CharArray(numString.length) val sortedOddIndexes = oddIndexes.sortedWith(Comparator {a, b -> numString[b].compareTo(numString[a])}) val sortedEvenIndexes = evenIndexes.sortedWith(Comparator {a, b -> numString[b].compareTo(numString[a])}) if (numString[0].toInt() % 2 != 0) { for ((i, j) in oddIndexes.withIndex()) { answer[j] = numString[sortedOddIndexes[i]] } for ((i, j) in evenIndexes.withIndex()) { answer[j] = numString[sortedEvenIndexes[i]] } } else { for ((i, j) in evenIndexes.withIndex()) { answer[j] = numString[sortedEvenIndexes[i]] } for ((i, j) in oddIndexes.withIndex()) { answer[j] = numString[sortedOddIndexes[i]] } } return String(answer).toInt() } }
0
Java
1
4
a59d77c4fd00674426a5f4f7b9b009d9b8321d6d
1,392
leetcode
MIT License
src/Day03.kt
joshpierce
573,265,121
false
{"Kotlin": 46425}
import java.io.File fun main() { // read the lines from the file var lines: List<String> = File("Day03.txt").readLines() // sum up the total of all priorities var total: Int = lines.map { // Find the priority by intersecting the two lists of items to get the common item // and then running our itemNumber function var priority: Int = it.substring(0, it.length / 2).toCharArray().toList() .intersect(it.substring(it.length / 2).toCharArray().toList()) .elementAt(0).itemNumber() // Return the priority return@map priority }.toMutableList().sum() // Solution to Part 1 println("The total is: " + total.toString()) // Create an Int Array for the total number of groups of elves val groups = IntArray((lines.size / 3)) { it } // Sum up the total of the matching items across each group val sum = groups.map { // Figure out the base index for the group val base = it * 3 // Find the priority by intersecting all three lists of items from the elves return@map lines[base].toCharArray().toList() .intersect(lines[base + 1].toCharArray().toList()) .intersect(lines[base + 2].toCharArray().toList()) .elementAt(0).itemNumber() }.sum() // Solution to Part 2 println("The total of the badge priorities is: " + sum.toString()) } // This extension function finds the index of the Character inside the alphabet fun Char.itemNumber(): Int { val items = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" return items.indexOf(this) + 1 }
0
Kotlin
0
1
fd5414c3ab919913ed0cd961348c8644db0330f4
1,697
advent-of-code-22
Apache License 2.0
src/day03/Day03.kt
scottpeterson
573,109,888
false
{"Kotlin": 15611}
fun Char.toValue() = if (code <= 'Z'.code) this - 'A' + 27 else this - 'a' + 1 fun partOne(input: List<String>): Int { val result = input .map { rucksack -> rucksack.chunked(rucksack.length / 2) } .map { (compartment1, compartment2) -> compartment1.first { it in compartment2 } } .sumOf { it.toValue() } print(result) return result } fun partTwo(input: List<String>): Int { val result = input .chunked(3) .map { (sack1, sack2, sack3) -> sack1.first { it in sack2 && it in sack3 } } .sumOf { it.toValue() } print(result) return result } fun main() { partOne(readInput("day03/Day03_input")) partTwo(readInput("day03/Day03_input")) }
0
Kotlin
0
0
0d86213c5e0cd5403349366d0f71e0c09588ca70
713
advent-of-code-2022
Apache License 2.0
src/main/kotlin/io/array/ReverseWordsInString.kt
jffiorillo
138,075,067
false
{"Kotlin": 434399, "Java": 14529, "Shell": 465}
package io.array import io.utils.runTests import kotlin.math.absoluteValue // https://leetcode.com/explore/learn/card/array-and-string/204/conclusion/1164/ class ReverseWordsInString { fun execute(phrase: String): String { val input = generateStringBuilderWithoutExtraSpaces(phrase) var startFirst = 0 var endSecond = input.length - 1 while (startFirst < endSecond) { val endFirst = findNextSpaceWord(input, startFirst) { it + 1 }.second - 1 val startSecond = findNextSpaceWord(input, endSecond) { it - 1 }.second + 1 if (startSecond <= startFirst) break val firstWordRange = startFirst..endFirst val firstWordSize = endFirst - startFirst + 1 val secondWordSize = endSecond - startSecond + 1 val sizeDif = (firstWordSize - secondWordSize).absoluteValue var secondWord: String if (secondWordSize > firstWordSize) { secondWord = moveFirstToSecond(input, startFirst, endFirst, startSecond, endSecond) input.changeToSpace(firstWordRange) moveDiffForward(input, sizeDif, endFirst, startSecond) } else { val firstWord = input.substring(firstWordRange) val secondWordRange = startSecond..endSecond secondWord = input.substring(secondWordRange) if (sizeDif > 0) moveDiffBackwards(input, sizeDif, endFirst, startSecond) input.changeToSpace(secondWordRange) (firstWord.length - 1 downTo 0).forEach { input[endSecond - (firstWord.length - it - 1)] = firstWord[it] } } secondWord.forEachIndexed { index, char -> input[startFirst + index] = char } startFirst += secondWordSize + 1 endSecond -= firstWordSize + 1 } return input.toString() } private fun moveDiffBackwards(input: StringBuilder, sizeDif: Int, endFirst: Int, startSecond: Int) { (endFirst + 1 until startSecond).forEach { input[it - sizeDif] = input[it] } } private fun moveFirstToSecond(input: StringBuilder, startFirst: Int, endFirst: Int, startSecond: Int, endSecond: Int): String { val secondWordRange = startSecond..endSecond val second = input.substring(secondWordRange) input.changeToSpace(secondWordRange) (endFirst downTo startFirst).forEach { input[endSecond - (endFirst - it)] = input[it] } return second } private fun moveDiffForward(input: StringBuilder, sizeDif: Int, endFirst: Int, startSecond: Int) { (startSecond - 1 downTo endFirst).forEach { input[it + sizeDif] = input[it] } } private fun StringBuilder.changeToSpace(range: IntRange) = range.forEach { this[it] = ' ' } private fun findNextSpaceWord(input: CharSequence, start: Int, action: (Int) -> Int): Pair<Int, Int> { var index = start while (index in input.indices && input[index] == ' ') index = action(index) val startWord = index while (index in input.indices && input[index] != ' ') index = action(index) return startWord to index } private fun generateStringBuilderWithoutExtraSpaces(input: String): StringBuilder { val result = StringBuilder() var current = 0 while (current < input.length) { val (start, end) = findNextSpaceWord(input, current) { it + 1 } (start until end).forEach { result.append(input[it]) } if (end != input.length && (end until input.length).fold(false) { acc, index -> acc || input[index] != ' ' }) { result.append(' ') } current = end } return result } } fun main() { runTests(listOf( "The sky is blue" to "blue is sky The", " hello world! " to "world! hello", "a good example" to "example good a", "a, yqo! qjktum ym. .fumuhau" to ".fumuhau ym. qjktum yqo! a," )) { (input, value) -> value to ReverseWordsInString().execute(input) } }
0
Kotlin
0
0
f093c2c19cd76c85fab87605ae4a3ea157325d43
3,781
coding
MIT License
solutions/src/FindHighestPeak.kt
JustAnotherSoftwareDeveloper
139,743,481
false
{"Kotlin": 305071, "Java": 14982}
/** * https://leetcode.com/problems/map-of-highest-peak/ * * Time Limit Exceeded, but same O(N) complexity (O(m*n)) as accepted solution */ class FindHighestPeak { fun highestPeak(isWater: Array<IntArray>): Array<IntArray> { val queue = mutableListOf<Space>() val visited = mutableSetOf<Pair<Int,Int>>() for (i in isWater.indices) { for (j in isWater[0].indices) { if (isWater[i][j] == 1) { queue.add(Space(Pair(i,j),0)) visited.add(Pair(i,j)) } } } val returnArray = Array(isWater.size){IntArray(isWater[0].size)} while (queue.isNotEmpty()) { val current = queue.removeAt(0) val point = current.point returnArray[point.first][point.second] = current.height listOf( Pair(point.first+1,point.second), Pair(point.first-1,point.second), Pair(point.first,point.second+1), Pair(point.first,point.second-1) ) .filter { !visited.contains(it) && !(it.first < 0 || it.first >= isWater.size || it.second < 0 || it.second >= isWater[0].size) } .forEach { visited.add(it) queue.add(Space(it,current.height+1)) } } return returnArray } private data class Space(val point: Pair<Int,Int>, val height : Int) }
0
Kotlin
0
0
fa4a9089be4af420a4ad51938a276657b2e4301f
1,521
leetcode-solutions
MIT License
src/main/kotlin/co/csadev/advent2021/Day09.kt
gtcompscientist
577,439,489
false
{"Kotlin": 252918}
/** * Copyright (c) 2021 by <NAME> * Advent of Code 2021, Day 9 * Problem Description: http://adventofcode.com/2021/day/9 */ package co.csadev.advent2021 import co.csadev.adventOfCode.BaseDay import co.csadev.adventOfCode.Point2D import co.csadev.adventOfCode.Resources.resourceAsList import co.csadev.adventOfCode.product class Day09(override val input: List<String> = resourceAsList("21day09.txt")) : BaseDay<List<String>, Int, Int> { private val inputGraph = input.flatMapIndexed { y, i -> i.mapIndexed { x, c -> Point2D(x, y) to c.toString().toInt() } }.toMap() override fun solvePart1(): Int = inputGraph.getLowPoints().sumOf { inputGraph[it]!! + 1 } override fun solvePart2(): Int { val basinGraph = inputGraph.getLowPoints().toMutableList() return basinGraph.map { b -> val basin = mutableListOf(b) val checkpoints = b.adjacent.toMutableList() while (checkpoints.isNotEmpty()) { val addTo = checkpoints.filter { 9 != (inputGraph[it] ?: 9) && !basin.contains(it) } basin.addAll(addTo) checkpoints.clear() checkpoints.addAll(addTo.flatMap { a -> a.adjacent }.distinct().filter { !basin.contains(it) }) } basin.size }.sortedDescending().take(3).product() } private fun Map<Point2D, Int>.getLowPoints() = keys.filter { p -> this[p]!!.let { i -> p.adjacent.all { i < this.getOrDefault(it, Int.MAX_VALUE) } } }.toMutableList() }
0
Kotlin
0
1
43cbaac4e8b0a53e8aaae0f67dfc4395080e1383
1,545
advent-of-kotlin
Apache License 2.0
Project/GameOfBones.kts
HKhademian
388,339,870
false
{"C++": 121772, "Python": 5608, "CMake": 2456, "Kotlin": 1815, "C": 14}
#! kotlinc -script // https://kotlinlang.org/docs/command-line.html#run-scripts // https://www.baeldung.com/java-minimax-algorithm object GameOfBones { fun getPossibleStates(noOfBonesInHeap: Int): List<Integer> { return (1..3) .map { noOfBonesInHeap - it } .filter { it >= 0 }.toList() } fun constructTree(noOfBones: Int): Tree { val root = Node(noOfBones, true) val tree = Tree(root) constructTree(root) return tree } private fun constructTree(parentNode: Node) { val listofPossibleHeaps = GameOfBones.getPossibleStates(parentNode.noOfBones) val isChildMaxPlayer: Boolean = !parentNode.isMaxPlayer() listofPossibleHeaps.forEach { n -> val newNode = Node(n, isChildMaxPlayer) parentNode.addChild(newNode) if (newNode.noOfBones > 0) { constructTree(newNode) } } } } class Node( var noOfBones: Int = 0, var isMaxPlayer: Boolean = false, var score: Int = 0, var children: List<Node> = emptyList(), ) class Tree( var root: Node, ) class MiniMax( var tree: Tree ) { fun checkWin(): Boolean { val root: Node = tree.root checkWin(root) return root.score == 1 } private fun checkWin(node: Node) { val children: List<Node> = node.children val isMaxPlayer: Boolean = node.isMaxPlayer children.forEach { child -> if (child.noOfBones === 0) { child.score = if (isMaxPlayer) 1 else -1 } else { checkWin(child) } } val bestChild: Node = findBestChild(isMaxPlayer, children) node.score = bestChild.score } private fun findBestChild(isMaxPlayer: Boolean, children: List<Node>): Node { return children.maxByOrNull { it.score } ?: throw Exception() } } val miniMax6 = MiniMax(GameOfBones.constructTree(6)) val result6 = miniMax.checkWin() val miniMax8 = MiniMax(GameOfBones.constructTree(8)) val result8 = miniMax.checkWin()
0
C++
0
0
0abfe552ce863338a04e4efc38d3e87c31a99013
1,815
UniGameDev
The Unlicense
src/test/kotlin/leetcode/hackercub/ProblemA2.kt
Magdi
390,731,717
false
null
package leetcode.hackercub import java.io.File import java.util.* import kotlin.collections.HashMap import kotlin.collections.HashSet class ProblemA2 { fun minSeconds(s: String, edges: List<String>): Int { val graph = HashMap<Char, HashSet<Char>>() edges.forEach { val adj = graph.getOrDefault(it[0], HashSet()) adj.add(it[1]) graph[it[0]] = adj } val cache = HashMap<Pair<Char, Char>, Int>() ('A'..'Z').forEach { a -> ('A'..'Z').forEach { b -> val x = bfs(a, b, graph) cache[Pair(a, b)] = x } } var res = Int.MAX_VALUE ('A'..'Z').forEach { t -> val target = "$t".repeat(s.length) val c = calc(s, target, cache) if (c != -1) { res = Math.min(c, res) } } return if (res == Int.MAX_VALUE) -1 else res } private fun calc(s: String, target: String, cache: HashMap<Pair<Char, Char>, Int>): Int { var ans = 0 for (i in 0..s.lastIndex) { val pair = Pair(s[i], target[i]) if (cache[pair] == -1) return -1 ans += cache[pair]!! } return ans } private fun bfs(s: Char, e: Char, graph: HashMap<Char, HashSet<Char>>): Int { val queue: Queue<Char> = LinkedList() val visited = HashSet<Char>() queue.add(s) var level = 0 while (queue.isNotEmpty()) { val l = queue.size for (i in 0 until l) { val c = queue.poll() if (c == e) return level if (visited.contains(c)) continue visited.add(c) graph.getOrDefault(c, HashSet()).forEach { queue.add(it) } } level++ } return -1 } } fun main() { val read = File("inA1.txt").readLines().iterator() val n = read.next().toInt() val problem = ProblemA2() val text = StringBuilder() for (i in 1..n) { val s = read.next() val m = read.next().toInt() val edges = (0 until m).map { read.next() } text.append("Case #${i}: ${problem.minSeconds(s, edges)}\n") } println(text) val fileOut = File("out1.txt") fileOut.writeText(text.toString()) }
0
Kotlin
0
0
63bc711dc8756735f210a71454144dd033e8927d
2,380
ProblemSolving
Apache License 2.0
2023/src/main/kotlin/net/daams/solutions/3b.kt
Michiel-Daams
573,040,288
false
{"Kotlin": 39925, "Nim": 34690}
package net.daams.solutions import net.daams.Solution class `3b`(input: String): Solution(input) { val gears: MutableList<List<Int>> = mutableListOf() var splitInput: List<String> = listOf() override fun run() { val gearRatios: MutableList<Int> = mutableListOf() splitInput = input.split("\n") splitInput.forEach{ val indices: MutableList<Int> = mutableListOf() it.forEachIndexed{ index, s -> if (s == '*') indices.add(index) } gears.add(indices.toList()) } gears.forEachIndexed{ y, xs -> xs.forEach { val adjacentNumbers: MutableList<Pair<Int, IntRange>> = mutableListOf() for (x: Int in it -1 .. it + 1) { if (x < 0 || x > 139) continue for (yy: Int in y - 1 .. y + 1) { if (yy < 0 || y > 139) continue if (splitInput[yy][x].isDigit()) adjacentNumbers.add(getFullDigit(x, yy)) } } if (adjacentNumbers.distinct().size == 2) gearRatios.add(adjacentNumbers.distinct()[0].first * adjacentNumbers.distinct()[1].first) } } println(gearRatios.sum()) } private fun getFullDigit(x: Int, y: Int): Pair<Int, IntRange> { var digit: String = splitInput[y][x].toString() var currentX = x var range = 0 .. 0 while (true) { currentX -= 1 if (currentX >= 0 && splitInput[y][currentX].isDigit()) digit = splitInput[y][currentX] + digit else { range = currentX + 1 .. range.last break } } currentX = x while (true) { currentX += 1 if (currentX <= 139 && splitInput[y][currentX].isDigit()) digit += splitInput[y][currentX] else { range = range.first..<currentX break } } return Pair(digit.toInt(), range) } }
0
Kotlin
0
0
f7b2e020f23ec0e5ecaeb97885f6521f7a903238
2,068
advent-of-code
MIT License
src/star05.kt
a-red-christmas
112,728,147
false
null
import java.lang.Math.abs import java.lang.Math.pow import kotlin.math.roundToInt import kotlin.math.sqrt fun main(args: Array<String>) { println(findManhattanDistance(368078)) } fun findManhattanDistance(start: Int) : Int { val size = getSpiralArraySize(start) val center = getSpiralArrayCenter(size) // q1, q2 == center, center val last = (pow((size).toDouble(), 2.0)).toInt() val bottomLeft = last - size + 1 val topLeft = bottomLeft - size + 1 val topRight = topLeft - size + 1 /* 1,1 ... size,1 . . . 1,size ... size,size */ val location = when { start >= bottomLeft -> Pair(size - (last - start), size) start >= topLeft -> Pair(1, size - (bottomLeft - start)) start >= topRight -> Pair(topLeft - start + 1, 1) else -> Pair(size, topRight - start + 1) } return abs(location.first - center) + abs(location.second - center) } fun getSpiralArrayCenter(size: Int): Int { val center = roundUp(size / 2.0) // q1, q2 == center, center return center } fun getSpiralArraySize(start: Int): Int { val sqrtStart = roundUp(sqrt(start.toDouble())) val size = if (sqrtStart % 2 == 0) sqrtStart + 1 else sqrtStart return size } fun roundUp(num : Double) : Int { val rounded = num.roundToInt() return if (num > rounded) rounded + 1 else rounded }
0
Kotlin
0
0
14e50f42c6550110b7007088af96f0260f4ac887
1,373
aoc2017-kt
Apache License 2.0
artifactfinder/src/main/kotlin/com/birbit/artifactfinder/VersionSelector.kt
yigit
209,722,505
false
null
/* * Copyright 2019 Google, Inc. * * 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.birbit.artifactfinder import com.birbit.artifactfinder.model.Version object VersionSelector { /** * Current version selection logic: * Take last 3 stable releases * Take latest rc, if it is greater than latest stable * Take latest beta, if it is greater than latest stable & rc * Take latest alpha, if it is greater than latest stable & rc & beta * */ fun selectVersions(input: List<Version>): Set<Version> { val sorted = input.sortedDescending() val selected = mutableListOf<Version>() val counters = Counters() sorted.forEach { version -> val select = if (version.isRelease) { true } else if (version.isRc) { selected.all { if (it.isRelease) { it < version } else { true // can pick rc when there is } } } else if (version.isBeta) { selected.all { if (it.isRelease || it.isRc) { it < version } else { true } } } else if (version.isAlpha) { selected.all { if (it.isRelease || it.isRc || it.isBeta) { it < version } else { true } } } else { false } if (select && counters.inc(version)) { selected.add(version) } } return selected.toSet() } } private class Counter( var limit: Int, var cnt: Int = 0 ) { fun inc(): Boolean { return if (cnt < limit) { cnt++ true } else { false } } } private class Counters { var stable = Counter(LIMIT_STABLE) var rc = Counter(LIMIT_RC) var beta = Counter(LIMIT_BETA) var alpha = Counter(LIMIT_ALPHA) fun inc(version: Version): Boolean { val counter = when { version.isRelease -> stable version.isRc -> rc version.isBeta -> beta version.isAlpha -> alpha else -> return false } return counter.inc() } companion object { val LIMIT_STABLE = 3 val LIMIT_RC = 1 val LIMIT_BETA = 1 val LIMIT_ALPHA = 1 } }
27
Kotlin
5
190
ee9f2870d32b8e438f36f0c405473edff28b6b3e
3,129
ArtifactFinder
Apache License 2.0
tmp/arrays/youTrackTests/8578.kt
vitekkor
600,111,569
true
{"Kotlin": 11763351, "JavaScript": 2761845, "ANTLR": 28803, "Java": 12579}
// Original bug: KT-20373 import java.util.Stack fun sumSubsets(arr: MutableList<Int>, num: Int): MutableList<MutableList<Int>> { class Subset(val indexes: IntArray) { fun add(index: Int) = Subset(indexes + index) fun values() = indexes.map { arr[it] } fun sum() = values().sum() fun missingValues() = (0 until arr.size).minus(indexes.toTypedArray()) } val solutions = mutableListOf<MutableList<Int>>() val arrSum = arr.sum() if (arrSum >= num) { val stack = Stack<Subset>() stack.push(Subset(IntArray(0))) while (stack.isNotEmpty()) { val subset = stack.pop() val sum = subset.sum() if (sum == num) solutions.add(subset.values().toMutableList()) else if (sum < num) { stack.addAll(subset.missingValues().map { subset.add(it) }) } } } return solutions } fun main(args: Array<String>) { println(sumSubsets(mutableListOf(1, 2, 3, 4, 5), 5)) println(sumSubsets(mutableListOf(1, 2, 2, 3, 4, 5), 5)) println(sumSubsets(mutableListOf(), 0)) println(sumSubsets(mutableListOf(1, 1, 1, 1, 1, 1, 1, 1, 1), 9)) println(sumSubsets(mutableListOf(1, 1, 2, 2, 2, 5, 5, 6, 8, 8), 9)) println(sumSubsets(mutableListOf(1, 1, 2, 4, 4, 4, 7, 9, 9, 13, 13, 13, 15, 15, 16, 16, 16, 19, 19, 20), 36)) }
1
Kotlin
12
0
f47406356a160ac61ab788f985b37121cc2e2a2a
1,293
bbfgradle
Apache License 2.0
src/Day09.kt
RickShaa
572,623,247
false
{"Kotlin": 34294}
import java.util.* import kotlin.collections.ArrayDeque import kotlin.math.abs import kotlin.math.sign fun main() { val fileName = "day09.txt" val testFileName = "day09_test.txt" val input = FileUtil.getListOfLines(fileName) fun moveHead(move: String, head: Point) { when (Direction.valueOf(move)) { Direction.L -> head.x -= 1 Direction.R -> head.x += 1 Direction.U -> head.y += 1 Direction.D -> head.y -= 1 } } /* CHESSBOARD DISTANCE dis(p1,p2) = (|xa -xb|, |ya-yb|) Use case: Finds the shortest distance while only considering horizontal and vertical movements If distance > 1 tail can follow head safely Source theory: https://towardsdatascience.com/3-distances-that-every-data-scientist-should-know-59d864e5030a Source Kotlin Advent of Code Day 9 Video https://www.youtube.com/watch?v=ShU9dNUa_3g&t=2153s */ fun distance(head:Point, tail:Point): Int { val deltaX = head.x - tail.x val deltaY = head.y - tail.y return maxOf(abs(deltaX),abs(deltaY)) } /* Direction Vector When subtracting two points the result is a Direction Vector Example: Head(x=2,y=4) Tail(x=1,y=2) Head - Tail = V V = <1,2> V represents an arrow from the origin (0,0) to (1,2), giving us the direction to move in Source Study Smarter: https://www.studysmarter.de/schule/mathe/geometrie/richtungsvektor/ Source Kotlin Advent of Code Day 9 Video https://www.youtube.com/watch?v=ShU9dNUa_3g&t=2153s */ fun moveTail(head:Point,tail:Point){ val(dX,dY) = head.delta(tail) val directionX = dX.coerceIn(-1,1) val directionY = dY.coerceIn(-1,1) tail.x+=directionX tail.y+=directionY } fun moveTail(head:Point,tail:Point, tailPos:MutableSet<Point>){ val(dX,dY) = head.delta(tail) /* Ensures value to be in a specific range Meaning: if head is two steps ahead of tail, we only want to move tail next to head, not make tail land on head. This would happen if we would move the entire length of the direction vector */ val directionX = dX.coerceIn(-1,1) val directionY = dY.coerceIn(-1,1) tail.x+=directionX tail.y+=directionY tailPos.add(Point(tail.x,tail.y)) } //Init head and tail position //val head = Point(0, 0) //val tail = Point(0, 0) val rope = Array(10){Point(0,0)} //Add distinct tail positions (Set) val tailPositions: MutableSet<Point> = mutableSetOf(rope.last()) for(i in input.indices){ val (direction,steps) = input[i].split(" ") for(step in 0 until steps.toInt()){ moveHead(direction,rope[0]) for(idx in 0 until 9){ //start at comparing head index = 0 to index +1 val head = rope[idx] val tail = rope[idx +1] if(distance(head, tail) > 1){ if(idx + 1 == 9){ moveTail(head,tail,tailPositions) }else{ moveTail(head, tail) } } } } } println(tailPositions.count()) } data class Point(var x:Int, var y:Int){ fun delta(p2:Point):Pair<Int,Int>{ val deltaX = this.x - p2.x val deltaY = this.y - p2.y return Pair(deltaX,deltaY) } } enum class Direction { L, R, U, D; }
0
Kotlin
0
1
76257b971649e656c1be6436f8cb70b80d5c992b
3,699
aoc
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/NumberOfAtoms.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2022 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import java.util.Stack import java.util.TreeMap import java.util.regex.Matcher import java.util.regex.Pattern /** * 726. Number of Atoms * @see <a href="https://leetcode.com/problems/number-of-atoms/">Source</a> */ fun interface NumberOfAtoms { fun countOfAtoms(formula: String): String } /** * Approach #1: Recursion */ class NumberOfAtomsRecursion : NumberOfAtoms { var i = 0 override fun countOfAtoms(formula: String): String { val ans = StringBuilder() i = 0 val count = parse(formula) for (name in count.keys) { ans.append(name) val multiplicity = count.getOrDefault(name, -1) if (multiplicity > 1) { ans.append("" + multiplicity) } } return String(ans) } private fun parse(formula: String): Map<String, Int> { val n = formula.length val count: MutableMap<String, Int> = TreeMap() while (i < n && formula[i] != ')') { if (formula[i] == '(') { i++ for ((key, value) in parse(formula)) { count[key] = count.getOrDefault(key, 0) + value } } else { var iStart: Int = i++ while (i < n && Character.isLowerCase(formula[i])) { i++ } val name = formula.substring(iStart, i) iStart = i while (i < n && Character.isDigit(formula[i])) { i++ } val multiplicity = if (iStart < i) formula.substring(iStart, i).toInt() else 1 count[name] = count.getOrDefault(name, 0) + multiplicity } } val iStart: Int = ++i while (i < n && Character.isDigit(formula[i])) { i++ } if (iStart < i) { val multiplicity = formula.substring(iStart, i).toInt() for (key in count.keys) { count[key] = count[key]!! * multiplicity } } return count } } /** * Approach #2: Stack */ class NumberOfAtomsStack : NumberOfAtoms { override fun countOfAtoms(formula: String): String { val n: Int = formula.length val stack: Stack<MutableMap<String, Int>> = Stack() stack.push(TreeMap()) var i = 0 while (i < n) { if (formula[i] == '(') { stack.push(TreeMap()) i++ } else if (formula[i] == ')') { val top: Map<String, Int> = stack.pop() val iStart = ++i var multiplicity = 1 while (i < n && Character.isDigit(formula[i])) { i++ } if (i > iStart) multiplicity = formula.substring(iStart, i).toInt() for (c in top.keys) { val v = top[c]!! stack.peek()[c] = stack.peek().getOrDefault(c, 0) + v * multiplicity } } else { var iStart = i++ while (i < n && Character.isLowerCase(formula[i])) { i++ } val name = formula.substring(iStart, i) iStart = i while (i < n && Character.isDigit(formula[i])) { i++ } val multiplicity = if (i > iStart) formula.substring(iStart, i).toInt() else 1 stack.peek()[name] = stack.peek().getOrDefault(name, 0) + multiplicity } } return format(stack) } fun format(stack: Stack<MutableMap<String, Int>>): String { val ans = StringBuilder() for (name in stack.peek().keys) { ans.append(name) val multiplicity: Int = stack.peek()[name] ?: -1 if (multiplicity > 1) { ans.append("" + multiplicity) } } return ans.toString() } } /** * Approach #3: Regular Expressions */ class NumberOfAtomsRegex : NumberOfAtoms { override fun countOfAtoms(formula: String): String { val matcher: Matcher = Pattern.compile("([A-Z][a-z]*)(\\d*)|(\\()|(\\))(\\d*)").matcher(formula) val stack: Stack<MutableMap<String, Int>> = Stack() stack.push(TreeMap()) while (matcher.find()) { val match: String = matcher.group() if (match == "(") { stack.push(TreeMap()) } else if (match.startsWith(")")) { val top: Map<String, Int> = stack.pop() val multiplicity = if (match.length > 1) match.substring(1, match.length).toInt() else 1 for (name in top.keys) { stack.peek()[name] = stack.peek().getOrDefault(name, 0) + top[name]!! * multiplicity } } else { var i = 1 while (i < match.length && Character.isLowerCase(match[i])) { i++ } val name = match.substring(0, i) val multiplicity = if (i < match.length) match.substring(i, match.length).toInt() else 1 stack.peek()[name] = stack.peek().getOrDefault(name, 0) + multiplicity } } val ans = StringBuilder() for (name in stack.peek().keys) { ans.append(name) val count = stack.peek()[name] ?: -1 if (count > 1) ans.append(count.toString()) } return ans.toString() } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
6,199
kotlab
Apache License 2.0
src/questions/RestoreIPAddresses.kt
realpacific
234,499,820
false
null
package questions import _utils.UseCommentAsDocumentation import utils.assertIterableSameInAnyOrder /** * A valid IP address consists of exactly four integers separated by single dots. * Each integer is between 0 and 255 (inclusive) and cannot have leading zeros. * Given a string s containing only digits, return all possible valid IP addresses that can be formed * by inserting dots into s. You are not allowed to reorder or remove any digits in s. * You may return the valid IP addresses in any order. * * [Source](https://leetcode.com/problems/restore-ip-addresses/) */ @UseCommentAsDocumentation private fun restoreIpAddresses(s: String): List<String> { if (s.length == 4) { val ip = s.toCharArray().joinToString(".") return listOf(ip) } // invalid ips if (s.length < 4 || s.length > 12) { return emptyList() } val result = mutableListOf<IPAddress>() generateIPAddress(s, 0, result) return result.mapNotNull { it.stringOrNull() }.distinct() } private class IPAddress { private var address = mutableListOf<String>() fun put(value: Char) { if (address.isEmpty()) { address.add(value.toString()) return } val last = address.last() val newValue = last + value if (newValue.toInt() <= 255) { // replace current field address[address.lastIndex] = newValue } else { // can't be accommodated into current field address.add(value.toString()) } } fun putInNext(value: Char) { address.add(value.toString()) } fun clone(): IPAddress { return IPAddress().let { it.address = mutableListOf<String>().apply { this.addAll(address) } it } } fun isNoLongerValid(): Boolean { return address.size > 4 || address.find { it.length > 1 && it.startsWith("0") } != null } fun stringOrNull(): String? { if (address.size != 4) return null if (address.find { it.length > 1 && it.startsWith("0") } != null) return null return toString() } override fun toString(): String { return address.joinToString(".") { it } } } private fun generateIPAddress(s: String, index: Int, result: MutableList<IPAddress>) { if (index > s.lastIndex) { return } val character = s[index] if (result.isEmpty()) { // add the first element val address = IPAddress().apply { put(character) } result.add(address) generateIPAddress(s, index + 1, result) return } val newIps = mutableListOf<IPAddress>() result.forEach { // when adding a new character to IP, you can either add it to currently active field // or put it in next field // add it to currently active field i.e. 10.1.. --2--> 10.12.. newIps.add(it.clone().apply { this.put(character) }) // put it in the next field i.e. 10.1.. --2--> 10.1.2. newIps.add(it.clone().apply { this.putInNext(character) }) } result.clear() // early break. If NONE of the current ips are no longer valid, then leave the remaining characters // as adding any other invalid will still make it invalid eg 530474625546 --> <IP_ADDRESS> is no longer valid if (newIps.filter { !it.isNoLongerValid() }.isEmpty()) { return } result.addAll(newIps) generateIPAddress(s, index + 1, result) } fun main() { assertIterableSameInAnyOrder( restoreIpAddresses("530474625546"), listOf() ) assertIterableSameInAnyOrder( restoreIpAddresses("103574606193"), listOf() ) assertIterableSameInAnyOrder( restoreIpAddresses("255255255255"), listOf("255.255.255.255") ) assertIterableSameInAnyOrder( restoreIpAddresses("25525511135"), listOf("255.255.11.135", "255.255.111.35") ) assertIterableSameInAnyOrder( restoreIpAddresses("0000"), listOf("0.0.0.0") ) assertIterableSameInAnyOrder( restoreIpAddresses("101023"), listOf("<IP_ADDRESS>", "<IP_ADDRESS>", "10.1.0.23", "10.10.2.3", "<IP_ADDRESS>") ) }
4
Kotlin
5
93
22eef528ef1bea9b9831178b64ff2f5b1f61a51f
4,213
algorithms
MIT License
kotlinLeetCode/src/main/kotlin/leetcode/editor/cn/[137]只出现一次的数字 II.kt
maoqitian
175,940,000
false
{"Kotlin": 354268, "Java": 297740, "C++": 634}
//给你一个整数数组 nums ,除某个元素仅出现 一次 外,其余每个元素都恰出现 三次 。请你找出并返回那个只出现了一次的元素。 // // // // 示例 1: // // //输入:nums = [2,2,3,2] //输出:3 // // // 示例 2: // // //输入:nums = [0,1,0,1,0,1,99] //输出:99 // // // // // 提示: // // // 1 <= nums.length <= 3 * 104 // -231 <= nums[i] <= 231 - 1 // nums 中,除某个元素仅出现 一次 外,其余每个元素都恰出现 三次 // // // // // 进阶:你的算法应该具有线性时间复杂度。 你可以不使用额外空间来实现吗? // Related Topics 位运算 数组 // 👍 780 👎 0 //leetcode submit region begin(Prohibit modification and deletion) class Solution { fun singleNumber(nums: IntArray): Int { var map = HashMap<Int,Int>() nums.forEach { if (map.containsKey(it)){ map.put(it,map.get(it)!!+1) }else{ map.put(it,1) } } map.forEach { (t, u) -> if (u == 1) return t } return -1 var res = 0 for (i in 0..31) { val mask = 1 shl i var cnt = 0 for (j in 0 until nums.size) { if (nums[j] and mask !== 0) { cnt++ } } if (cnt % 3 != 0) { res = res or mask } } return res } } //leetcode submit region end(Prohibit modification and deletion)
0
Kotlin
0
1
8a85996352a88bb9a8a6a2712dce3eac2e1c3463
1,567
MyLeetCode
Apache License 2.0
src/main/kotlin/io/recursion/SkylineProblem.kt
jffiorillo
138,075,067
false
{"Kotlin": 434399, "Java": 14529, "Shell": 465}
package io.recursion // https://leetcode.com/explore/learn/card/recursion-ii/507/beyond-recursion/3006/ class SkylineProblem { fun execute(buildings: Array<IntArray>): List<List<Int>> { val sortDots = convertToPoints(buildings) val currentArea = mutableListOf<Int>() val result: MutableList<List<Int>> = mutableListOf() var currentAreaMax = 0 sortDots.forEach { element -> when (element.type) { BuildingPointType.BEGIN -> { currentArea.add(element.height) if (element.height > currentAreaMax) { currentAreaMax = element.height result.add(element.toList()) } } BuildingPointType.END -> { currentArea.remove(element.height) val newCurrentAreaMax = currentArea.maxOrNull() ?: 0 if (newCurrentAreaMax != currentAreaMax) { currentAreaMax = newCurrentAreaMax result.add(listOf(element.x, currentAreaMax)) } } } } return result } fun convertToPoints(buildings: Array<IntArray>): List<BuildingPoint> = buildings.flatMap { listOf(BuildingPoint(it[0], it[2], BuildingPointType.BEGIN), BuildingPoint(it[1], it[2], BuildingPointType.END)) }.sorted() data class BuildingPoint(val x: Int, val height: Int, val type: BuildingPointType) : Comparable<BuildingPoint> { fun toList() = listOf(x, height) private fun getComparableValue() = if (this.type == BuildingPointType.BEGIN) -this.height else this.height override fun compareTo(other: BuildingPoint): Int = when { this.x != other.x -> this.x - other.x else -> getComparableValue() - other.getComparableValue() } } enum class BuildingPointType { BEGIN, END } } fun main() { val skylineProblem = SkylineProblem() skylineProblem.convertToPoints(arrayOf(intArrayOf(0, 2, 3), intArrayOf(0, 1, 2), intArrayOf(3, 5, 3), intArrayOf(4, 5, 2))).map { println(it) } }
0
Kotlin
0
0
f093c2c19cd76c85fab87605ae4a3ea157325d43
1,997
coding
MIT License
src/main/kotlin/day12/solution.kt
bukajsytlos
433,979,778
false
{"Kotlin": 63913}
package day12 import java.io.File fun main() { val lines = File("src/main/kotlin/day12/input.txt").readLines() val cavesByName: MutableMap<String, Cave> = mutableMapOf() lines.forEach { val fromCaveName = it.substringBefore("-") val toCaveName = it.substringAfter("-") val fromCave = cavesByName.computeIfAbsent(fromCaveName) { Cave(fromCaveName) } val toCave = cavesByName.computeIfAbsent(toCaveName) { Cave(toCaveName) } fromCave.addConnection(toCave) } val startCave = cavesByName.getValue("start") val endCave = cavesByName.getValue("end") println( search(endCave, listOf(startCave)) { cave, visitedCavesPath -> cave.isLarge() || cave !in visitedCavesPath } .count() ) println( search(endCave, listOf(startCave)) { cave, visitedCavesPath -> cave.isLarge() || cave !in visitedCavesPath || cave.name != "start" && visitedCavesPath.filter { !it.isLarge() } .groupBy { it } .mapValues { it.value.size } .let { map -> map.isNotEmpty() && map.all { it.value == 1 } } } .count() ) } fun search(toCave: Cave, visitedCavesPath: List<Cave>, visitStrategy: (Cave, List<Cave>) -> Boolean): Set<List<Cave>> { val lastVisited = visitedCavesPath.last() if (lastVisited == toCave) return mutableSetOf(visitedCavesPath) return lastVisited.connectsTo .filter { visitStrategy(it, visitedCavesPath) } .map { search(toCave, visitedCavesPath + it, visitStrategy) } .flatten().toSet() } data class Cave(val name: String) { val connectsTo: MutableSet<Cave> = mutableSetOf() fun addConnection(other: Cave) { if (other !in connectsTo) { connectsTo.add(other) other.addConnection(this) } } fun isLarge() = name.all { it.isUpperCase() } override fun toString(): String { return name } }
0
Kotlin
0
0
f47d092399c3e395381406b7a0048c0795d332b9
1,968
aoc-2021
MIT License
exercises/practice/etl/src/test/kotlin/ETLTest.kt
exercism
47,675,865
false
{"Kotlin": 382097, "Shell": 14600}
import org.junit.Test import org.junit.Ignore import kotlin.test.assertEquals class ETLTest { @Test fun `single letter`() = assertTransformedEquals( mapOf( 1 to listOf('A')), mapOf( 'a' to 1)) @Ignore @Test fun `single score with multiple letters`() = assertTransformedEquals( mapOf( 1 to listOf('A', 'E', 'I', 'O', 'U')), mapOf( 'a' to 1, 'e' to 1, 'i' to 1, 'o' to 1, 'u' to 1)) @Ignore @Test fun `multiple scores with multiple letters`() = assertTransformedEquals( mapOf( 1 to listOf('A', 'E'), 2 to listOf('D', 'G')), mapOf( 'a' to 1, 'd' to 2, 'e' to 1, 'g' to 2)) @Ignore @Test fun `multiple scores with differing numbers of letters`() = assertTransformedEquals( mapOf( 1 to listOf('A', 'E', 'I', 'O', 'U', 'L', 'N', 'R', 'S', 'T'), 2 to listOf('D', 'G'), 3 to listOf('B', 'C', 'M', 'P'), 4 to listOf('F', 'H', 'V', 'W', 'Y'), 5 to listOf('K'), 8 to listOf('J', 'X'), 10 to listOf('Q', 'Z')), mapOf( 'a' to 1, 'b' to 3, 'c' to 3, 'd' to 2, 'e' to 1, 'f' to 4, 'g' to 2, 'h' to 4, 'i' to 1, 'j' to 8, 'k' to 5, 'l' to 1, 'm' to 3, 'n' to 1, 'o' to 1, 'p' to 3, 'q' to 10, 'r' to 1, 's' to 1, 't' to 1, 'u' to 1, 'v' to 4, 'w' to 4, 'x' to 8, 'y' to 4, 'z' to 10)) } private fun assertTransformedEquals(input: Map<Int, List<Char>>, expectation: Map<Char, Int>) = assertEquals(expectation, ETL.transform(input))
51
Kotlin
190
199
7f1c7a11cfe84499cfef4ea2ecbc6c6bf34a6ab9
1,983
kotlin
MIT License
src/main/kotlin/utils/graph/Dijkstra.kt
chjaeggi
728,738,815
false
{"Kotlin": 87254}
package utils.graph import AdjacencyList import Edge import Vertex import java.util.PriorityQueue import kotlin.Comparator import kotlin.collections.ArrayList import kotlin.collections.HashMap class Dijkstra<T : Any>(private val graph: AdjacencyList<T>) { private fun route( destination: Vertex<T>, paths: HashMap<Vertex<T>, Visit<T>> ): ArrayList<Edge<T>> { var vertex = destination val path = arrayListOf<Edge<T>>() loop@ while (true) { val visit = paths[vertex] ?: break when (visit.type) { VisitType.START -> break@loop VisitType.EDGE -> visit.edge?.let { path.add(it) vertex = it.source } } } return path } private fun distance(destination: Vertex<T>, paths: HashMap<Vertex<T>, Visit<T>>): Double { val path = route(destination, paths) return path.sumOf { it.weight ?: 0.0 } } private fun shortestPath(start: Vertex<T>): HashMap<Vertex<T>, Visit<T>> { val paths: HashMap<Vertex<T>, Visit<T>> = HashMap() paths[start] = Visit(VisitType.START) val distanceComparator = Comparator<Vertex<T>> { first, second -> (distance(second, paths) - distance(first, paths)).toInt() } val priorityQueue = PriorityQueue(distanceComparator) priorityQueue.add(start) while (priorityQueue.isNotEmpty()) { val vertex = priorityQueue.remove() val edges = graph.edges(vertex) edges.forEach { val weight = it.weight ?: return@forEach if (paths[it.destination] == null || distance(vertex, paths) + weight < distance(it.destination, paths) ) { paths[it.destination] = Visit(VisitType.EDGE, it) priorityQueue.add(it.destination) } } } return paths } fun shortestPath( destination: Vertex<T>, paths: HashMap<Vertex<T>, Visit<T>> ): ArrayList<Edge<T>> { return route(destination, paths) } fun getAllShortestPath(source: Vertex<T>): HashMap<Vertex<T>, ArrayList<Edge<T>>> { val paths = HashMap<Vertex<T>, ArrayList<Edge<T>>>() val pathsFromSource = shortestPath(source) graph.vertices.forEach { val path = shortestPath(it, pathsFromSource) paths[it] = path } return paths } } class Visit<T : Any>(val type: VisitType, val edge: Edge<T>? = null) enum class VisitType { START, EDGE }
0
Kotlin
1
1
a6522b7b8dc55bfc03d8105086facde1e338086a
2,674
aoc2023
Apache License 2.0
kotlin/src/main/kotlin/adventofcode/day12/Day12_1.kt
thelastnode
160,586,229
false
null
package adventofcode.day12 import java.io.File import java.lang.Exception import java.lang.IllegalArgumentException object Day12_1 { data class Rule(val condition: String, val result: Char) fun parse(lines: List<String>): Pair<String, List<Rule>> { val initialState = lines[0].split(": ")[1].trim() val rules = lines.drop(2) .filter { it.trim().isNotEmpty() } .map { it.split(" => ") } .map { (condition, result) -> Rule(condition, result[0])} return Pair(initialState, rules) } fun conditions(state: String): List<String> { return ("..$state..").windowed(5) } private fun step(initialState: String, rules: List<Rule>): String { val rulesMap = rules.groupBy { it.condition } .mapValues { (_, v) -> if (v.size != 1) { throw IllegalArgumentException() } v[0] } return conditions(initialState) .map { if (it in rulesMap) { rulesMap[it]!!.result } else { '.' } } .joinToString("") } fun process(initialState: String, rules: List<Rule>): Int { val pad = (0 until 100).map { '.' }.joinToString("") var state = pad + initialState + pad for (i in 0 until 20) { state = step(state, rules) } return state.withIndex().sumBy { (i, x) -> if (x == '.') 0 else i - pad.length } } } fun main(args: Array<String>) { val lines = File("./day12-input").readLines() val (initialState, rules) = Day12_1.parse(lines) println(Day12_1.process(initialState, rules)) }
0
Kotlin
0
0
8c9a3e5a9c8b9dd49eedf274075c28d1ebe9f6fa
1,820
adventofcode
MIT License
src/test/kotlin/be/brammeerten/y2022/Day11Test.kt
BramMeerten
572,879,653
false
{"Kotlin": 170522}
package be.brammeerten.y2022 import be.brammeerten.extractRegexGroups import be.brammeerten.readFileSplitted import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.Test class Day11Test { val ITEMS_REGEX = "^ {2}Starting items: ((-?\\d+, )*(-?\\d+)+)$" val OP_REGEX = "^ {2}Operation: new = (.+)$" val DIV_REGEX = "^ {2}Test: divisible by (-?\\d+)$" val TRUE_REGEX = "^ {4}If true: throw to monkey (\\d+)$" val FALSE_REGEX = "^ {4}If false: throw to monkey (\\d+)$" @Test fun `part 1`() { val monkeys = parseMonkeys("2022/day11/input.txt") for (round in (1..20)) doRound(monkeys, relieve = true) val counts = monkeys.map { it.count }.sortedDescending() Assertions.assertEquals(61503L, counts[0] * counts[1]) } @Test fun `part 2`() { val monkeys = parseMonkeys("2022/day11/input.txt") for (round in (1..10000)) doRound(monkeys) monkeys.forEachIndexed { i, m -> println("Monkey $i: ${m.count}") } val counts = monkeys.map { it.count }.sortedDescending() Assertions.assertEquals(14081365540L, counts[0] * counts[1]) } fun doRound(monkeys: List<Monkey>, relieve: Boolean = false) { val optimizeFactor = calcOptimizeFactor(monkeys) monkeys.forEachIndexed { i, monkey -> monkey.items.forEach { item -> // Inspect var worry = monkey.operation(item) monkey.count++ // Optimize worry %= optimizeFactor // Relieve if (relieve) worry /= 3 // Test and throw val newMonk = monkey.nextMonkey(worry) monkeys[newMonk].items.add(worry) } monkey.items.clear() } } fun parseMonkeys(fileName: String) = readFileSplitted(fileName, "\n\n").map { parseMonkey(it) } fun parseMonkey(lines: List<String>): Monkey { val items = extractRegexGroups(ITEMS_REGEX, lines[1])[0].split(", ").map { it.toLong() } val div = extractRegexGroups(DIV_REGEX, lines[3])[0].toInt() val trueMonkey = extractRegexGroups(TRUE_REGEX, lines[4])[0].toInt() val falseMonkey = extractRegexGroups(FALSE_REGEX, lines[5])[0].toInt() return Monkey( readOperation(lines[2]), div, trueMonkey, falseMonkey, items.toMutableList() ) } fun readOperation(line: String): (Long) -> Long { val opString = extractRegexGroups(OP_REGEX, line)[0] return { old -> val ops = opString.replace("old", old.toString(), false).split(" ") val start = ops[0].toLong() ops.drop(1) .windowed(2, 2) .fold(start) { result, (op, num) -> when (op) { "+" -> result + num.toLong() "*" -> result * num.toLong() else -> throw IllegalStateException("Unknown operation: $op") } } } } fun calcOptimizeFactor(monkeys: List<Monkey>) = monkeys.map { it.divByTest }.reduce{a, b -> a * b} class Monkey( val operation: (Long) -> Long, val divByTest: Int, private val monkeyDivTrue: Int, private val monkeyDivFalse: Int, val items: MutableList<Long>) { var count = 0L fun nextMonkey(item: Long): Int { return if (item % divByTest == 0L) monkeyDivTrue else monkeyDivFalse } } }
0
Kotlin
0
0
1defe58b8cbaaca17e41b87979c3107c3cb76de0
3,599
Advent-of-Code
MIT License
src/Day01.kt
splinkmo
573,209,594
false
{"Kotlin": 6593}
fun main() { fun part1(input: List<String>): Int { var maxCalorie = 0 var elfCalories = 0 for (value in input){ if (value != ""){ elfCalories += value.toInt() } else { if (elfCalories > maxCalorie) { maxCalorie = elfCalories } elfCalories = 0 } } return maxCalorie } fun part2(input: List<String>): Int { val maxCalArray = arrayOf(0,0,0) var elfCalories = 0 for (value in input){ if (value != ""){ elfCalories += value.toInt() } else { if (elfCalories > maxCalArray[0]) { println("Replacing " + maxCalArray[0] + " with $elfCalories") maxCalArray[0] = elfCalories maxCalArray.sort() } elfCalories = 0 } } if (elfCalories > maxCalArray[0]) { println("Replacing " + maxCalArray[0] + " with $elfCalories") maxCalArray[0] = elfCalories maxCalArray.sort() } return maxCalArray[0] + maxCalArray[1] + maxCalArray[2] } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") //println(part2(testInput)) val input = readInput("Day01") //println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
4ead85d0868feec13cc300055beba7830b798345
1,507
advent-code-22
Apache License 2.0
src/main/kotlin/io/github/clechasseur/adventofcode/y2022/Day7.kt
clechasseur
567,968,171
false
{"Kotlin": 493887}
package io.github.clechasseur.adventofcode.y2022 import io.github.clechasseur.adventofcode.y2022.data.Day7Data object Day7 { private val input = Day7Data.input private val shellRegex = """^\$ (cd|ls)(?: ([a-zA-Z./]+))?$""".toRegex() private val fileRegex = """^(\d+|dir) (.+)$""".toRegex() fun part1(): Long = input.toFilesystem().flat().filter { it.size <= 100_000L }.sumOf { it.size } fun part2(): Long { val fs = input.toFilesystem() val avail = 70_000_000L - fs.size val needed = 30_000_000L - avail return fs.flat().filter { it.size >= needed }.minOf { it.size } } private data class File(val name: String, val size: Long) private class Dir(val name: String) { val files = mutableListOf<File>() val dirs = mutableListOf<Dir>() var parent: Dir? = null val size: Long get() = files.sumOf { it.size } + dirs.sumOf { it.size } fun flat(): Sequence<Dir> = sequenceOf(this) + dirs.asSequence().flatMap { it.flat() } } private fun String.toFilesystem(): Dir { val root = Dir("/") var pwd = root var ls = false for (line in lines()) { val shellMatch = shellRegex.matchEntire(line) if (shellMatch != null) { when (shellMatch.groupValues[1]) { "cd" -> { ls = false pwd = when (val dirName = shellMatch.groupValues[2]) { "/" -> root ".." -> pwd.parent ?: error("..: unknown directory") else -> pwd.dirs.singleOrNull { it.name == dirName } ?: error("$dirName: not found") } } "ls" -> ls = true else -> error("${shellMatch.groupValues[1]}: unknown command") } } else { require(ls) { "Invalid command in command mode: $line" } val fileMatch = fileRegex.matchEntire(line) ?: error("Invalid file in ls mode: $line") val (size, name) = fileMatch.destructured when (size) { "dir" -> { val subdir = Dir(name) subdir.parent = pwd pwd.dirs.add(subdir) } else -> pwd.files.add(File(name, size.toLong())) } } } return root } }
0
Kotlin
0
0
7ead7db6491d6fba2479cd604f684f0f8c1e450f
2,525
adventofcode2022
MIT License
src/main/kotlin/graph/variation/PathReachability.kt
yx-z
106,589,674
false
null
package graph.variation import java.util.* import kotlin.collections.HashSet // given a isDirected graph // and two nodes in the graph // find if there exists a valid (isDirected) path between them fun main(args: Array<String>) { // a -> b -> e // | ^ | // | | | // | -> d | // | ^ | // | | | // |--> c <--| val adjList = arrayOf( // first -> second "a" to "b", "a" to "d", "a" to "c", "b" to "e", "e" to "c", "c" to "d", "d" to "b" ) // true println(adjList.pathBFS("e", "b")) println(adjList.pathDFS("e", "b")) // false println(adjList.pathBFS("b", "a")) println(adjList.pathDFS("b", "a")) // true println(adjList.pathBFS("b", "d")) println(adjList.pathDFS("b", "d")) // false println(adjList.pathBFS("e", "a")) println(adjList.pathDFS("e", "a")) } // bfs to see if start -> end fun Array<Pair<String, String>>.pathBFS(start: String, end: String): Boolean { val visitedSet = HashSet<String>() val visitedQueue: Queue<String> = LinkedList<String>() visitedQueue.add(start) while (visitedQueue.isNotEmpty()) { val trav = visitedQueue.remove() if (trav == end) { return true } visitedSet.add(trav) filter { it.first == trav && !visitedSet.contains(it.second) } .forEach { visitedQueue.add(it.second) } } return false } // recursive dfs version (implicit stack) fun Array<Pair<String, String>>.pathDFS(start: String, end: String, visitedSet: HashSet<String> = HashSet()): Boolean { if (start == end) { return true } visitedSet.add(start) return filter { it.first == start && !visitedSet.contains(it.second) } .any { pathDFS(it.second, end, visitedSet) } }
0
Kotlin
0
1
15494d3dba5e5aa825ffa760107d60c297fb5206
1,666
AlgoKt
MIT License
src/main/kotlin/com/chriswk/aoc/advent2021/Day3.kt
chriswk
317,863,220
false
{"Kotlin": 481061}
package com.chriswk.aoc.advent2021 import com.chriswk.aoc.AdventDay import com.chriswk.aoc.util.report import kotlin.math.pow class Day3 : AdventDay(2021, 3) { companion object { @JvmStatic fun main(args: Array<String>) { val day = Day3() report { day.part1() } report { day.part2() } } } fun epsilon(gamma: Int, mask: Int): Int { return gamma xor mask } fun gamma(input: List<String>): String { return (0.until(input[0].length)).map { idx -> mostUsedBit(input, idx) }.joinToString(separator = "") } fun mostUsedBit(input: List<String>, idx: Int): Char { val (zeros, ones) = input.map { it[idx] }.partition { it == '0' } return if (zeros.size >= ones.size) '0' else '1' } fun leastUsedBit(input: List<String>, idx: Int): Char { val (zeros, ones) = input.map { it[idx] }.partition { it == '0' } return if (zeros.size <= ones.size) '0' else '1' } fun mostUsedBitOnes(input: List<String>, idx: Int): Char { val (zeros, ones) = input.map { it[idx] }.partition { it == '0' } return if (ones.size >= zeros.size) '1' else '0' } fun oxygen(input: List<String>): String { return (0 until input[0].length).fold(input) { remaining, idx -> if (remaining.size == 1) { remaining } else { val toKeep = mostUsedBitOnes(remaining, idx) remaining.filter { it[idx] == toKeep } } }.first() } fun co2(input: List<String>): String { return (0 until input[0].length).fold(input) { remaining, idx -> if (remaining.size == 1) { return remaining.first() } else { val toKeep = leastUsedBit(remaining, idx) remaining.filter { it[idx] == toKeep } } }.first() } fun part1(): Int { val bitCount = inputAsLines[0].length val mask = 2.0.pow(bitCount) - 1 val gamma = gamma(inputAsLines).toInt(2) val epsilon = epsilon(gamma, mask.toInt()) return gamma * epsilon } fun part2(): Int { val oxygen = oxygen(inputAsLines) val co2 = co2(inputAsLines) return oxygen.toInt(2) * co2.toInt(2) } }
116
Kotlin
0
0
69fa3dfed62d5cb7d961fe16924066cb7f9f5985
2,412
adventofcode
MIT License
kotlinLeetCode/src/main/kotlin/leetcode/editor/cn/[5]最长回文子串.kt
maoqitian
175,940,000
false
{"Kotlin": 354268, "Java": 297740, "C++": 634}
//给你一个字符串 s,找到 s 中最长的回文子串。 // // // // 示例 1: // // //输入:s = "babad" //输出:"bab" //解释:"aba" 同样是符合题意的答案。 // // // 示例 2: // // //输入:s = "cbbd" //输出:"bb" // // // 示例 3: // // //输入:s = "a" //输出:"a" // // // 示例 4: // // //输入:s = "ac" //输出:"a" // // // // // 提示: // // // 1 <= s.length <= 1000 // s 仅由数字和英文字母(大写和/或小写)组成 // // Related Topics 字符串 动态规划 // 👍 3635 👎 0 //leetcode submit region begin(Prohibit modification and deletion) class Solution { fun longestPalindrome(s: String): String { //找出开始结束边界 左右扩散 //时间复杂度 O(n) var start = 0 var end = 0 for(i in s.indices){ //左右边界 var tempChar = s[i] var left = i var right = i //字符相等 //左边界查找 while (left >= 0 && s[left] == tempChar){ left -- } //字符相等 //右边界查找 while (right < s.length && s[right] == tempChar){ right ++ } //字符串不相等 while (left >=0 && right < s.length){ if (s[left] != s[right]){ //字符不等跳过 break } left-- right++ } //更新初始值 left += 1 if(end - start < right - left){ start = left end = right } } return s.substring(start,end) } } //leetcode submit region end(Prohibit modification and deletion)
0
Kotlin
0
1
8a85996352a88bb9a8a6a2712dce3eac2e1c3463
1,848
MyLeetCode
Apache License 2.0
src/day10/Day10_functional.kt
seastco
574,758,881
false
{"Kotlin": 72220}
package day10 import readLines import kotlin.math.absoluteValue /** * Credit goes to tginsberg (https://github.com/tginsberg/advent-2022-kotlin) * I'm experimenting with his solutions to better learn functional programming in Kotlin. * Files without the _functional suffix are my original solutions. */ private fun parseInput(input: List<String>): List<Int> = buildList { add(1) // register starts at 1 input.forEach { line -> add(0) // no-op and first cycle of addx will be 0 if (line.startsWith("addx")) { add(line.substringAfter(" ").toInt()) } } } private fun List<Int>.sampleSignals(): List<Int> = (20 .. size step 40).map { cycle -> cycle * this[cycle - 1] } private fun List<Int>.screen(): List<Boolean> = this.mapIndexed { pixel, register -> (register - (pixel % 40)).absoluteValue <= 1 } private fun List<Boolean>.print() { this.windowed(40, 40, false).forEach { row -> row.forEach { pixel -> print(if(pixel) '#' else ' ') } println() } } private fun part1(input: List<String>): Int { val signals = parseInput(input).runningReduce(Int::plus) return signals.sampleSignals().sum() } private fun part2(input: List<String>) { val signals = parseInput(input).runningReduce(Int::plus) signals.screen().print() } fun main() { println(part1(readLines("day10/input"))) part2(readLines("day10/input")) }
0
Kotlin
0
0
2d8f796089cd53afc6b575d4b4279e70d99875f5
1,499
aoc2022
Apache License 2.0
2022/main/day_05/Main.kt
Bluesy1
572,214,020
false
{"Rust": 280861, "Kotlin": 94178, "Shell": 996}
package day_05_2022 import java.io.File fun extractStacks(input: List<String>): MutableList<MutableList<Char>> { val boxes = input.subList(0, 8) val stacks = mutableListOf(mutableListOf<Char>(), mutableListOf(), mutableListOf(), mutableListOf(), mutableListOf(), mutableListOf(), mutableListOf(), mutableListOf(), mutableListOf() ) for (row in boxes) { for (i in 0..8) { if (row[(i*4)+ 1] != ' ') { stacks[i].add(row[(i*4)+ 1]) } } } return stacks } fun part1(input: List<String>) { val stacks = extractStacks(input) val remaining = input.subList(10, input.size) for (row in remaining) { val instructions = row.splitToSequence(' ') .filter { it != " " && it.length in 1..2 && it != "to" } .map { it.trim().toInt() } .toList() for (i in 0..instructions[0]-1){ stacks[instructions[2]-1].add(0, stacks[instructions[1]-1].removeAt(0)) } } val result = stacks.map { it[0] }.joinToString("") println("Top row of boxes: $result") } fun part2(input: List<String>) { val stacks = extractStacks(input) val remaining = input.subList(10, input.size) for (row in remaining) { val instructions = row.splitToSequence(' ') .filter { it != " " && it.length in 1..2 && it != "to" } .map { it.trim().toInt() } .toList() val sub = stacks[instructions[1]-1].subList(0, instructions[0]) for (item in sub.reversed()) { stacks[instructions[2] - 1].add(0, item) stacks[instructions[1]-1].remove(item) } } val result = stacks.map { it[0] }.joinToString("") println("Top row of boxes: $result") } fun main(){ val inputFile = File("src/inputs/Day_05.txt") print("\n----- Part 1 -----\n") part1(inputFile.readLines()) print("\n----- Part 2 -----\n") part2(inputFile.readLines()) }
0
Rust
0
0
537497bdb2fc0c75f7281186abe52985b600cbfb
1,985
AdventofCode
MIT License
src/Day02.kt
bin-wang
572,801,360
false
{"Kotlin": 19395}
fun main() { fun part1(input: List<String>) = input .map { it[0] - 'A' to it[2] - 'X' } .sumOf { (opponent, mine) -> 1 + mine + 3 * (mine - opponent + 1).mod(3) } fun part2(input: List<String>) = input .map { it[0] - 'A' to it[2] - 'X' } .sumOf { (opponent, result) -> 1 + (opponent + result - 1).mod(3) + 3 * result } val testInput = readInput("Day02_test") check(part1(testInput) == 15) check(part2(testInput) == 12) val input = readInput("Day02") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
dca2c4915594a4b4ca2791843b53b71fd068fe28
596
aoc22-kt
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/PalindromePermutation.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2020 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import java.util.TreeSet private const val MAX_VALUE = 128 fun interface PalindromePermutationBehavior { fun canPermutePalindrome(s: String): Boolean } /** * Time complexity : O(n). * Space complexity : O(1). */ class PalindromePermutationBruteForce : PalindromePermutationBehavior { override fun canPermutePalindrome(s: String): Boolean { var count = 0 var i = 0.toChar() while (i.code < MAX_VALUE && count <= 1) { var ct = 0 for (j in s.indices) { if (s[j] == i) ct++ } count += ct % 2 i++ } return count <= 1 } } /** * Time complexity : O(n). * Space complexity : O(1). */ class PalindromePermutationHashMap : PalindromePermutationBehavior { override fun canPermutePalindrome(s: String): Boolean { val map: HashMap<Char, Int> = HashMap() for (i in s.indices) { map[s[i]] = map.getOrDefault(s[i], 0) + 1 } var count = 0 for (key in map.keys) { count += map[key]!! % 2 } return count <= 1 } } /** * Time complexity : O(n). * Space complexity : O(1). */ class PalindromePermutationArray : PalindromePermutationBehavior { override fun canPermutePalindrome(s: String): Boolean { val map = IntArray(MAX_VALUE) for (element in s) { map[element.code]++ } var count = 0 var key = 0 while (key < map.size && count <= 1) { count += map[key] % 2 key++ } return count <= 1 } } /** * Time complexity : O(n). * Space complexity : O(1). */ class PalindromePermutationSinglePass : PalindromePermutationBehavior { override fun canPermutePalindrome(s: String): Boolean { val map = IntArray(MAX_VALUE) var count = 0 for (i in s.indices) { map[s[i].code]++ if (map[s[i].code] % 2 == 0) count-- else count++ } return count <= 1 } } /** * Time complexity : O(n). * Space complexity : O(1). */ class PalindromePermutationSet : PalindromePermutationBehavior by PalindromePermutationDelegate(HashSet()) /** * Time complexity : O(n). * Space complexity : O(1). */ class PalindromePermutationTree : PalindromePermutationBehavior by PalindromePermutationDelegate(TreeSet()) class PalindromePermutationDelegate(private val set: MutableSet<Char>) : PalindromePermutationBehavior { override fun canPermutePalindrome(s: String): Boolean { for (i in s.indices) { if (!set.add(s[i])) set.remove(s[i]) } return set.size <= 1 } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
3,305
kotlab
Apache License 2.0