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/Day20.kt
rosyish
573,297,490
false
{"Kotlin": 51693}
import kotlin.math.abs fun main() { val multiplier = 811589153L val reps = 10 val input = readInput("Day20_input").map{ it.trim().toLong() * multiplier }.toList() val output = input.mapIndexed{ index, value -> Pair(index, value) }.toMutableList() val originalPosToCurrentPos = input.indices.map { index -> index to index }.toMap().toMutableMap() val n = input.size repeat(reps) { for (originalIndex in input.indices) { val currentIndex = originalPosToCurrentPos[originalIndex]!! if (output[currentIndex].second == 0L) continue var newIndex = (currentIndex + (output[currentIndex].second % (n - 1))) % (n - 1) newIndex = if (newIndex <= 0) (n - 1 - abs(newIndex)) else newIndex // println("moving ${output[currentIndex].second}, currentpos = $currentIndex, newPos=$newIndex") if ( newIndex.toInt() != currentIndex) { val valueRemoved = output.removeAt(currentIndex) output.add(newIndex.toInt(), valueRemoved) for (i in output.indices) { originalPosToCurrentPos[output[i].first] = i } } // println(output.map { it.second }.toList()) } } val indexOfZero = originalPosToCurrentPos[output.find { it.second == 0L }!!.first]!! val computeIndex = { a: Int -> (indexOfZero + (a % n)) % n } //println(indexOfZero) println(listOf(1000, 2000, 3000).map { value -> 1L * output[computeIndex(value)].second }.sum()) }
0
Kotlin
0
2
43560f3e6a814bfd52ebadb939594290cd43549f
1,564
aoc-2022
Apache License 2.0
Sudoku_Solver.kt
xiekch
166,329,519
false
{"C++": 165148, "Java": 103273, "Kotlin": 97031, "Go": 40017, "Python": 22302, "TypeScript": 17514, "Swift": 6748, "Rust": 6579, "JavaScript": 4244, "Makefile": 349}
class Solution { private var found = false fun solveSudoku(board: Array<CharArray>) { found = false val rows = Array(9) { BooleanArray(10) { it == 0 } } val columns = Array(9) { BooleanArray(10) { it == 0 } } val boxes = Array(9) { BooleanArray(10) { it == 0 } } for (i in 0..8) { for (j in 0..8) { if (board[i][j] != '.') { val k = Integer.parseInt(board[i][j].toString()) rows[i][k] = true columns[j][k] = true boxes[(i / 3) * 3 + j / 3][k] = true } } } solveSudoku(board, rows, columns, boxes, 0, 0) // println(found) } private fun solveSudoku( board: Array<CharArray>, rows: Array<BooleanArray>, columns: Array<BooleanArray>, boxes: Array<BooleanArray>, curRow: Int, curColumn: Int ) { if (found) return if (curRow == 9) { if (rows.all { row -> row.all { it } } && columns.all { col -> col.all { it } } && boxes.all { box -> box.all { it } }) { found = true } return } for (j in curColumn..8) { if (board[curRow][j] == '.') { for (k in 1..9) { if (!rows[curRow][k] && !columns[j][k] && !boxes[(curRow / 3) * 3 + j / 3][k] && !found) { board[curRow][j] = (k + '0'.toInt()).toChar() rows[curRow][k] = true columns[j][k] = true boxes[(curRow / 3) * 3 + j / 3][k] = true if (j == 8) solveSudoku(board, rows, columns, boxes, curRow + 1, 0) else solveSudoku(board, rows, columns, boxes, curRow, j + 1) if (found) return board[curRow][j] = '.' rows[curRow][k] = false columns[j][k] = false boxes[(curRow / 3) * 3 + j / 3][k] = false } } return } else if (j == 8 && rows[curRow].all { it }) { solveSudoku(board, rows, columns, boxes, curRow + 1, 0) } } } } fun main() { val solution = Solution() val testCases = arrayOf( arrayOf( charArrayOf('5', '3', '4', '6', '7', '8', '9', '.', '2'), charArrayOf('6', '7', '2', '1', '9', '5', '.', '.', '.'), charArrayOf('.', '9', '8', '.', '.', '.', '.', '6', '.'), charArrayOf('8', '.', '9', '.', '6', '.', '.', '.', '3'), charArrayOf('4', '.', '6', '8', '.', '3', '.', '.', '1'), charArrayOf('7', '.', '.', '.', '2', '.', '.', '.', '6'), charArrayOf('.', '6', '.', '.', '.', '.', '2', '8', '.'), charArrayOf('.', '.', '.', '4', '1', '9', '.', '.', '5'), charArrayOf('3', '4', '.', '.', '8', '.', '.', '7', '9') ), arrayOf( charArrayOf('5', '3', '.', '.', '7', '.', '.', '.', '.'), charArrayOf('6', '.', '.', '1', '9', '5', '.', '.', '.'), charArrayOf('.', '9', '8', '.', '.', '.', '.', '6', '.'), charArrayOf('8', '.', '.', '.', '6', '.', '.', '.', '3'), charArrayOf('4', '.', '.', '8', '.', '3', '.', '.', '1'), charArrayOf('7', '.', '.', '.', '2', '.', '.', '.', '6'), charArrayOf('.', '6', '.', '.', '.', '.', '2', '8', '.'), charArrayOf('.', '.', '.', '4', '1', '9', '.', '.', '5'), charArrayOf('.', '.', '.', '.', '8', '.', '.', '7', '9') ) ) for (testCase in testCases) { solution.solveSudoku(testCase) println(testCase.joinToString("\n") { it.joinToString() }) println() } }
0
C++
0
0
eb5b6814e8ba0847f0b36aec9ab63bcf1bbbc134
3,927
leetcode
MIT License
2022/src/main/kotlin/Day04.kt
dlew
498,498,097
false
{"Kotlin": 331659, "TypeScript": 60083, "JavaScript": 262}
object Day04 { fun part1(input: String): Int { return parse(input).count { (a, b) -> a.containsAll(b) || b.containsAll(a) } } fun part2(input: String): Int { return parse(input).count { (a, b) -> a.containsAny(b) } } private fun IntRange.containsAll(other: IntRange) = this.first <= other.first && this.last >= other.last private fun IntRange.containsAny(other: IntRange) = this.intersect(other).isNotEmpty() private fun parse(input: String): List<Pair<IntRange, IntRange>> { return input .splitNewlines() .flatMap { line -> line.splitCommas() .map { it.toRange() } .zipWithNext() } } private fun String.toRange(): IntRange { val split = split("-").toIntList() return IntRange(split[0], split[1]) } }
0
Kotlin
0
0
6972f6e3addae03ec1090b64fa1dcecac3bc275c
793
advent-of-code
MIT License
src/main/kotlin/days/Day7.kt
hughjdavey
433,597,582
false
{"Kotlin": 53042}
package days import kotlin.math.abs class Day7 : Day(7) { private val crabs = inputString.split(",").map { it.replace(Regex("\\s+"), "").toInt() } override fun partOne(): Any { // simplification of calculateMinFuel { fuel, distance -> fuel + distance } return calculateMinFuel(Int::plus) } // todo improve performance as this takes over 10s on my real input override fun partTwo(): Any { return calculateMinFuel { fuel, distance -> (0 until distance).fold(fuel to 1) { (fuelSpent, fuelCost), _ -> fuelSpent + fuelCost to fuelCost + 1 }.first } } private fun calculateMinFuel(consumptionFunction: (fuel: Int, distance: Int) -> Int): Int { val (min, max) = crabs.minOf { it } to crabs.maxOf { it } return (min..max).map { alignPos -> crabs.fold(0) { fuel, pos -> consumptionFunction(fuel, abs(pos - alignPos)) } }.minOf { it } } }
0
Kotlin
0
0
a3c2fe866f6b1811782d774a4317457f0882f5ef
975
aoc-2021
Creative Commons Zero v1.0 Universal
2022/src/main/kotlin/Day17.kt
dlew
498,498,097
false
{"Kotlin": 331659, "TypeScript": 60083, "JavaScript": 262}
import Day17.Direction.LEFT import Day17.Direction.RIGHT object Day17 { fun part1(input: String): Int { val chamber = Chamber(parseInput(input)) repeat(2022) { chamber.dropNext() } return chamber.height() } fun part2(input: String, testSize: Int, startingCycleSize: Int): Long { val chamber = Chamber(parseInput(input)) val heightChanges = (0..testSize) .map { chamber.dropNext() chamber.height() } .windowed(2) .map { (prev, next) -> next - prev } // Automatically detect the cycle and calculate the value based on that var cycleSize = startingCycleSize while (cycleSize < heightChanges.size) { val cycleStart = cycleExists(heightChanges, cycleSize) // If we detected a cycle, we can calculate the total now if (cycleStart != null) { val initialSum = heightChanges.take(cycleStart).sum() val cycleSum = heightChanges.drop(cycleStart).take(cycleSize).sum() val iterationsAfterStart = 1000000000000L - cycleStart val numCycles = iterationsAfterStart / cycleSize val cycleRemainder = (iterationsAfterStart % cycleSize).toInt() val remainderSum = heightChanges.drop(cycleStart).take(cycleRemainder).sum() return initialSum + (cycleSum * numCycles) + remainderSum } cycleSize++ } throw IllegalStateException("Could not find a cycle in changes of size ${heightChanges.size}") } // This is admittedly a rather slow & janky way to detect cycles w/ initial start private fun cycleExists(heightChanges: List<Int>, cycleSize: Int): Int? { return (0 until heightChanges.size - (cycleSize * 2)).find { start -> heightChanges .asSequence() .drop(start) .chunked(cycleSize) .take(4) .zipWithNext() .all { (first, second) -> if (first.size == second.size) first == second else true } } } private class Chamber(private val jetPattern: List<Direction>) { private val rocks = mutableSetOf<Point>() private var shapeToSpawn = Shape.HORIZONTAL_LINE private var jetIndex = 0 fun dropNext() { var shape = shapeToSpawn.spawn(2, nextRockStartingHeight()) incrementShape() while (true) { // Blow with jet left or right val direction = jetPattern[jetIndex] shape = when (direction) { LEFT -> moveLeft(shape) RIGHT -> moveRight(shape) } incrementJetIndex() // Move downwards val downShape = moveDown(shape) // It didn't move downwards, must be stuck, go on if (downShape == shape) { break } shape = downShape } // Add shape to settled rocks rocks.addAll(shape) } fun height() = if (rocks.isEmpty()) 0 else rocks.maxOf { it.y } + 1 private fun moveLeft(shape: List<Point>): List<Point> { val moved = shape.map { it.copy(x = it.x - 1) } return if (validLocation(moved)) moved else shape } private fun moveRight(shape: List<Point>): List<Point> { val moved = shape.map { it.copy(x = it.x + 1) } return if (validLocation(moved)) moved else shape } private fun moveDown(shape: List<Point>): List<Point> { val moved = shape.map { it.copy(y = it.y - 1) } return if (validLocation(moved)) moved else shape } private fun validLocation(shape: List<Point>): Boolean { return shape.all { it.x in 0..6 && it.y >= 0 && it !in rocks } } private fun nextRockStartingHeight() = height() + 3 private fun incrementJetIndex() { jetIndex = (jetIndex + 1) % jetPattern.size } private fun incrementShape() { shapeToSpawn = shapeToSpawn.next() } } private fun parseInput(input: String) = input.map { if (it == '<') LEFT else RIGHT } private data class Point(val x: Int, val y: Int) private enum class Direction { LEFT, RIGHT } private enum class Shape { HORIZONTAL_LINE, PLUS, BACKWARDS_L, VERTICAL_LINE, SQUARE; fun next(): Shape { val values = Shape.values() return values[(this.ordinal + 1) % values.size] } fun spawn(left: Int, bottom: Int): List<Point> { return when (this) { HORIZONTAL_LINE -> listOf( Point(left, bottom), Point(left + 1, bottom), Point(left + 2, bottom), Point(left + 3, bottom), ) PLUS -> listOf( Point(left + 1, bottom + 2), Point(left, bottom + 1), Point(left + 1, bottom + 1), Point(left + 2, bottom + 1), Point(left + 1, bottom) ) BACKWARDS_L -> listOf( Point(left + 2, bottom + 2), Point(left + 2, bottom + 1), Point(left, bottom), Point(left + 1, bottom), Point(left + 2, bottom), ) VERTICAL_LINE -> listOf( Point(left, bottom + 3), Point(left, bottom + 2), Point(left, bottom + 1), Point(left, bottom), ) SQUARE -> listOf( Point(left, bottom + 1), Point(left + 1, bottom + 1), Point(left, bottom), Point(left + 1, bottom), ) } } } }
0
Kotlin
0
0
6972f6e3addae03ec1090b64fa1dcecac3bc275c
5,275
advent-of-code
MIT License
src/main/kotlin/g2201_2300/s2271_maximum_white_tiles_covered_by_a_carpet/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g2201_2300.s2271_maximum_white_tiles_covered_by_a_carpet // #Medium #Array #Sorting #Greedy #Binary_Search #Prefix_Sum // #2023_06_28_Time_692_ms_(100.00%)_Space_66.2_MB_(100.00%) import java.util.Arrays class Solution { fun maximumWhiteTiles(tiles: Array<IntArray>, carpetLength: Int): Int { Arrays.sort(tiles, { x: IntArray, y: IntArray -> x[0].compareTo(y[0]) }) var currentCover = Math.min(tiles[0][1] - tiles[0][0] + 1, carpetLength) var maxCover = currentCover var head = 1 var tail = 0 while (tail < tiles.size && head < tiles.size && maxCover < carpetLength) { if (tiles[head][1] - tiles[tail][0] + 1 <= carpetLength) { currentCover += tiles[head][1] - tiles[head][0] + 1 maxCover = Math.max(maxCover, currentCover) ++head } else { val possiblePartialCoverOverCurrentHead = carpetLength - (tiles[head][0] - tiles[tail][0]) maxCover = Math.max(maxCover, currentCover + possiblePartialCoverOverCurrentHead) currentCover = currentCover - (tiles[tail][1] - tiles[tail][0] + 1) ++tail } } return maxCover } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,243
LeetCode-in-Kotlin
MIT License
day08/kotlin/RJPlog/day2108_1_2.kts
razziel89
438,180,535
true
{"Rust": 132841, "Python": 99823, "Go": 86335, "Groovy": 67858, "TypeScript": 43504, "Kotlin": 42281, "CSS": 35030, "Shell": 18611, "C": 5260, "JavaScript": 2624, "Ruby": 2359, "Dockerfile": 2115, "HTML": 227, "C++": 153}
import java.io.File //fun main(args: Array<String>) { // tag::firstpart[] // part 1 var solution1: Int = 0 File("day2108_puzzle_input.txt").forEachLine { var instruction = it.split(" | ") var output = instruction[1].split(" ") output.forEach { if (it.length == 2 || it.length == 4 || it.length == 3 || it.length == 7) { solution1 += 1 } } } // end::firstpart[] // tag::secondpart[] // part 2 var solution2: Int = 0 var mapTable = mutableListOf<String>() for (i in 0..9) { mapTable.add("") } File("day2108_puzzle_input.txt").forEachLine { var instruction = it.split(" | ") var inp = instruction[0].split(" ") // sort all input values alphabetically var input = mutableListOf<String>() inp.forEach { input.add(it.toCharArray().sorted().joinToString("")) } // assigning 1, 4, 7, 8 input.forEach { if (it.length == 2) { mapTable[1] = it } else if (it.length == 4) { mapTable[4] = it } else if (it.length == 3) { mapTable[7] = it } else if (it.length == 7) { mapTable[8] = it } } // assigning 5 input.forEach { var help: String = "" mapTable[4].forEach { if (!mapTable[1].contains(it)) { help = help + it } } if (it.length == 5) { if (it.toList().containsAll(mapTable[1].toList())) { // if it contains 1 --> 3 mapTable.set(3, it) } else if (it.toList().containsAll(help.toList())) { // if it contains 4 -->5 mapTable.set(5, it) } else { // else --> 2 mapTable.set(2, it) } } } // assigning 6 input.forEach { if (it.length == 6) { if (it.toList().containsAll(mapTable[3].toList())) { // if it contains 3 --> 9 mapTable.set(9, it) } else if (it.toList().containsAll(mapTable[5].toList())) { // if it contains 5 --> 9 mapTable.set(6, it) // if it containns 4 --> 9 } else { mapTable.set(0, it) } } } var out = instruction[1].split(" ") // sort all input values alphabetically var output = mutableListOf<String>() out.forEach { output.add(it.toCharArray().sorted().joinToString("")) } solution2 = solution2 + mapTable.indexOf(output[0]) * 1000 + mapTable.indexOf(output[1]) * 100 + mapTable.indexOf(output[2]) * 10 + mapTable.indexOf(output[3]) } // end::secondpart[] // tag::output[] // print solution for part 1 println("***********************************") println("--- Day 8: Seven Segment Search ---") println("***********************************") println("Solution for part1") println(" $solution1 times do digits 1, 4, 7, or 8 appear") println() // print solution for part 2 println("*********************************") println("Solution for part2") println(" You get $solution2 if you add up all of the output values") println() // end::output[] //}
1
Rust
0
0
91a801b3c812cc3d37d6088a2544227cf158d114
2,857
aoc-2021
MIT License
src/main/kotlin/g2301_2400/s2316_count_unreachable_pairs_of_nodes_in_an_undirected_graph/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g2301_2400.s2316_count_unreachable_pairs_of_nodes_in_an_undirected_graph // #Medium #Depth_First_Search #Breadth_First_Search #Graph #Union_Find // #2023_06_30_Time_981_ms_(87.50%)_Space_118.4_MB_(50.00%) class Solution { fun countPairs(n: Int, edges: Array<IntArray>): Long { val d = DSU(n) val map = HashMap<Int, Int>() for (e in edges) { d.union(e[0], e[1]) } var ans: Long = 0 for (i in 0 until n) { val p = d.findParent(i) val cnt = if (map.containsKey(p)) map[p]!! else 0 ans += (i - cnt).toLong() map[p] = map.getOrDefault(p, 0) + 1 } return ans } private class DSU internal constructor(n: Int) { var rank: IntArray var parent: IntArray init { rank = IntArray(n + 1) parent = IntArray(n + 1) for (i in 1..n) { parent[i] = i } } fun findParent(node: Int): Int { if (parent[node] == node) { return node } parent[node] = findParent(parent[node]) return findParent(parent[node]) } fun union(x: Int, y: Int): Boolean { val px = findParent(x) val py = findParent(y) if (px == py) { return false } if (rank[px] > rank[py]) { parent[py] = px } else { parent[px] = py rank[py]++ } return true } } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,603
LeetCode-in-Kotlin
MIT License
2015/src/main/kotlin/com/koenv/adventofcode/Day3.kt
koesie10
47,333,954
false
null
package com.koenv.adventofcode object Day3 { public fun getTotalVisitedHouses(input: String): Int { var currentPosition = Coordinate(0, 0) val visitedHouses = arrayListOf(currentPosition) input.forEach { currentPosition += getCoordinateDelta(it) visitedHouses.add(currentPosition) } return visitedHouses.distinct().size } public fun getTotalVisitedHousesWithRoboSanta(input: String): Int { var santaCurrentPosition = Coordinate(0, 0) var roboSantaCurrentPosition = santaCurrentPosition val visitedHouses = arrayListOf(santaCurrentPosition) input.forEachIndexed { i, it -> if (i % 2 == 0) { santaCurrentPosition += getCoordinateDelta(it) visitedHouses.add(santaCurrentPosition) } else { roboSantaCurrentPosition += getCoordinateDelta(it) visitedHouses.add(roboSantaCurrentPosition) } } return visitedHouses.distinct().size } private fun getCoordinateDelta(input: Char): Coordinate { when (input) { '>' -> { return Coordinate(1, 0) } '<' -> { return Coordinate(-1, 0) } '^' -> { return Coordinate(0, -1) } 'v' -> { return Coordinate(0, 1) } } throw IllegalArgumentException("Invalid input: $input") } data class Coordinate(val x: Int, val y: Int) { public operator fun plus(other: Coordinate): Coordinate { return Coordinate(x + other.x, y + other.y) } } }
0
Kotlin
0
0
29f3d426cfceaa131371df09785fa6598405a55f
1,719
AdventOfCode-Solutions-Kotlin
MIT License
kotlin/src/katas/kotlin/adventofcode/day5/Part1.kt
dkandalov
2,517,870
false
{"Roff": 9263219, "JavaScript": 1513061, "Kotlin": 836347, "Scala": 475843, "Java": 475579, "Groovy": 414833, "Haskell": 148306, "HTML": 112989, "Ruby": 87169, "Python": 35433, "Rust": 32693, "C": 31069, "Clojure": 23648, "Lua": 19599, "C#": 12576, "q": 11524, "Scheme": 10734, "CSS": 8639, "R": 7235, "Racket": 6875, "C++": 5059, "Swift": 4500, "Elixir": 2877, "SuperCollider": 2822, "CMake": 1967, "Idris": 1741, "CoffeeScript": 1510, "Factor": 1428, "Makefile": 1379, "Gherkin": 221}
package katas.kotlin.adventofcode.day5 import katas.kotlin.adventofcode.day5.ParamMode.* import java.io.* fun main() { val text = File("src/katas/kotlin/adventofcode/day5/input.txt").readText() val program = text.split(",").map(String::toInt).toMutableList() val io = object: IO { override fun read() = 1 override fun write(value: Int) = println(value) } execute(program, io) } fun execute(program: MutableList<Int>, io: IO) { execute( program, read = { io.read() }, write = { io.write(it) } ) } inline fun execute(program: MutableList<Int>, read: () -> Int, write: (Int) -> Unit) { var address = 0 while (address < program.size) { val opCode = program[address].toString().takeLast(2).toInt() val paramModes = program[address].toString().dropLast(2) .map { it.toString().toInt() } .let { List(3 - it.size) { 0 } + it } .map { if (it == 0) PositionMode else ImmediateMode } .reversed() val param = { index: Int -> paramModes[index - 1].read(address + index, program) } val paramValue = { index: Int -> ImmediateMode.read(address + index, program) } when (opCode) { 1 -> { program[paramValue(3)] = param(1) + param(2) address += 4 } 2 -> { program[paramValue(3)] = param(1) * param(2) address += 4 } 3 -> { program[paramValue(1)] = read() address += 2 } 4 -> { write(param(1)) address += 2 } 5 -> address = if (param(1) != 0) param(2) else address + 3 6 -> address = if (param(1) == 0) param(2) else address + 3 7 -> { program[paramValue(3)] = if (param(1) < param(2)) 1 else 0 address += 4 } 8 -> { program[paramValue(3)] = if (param(1) == param(2)) 1 else 0 address += 4 } 99 -> return else -> error("Unexpected opCode ${program[address]} at index $address") } } } enum class ParamMode { PositionMode, ImmediateMode; fun read(index: Int, program: List<Int>): Int = when (this) { PositionMode -> program[program[index]] ImmediateMode -> program[index] } } interface IO { fun read(): Int fun write(value: Int) }
7
Roff
3
5
0f169804fae2984b1a78fc25da2d7157a8c7a7be
2,562
katas
The Unlicense
src/main/kotlin/ru/glukhov/aoc/Day8.kt
cobaku
576,736,856
false
{"Kotlin": 25268}
package ru.glukhov.aoc import java.io.Reader fun main() { val field = Problem.forDay("day8").use { parseTree(it) } println("Result of the first problem is ${solvePartOne(field)}") println("Result of the second problem is ${solvePartTwo(field)}") } private fun parseTree(reader: Reader): Array<IntArray> { val buffer = mutableListOf<IntArray>() reader.forEachLine { val array = IntArray(it.length) it.forEachIndexed { index, num -> array[index] = num.digitToInt() } buffer.add(array) } return buffer.toTypedArray() } private fun walk(array: Array<IntArray>, action: (x: Int, y: Int) -> Int): Int { var target = 0 for (vertical in array.indices) { for (horizontal in array.indices) { target += action(horizontal, vertical) } } return target } private fun solvePartOne(field: Array<IntArray>): Int = walk(field) { x, y -> return@walk if (isBorder(x, y, field) || isVisibleLtr(x, y, field) || isVisibleRtl(x, y, field) || isVisibleTtb( x, y, field ) || isVisibleBtt(x, y, field) ) 1 else 0 } private fun solvePartTwo(field: Array<IntArray>): Int { val target = mutableListOf<Int>() for (vertical in field.indices) { for (horizontal in field.indices) { if (isBorder(horizontal, vertical, field)) { continue } val step = powerLtr(horizontal, vertical, field) * powerRtl(horizontal, vertical, field) * powerTtb( horizontal, vertical, field ) * powerBtt(horizontal, vertical, field) target.add(step) } } return target.sortedDescending()[0] } private fun isBorder(x: Int, y: Int, field: Array<IntArray>): Boolean { if (y == 0 || y == field.size - 1) { return true } if (x == 0 || x == field[y].size - 1) { return true } return false } private fun isVisibleLtr(x: Int, y: Int, field: Array<IntArray>): Boolean { val row = field[y] val value = row[x] for (i in x + 1 until row.size) { if (value <= row[i]) { return false } } return true } private fun isVisibleRtl(x: Int, y: Int, field: Array<IntArray>): Boolean { val row = field[y] val value = row[x] for (i in 0 until x) { if (value <= row[i]) { return false } } return true } private fun isVisibleTtb(x: Int, y: Int, field: Array<IntArray>): Boolean { val value = field[y][x] for (i in y + 1 until field.size) { if (value <= field[i][x]) { return false } } return true } private fun isVisibleBtt(x: Int, y: Int, field: Array<IntArray>): Boolean { val value = field[y][x] for (i in 0 until y) { if (value <= field[i][x]) { return false } } return true } private fun powerLtr(x: Int, y: Int, field: Array<IntArray>): Int { var power = 0 val row = field[y] val value = row[x] for (i in x + 1 until row.size) { if (value > row[i]) { power++ } else { return power + 1 } } return power } private fun powerRtl(x: Int, y: Int, field: Array<IntArray>): Int { var power = 0 val row = field[y] val value = row[x] for (i in x - 1 downTo 0) { if (value > row[i]) { power++ } else { return power + 1 } } return power } private fun powerTtb(x: Int, y: Int, field: Array<IntArray>): Int { var power = 0 val value = field[y][x] for (i in y + 1 until field.size) { if (value > field[i][x]) { power++ } else { return power + 1 } } return power } private fun powerBtt(x: Int, y: Int, field: Array<IntArray>): Int { var power = 0 val value = field[y][x] for (i in y - 1 downTo 0) { if (value > field[i][x]) { power++ } else { return power + 1 } } return power }
0
Kotlin
0
0
a40975c1852db83a193c173067aba36b6fe11e7b
4,066
aoc2022
MIT License
kt-string-similarity/src/commonMain/kotlin/ca/solostudios/stringsimilarity/LCS.kt
solo-studios
420,274,115
false
{"Kotlin": 201452, "SCSS": 10556, "JavaScript": 3786, "FreeMarker": 2581}
/* * kt-fuzzy - A Kotlin library for fuzzy string matching * Copyright (c) 2015-2023 solonovamax <<EMAIL>> * * The file LCS.kt is part of kotlin-fuzzy * Last modified on 19-10-2023 04:33 p.m. * * MIT License * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * KT-FUZZY IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package ca.solostudios.stringsimilarity import ca.solostudios.stringsimilarity.interfaces.MetricStringDistance import ca.solostudios.stringsimilarity.interfaces.StringDistance import ca.solostudios.stringsimilarity.interfaces.StringSimilarity import ca.solostudios.stringsimilarity.util.minMaxByLength import kotlin.math.max /** * Implements the Longest Common Subsequence (LCS) problem consists in finding the longest * subsequence common to two (or more) sequences. It differs from problems of * finding common substrings: unlike substrings, subsequences are not required * to occupy consecutive positions within the original sequences. * * It is used by the diff utility, by Git for reconciling multiple changes, etc. * * The LCS edit distance between strings \(X\) and \(Y\) is: * \(\lvert X \rvert + \lvert Y \rvert - 2 \times \lvert LCS(X, Y) \rvert\) * - \(\text{min} = 0\) * - \(\text{max} = \lvert X \rvert + \lvert Y \rvert\). * * LCS distance is equivalent to Levenshtein distance, when only insertion and * deletion is allowed (no substitution), or when the cost of the substitution * is the double of the cost of an insertion or deletion. * * @see MetricStringDistance * @see StringDistance * @see StringSimilarity * * @author solonovamax */ public object LCS : MetricStringDistance, StringSimilarity, StringDistance { override fun distance(s1: String, s2: String): Double { return s1.length + s2.length - (similarity(s1, s2)) * 2 } override fun similarity(s1: String, s2: String): Double { if (s1 == s2) return s1.length.toDouble() if (s1.isEmpty()) return 0.0 if (s2.isEmpty()) return 0.0 val (shorter, longer) = minMaxByLength(s1, s2) val previous = DoubleArray(shorter.length + 1) val current = DoubleArray(shorter.length + 1) longer.forEachIndexed { _, c1 -> shorter.forEachIndexed { j, c2 -> current[j + 1] = if (c1 == c2) previous[j] + 1 else max(current[j], previous[j + 1]) } current.copyInto(previous) } return current.last() } }
2
Kotlin
0
5
b3ae4f9f0e15ee38feb81b0edd88cdad68124b21
3,536
kt-fuzzy
MIT License
src/main/kotlin/year2022/day14/Problem.kt
Ddxcv98
573,823,241
false
{"Kotlin": 154634}
package year2022.day14 import IProblem import java.util.regex.Pattern import kotlin.math.max import kotlin.math.min class Problem : IProblem { private val map = mutableMapOf<Point, Char>() private val topLeft: Point private val botRight: Point init { val pattern = Pattern.compile("(\\d+),(\\d+)") var topLeftX = START.x var topLeftY = START.y var botRightX = START.x var botRightY = START.y javaClass .getResourceAsStream("/2022/14.txt")!! .bufferedReader() .forEachLine { val matcher = pattern.matcher(it) if (!matcher.find()) return@forEachLine var x1 = matcher.group(1).toInt() var y1 = matcher.group(2).toInt() while (matcher.find()) { val x2 = matcher.group(1).toInt() val y2 = matcher.group(2).toInt() val minX = min(x1, x2) val maxX = max(x1, x2) val minY = min(y1, y2) val maxY = max(y1, y2) topLeftX = min(minX, topLeftX) topLeftY = min(minY, topLeftY) botRightX = max(maxX, botRightX) botRightY = max(maxY, botRightY) if (x1 == x2) { for (y in minY..maxY) { map[Point(x2, y)] = ROCK } } else { for (x in minX..maxX) { map[Point(x, y2)] = ROCK } } x1 = x2 y1 = y2 } } topLeft = Point(topLeftX, topLeftY) botRight = Point(botRightX, botRightY) } private fun countWhile(predicate: () -> Boolean): Int { var count = 0 while (predicate()) { count++ } return count } private fun nextPos(map: Map<Point, Char>, curr: Point): Point { for (j in DROP_ORDER) { val next = Point(curr.x + j, curr.y + 1) if (!map.containsKey(next)) { return next } } return curr } private fun dropVoid(map: MutableMap<Point, Char>): Boolean { var curr = START while (curr.x in topLeft.x..botRight.x && curr.y <= botRight.y) { val next = nextPos(map, curr) if (curr == next) { map[next] = SAND return true } curr = next } return false } private fun dropGround(map: MutableMap<Point, Char>): Boolean { var curr = START while (curr.y != botRight.y + 1) { val next = nextPos(map, curr) if (curr == next) { map[next] = SAND return curr != START } curr = next } map[curr] = SAND return true } override fun part1(): Int { val copy = map.toMutableMap() return countWhile { dropVoid(copy) } } override fun part2(): Int { val copy = map.toMutableMap() return countWhile { dropGround(copy) } + 1 } }
0
Kotlin
0
0
455bc8a69527c6c2f20362945b73bdee496ace41
3,311
advent-of-code
The Unlicense
src/main/kotlin/day22.kt
p88h
317,362,882
false
null
import java.util.* internal data class Deck(val name: String, var cards: Deque<Int>) { fun str() = cards.joinToString(",") fun copy(limit: Int = cards.size) = Deck(name, ArrayDeque(cards.take(limit))) } internal fun load(deck: String): Deck { val lines = deck.split('\n') return Deck(lines.first(), ArrayDeque(lines.subList(1, lines.size).map { it.toInt() })) } internal fun game(p1: Deck, p2: Deck, recurse: Boolean = false, level: Int = 0): Boolean { var history = HashSet<String>() while (p1.cards.isNotEmpty() && p2.cards.isNotEmpty()) { val state = p1.str() + ":" + p2.str() if (history.contains(state)) return true history.add(state) // println("Level $level Round ${history.size}\n$p1\n$p2") var c1 = p1.cards.pop() var c2 = p2.cards.pop() var win = true if (recurse && p1.cards.size >= c1 && p2.cards.size >= c2) { win = game(p1.copy(c1), p2.copy(c2), recurse, level + 1) } else win = c1 > c2 if (win) { // println("Player 1 wins") p1.cards.addLast(c1) p1.cards.addLast(c2) } else { // println("Player 2 wins") p2.cards.addLast(c2) p2.cards.addLast(c1) } } if (level == 0) { val cards = if (p1.cards.isEmpty()) p2.cards else p1.cards println(cards.toList().mapIndexed { i, v -> (cards.size - i) * v }.sum()) } return p1.cards.isNotEmpty() } fun main(args: Array<String>) { val decks = allBlocks(args, "day22.in").map { load(it) } game(decks[0].copy(), decks[1].copy()) game(decks[0].copy(), decks[1].copy(), true) }
0
Kotlin
0
5
846ad4a978823563b2910c743056d44552a4b172
1,676
aoc2020
The Unlicense
src/main/kotlin/org/flightofstairs/ctci/recusionAndDynamicProgramming/NQueens.kt
FlightOfStairs
509,587,102
false
{"Kotlin": 38930}
package org.flightofstairs.ctci.recusionAndDynamicProgramming import org.flightofstairs.ctci.treesAndGraphs.Position fun nQueens(count: Int) = (0 until count).toList().permutations().map { it.mapIndexed { row, col -> Position(row, col) } }.filter { solution -> val posIntercepts = solution.map { (it.y - it.x) }.toSet() val negIntercepts = solution.map { (it.y + it.x) }.toSet() posIntercepts.size == count && negIntercepts.size == count } fun <T> List<T>.permutations(): Sequence<List<T>> = toMutableList().permutations(size) // Heap's algorithm: https://en.wikipedia.org/wiki/Heap%27s_algorithm private fun <T> MutableList<T>.permutations(k: Int): Sequence<List<T>> = sequence { if (k == 1) yield(this@permutations.toList()) // yield copy else { yieldAll(permutations(k - 1)) for (i in (0 until k - 1)) { val swapIdx = if (k % 2 == 0) i else 0 val tmp = this@permutations[swapIdx] this@permutations[swapIdx] = this@permutations[k - 1] this@permutations[k - 1] = tmp yieldAll(permutations(k - 1)) } } }
0
Kotlin
0
0
5f4636ac342f0ee5e4f3517f7b5771e5aabe5992
1,124
FlightOfStairs-ctci
MIT License
kotlinLeetCode/src/main/kotlin/leetcode/editor/cn/[55]跳跃游戏.kt
maoqitian
175,940,000
false
{"Kotlin": 354268, "Java": 297740, "C++": 634}
//给定一个非负整数数组 nums ,你最初位于数组的 第一个下标 。 // // 数组中的每个元素代表你在该位置可以跳跃的最大长度。 // // 判断你是否能够到达最后一个下标。 // // // // 示例 1: // // //输入:nums = [2,3,1,1,4] //输出:true //解释:可以先跳 1 步,从下标 0 到达下标 1, 然后再从下标 1 跳 3 步到达最后一个下标。 // // // 示例 2: // // //输入:nums = [3,2,1,0,4] //输出:false //解释:无论怎样,总会到达下标为 3 的位置。但该下标的最大跳跃长度是 0 , 所以永远不可能到达最后一个下标。 // // // // // 提示: // // // 1 <= nums.length <= 3 * 104 // 0 <= nums[i] <= 105 // // Related Topics 贪心 数组 动态规划 // 👍 1260 👎 0 //leetcode submit region begin(Prohibit modification and deletion) class Solution { fun canJump(nums: IntArray): Boolean { //贪心算法 从后往前数 //当前 index + 当前可以跳跃步数大于当前下标 说明可以进行跳跃 //时间复杂度 O(n) if(nums.isEmpty()) return false //最终下标 var endIndex = nums.size-1 for ( i in nums.size-1 downTo 0){ if(nums[i]+i >= endIndex){ endIndex = i } } return endIndex == 0 } } //leetcode submit region end(Prohibit modification and deletion)
0
Kotlin
0
1
8a85996352a88bb9a8a6a2712dce3eac2e1c3463
1,443
MyLeetCode
Apache License 2.0
kotlinLeetCode/src/main/kotlin/leetcode/editor/cn/[697]数组的度.kt
maoqitian
175,940,000
false
{"Kotlin": 354268, "Java": 297740, "C++": 634}
import java.util.* //给定一个非空且只包含非负数的整数数组 nums,数组的度的定义是指数组里任一元素出现频数的最大值。 // // 你的任务是在 nums 中找到与 nums 拥有相同大小的度的最短连续子数组,返回其长度。 // // // // 示例 1: // // //输入:[1, 2, 2, 3, 1] //输出:2 //解释: //输入数组的度是2,因为元素1和2的出现频数最大,均为2. //连续子数组里面拥有相同度的有如下所示: //[1, 2, 2, 3, 1], [1, 2, 2, 3], [2, 2, 3, 1], [1, 2, 2], [2, 2, 3], [2, 2] //最短连续子数组[2, 2]的长度为2,所以返回2. // // // 示例 2: // // //输入:[1,2,2,3,1,4,2] //输出:6 // // // // // 提示: // // // nums.length 在1到 50,000 区间范围内。 // nums[i] 是一个在 0 到 49,999 范围内的整数。 // // Related Topics 数组 // 👍 303 👎 0 //leetcode submit region begin(Prohibit modification and deletion) class Solution { fun findShortestSubArray(nums: IntArray): Int { //两次遍历 时间复杂度 O(n) //时间复杂度 O(n) var maxCnt = 0 var res: Int = nums.size //数组记录 出现次数 度 左边界 右边界 //第一次计算出所有的度 使用 HashMap 保存 var hashMap = HashMap<Int,IntArray>() for (i in nums.indices){ if(hashMap.containsKey(nums[i])){ hashMap[nums[i]]!![0]++ hashMap[nums[i]]!![2] = i }else{ hashMap[nums[i]] = intArrayOf(1, i, i) } maxCnt = Math.max(maxCnt, hashMap.get(nums[i])?.get(0)!!) } //第二次找到对应相等的度最小长度 for ((_, arr) in hashMap) { if (arr[0] == maxCnt) { res = Math.min(res, arr[2] - arr[1] + 1) } } return res } } //leetcode submit region end(Prohibit modification and deletion)
0
Kotlin
0
1
8a85996352a88bb9a8a6a2712dce3eac2e1c3463
1,973
MyLeetCode
Apache License 2.0
hoon/HoonAlgorithm/src/main/kotlin/programmers/lv01/Lv1_68935.kt
boris920308
618,428,844
false
{"Kotlin": 137657, "Swift": 35553, "Java": 1947, "Rich Text Format": 407}
package main.kotlin.programmers.lv01 /** * * https://school.programmers.co.kr/learn/courses/30/lessons/68935 * * 3진법 뒤집기 * 문제 설명 * 자연수 n이 매개변수로 주어집니다. * n을 3진법 상에서 앞뒤로 뒤집은 후, 이를 다시 10진법으로 표현한 수를 return 하도록 solution 함수를 완성해주세요. * * 제한사항 * n은 1 이상 100,000,000 이하인 자연수입니다. * 입출력 예 * n result * 45 7 * 125 229 * 입출력 예 설명 * 입출력 예 #1 * * 답을 도출하는 과정은 다음과 같습니다. * n (10진법) n (3진법) 앞뒤 반전(3진법) 10진법으로 표현 * 45 1200 0021 7 * 따라서 7을 return 해야 합니다. * 입출력 예 #2 * * 답을 도출하는 과정은 다음과 같습니다. * n (10진법) n (3진법) 앞뒤 반전(3진법) 10진법으로 표현 * 125 11122 22111 229 * 따라서 229를 return 해야 합니다. */ fun main() { solution(45) } private fun solution(n: Int): Int { return Integer.parseInt(n.toString(3).reversed(), 3) } private fun solution_1(n: Int): Int { return n.toString(3).reversed().toInt(10) }
1
Kotlin
1
2
88814681f7ded76e8aa0fa7b85fe472769e760b4
1,200
HoOne
Apache License 2.0
2020/10/week4/minhyungPark/algorithm/Leetcode1626.kt
Road-of-CODEr
270,008,701
false
{"Java": 199573, "C++": 42297, "JavaScript": 29489, "Kotlin": 28801, "Python": 20313, "HTML": 7981, "Shell": 7160}
/** * Leetcode 1626. Best Team With No Conflicts * https://leetcode.com/contest/weekly-contest-211/problems/best-team-with-no-conflicts/ */ import kotlin.math.max class Leetcode1626 { fun bestTeamScore(scores: IntArray, ages: IntArray): Int { val players = List(scores.size) { ages[it] to scores[it] }.sortedWith(compareBy({it.first}, {it.second})).reversed() val dp = IntArray(scores.size) for (i in players.indices) { val score = players[i].second dp[i] = score for (j in 0 until i) { if (players[j].second >= players[i].second) { dp[i] = max(dp[i], dp[j] + score) } } } return dp.max()!! } }
3
Java
11
36
1c603bc40359aeb674da9956129887e6f7c8c30a
749
stupid-week-2020
MIT License
src/day4/second/Solution.kt
verwoerd
224,986,977
false
null
package day4.second import tools.timeSolution // BLEH, I tried to solve the wrong problem where the grouped digits may be part of a group of larger then 2 fun main() = timeSolution { println("should all be false") println(isValidPassword(123444)) println(isValidPassword(277777)) println(isValidPassword(777778)) println(isValidPassword(223450)) println(isValidPassword(123789)) println(isValidPassword(444555)) println("xxxxxx" + isValidPassword(222222)) //xxxxxx println("xxxx89" + isValidPassword(222289)) println("0xxxx9" + isValidPassword(233338)) println("01xxxx" + isValidPassword(234444)) println("should all be true") println(isValidPassword(<PASSWORD>)) println(isValidPassword(<PASSWORD>)) println(isValidPassword(1<PASSWORD>3)) println(isValidPassword(2<PASSWORD>)) println("xxxxyy" + isValidPassword(222288)) //xxxxyy println("xxyyyy" + isValidPassword(228888)) //xxyyyy println("xxyy78" + isValidPassword(223389)) println("xxyyzz" + isValidPassword(227788)) // println("0xxyy9" + isValidPassword(233448)) println("1<PASSWORD>" + isValidPassword(1<PASSWORD>8)) println("1xx6yy" + isValidPassword(122688)) println("01xxyy" + isValidPassword(234455)) println("012xx9" + isValidPassword(234559)) println("0123xx" + isValidPassword(234588)) println("xx56yy" + isValidPassword(226788)) println("xx5yy9" + isValidPassword(225889)) println("xx5678" + isValidPassword(225678)) val (min, max) = readLine()!!.split("-").map { it.toInt() } val valid = mutableSetOf<Int>() for (i in min..max) { if (isValidPassword(i)) { valid.add(i) } } println("Found possible passwords in range: ${valid.size}") } fun isValidPassword(number: Int): Boolean = neverDecreases(number) && atleastOneDoubleSequential(number) // && !groupsOfFive(number) && !groupsOfThree(number) fun neverDecreases(number: Int) = (number / 100_000 % 10 <= number / 10_000 % 10) && (number / 10_000 % 10 <= number / 1000 % 10) && (number / 1000 % 10 <= number / 100 % 10) && (number / 100 % 10 <= number / 10 % 10) && (number / 10 % 10 <= number % 10) fun atleastOneDoubleSequential(number: Int) = (number / 100_000 % 10 == number / 10_000 % 10 && number / 10_000 % 10 != number / 1000 % 10) || (number / 100_000 % 10 != number / 10_000 % 10 && number / 10_000 % 10 == number / 1000 % 10 && number / 1000 % 10 != number / 100 % 10) || (number / 10_000 % 10 != number / 1000 % 10 && number / 1000 % 10 == number / 100 % 10 && number / 100 % 10 != number / 10 % 10) || (number / 1000 % 10 != number / 100 % 10 && number / 100 % 10 == number / 10 % 10 && number / 10 % 10 != number % 10) || (number / 100 % 10 != number / 10 % 10 && number / 10 % 10 == number % 10) // NOTE TO SELF: READ THE PROBLEM SPECIFICATION CAREFULLY! fun groupsOfFive(number: Int) = (number / 100_000 % 10 == number / 10_000 % 10 && number / 10_000 % 10 == number / 1000 % 10 && number / 1000 % 10 == number / 100 % 10 && number / 100 % 10 == number / 10 % 10 && number / 10 % 10 != number % 10) || (number / 100_000 % 10 != number / 10_000 % 10 && number / 10_000 % 10 == number / 1000 % 10 && number / 1000 % 10 == number / 100 % 10 && number / 100 % 10 == number / 10 % 10 && number / 10 % 10 == number % 10) fun groupsOfThree(number: Int) = (number / 100_000 % 10 == number / 10_000 % 10 && number / 10_000 % 10 == number / 1000 % 10 && number / 1000 % 10 != number / 100 % 10) || (number / 100_000 % 10 != number / 10_000 % 10 && number / 10_000 % 10 == number / 1000 % 10 && number / 1000 % 10 == number / 100 % 10 && number / 100 % 10 != number / 10 % 10) || (number / 10_000 % 10 != number / 1000 % 10 && number / 1000 % 10 == number / 100 % 10 && number / 100 % 10 == number / 10 % 10 && number / 10 % 10 != number % 10) || (number / 1000 % 10 != number / 100 % 10 && number / 100 % 10 == number / 10 % 10 && number / 10 % 10 == number % 10)
0
Kotlin
0
0
554377cc4cf56cdb770ba0b49ddcf2c991d5d0b7
3,912
AoC2019
MIT License
src/Day02.kt
vitind
578,020,578
false
{"Kotlin": 60987}
// Part 1 Scoring // A = Rock (Get 1 point for choosing) // B = Paper (Get 2 point for choosing) // C = Scissors (Get 3 point for choosing) // X = Rock // Y = Paper // Z = Scissors // Lose = 0 points // Draw = 3 points // Win = 6 points // A X = Rock Rock + Draw = 1 + 3 = 4 // A Y = Rock Paper + Win = 2 + 6 = 8 // A Z = Rock Scissors + Lose = 3 + 0 = 3 // B X = Paper Rock + Lose = 1 + 0 = 1 // B Y = Paper Paper + Draw = 2 + 3 = 5 // B Z = Paper Scissors + Win = 3 + 6 = 9 // C X = Scissors Rock + Win = 1 + 6 = 7 // C Y = Scissors Paper + Lose = 2 + 0 = 2 // C Z = Scissors Scissors + Draw = 3 + 3 = 6 // Part 2 Scoring // A = Rock (Get 1 point for choosing) // B = Paper (Get 2 point for choosing) // C = Scissors (Get 3 point for choosing) // X = Lose // Y = Draw // Z = Win // Lose = 0 points // Draw = 3 points // Win = 6 points // A X = Rock Scissors + Lose = 3 + 0 = 3 // A Y = Rock Rock + Draw = 1 + 3 = 4 // A Z = Rock Paper + Win = 2 + 6 = 8 // B X = Paper Rock + Lose = 1 + 0 = 1 // B Y = Paper Paper + Draw = 2 + 3 = 5 // B Z = Paper Scissors + Win = 3 + 6 = 9 // C X = Scissors Paper + Lose = 2 + 0 = 2 // C Y = Scissors Scissors + Draw = 3 + 3 = 6 // C Z = Scissors Rock + Win = 1 + 6 = 7 fun main() { fun part1(input: List<String>): Int { val finalScore = input.fold(0) { totalScore, strategy -> val score = when (strategy) { "A X" -> 4 "A Y" -> 8 "A Z" -> 3 "B X" -> 1 "B Y" -> 5 "B Z" -> 9 "C X" -> 7 "C Y" -> 2 "C Z" -> 6 else -> 0 } totalScore + score } return finalScore } fun part2(input: List<String>): Int { val finalScore = input.fold(0) { totalScore, strategy -> val score = when (strategy) { "A X" -> 3 "A Y" -> 4 "A Z" -> 8 "B X" -> 1 "B Y" -> 5 "B Z" -> 9 "C X" -> 2 "C Y" -> 6 "C Z" -> 7 else -> 0 } totalScore + score } return finalScore } val input = readInput("Day02") part1(input).println() part2(input).println() }
0
Kotlin
0
0
2698c65af0acd1fce51525737ab50f225d6502d1
2,366
aoc2022
Apache License 2.0
PacMan/src/main/kotlin/org.neige.codingame.pacman/Pac.kt
CedrickFlocon
106,032,469
false
null
package org.neige.codingame.pacman import org.neige.codingame.geometry.Coordinate import java.util.* data class Pac( val id: Int, val team: Team, val type: Type, val speedTurnsLeft: Int, val abilityCooldown: Int, override val coordinate: Coordinate, override var lastTurnSeen: Int ) : Element { var hiddenCollision = false val commandHistory = mutableListOf<Command>() var command: Command? = null private set val speed: Int get() = if (speedTurnsLeft > 0) 2 else 1 companion object { private val TYPE_WIN = mapOf(Type.ROCK to Type.SCISSORS, Type.SCISSORS to Type.PAPER, Type.PAPER to Type.ROCK) private val TYPE_LOST = mapOf(Type.ROCK to Type.PAPER, Type.SCISSORS to Type.ROCK, Type.PAPER to Type.SCISSORS) fun readPac(input: Scanner): Pac { val pacId = input.nextInt() val team = if (input.nextInt() != 0) Team.ALLY else Team.ENEMY val x = input.nextInt() val y = input.nextInt() val type = when (input.next()) { "ROCK" -> Type.ROCK "SCISSORS" -> Type.SCISSORS "PAPER" -> Type.PAPER "DEAD" -> Type.DEAD else -> throw IllegalArgumentException() } val speedTurnsLeft = input.nextInt() val abilityCooldown = input.nextInt() return Pac(pacId, team, type, speedTurnsLeft, abilityCooldown, Coordinate(x, y), 0) } } fun buildCommand(board: Board) { if (hiddenCollision && this.abilityCooldown == 0) { command = switch(getVulnerability(this)) return } val depth = when (board.height) { in 10..14 -> 10 in 15..17 -> 7 else -> throw IllegalStateException() } + when (board.width) { in 19..26 -> 10 in 27..35 -> 7 else -> throw IllegalStateException() } + when (board.alivePacs.filter { it.team == Team.ALLY }.count()) { 1 -> 4 2 -> 3 3 -> 2 4 -> 2 5 -> 1 else -> throw IllegalStateException() } val scoredPath = board.buildPath(coordinate, depth) .map { paths -> paths to pathScore(board, paths) } .sortedByDescending { it.second } val threat = (board.buildPath(coordinate, if (speed == 2) 4 else 3) .map { it.map { board[it] } .withIndex() .filter { (index, element) -> element is Pac && element.team == Team.ENEMY && element.type != Type.DEAD && element.lastTurnSeen < 2 && index < element.speed + speed } }.flatten() as List<IndexedValue<Pac>>) .distinctBy { it.value.id } if (abilityCooldown == 0) { if (threat.none { fight(it.value) == Fight.BEATEN }) { command = speed() return } else if (threat.all { fight(it.value) == Fight.BEATEN }) { command = switch(getVulnerability(threat.first { fight(it.value) == Fight.BEATEN }.value)) return } } val bestPath = scoredPath.first() command = move(bestPath.first, bestPath.second.toString()) } fun cancelCommand() { command = null } private fun pathScore(board: Board, coordinates: List<Coordinate>): Double { val threat = if (board.neighbor(coordinates.first()).mapNotNull { board[it] }.filterIsInstance<Pac>().filter { it.lastTurnSeen == 0 }.any { fight(it) == Fight.BEATEN }) { -1.0 } else { 0.0 } val lastCommand = commandHistory.firstOrNull() val collision = if (hiddenCollision && lastCommand is Move && lastCommand.path.first() == coordinates.first()) { -0.2 } else { 0.0 } return coordinates .map { board[it] } .withIndex() .filter { (_, element) -> element !is Pac || element.lastTurnSeen < 2 } .sumByDouble { (index, element) -> val distance = index + 1 when (element) { is Pellet -> if (board.pelletsPercentageLeft > 80 && element.lastTurnSeen > 20) { (element.value.toDouble() / 10.0) / 10 } else { (element.value.toDouble() / 10.0) } is Pac -> when (element.team) { Team.ALLY -> -0.3 Team.ENEMY -> when (fight(element)) { Fight.DRAW, Fight.BEAT -> if (element.abilityCooldown == 0) { -0.7 } else if (coordinates.size < 5 && (abilityCooldown < element.abilityCooldown || fight(element) == Fight.BEAT) && coordinates.size < element.abilityCooldown) { 1.0 } else { -0.2 } Fight.BEATEN -> -0.7 } } else -> 0.0 } * coefDistance(distance) } + threat + collision } private fun coefDistance(distance: Int): Double { return 1.0 / distance } private fun move(path: List<Coordinate>, message: String? = null): Command { assert(this.coordinate != path.lastOrNull()) return Move(this, path, message) } private fun switch(type: Type): Command { assert(this.type != type) assert(this.abilityCooldown == 0) return Switch(this, type) } private fun speed(): Command { assert(this.abilityCooldown == 0) return Speed(this) } private fun fight(enemy: Pac): Fight { assert(this.type != Type.DEAD) return when (enemy.type) { TYPE_WIN[type] -> Fight.BEAT TYPE_LOST[type] -> Fight.BEATEN else -> Fight.DRAW } } private fun getVulnerability(enemy: Pac): Type { assert(this.type != Type.DEAD) return TYPE_LOST.getValue(enemy.type) } override fun toString(): String { return "Pac : $id ${team.name} $coordinate ${type.name} $lastTurnSeen" } override fun equals(other: Any?): Boolean { return other is Pac && other.id == id && other.team == team } enum class Team { ALLY, ENEMY, } enum class Type { DEAD, ROCK, PAPER, SCISSORS, } enum class Fight { DRAW, BEAT, BEATEN, } }
0
Kotlin
0
4
8d3ba5436af69a603127755613612c3540ed23a2
7,239
Codingame
Do What The F*ck You Want To Public License
src/day23/Code.kt
fcolasuonno
162,470,286
false
null
package day23 import java.io.File fun main(args: Array<String>) { val name = if (false) "test.txt" else "input.txt" val dir = ::main::class.java.`package`.name val input = File("src/$dir/$name").readLines() val parsed = parse(input) println("Part 1 = ${part1(parsed)}") println("Part 2 = ${part2(parsed)}") } data class Op(val symbol: String, val reg: Char, val jump: Int) { fun exec(regs: MutableMap<Char, Long>) { when (symbol) { "hlf" -> regs[reg] = regs.getValue(reg) / 2 "tpl" -> regs[reg] = regs.getValue(reg) * 3 "inc" -> regs[reg] = regs.getValue(reg) + 1 "jmp" -> regs['i'] = regs.getValue('i') + jump - 1 "jie" -> if (regs.getValue(reg) % 2L == 0L) { regs['i'] = regs.getValue('i') + jump - 1 } "jio" -> if (regs.getValue(reg) == 1L) { regs['i'] = regs.getValue('i') + jump - 1 } } regs['i'] = regs.getValue('i') + 1 } } private val lineStructure = """(\w\w\w) (\w)(, ([+-]?\d+))?""".toRegex() private val lineStructure1 = """(jmp) ([+-]?\d+)""".toRegex() fun parse(input: List<String>) = input.map { lineStructure.matchEntire(it)?.destructured?.let { val (op, reg, _, jump) = it.toList() Op(op, reg.single(), jump.toIntOrNull() ?: 0) } ?: lineStructure1.matchEntire(it)?.destructured?.let { val (op, jump) = it.toList() Op(op, 'i', jump.toIntOrNull() ?: 0) } }.requireNoNulls() fun part1(input: List<Op>): Any? = mutableMapOf('i' to 0L, 'a' to 0L, 'b' to 0L).let { regs -> generateSequence { input.getOrNull(regs.getValue('i').toInt())?.also { it.exec(regs) } }.last() regs['b'] } fun part2(input: List<Op>): Any? = mutableMapOf('i' to 0L, 'a' to 1L, 'b' to 0L).let { regs -> generateSequence { input.getOrNull(regs.getValue('i').toInt())?.also { it.exec(regs) } }.last() regs['b'] }
0
Kotlin
0
0
24f54bf7be4b5d2a91a82a6998f633f353b2afb6
1,970
AOC2015
MIT License
src/main/kotlin/1360. Number of Days Between Two Dates.kts
ShreckYe
206,086,675
false
null
import kotlin.math.abs class Solution { companion object { val NUM_MONTHS = 12 val COMMON_YEAR_MONTH_DAYS = intArrayOf(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31) val COMMON_YEAR_MONTH_DAYS_ACC = IntArray(NUM_MONTHS + 1).also { it[0] = 0 for (i in 0 until NUM_MONTHS) it[i + 1] = it[i] + COMMON_YEAR_MONTH_DAYS[i] } fun getMonthDaysAcc(month: Int, isLeapYear: Boolean) = COMMON_YEAR_MONTH_DAYS_ACC[month - 1].let { if (month > 2 && isLeapYear) it + 1 else it } } fun daysBetweenDates(date1: String, date2: String): Int { fun String.splitDate() = split('-').map(String::toInt) val (year1, month1, day1) = date1.splitDate() val (year2, month2, day2) = date2.splitDate() return abs( daysBetweenYears(year1, year2) + daysBetweenMonths(month1, isLeapYear(year1), month2, isLeapYear(year2)) + (day2 - day1) ) } fun daysBetweenYears(year1: Int, year2: Int): Int = 365 * (year2 - year1) + (countLeapYearsAcUntil(year2) - countLeapYearsAcUntil(year1)) fun daysBetweenMonths(month1: Int, isMonth1InLeapYear: Boolean, month2: Int, isMonth2InLeapYear: Boolean) = getMonthDaysAcc(month2, isMonth2InLeapYear) - getMonthDaysAcc(month1, isMonth1InLeapYear) fun countLeapYearsAcUntil(year: Int): Int { val maxYear = year - 1 return maxYear / 4 - maxYear / 100 + maxYear / 400 } fun isLeapYear(year: Int): Boolean = year % 4 == 0 && year % 100 != 0 || year % 400 == 0 }
0
Kotlin
0
0
20e8b77049fde293b5b1b3576175eb5703c81ce2
1,623
leetcode-solutions-kotlin
MIT License
src/main/kotlin/com/github/solairerove/algs4/leprosorium/linked_list/ReverseNodesInEvenLengthGroups.kt
solairerove
282,922,172
false
{"Kotlin": 251919}
package com.github.solairerove.algs4.leprosorium.linked_list /** * You are given the head of a linked list. * * The nodes in the linked list are sequentially assigned to non-empty groups * whose lengths form the sequence of the natural numbers (1, 2, 3, 4, ...). * The length of a group is the number of nodes assigned to it. In other words, * * The 1st node is assigned to the first group. * The 2nd and the 3rd nodes are assigned to the second group. * The 4th, 5th, and 6th nodes are assigned to the third group, and so on. * Note that the length of the last group may be less than or equal to 1 + the length of the second to last group. * * Reverse the nodes in each group with an even length, and return the head of the modified linked list. * * Input: head = [5,2,6,3,9,1,7,3,8,4] * Output: [5,6,2,3,9,1,4,8,3,7] * Explanation: * - The length of the first group is 1, which is odd, hence no reversal occurs. * - The length of the second group is 2, which is even, hence the nodes are reversed. * - The length of the third group is 3, which is odd, hence no reversal occurs. * - The length of the last group is 4, which is even, hence the nodes are reversed. * * Input: head = [1,1,0,6] * Output: [1,0,1,6] * Explanation: * - The length of the first group is 1. No reversal occurs. * - The length of the second group is 2. The nodes are reversed. * - The length of the last group is 1. No reversal occurs. * * Input: head = [1,1,0,6,5] * Output: [1,0,1,5,6] * Explanation: * - The length of the first group is 1. No reversal occurs. * - The length of the second group is 2. The nodes are reversed. * - The length of the last group is 2. The nodes are reversed. */ // O(n) time | O(1) space fun reverseEvenLengthGroups(head: ListNode?): ListNode? { if (head?.next == null) return head var group = 2 var cnt = 0 var prev: ListNode? = head var curr: ListNode? = head.next while (curr != null) { if (++cnt == group) { if (group % 2 == 0) { curr = prev?.next prev?.next = reverseKNodes(prev?.next, cnt) } prev = curr cnt = 0 group++ } curr = curr?.next } if (cnt % 2 == 0 && prev?.next != null) { prev.next = reverseKNodes(prev.next, cnt) } return head } private fun reverseKNodes(head: ListNode?, k: Int): ListNode? { var curr: ListNode? = head var prev: ListNode? = null var i = 0 while (curr != null && i++ < k) { val next = curr.next curr.next = prev prev = curr curr = next } head?.next = curr return prev }
1
Kotlin
0
3
64c1acb0c0d54b031e4b2e539b3bc70710137578
2,678
algs4-leprosorium
MIT License
src/main/kotlin/com/chriswk/aoc/advent2020/Day13.kt
chriswk
317,863,220
false
{"Kotlin": 481061}
package com.chriswk.aoc.advent2020 import com.chriswk.aoc.AdventDay import com.chriswk.aoc.util.report class Day13: AdventDay(2020, 13) { companion object { @JvmStatic fun main(args: Array<String>) { val day = Day13() report { day.part1() } report { day.part2() } } } fun findEarliestDepartureAndBuses(input: List<String>): Pair<Int, List<Int>> { val myDeparture = input.first().toInt() val buses = input.drop(1).first().split(",").filterNot { it == "x" }.map { it.toInt() } return myDeparture to buses } fun findClosestBus(earliestDeparture: Int, buses: List<Int>) : BusDeparture { val (busId, waitTime) = buses.map { id -> id to id - (earliestDeparture % id) }.minByOrNull { it.second }!! return BusDeparture(busId, waitTime) } fun solvePart2(input: String): Long { val busPairs = input.split(",") .mapIndexed { idx, b -> idx to b } .filterNot { it.second == "x" } .map { it.second.toLong() to it.first.toLong() } var currentJump = 1L var offset = 0L busPairs.forEach { (bus, diff) -> while ((offset + diff) % bus != 0L) { offset += currentJump } currentJump *= bus } return offset } fun part1(): Int { val (earliestDeparture, buses) = findEarliestDepartureAndBuses(inputAsLines) return findClosestBus(earliestDeparture, buses).part1 } fun part2(): Long { return solvePart2(inputAsLines[1]) } data class BusDeparture(val id: Int, val waitTime: Int) { val part1 = id*waitTime } }
116
Kotlin
0
0
69fa3dfed62d5cb7d961fe16924066cb7f9f5985
1,769
adventofcode
MIT License
src/Day05.kt
gojoel
573,543,233
false
{"Kotlin": 28426}
import java.rmi.UnexpectedException import java.util.* import kotlin.collections.ArrayList import kotlin.collections.HashMap fun main() { val input = readInput("05") // val input = readInput("05_test") data class Step(val amount: Int, val sourceIndex: Int, val destIndex: Int) fun buildStack(row: String, cratesMap: HashMap<Int, ArrayDeque<Char>>) { var mutableRow = row var position = 1 while (mutableRow.isNotEmpty()) { // each crate is represented by 3 characters followed separating space val crate = mutableRow.take(3)[1] if (!crate.isWhitespace()) { val queue = cratesMap.getOrElse(position) { ArrayDeque() } queue.offer(crate) cratesMap[position] = queue } mutableRow = mutableRow.drop(4) position++ } } fun buildSteps(step: String, list: ArrayList<Step>) { val stepValues = step.split(" ") .filter { it.toIntOrNull()?.let { true } ?: false } .map { it.toInt() } list.add(Step(stepValues[0], stepValues[1], stepValues[2])) } fun moveCrate(step: Step, crateMap: HashMap<Int, ArrayDeque<Char>>, movesMultiple: Boolean) { val src = crateMap.getOrElse(step.sourceIndex) { throw UnexpectedException("Crate stack should not be null") } val dst = crateMap.getOrElse(step.destIndex) { throw UnexpectedException("Crate stack should not be null") } if (movesMultiple) { val crates = src.take(step.amount).reversed() for (i in 1..step.amount) { dst.push(crates[i - 1]) src.pop() } } else { for (i in 1..step.amount) { dst.push(src.pop()) } } } fun organizeStacks(input: List<String>, movesMultiple: Boolean = false) : List<ArrayDeque<Char>> { val indexRegex = """(\s*\d)+\s*""".toRegex() val cratesMap: HashMap<Int, ArrayDeque<Char>> = hashMapOf() val steps: ArrayList<Step> = arrayListOf() input .filter { it.isNotBlank() } .forEach { if (it.matches(indexRegex)) { // no-op } else if (it.startsWith("move")) { buildSteps(it, steps) } else { buildStack(it, cratesMap) } } // println(cratesMap) for (step in steps) { moveCrate(step, cratesMap, movesMultiple) // println(cratesMap) } return cratesMap.values.toList() } fun topCrates(stacks: List<ArrayDeque<Char>>) : String { var topCrates = "" for (crateStack in stacks) { topCrates = "$topCrates${crateStack.peek()}" } return topCrates } fun part1(input: List<String>) : String { return topCrates(organizeStacks(input)) } fun part2(input: List<String>) : String { return topCrates(organizeStacks(input, true)) } println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
0690030de456dad6dcfdcd9d6d2bd9300cc23d4a
3,144
aoc-kotlin-22
Apache License 2.0
leetcode/src/offer/middle/Offer59_2.kt
zhangweizhe
387,808,774
false
null
package offer.middle import java.util.* fun main() { // 剑指 Offer 59 - II. 队列的最大值 // https://leetcode.cn/problems/dui-lie-de-zui-da-zhi-lcof/ val maxQueue = MaxQueue() println(maxQueue.max_value()) println(maxQueue.pop_front()) maxQueue.push_back(4) maxQueue.push_back(3) maxQueue.push_back(0) maxQueue.push_back(1) println(maxQueue.max_value()) println(maxQueue.pop_front()) println(maxQueue.max_value()) println(maxQueue.pop_front()) println(maxQueue.max_value()) println(maxQueue.pop_front()) println(maxQueue.max_value()) println(maxQueue.pop_front()) } class MaxQueue() { /** * 关键点:使用一个辅助队列,每次 push_back 的时候,都把辅助队列队尾比 push_back.value 小的元素弹出,维持辅助队列的单调递减; * 因为如果后入队列的一个元素x,比前面的元素大,那只要前面的元素还没出队列,那x就一定是最大的; * 根据队列先进先出的特点,前面那些小的元素,肯定比后面大的元素先出队列,所以前面小的元素是不会影响 max 值的了,所以可以把他们从辅助队列中弹出 */ private val queue = LinkedList<Int>() // 辅助队列,存储最大值 private val helpQueue = LinkedList<Int>() fun max_value(): Int { if (helpQueue.isEmpty()) { return -1 } return helpQueue.peek() } fun push_back(value: Int) { queue.offer(value) // 把辅助队列队尾比 value 小的元素,都弹出,保证辅助队列是单调递减的 // 虽然这里有循环,但并不是每次 push_back 都要执行这个循环,分摊到 n 个数上的话,就是 O(1) 的时间复杂度 while (helpQueue.isNotEmpty() && helpQueue.last < value) { helpQueue.pollLast() } helpQueue.offer(value) } fun pop_front(): Int { if (queue.isEmpty()) { return -1 } val pop = queue.pop() if (pop == helpQueue.peek()) { helpQueue.pop() } return pop } }
0
Kotlin
0
0
1d213b6162dd8b065d6ca06ac961c7873c65bcdc
2,166
kotlin-study
MIT License
advent-of-code-2018/src/test/java/aoc/Advent10.kt
yuriykulikov
159,951,728
false
{"Kotlin": 1666784, "Rust": 33275}
package aoc import org.assertj.core.api.Assertions.assertThat import org.junit.Test import kotlin.math.absoluteValue class Advent10 { @Test fun `stars say hi in 3 seconds`() { val matrix = Array(20) { Array(20) { " " } } parseInput(testInput) .map { it.position(3) } .forEach { (x, y) -> matrix[y][x] = "#" } matrix.forEach { row -> println(row.joinToString(" ")) } } @Test fun `Stars align in 10007 seconds`() { val stars = parseInput(input) val result = generateSequence(0) { it + 1 } .take(20000) .map { second -> Sky(second, stars) } .filter { it.span < 100 } .sortedBy { it.span } // increase this for debugging .take(1) .toList() .onEach { sky -> println("Second: ${sky.second}") sky.matrix.forEach { row -> println(row.joinToString("")) } } .first() .second assertThat(result).isEqualTo(10007) } data class Sky(val second: Int, val stars: List<Star>) { /** Distance between the stars */ val span by lazy { val xPositions: List<Int> = stars.map { star -> star.x + star.dx * second } val max = xPositions.max() ?: 0 val min = xPositions.min() ?: 0 (max - min).absoluteValue } val matrix by lazy { val points: List<Pair<Int, Int>> = stars.map { star -> star.position(second) } val minX = points.map { it.first }.min() ?: 0 val maxX = points.map { it.first }.max() ?: 0 val minY = points.map { it.second }.min() ?: 0 val maxY = points.map { it.second }.max() ?: 0 val matrix = Array(maxY - minY + 1) { Array(maxX - minX + 1) { " " } } points.forEach { (x, y) -> matrix[y - minY][x - minX] = "#" } matrix } } data class Star(val x: Int, val y: Int, val dx: Int, val dy: Int) { fun position(seconds: Int): Pair<Int, Int> { return x + dx * seconds to y + dy * seconds } } fun parseInput(input: String): List<Star> { return input.lines().map { line -> val split = line.split('<', ',', '>').map { it.trim() } Star(split[1].toInt(), split[2].toInt(), split[4].toInt(), split[5].toInt()) } } val testInput = """ position=< 9, 1> velocity=< 0, 2> position=< 7, 0> velocity=<-1, 0> position=< 3, -2> velocity=<-1, 1> position=< 6, 10> velocity=<-2, -1> position=< 2, -4> velocity=< 2, 2> position=<-6, 10> velocity=< 2, -2> position=< 1, 8> velocity=< 1, -1> position=< 1, 7> velocity=< 1, 0> position=<-3, 11> velocity=< 1, -2> position=< 7, 6> velocity=<-1, -1> position=<-2, 3> velocity=< 1, 0> position=<-4, 3> velocity=< 2, 0> position=<10, -3> velocity=<-1, 1> position=< 5, 11> velocity=< 1, -2> position=< 4, 7> velocity=< 0, -1> position=< 8, -2> velocity=< 0, 1> position=<15, 0> velocity=<-2, 0> position=< 1, 6> velocity=< 1, 0> position=< 8, 9> velocity=< 0, -1> position=< 3, 3> velocity=<-1, 1> position=< 0, 5> velocity=< 0, -1> position=<-2, 2> velocity=< 2, 0> position=< 5, -2> velocity=< 1, 2> position=< 1, 4> velocity=< 2, 1> position=<-2, 7> velocity=< 2, -2> position=< 3, 6> velocity=<-1, -1> position=< 5, 0> velocity=< 1, 0> position=<-6, 0> velocity=< 2, 0> position=< 5, 9> velocity=< 1, -2> position=<14, 7> velocity=<-2, 0> position=<-3, 6> velocity=< 2, -1> """.trimIndent() val input = """ position=< 20168, 40187> velocity=<-2, -4> position=<-39906, -49878> velocity=< 4, 5> position=< 30186, 10170> velocity=<-3, -1> position=< 30150, 50195> velocity=<-3, -5> position=< 50184, 40190> velocity=<-5, -4> position=< 40154, 30186> velocity=<-4, -3> position=<-39879, 40188> velocity=< 4, -4> position=<-49865, -49878> velocity=< 5, 5> position=< 50184, 30183> velocity=<-5, -3> position=<-19872, 40193> velocity=< 2, -4> position=< 10148, 10166> velocity=<-1, -1> position=< 30143, -19855> velocity=<-3, 2> position=<-29901, -49875> velocity=< 3, 5> position=< 30183, -29857> velocity=<-3, 3> position=< 50211, 30181> velocity=<-5, -3> position=< 50203, 50195> velocity=<-5, -5> position=< 20175, 30184> velocity=<-2, -3> position=<-29851, 50191> velocity=< 3, -5> position=< -9838, -29865> velocity=< 1, 3> position=< 20133, -49879> velocity=<-2, 5> position=< 30190, -19849> velocity=<-3, 2> position=< 50205, 30186> velocity=<-5, -3> position=< 30162, 10171> velocity=<-3, -1> position=<-49859, -29861> velocity=< 5, 3> position=<-19840, 50191> velocity=< 2, -5> position=<-49918, 10164> velocity=< 5, -1> position=< 50160, -39870> velocity=<-5, 4> position=< -9866, -29859> velocity=< 1, 3> position=< 40148, -9846> velocity=<-4, 1> position=<-29867, 20179> velocity=< 3, -2> position=<-29862, -9847> velocity=< 3, 1> position=< 50208, -29861> velocity=<-5, 3> position=< 50176, 40191> velocity=<-5, -4> position=<-49890, -9842> velocity=< 5, 1> position=<-19860, -19856> velocity=< 2, 2> position=< 10134, 20179> velocity=<-1, -2> position=< 30138, 50196> velocity=<-3, -5> position=< 10148, 50193> velocity=<-1, -5> position=< 20184, -29863> velocity=<-2, 3> position=< 30178, -49876> velocity=<-3, 5> position=< -9881, -49879> velocity=< 1, 5> position=< 40162, -29865> velocity=<-4, 3> position=<-29851, -9851> velocity=< 3, 1> position=< -9833, -49870> velocity=< 1, 5> position=<-39867, -49871> velocity=< 4, 5> position=<-19897, 40184> velocity=< 2, -4> position=< 10164, 10165> velocity=<-1, -1> position=< 40182, 40192> velocity=<-4, -4> position=<-39910, 10163> velocity=< 4, -1> position=<-39851, 40193> velocity=< 4, -4> position=<-39882, 20179> velocity=< 4, -2> position=< 20155, -29861> velocity=<-2, 3> position=<-49902, 20173> velocity=< 5, -2> position=<-29853, 50191> velocity=< 3, -5> position=<-29856, -19849> velocity=< 3, 2> position=<-29843, 20170> velocity=< 3, -2> position=<-19892, 10165> velocity=< 2, -1> position=<-19857, 30182> velocity=< 2, -3> position=< -9850, 30178> velocity=< 1, -3> position=< -9848, -29862> velocity=< 1, 3> position=< 40153, 20173> velocity=<-4, -2> position=<-49894, 20179> velocity=< 5, -2> position=<-29848, -9843> velocity=< 3, 1> position=<-29859, 50195> velocity=< 3, -5> position=<-19847, -39872> velocity=< 2, 4> position=< -9830, 40184> velocity=< 1, -4> position=<-19887, -9847> velocity=< 2, 1> position=< 30138, 10164> velocity=<-3, -1> position=< 20155, -9843> velocity=<-2, 1> position=<-39911, 20172> velocity=< 4, -2> position=< 50173, -19850> velocity=<-5, 2> position=<-19846, 20174> velocity=< 2, -2> position=< 40181, 30177> velocity=<-4, -3> position=< 10126, 40188> velocity=<-1, -4> position=< 40205, -49875> velocity=<-4, 5> position=<-29867, 10165> velocity=< 3, -1> position=<-49873, 30179> velocity=< 5, -3> position=< 50208, -49870> velocity=<-5, 5> position=< 30143, 50193> velocity=<-3, -5> position=< 20171, 10166> velocity=<-2, -1> position=< 40197, 20170> velocity=<-4, -2> position=< 20166, -9847> velocity=<-2, 1> position=<-49890, -49870> velocity=< 5, 5> position=< 10177, 40185> velocity=<-1, -4> position=< 10124, 30186> velocity=<-1, -3> position=<-39907, 40188> velocity=< 4, -4> position=< 50163, -9842> velocity=<-5, 1> position=<-19881, 10168> velocity=< 2, -1> position=< 20179, -39872> velocity=<-2, 4> position=< 20171, -29864> velocity=<-2, 3> position=<-49899, 30177> velocity=< 5, -3> position=< 30154, 10170> velocity=<-3, -1> position=<-49902, 20175> velocity=< 5, -2> position=< 50176, 10164> velocity=<-5, -1> position=<-29871, -19858> velocity=< 3, 2> position=<-49860, 20179> velocity=< 5, -2> position=< -9866, 50196> velocity=< 1, -5> position=<-49910, -29857> velocity=< 5, 3> position=< 40203, -39872> velocity=<-4, 4> position=< 20144, 40193> velocity=<-2, -4> position=<-29859, 20173> velocity=< 3, -2> position=<-19839, -39868> velocity=< 2, 4> position=<-19868, -29856> velocity=< 2, 3> position=<-19848, 10163> velocity=< 2, -1> position=< 10167, -49873> velocity=<-1, 5> position=< 10132, 10169> velocity=<-1, -1> position=< 20190, 40188> velocity=<-2, -4> position=< 40177, -19849> velocity=<-4, 2> position=<-49883, 20170> velocity=< 5, -2> position=< 40177, 50194> velocity=<-4, -5> position=<-39899, 10163> velocity=< 4, -1> position=<-19865, 20178> velocity=< 2, -2> position=< 40188, 40189> velocity=<-4, -4> position=< -9866, 20175> velocity=< 1, -2> position=<-49885, -49879> velocity=< 5, 5> position=<-39850, -49870> velocity=< 4, 5> position=<-39879, 50192> velocity=< 4, -5> position=< 30148, 30186> velocity=<-3, -3> position=< -9845, 30178> velocity=< 1, -3> position=< -9850, 50197> velocity=< 1, -5> position=< 50187, 40188> velocity=<-5, -4> position=< 10156, 40188> velocity=<-1, -4> position=< 50197, 50193> velocity=<-5, -5> position=<-29859, -49870> velocity=< 3, 5> position=<-49862, 20179> velocity=< 5, -2> position=< 40190, 20170> velocity=<-4, -2> position=< 30162, -29862> velocity=<-3, 3> position=< 10184, 30177> velocity=<-1, -3> position=< 10180, -39866> velocity=<-1, 4> position=<-39854, 10167> velocity=< 4, -1> position=< -9890, -39869> velocity=< 1, 4> position=<-29888, 40187> velocity=< 3, -4> position=< 10148, -49870> velocity=<-1, 5> position=<-39866, 40187> velocity=< 4, -4> position=< 10164, 20174> velocity=<-1, -2> position=<-29888, -49875> velocity=< 3, 5> position=< 20155, -9849> velocity=<-2, 1> position=< 50154, -19858> velocity=<-5, 2> position=<-49900, -29856> velocity=< 5, 3> position=< 30183, -39866> velocity=<-3, 4> position=< 30183, 40186> velocity=<-3, -4> position=<-39862, -9842> velocity=< 4, 1> position=<-49907, -19858> velocity=< 5, 2> position=< 10136, -29865> velocity=<-1, 3> position=<-29872, -9843> velocity=< 3, 1> position=<-29864, 20179> velocity=< 3, -2> position=<-39895, -49878> velocity=< 4, 5> position=< 20147, 30179> velocity=<-2, -3> position=< 10175, -39868> velocity=<-1, 4> position=< 10125, -19858> velocity=<-1, 2> position=< 30186, -49872> velocity=<-3, 5> position=<-29880, -29864> velocity=< 3, 3> position=<-29903, -19854> velocity=< 3, 2> position=< -9839, -39863> velocity=< 1, 4> position=< 50173, -19857> velocity=<-5, 2> position=< -9842, -9842> velocity=< 1, 1> position=<-19852, -39865> velocity=< 2, 4> position=< 10124, -9842> velocity=<-1, 1> position=< 10180, 10170> velocity=<-1, -1> position=< 40201, 20174> velocity=<-4, -2> position=< 10156, 10163> velocity=<-1, -1> position=<-19888, -29856> velocity=< 2, 3> position=< 50197, -9848> velocity=<-5, 1> position=< -9882, -9844> velocity=< 1, 1> position=< 20158, -19849> velocity=<-2, 2> position=<-29878, 20179> velocity=< 3, -2> position=<-19881, -19851> velocity=< 2, 2> position=<-29896, 10171> velocity=< 3, -1> position=< 20164, 10167> velocity=<-2, -1> position=<-19889, 40184> velocity=< 2, -4> position=< 30146, -49875> velocity=<-3, 5> position=< 20155, -29859> velocity=<-2, 3> position=<-19885, 40184> velocity=< 2, -4> position=< 10156, -9849> velocity=<-1, 1> position=< 40145, -19852> velocity=<-4, 2> position=< 20139, 10170> velocity=<-2, -1> position=< 20143, 20179> velocity=<-2, -2> position=<-39903, -49871> velocity=< 4, 5> position=<-49918, 30179> velocity=< 5, -3> position=<-39908, 30177> velocity=< 4, -3> position=<-29899, -29864> velocity=< 3, 3> position=< -9853, -19855> velocity=< 1, 2> position=< 30175, -49871> velocity=<-3, 5> position=< 50197, -29860> velocity=<-5, 3> position=< 40186, -19856> velocity=<-4, 2> position=< 20139, -9846> velocity=<-2, 1> position=< 20156, -49870> velocity=<-2, 5> position=< 50208, -39870> velocity=<-5, 4> position=< -9856, 20174> velocity=< 1, -2> position=<-19865, 10172> velocity=< 2, -1> position=< 50160, -19855> velocity=<-5, 2> position=< 40155, 30181> velocity=<-4, -3> position=< 40162, -9842> velocity=<-4, 1> position=< 20172, -49877> velocity=<-2, 5> position=< 20166, -19853> velocity=<-2, 2> position=<-49859, 50191> velocity=< 5, -5> position=<-49894, -9851> velocity=< 5, 1> position=<-19881, -49873> velocity=< 2, 5> position=<-49873, 10168> velocity=< 5, -1> position=<-29864, 50195> velocity=< 3, -5> position=< 20143, 10167> velocity=<-2, -1> position=<-29900, -29858> velocity=< 3, 3> position=<-19878, -49879> velocity=< 2, 5> position=<-49866, 30186> velocity=< 5, -3> position=< 10177, -9842> velocity=<-1, 1> position=<-49868, -29856> velocity=< 5, 3> position=< 20148, 10163> velocity=<-2, -1> position=< 30194, -49879> velocity=<-3, 5> position=< 10160, 40190> velocity=<-1, -4> position=<-39859, 50194> velocity=< 4, -5> position=<-39901, 30181> velocity=< 4, -3> position=< 40198, -19858> velocity=<-4, 2> position=< 30179, 20171> velocity=<-3, -2> position=<-49905, 40184> velocity=< 5, -4> position=< 50204, 40187> velocity=<-5, -4> position=< 20139, -49878> velocity=<-2, 5> position=< 40149, 20176> velocity=<-4, -2> position=< -9845, 10168> velocity=< 1, -1> position=<-29900, -9851> velocity=< 3, 1> position=< 40145, -49878> velocity=<-4, 5> position=<-39871, -19850> velocity=< 4, 2> position=<-29904, -9844> velocity=< 3, 1> position=< 10165, 50192> velocity=<-1, -5> position=< 50184, 40186> velocity=<-5, -4> position=< 10125, 30177> velocity=<-1, -3> position=<-49878, -49877> velocity=< 5, 5> position=< 40201, -9842> velocity=<-4, 1> position=<-39876, 50191> velocity=< 4, -5> position=<-29904, 30180> velocity=< 3, -3> position=< 10169, 50195> velocity=<-1, -5> position=< 30146, -29856> velocity=<-3, 3> position=<-39877, -49875> velocity=< 4, 5> position=< 10166, -9848> velocity=<-1, 1> position=< 30154, 40186> velocity=<-3, -4> position=< 20148, -19849> velocity=<-2, 2> position=<-19849, -19849> velocity=< 2, 2> position=<-29862, -29861> velocity=< 3, 3> position=< 20166, -19853> velocity=<-2, 2> position=<-39853, -19854> velocity=< 4, 2> position=< 20151, 50191> velocity=<-2, -5> position=< -9830, -49870> velocity=< 1, 5> position=< 30189, 40184> velocity=<-3, -4> position=< 20139, 20174> velocity=<-2, -2> position=< 10169, -19857> velocity=<-1, 2> position=< 40186, -19857> velocity=<-4, 2> position=< 30183, -29857> velocity=<-3, 3> position=< 20163, 40189> velocity=<-2, -4> position=<-19897, 20175> velocity=< 2, -2> position=<-19892, -9848> velocity=< 2, 1> position=< 50197, -19857> velocity=<-5, 2> position=< 20150, -9842> velocity=<-2, 1> position=<-29900, -49879> velocity=< 3, 5> position=< 20136, -19850> velocity=<-2, 2> position=<-49873, -39872> velocity=< 5, 4> position=< 50154, -29861> velocity=<-5, 3> position=<-49892, 30186> velocity=< 5, -3> position=<-49873, 10170> velocity=< 5, -1> position=< 40186, -49877> velocity=<-4, 5> position=<-39901, 20170> velocity=< 4, -2> position=<-39887, 30185> velocity=< 4, -3> position=<-29859, -49871> velocity=< 3, 5> position=< 50189, 10164> velocity=<-5, -1> position=< 30178, 30186> velocity=<-3, -3> position=< 50192, -49878> velocity=<-5, 5> position=< 30178, 40184> velocity=<-3, -4> position=<-39902, 40188> velocity=< 4, -4> position=< 30178, -39868> velocity=<-3, 4> position=<-39861, 20175> velocity=< 4, -2> position=< 10132, -9844> velocity=<-1, 1> position=< 30165, 20179> velocity=<-3, -2> position=<-19879, -29856> velocity=< 2, 3> position=<-49890, 30186> velocity=< 5, -3> position=<-19838, 30186> velocity=< 2, -3> position=< 30155, 40184> velocity=<-3, -4> position=<-49884, -9847> velocity=< 5, 1> position=<-29868, 10167> velocity=< 3, -1> position=< 50187, 30182> velocity=<-5, -3> position=< 30191, 20171> velocity=<-3, -2> position=< -9856, -19858> velocity=< 1, 2> position=<-19889, -29859> velocity=< 2, 3> position=< 10134, 50191> velocity=<-1, -5> position=<-29893, 10167> velocity=< 3, -1> position=< -9834, 10169> velocity=< 1, -1> position=< 50184, 30184> velocity=<-5, -3> position=< 30146, 50192> velocity=<-3, -5> position=<-29856, -39864> velocity=< 3, 4> position=< 20167, 20174> velocity=<-2, -2> position=< 50168, 40185> velocity=<-5, -4> position=<-39854, 50200> velocity=< 4, -5> position=<-19857, 20170> velocity=< 2, -2> position=<-39851, -9851> velocity=< 4, 1> position=< 10160, -49873> velocity=<-1, 5> position=< 20173, 20173> velocity=<-2, -2> position=<-39901, 50191> velocity=< 4, -5> position=<-29856, -29858> velocity=< 3, 3> position=<-39911, 50196> velocity=< 4, -5> position=<-29864, 10172> velocity=< 3, -1> position=<-39911, 20174> velocity=< 4, -2> position=<-49894, -29861> velocity=< 5, 3> position=< 30174, -9851> velocity=<-3, 1> position=<-39855, -9850> velocity=< 4, 1> position=<-19848, -39866> velocity=< 2, 4> position=<-19865, 10165> velocity=< 2, -1> position=< -9885, 30186> velocity=< 1, -3> position=<-49861, 40184> velocity=< 5, -4> position=< -9850, 50198> velocity=< 1, -5> position=< 30154, 10167> velocity=<-3, -1> position=< 20187, 20173> velocity=<-2, -2> position=< 30197, -9851> velocity=<-3, 1> position=<-49902, 50199> velocity=< 5, -5> position=<-19888, -19858> velocity=< 2, 2> position=<-39900, -49875> velocity=< 4, 5> position=<-19865, 10170> velocity=< 2, -1> position=<-49862, -9845> velocity=< 5, 1> position=< -9871, -9851> velocity=< 1, 1> position=<-19845, -19858> velocity=< 2, 2> position=< 20133, 40188> velocity=<-2, -4> position=< -9832, 10167> velocity=< 1, -1> position=< 50165, -19849> velocity=<-5, 2> position=<-49862, 40189> velocity=< 5, -4> position=< -9854, -19854> velocity=< 1, 2> position=< -9853, -29862> velocity=< 1, 3> position=<-19878, -29856> velocity=< 2, 3> position=< 40145, -9843> velocity=<-4, 1> position=< 30143, -29864> velocity=<-3, 3> position=<-29880, 20175> velocity=< 3, -2> position=< 10136, -39868> velocity=<-1, 4> position=< 10133, -19858> velocity=<-1, 2> position=< 20139, -29864> velocity=<-2, 3> position=<-39899, 50200> velocity=< 4, -5> position=< 20155, -9847> velocity=<-2, 1> position=<-29880, -49876> velocity=< 3, 5> position=<-29856, -29857> velocity=< 3, 3> position=<-39903, 40189> velocity=< 4, -4> position=< 50184, 20179> velocity=<-5, -2> position=< 10144, 30186> velocity=<-1, -3> position=< 10142, -19858> velocity=<-1, 2> position=<-29879, 30186> velocity=< 3, -3> position=< -9866, -9842> velocity=< 1, 1> position=<-19836, -9851> velocity=< 2, 1> position=<-39875, 20177> velocity=< 4, -2> position=<-39866, 30181> velocity=< 4, -3> position=< 40147, 20170> velocity=<-4, -2> position=< 10181, -39868> velocity=<-1, 4> position=<-29880, 50198> velocity=< 3, -5> position=< -9890, -49877> velocity=< 1, 5> position=< -9866, -9850> velocity=< 1, 1> position=< 30162, -39866> velocity=<-3, 4> position=< 20171, 50193> velocity=<-2, -5> position=<-39855, -49876> velocity=< 4, 5> """.trimIndent() }
0
Kotlin
0
1
f5efe2f0b6b09b0e41045dc7fda3a7565cb21db3
19,099
advent-of-code
MIT License
kotlin-leetcode/src/main/kotlin/io/github/dreamylost/Leetcode_164.kt
jxnu-liguobin
123,690,567
false
null
/* Licensed under Apache-2.0 @梦境迷离 */ package io.github.dreamylost import kotlin.math.ceil import kotlin.math.max import kotlin.math.min /** * 164. 最大间距 * * 给定一个无序的数组,找出数组在排序之后,相邻元素之间最大的差值。 * 如果数组元素个数小于 2,则返回 0。 * @author 梦境迷离 * @version 1.0,2020/11/26 */ class Leetcode_164 { companion object { /** * 桶排序(不需要桶间的排序) * 208 ms,100.00% * 35.7 MB,50.00% */ fun maximumGap(nums: IntArray): Int { if (nums.size < 2) return 0 val len = nums.size var max = Int.MIN_VALUE var min = Int.MAX_VALUE for (i in nums.indices) { max = max(max, nums[i]) min = min(min, nums[i]) } if (max - min == 0) return 0 val bucketMin = Array(len - 1) { Int.MAX_VALUE } val bucketMax = Array(len - 1) { Int.MIN_VALUE } val interval = ceil((max - min).toDouble() / (len - 1)).toInt() for (i in nums.indices) { val index: Int = (nums[i] - min) / interval if (nums[i] == min || nums[i] == max) continue bucketMax[index] = max(bucketMax[index], nums[i]) bucketMin[index] = min(bucketMin[index], nums[i]) } var ret = 0 var preBucketMax = min for (i in 0 until len - 1) { if (bucketMax[i] == Int.MIN_VALUE) continue ret = max(bucketMin[i] - preBucketMax, ret) preBucketMax = bucketMax[i] } return max(ret, max - preBucketMax) } /** * 基数排序 * 240 ms,50.00% * 34.4 MB,50.00% */ fun maximumGap_(nums: IntArray): Int { if (nums.size < 2) return 0 var max = nums[0] for (anArr in nums) { if (anArr > max) { max = anArr } } // 分别针对数值的个位、十位、百分位等进行排序 var exp = 1 while (max / exp > 0) { // 存储待排元素的临时数组 val temp = IntArray(nums.size) val buckets = IntArray(10) // 统计每个桶中的个数 for (value in nums) { buckets[value / exp % 10]++ } // 计算排序后数字的下标 for (i in 1..9) { buckets[i] += buckets[i - 1] } // 排序 for (i in nums.indices.reversed()) { val index = nums[i] / exp % 10 temp[buckets[index] - 1] = nums[i] buckets[index]-- } System.arraycopy(temp, 0, nums, 0, nums.size) exp *= 10 } var res = -1 for (i in 1 until nums.size) { res = max(res, nums[i] - nums[i - 1]) } return res } @JvmStatic fun main(args: Array<String>) { val arr = arrayOf(2, 99999999) val ret = maximumGap(arr.toIntArray()) val ret2 = maximumGap_(arr.toIntArray()) println(ret) println(ret2) } } }
13
Java
190
526
a97159e99fc6592bec5032d18391d18b84708175
3,480
cs-summary-reflection
Apache License 2.0
src/main/kotlin/day2/Day2InventoryManagementSystem.kt
Zordid
160,908,640
false
null
package day2 import shared.allPairs import shared.readPuzzle fun String.containsOneCharExactly(times: Int) = toCharArray().distinct().any { c -> count { it == c } == times } infix fun String.difference(other: String) = indices.count { this[it] != other.getOrNull(it) } + (other.length - length).coerceAtLeast(0) infix fun String.common(other: String) = toCharArray().filterIndexed { index, c -> c == other[index] }.joinToString("") fun part1(ids: List<String>): Int { return ids.count { it.containsOneCharExactly(2) } * ids.count { it.containsOneCharExactly(3) } } fun part2(ids: List<String>): String { return ids.allPairs().single { it.first difference it.second == 1 }.let { it.first common it.second } } fun main() { val puzzle = readPuzzle(2) println(part1(puzzle)) println(part2(puzzle)) }
0
Kotlin
0
0
f246234df868eabecb25387d75e9df7040fab4f7
847
adventofcode-kotlin-2018
Apache License 2.0
src/main/kotlin/g2001_2100/s2099_find_subsequence_of_length_k_with_the_largest_sum/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g2001_2100.s2099_find_subsequence_of_length_k_with_the_largest_sum // #Easy #Array #Hash_Table #Sorting #Heap_Priority_Queue // #2023_06_28_Time_203_ms_(100.00%)_Space_37.5_MB_(100.00%) import java.util.PriorityQueue class Solution { fun maxSubsequence(nums: IntArray, k: Int): IntArray { // Create proirity queue with min priority queue so that min element will be removed first, // with index // Add those unique index in a set // Loop from 0 to n-1 and add element in result if set contains those index // For ex. set has index 3,5,6 Just add those element. Order will be maintained // We are defining the min priority queue val q = PriorityQueue { a: IntArray, b: IntArray -> a[0] - b[0] } // Add element with index to priority queue for (i in nums.indices) { q.offer(intArrayOf(nums[i], i)) if (q.size > k) { q.poll() } } // Set to keep index val index: MutableSet<Int> = HashSet() // At the index in the set since index are unique while (q.isNotEmpty()) { val top = q.poll() index.add(top[1]) } // Final result add here val result = IntArray(k) // Just add the element in the result for those index present in SET var p = 0 for (i in nums.indices) { if (index.contains(i)) { result[p] = nums[i] ++p } } return result } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,554
LeetCode-in-Kotlin
MIT License
Algorithm/coding_interviews/Kotlin/Questions28.kt
ck76
314,136,865
false
{"HTML": 1420929, "Java": 723214, "JavaScript": 534260, "Python": 437495, "CSS": 348978, "C++": 348274, "Swift": 325819, "Go": 310456, "Less": 203040, "Rust": 105712, "Ruby": 96050, "Kotlin": 88868, "PHP": 67753, "Lua": 52032, "C": 30808, "TypeScript": 23395, "C#": 4973, "Elixir": 4945, "Pug": 1853, "PowerShell": 471, "Shell": 163}
package com.qiaoyuang.algorithm fun main() { val a = BinaryTreeNode(8) val b = BinaryTreeNode(6) val c = BinaryTreeNode(6) val d = BinaryTreeNode(5) val e = BinaryTreeNode(7) val f = BinaryTreeNode(7) val g = BinaryTreeNode(5) a.mLeft = b a.mRight = c b.mLeft = d b.mRight = e c.mLeft = f c.mRight = g println(a.isSymmetrical()) c.mValue = 9 println(a.isSymmetrical()) val h = BinaryTreeNode(7) val i = BinaryTreeNode(7) val j = BinaryTreeNode(7) val k = BinaryTreeNode(7) val l = BinaryTreeNode(7) val m = BinaryTreeNode(7) h.mLeft = i h.mRight = j i.mLeft = k i.mRight = l j.mLeft = m println(h.isSymmetrical()) } fun <T> BinaryTreeNode<T>.isSymmetrical(): Boolean { if (preOrderJudgment()) { if (preOrderBack() == _preOrderBack()) { return true } } return false } fun <T> BinaryTreeNode<T>.preOrderJudgment(): Boolean { var boo = judgment() if (boo) { mLeft?.let { boo = it.preOrderJudgment() } mRight?.let { boo = it.preOrderJudgment() } } return boo } private fun <T> BinaryTreeNode<T>.judgment() = (mLeft == null && mRight == null) || (mLeft != null && mRight != null) fun <T> BinaryTreeNode<T>.preOrderBack(): String { var str = mValue.toString() str += mLeft?.preOrderBack() str += mRight?.preOrderBack() return str } fun <T> BinaryTreeNode<T>._preOrderBack(): String { var str = mValue.toString() str += mRight?._preOrderBack() str += mLeft?._preOrderBack() return str }
0
HTML
0
2
2a989fe85941f27b9dd85b3958514371c8ace13b
1,451
awesome-cs
Apache License 2.0
src/main/kotlin/aoc10/Solution10.kt
rainer-gepardec
573,386,353
false
{"Kotlin": 13070}
package aoc10 import java.nio.file.Paths fun main() { val lines = Paths.get("src/main/resources/aoc_10.txt").toFile().useLines { it.toList() } println(solution1(lines)) println(solution2(lines)) } fun solution1(lines: List<String>): Int { return solve(lines) .filter { it.first == 20 || ((it.first - 20) % 40) == 0 } .sumOf { it.first * it.second } } fun solution2(lines: List<String>): Int { val crt = Array(6) { CharArray(40) } for (row in 0 until 6) { for (column in 0 until 40) { crt[row][column] = '.' } } solve(lines) .forEach { val row = (it.first - 1) / 40 val column = (it.first - 1) % 40 if (IntRange(it.second - 1, it.second + 1).contains(column)) { crt[row][column] = '#' } } crt.forEach { println(it) } return 0 } fun solve(lines: List<String>): List<Pair<Int, Int>> { val cycles = mutableListOf<Pair<Int, Int>>() lines .map { if (it.startsWith("addx")) listOf("noop", it) else listOf(it) } .flatten() .map { it.split(" ").getOrElse(1) { "0" }.toInt() } .foldIndexed(1) { index, result, add -> cycles.add(Pair(index + 1, result)); result.plus(add) } return cycles }
0
Kotlin
0
0
c920692d23e8c414a996e8c1f5faeee07d0f18f2
1,329
aoc2022
Apache License 2.0
src/test/kotlin/day13/BusTest.kt
gmpalmer
319,038,590
false
null
package day13 import org.junit.jupiter.api.Test import kotlin.test.assertEquals class BusTest { @Test fun example_a() { val input = AdventUtils.getResourceAsText("/day13/example.txt").lines() val result = solveA(input) assertEquals(295, result) } @Test fun input_a() { val input = AdventUtils.getResourceAsText("/day13/input.txt").lines() val result = solveA(input) assertEquals(5257, result) } @Test fun example_b() { val input = AdventUtils.getResourceAsText("/day13/example.txt").lines() val result = solveB(input) assertEquals(1068781, result) } @Test fun input_b() { val input = AdventUtils.getResourceAsText("/day13/input.txt").lines() val result = solveB(input) assertEquals(538703333547789, result) } //"538703333547789" private fun solveB(input: List<String>): Long { val routes = input[1].split(",") .mapIndexed { index, s -> Pair(s, index)} .filter({ it.first != "x"}) .map{Pair(it.first.toLong(), it.second)} .sortedByDescending { it.first } println("${routes}") var currVal = routes[0].first - routes[0].second var foundResult = false var routesToCheck = ArrayList<Pair<Long, Int>>() routesToCheck.addAll(routes) routesToCheck.removeAt(0) var toAdd = routes[0].first var newRoutes = 0 while(!foundResult) { currVal += toAdd // println("${currVal}") if(currVal > 999999999999999999) { throw IllegalStateException("Bad") } foundResult = true for(route in routesToCheck) { if (!matches(currVal, route)) { //println("${route} fails check") foundResult = false break } else { newRoutes++ } } if(foundResult == false && newRoutes > 0) { for (index in 1..newRoutes) { toAdd = calcValueToAdd(toAdd, routesToCheck[0].first) println("${currVal}: ${routesToCheck[0]} = ${toAdd}") routesToCheck.removeAt(0) } newRoutes = 0 } } return currVal } private fun calcValueToAdd(in1: Long, in2: Long):Long { var n1 = in1 var n2 = in2 while (n1 != n2) { if (n1 > n2) n1 -= n2 else n2 -= n1 } return n1 * (in1/n1) * (in2/n1) } private fun matches(valueToCheck: Long, route: Pair<Long, Int>): Boolean { val result = ((valueToCheck + route.second) % route.first) return result == 0L } private fun solveA(input: List<String>): Long { val startTime = input[0].toLong() val routes = input[1].split(",").filter { it != "x" }.map { it.toInt() } val minRoute = routes.minBy { calcNextBus(startTime, it) }!! println("${startTime} = ${routes} | ${minRoute}") return minRoute * (calcNextBus(startTime, minRoute) - startTime) } private fun calcNextBus(startTime: Long, route: Int): Long { if( startTime % route == 0L) { return startTime } val temp = (startTime / route ) * route return temp + route } }
0
Kotlin
0
0
ec8eba4c247973ac6f1d1fce2bae76c5a938cda2
3,502
advent2020
Apache License 2.0
LeetCode/0017. Letter Combinations of a Phone Number/Solution.kt
InnoFang
86,413,001
false
{"C++": 501928, "Kotlin": 291271, "Python": 280936, "Java": 78746, "Go": 43858, "JavaScript": 27490, "Rust": 6410}
/** * Created by <NAME> on 2017/12/31. */ class Solution { private val res = ArrayList<String>() private val map = hashMapOf( '0' to "", '1' to "", '2' to "abc", '3' to "def", '4' to "ghi", '5' to "jkl", '6' to "mno", '7' to "pqrs", '8' to "tuv", '9' to "wxyz") fun letterCombinations(digits: String): List<String> { if ("" == digits) return res tryCombinations(digits, 0, "") return res } private fun tryCombinations(digits: String, index: Int, s: String) { if (digits.length == index) { res.add(s) return } map[digits[index]]?.forEachIndexed { _, c -> tryCombinations(digits, index + 1, s + c) } } } class Solution2 { fun letterCombinations(digits: String): List<String> { if (digits.isEmpty()) return emptyList() val letters = mapOf('2' to "abc", '3' to "def", '4' to "hgi", '5' to "jkl", '6' to "mno", '7' to "pqrs", '8' to "tuv", '9' to "wxyz") return digits.fold(listOf("")) { acc, c -> acc.flatMap { o -> letters[c]?.map { o + it }.orEmpty() } } } } fun main(args: Array<String>) { Solution().letterCombinations("10").forEach { print("$it ") } println() Solution2().letterCombinations("23").forEach { print("$it ") } println() } // 93 Restore IP Address // 131 Palindrome Partitioning
0
C++
8
20
2419a7d720bea1fd6ff3b75c38342a0ace18b205
1,487
algo-set
Apache License 2.0
src/main/kotlin/tr/emreone/adventofcode/days/Day15.kt
EmRe-One
433,772,813
false
{"Kotlin": 118159}
package tr.emreone.adventofcode.days import tr.emreone.kotlin_utils.Logger.logger import tr.emreone.kotlin_utils.automation.Day import tr.emreone.kotlin_utils.math.Coords import java.util.* import kotlin.math.max import kotlin.math.min class Day15 : Day(15, 2021, "Chiton") { class Traversal(val location: Coords, val totalRisk: Int, val totalPath: List<Coords>) : Comparable<Traversal> { override fun compareTo(other: Traversal): Int = this.totalRisk - other.totalRisk } class Cavern(var grid: Array<IntArray>) { val height = grid.size val width = grid[0].size fun get(coord: Coords): Int { return grid[coord.second][coord.first] } fun traverse(start: Coords, destination: Coords): Traversal { val toBeEvaluated = PriorityQueue<Traversal>().also { it.add(Traversal(start, 0, mutableListOf(start))) } val visited = mutableSetOf<Coords>() while (toBeEvaluated.isNotEmpty()) { val currentTraversal = toBeEvaluated.poll() if (currentTraversal.location == destination) { return currentTraversal } if (currentTraversal.location !in visited) { visited.add(currentTraversal.location) this.getNeighbors(currentTraversal.location).filter { it.first in 0..destination.first && it.second in 0..destination.second }.forEach { toBeEvaluated.offer( Traversal( it, currentTraversal.totalRisk + this.get(it), currentTraversal.totalPath + it ) ) } } } error("No path to destination (which is really weird, right?)") } private fun getNeighbors(location: Coords): List<Coords> { val neighbors = mutableSetOf<Coords>() // up neighbors.add(Coords(location.first, max(0, location.second - 1))) // right neighbors.add(Coords(min(this.width - 1, location.first + 1), location.second)) // down neighbors.add(Coords(location.first, min(this.height - 1, location.second + 1))) // left neighbors.add(Coords(max(0, location.first - 1), location.second)) return neighbors.filter { it != location } } fun drawPath(minRiskLevelPath: List<Coords>) { buildString { appendLine() this@Cavern.grid.forEachIndexed { y, row -> row.forEachIndexed { x, riskLevel -> if (minRiskLevelPath.contains(Coords(x, y))) { append("[") append(riskLevel) append("]") } else { append(" $riskLevel ") } } appendLine() } logger.debug { this.toString() } } } } override fun part1(): Int { val grid = inputAsList .mapIndexed { _, line -> line.mapIndexed { _, c -> c.digitToInt() }.toIntArray() } .toTypedArray() val cavern = Cavern(grid) val start = Coords(0, 0) val destination = Coords(cavern.width - 1, cavern.height - 1) val traversal = cavern.traverse(start, destination) cavern.drawPath(traversal.totalPath) return traversal.totalRisk } override fun part2(): Int { val repeatX = 5 val repeatY = 5 val grid = inputAsList .mapIndexed { _, line -> line.mapIndexed { _, c -> c.digitToInt() }.toIntArray() } .toTypedArray() val width = grid[0].size val height = grid.size val fullMap = Array(repeatY * height) { IntArray(repeatX * width) { 0 } } for (y in 0 until height) { for (x in 0 until width) { val riskLevel = grid[y][x] for (yIter in 0 until repeatY) { for (xIter in 0 until repeatX) { val newValue = riskLevel + yIter + xIter fullMap[yIter * height + y][xIter * width + x] = if (newValue > 9) { newValue - (newValue / 9) * 9 } else { newValue } } } } } val cavern = Cavern(fullMap) val start = Coords(0, 0) val destination = Coords(cavern.width - 1, cavern.height - 1) val traversal = cavern.traverse(start, destination) cavern.drawPath(traversal.totalPath) return traversal.totalRisk } }
0
Kotlin
0
0
516718bd31fbf00693752c1eabdfcf3fe2ce903c
5,162
advent-of-code-2021
Apache License 2.0
day_13/src/main/kotlin/io/github/zebalu/advent2020/IdealTimeFinder.kt
zebalu
317,448,231
false
null
package io.github.zebalu.advent2020 import java.math.BigInteger object IdealTimeFinder { fun findTime2(buses: List<Pair<Int, Int>>): Long = longBuses(buses) .fold(Pair(0L, 1L)) { acc, next -> applyBus(acc.first, acc.second, next.first, next.second) }.first private fun applyBus(sum: Long, interval: Long, bus: Long, timeDif: Long) = Pair(findTimeWithRightDiff(sum, interval, timeDif, bus), interval * bus) private tailrec fun findTimeWithRightDiff(start: Long, interval: Long, expected: Long, bus: Long): Long = if ((start + expected) % bus == 0L) start else findTimeWithRightDiff(start + interval, interval, expected, bus) private fun longBuses(buses: List<Pair<Int, Int>>) = buses.map { Pair(it.first.toLong(), it.second.toLong()) } fun findTime(buses: List<Pair<Long, Long>>): Long { return chineseRemainder(buses) } /* returns x where (a * x) % b == 1 */ fun multInv(a: Long, b: Long): Long { if (b == 1L) return 1L var aa = a var bb = b var x0 = 0L var x1 = 1L while (aa > 1) { x0 = (x1 - (aa / bb) * x0).also { x1 = x0 } bb = (aa % bb).also { aa = bb } } if (x1 < 0) x1 += b return x1 } fun chineseRemainder(buses: List<Pair<Long, Long>>): Long { val prod = buses.map { it.first }.fold(1L) { acc, i -> acc * i } var sum = 0L for (i in buses.indices) { val p = prod / buses[i].first sum += buses[i].second * multInv(p, buses[i].first) * p } return sum % prod } }
0
Kotlin
0
1
ca54c64a07755ba044440832ba4abaa7105cdd6e
1,437
advent2020
Apache License 2.0
2020/day23/day23.kt
flwyd
426,866,266
false
{"Julia": 207516, "Elixir": 120623, "Raku": 119287, "Kotlin": 89230, "Go": 37074, "Shell": 24820, "Makefile": 16393, "sed": 2310, "Jsonnet": 1104, "HTML": 398}
/* * Copyright 2021 Google LLC * * Use of this source code is governed by an MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. */ package day23 import kotlin.time.ExperimentalTime import kotlin.time.TimeSource import kotlin.time.measureTimedValue /* Input: A string of digits, representing a cycle. Current cup is the first digit. Repeat N times: 1. Remove the three cups after the current cup from the cycle. 2: Destination value is current value minus one, excluding the three cups just removed, and wrapping from min up to max. Insert the three removed cups after the destination cup. Advance the current position by one. */ /* Model this as a linked list. Standard library LinkedList class (and LinkedHashMap) doesn't make splicing easy, so implement our own node class. */ class ListNode(val value: Int) { lateinit var next: ListNode fun take(n: Int): List<ListNode> { val result = mutableListOf<ListNode>() var node = this repeat(n) { result.add(node) node = node.next } return result } override fun toString(): String { val result = mutableListOf<Int>() var node = this do { result.add(node.value) node = node.next } while (node != this) return result.joinToString(",") } } /* CupCycle is a linked list that also provides a by-value node index and knows how to play a round of the cup game. */ class CupCycle(initial: List<Int>, totalSize: Int) { // Reddit's /r/adventofcode commenters pointed out that a mapping from int to next int is // sufficient; we don't need both a map and a circular linked list. private val nodeIndex = mutableMapOf<Int, ListNode>() private val min = initial.minOrNull()!! private val max = totalSize + min - 1 var cur = ListNode(initial.first()) init { nodeIndex[cur.value] = cur var prev = cur for (i in initial.drop(1) + (initial.maxOrNull()!! + 1..max)) { val node = ListNode(i) prev.next = node nodeIndex[i] = node prev = node } prev.next = cur } fun playRound() { val slice = cur.next.take(3) val sliceVals = slice.map(ListNode::value) cur.next = slice.last().next var destVal = cur.value do { destVal = if (destVal <= min) max else destVal - 1 } while (destVal in sliceVals) val dest = nodeIndex.getValue(destVal) slice.last().next = dest.next dest.next = slice.first() cur = cur.next } } /* Play 100 rounds, print the numbers in the cycle between "one after 1" and "one before 1". */ object Part1 { fun solve(input: Sequence<String>): String { return input.map { line -> val list = line.toCharArray().map(Char::toString).map(String::toInt) val cups = CupCycle(list, list.size) repeat(100) { cups.playRound() } var node = cups.cur while (node.value != 1) { node = node.next } node.next.take(list.size - 1).map(ListNode::value).joinToString("") }.joinToString("\n") } } /* Extend the list to contain one million cups and play ten million rounds. Output: product of the two values following 1. */ object Part2 { fun solve(input: Sequence<String>): String { return input.map { line -> val list = line.toCharArray().map(Char::toString).map(String::toInt) val cups = CupCycle(list, 1_000_000) repeat(10_000_000) { cups.playRound() } var node = cups.cur while (node.value != 1) { node = node.next } node.next.value.toLong() * node.next.next.value.toLong() }.joinToString("\n") } } @ExperimentalTime @Suppress("UNUSED_PARAMETER") fun main(args: Array<String>) { val lines = generateSequence(::readLine).toList() print("part1: ") TimeSource.Monotonic.measureTimedValue { Part1.solve(lines.asSequence()) }.let { println(it.value) System.err.println("Completed in ${it.duration}") } print("part2: ") TimeSource.Monotonic.measureTimedValue { Part2.solve(lines.asSequence()) }.let { println(it.value) System.err.println("Completed in ${it.duration}") } }
0
Julia
1
5
f2d6dbb67d41f8f2898dbbc6a98477d05473888f
4,092
adventofcode
MIT License
src/chapter1/section2/ex18_VarianceForAccumulator.kt
w1374720640
265,536,015
false
{"Kotlin": 1373556}
package chapter1.section2 import edu.princeton.cs.algs4.Accumulator import extensions.inputPrompt import extensions.readAllDoubles import kotlin.math.sqrt /** * 累加器的方差 * 以下代码为Accumulator类添加了var()和stddev()方法,它们计算了addDataValue()方法的参数的方差和标准差,验证这段代码。 * 与直接对所有数据的平方求和的方法相比较,这种实现能够更好的避免四舍五入产生的误差。 * * 解:标准差计算公式简化过程参考 https://zh.wikipedia.org/wiki/%E6%A8%99%E6%BA%96%E5%B7%AE * 书中的简化公式没看懂,参考edu.princeton.cs.algs4.Accumulator类 */ class CustomAccumulator { var count = 0 //平均值 var mean = 0.0 //所有样本的平方和 var sumOfSquare = 0.0 //添加数据 fun add(value: Double) { count++ mean += (value - mean) / count sumOfSquare += value * value } /** * 获取样本方差 * 如果是获取总体方差,需要把除数count-1改为count */ fun getVariance(): Double { return (sumOfSquare - count * mean * mean) / (count - 1) } //获取样本标准差 fun getStandardDeviation(): Double { return sqrt(getVariance()) } } fun main() { inputPrompt() //对比自己实现的计算标准差方法和书中实现的标准差计算方法返回值是否相同 val customAccumulator = CustomAccumulator() val accumulator = Accumulator() val array = readAllDoubles() array.forEach { customAccumulator.add(it) accumulator.addDataValue(it) } println(customAccumulator.count) println(accumulator.count()) println(customAccumulator.mean) println(accumulator.mean()) println(customAccumulator.getStandardDeviation()) println(accumulator.stddev()) }
0
Kotlin
1
6
879885b82ef51d58efe578c9391f04bc54c2531d
1,859
Algorithms-4th-Edition-in-Kotlin
MIT License
src/main/kotlin/puzzle2/SubCommand.kt
tpoujol
436,532,129
false
{"Kotlin": 47470}
package puzzle2 fun main() { println("Hello World!") val subCommand = SubCommand() println("Result is: ${subCommand.pilotSub()}, ${subCommand.pilotSubWithAim()}") } enum class Command { forward, down, up } data class Position (val horizontal: Int, val depth: Int, val aim: Int = 0) class SubCommand { private val input: List<Pair<Command, Int>> = SubCommand::class.java.getResource("/input/puzzle2.txt") ?.readText() ?.split("\n") ?.filter { it.isNotEmpty() } ?.map { val values = it.split(" ") Pair(Command.valueOf(values[0]), values[1].toInt()) } ?: listOf() fun pilotSub(): Int { val position = input.fold(Position(0, 0)) { currentPos, pair -> when (pair.first) { Command.forward -> currentPos.copy(horizontal = currentPos.horizontal + pair.second) Command.down -> currentPos.copy(depth = currentPos.depth + pair.second) Command.up -> currentPos.copy(depth = currentPos.depth - pair.second) } } return position.horizontal * position.depth } fun pilotSubWithAim(): Int { val position = input.fold(Position(0, 0, 0)) { currentPos, pair -> when (pair.first) { Command.forward -> currentPos.copy( horizontal = currentPos.horizontal + pair.second, depth = currentPos.depth + currentPos.aim * pair.second ) Command.down -> currentPos.copy(aim = currentPos.aim + pair.second) Command.up -> currentPos.copy(aim = currentPos.aim - pair.second) } } return position.horizontal * position.depth } }
0
Kotlin
0
1
6d474b30e5204d3bd9c86b50ed657f756a638b2b
1,761
aoc-2021
Apache License 2.0
src/year2020/day01/Day01.kt
fadi426
433,496,346
false
{"Kotlin": 44622}
package year2020.day01 import util.assertTrue import util.read2020DayInput fun main() { val input = read2020DayInput("Day01").map { it.toInt() } assertTrue(task01(input) == 996075) assertTrue(task02(input) == 51810360) } private fun task01(input: List<Int>): Int { input.forEachIndexed { i, primary -> val inputWithoutIndex = input.toMutableList() inputWithoutIndex.removeAt(i) inputWithoutIndex.forEach { secondary -> if ((primary + secondary) == 2020) return primary * secondary } } throw Exception("No combinations could be found") } private fun task02(input: List<Int>): Int { input.forEachIndexed { i, primary -> val secondaryInput = input.toMutableList() secondaryInput.removeAt(i) secondaryInput.forEachIndexed { i2, secondary -> val tertiaryInput = secondaryInput.toMutableList() tertiaryInput.removeAt(i2) tertiaryInput.forEach { tertiary -> if ((primary + secondary + tertiary) == 2020) return primary * secondary * tertiary } } } throw Exception("No combinations could be found") }
0
Kotlin
0
0
acf8b6db03edd5ff72ee8cbde0372113824833b6
1,174
advent-of-code-kotlin-template
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/BitwiseComplement.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.ln /** * 1009. Complement of Base 10 Integer * @see <a href="https://leetcode.com/problems/complement-of-base-10-integer/">Source</a> */ fun interface BitwiseComplement { operator fun invoke(n: Int): Int } /** * Approach 1: Flip Bit by Bit * Time Complexity: O(1), since we're doing not more than 32 iterations here. * Space Complexity: O(1). */ class BitwiseComplementFlipBit : BitwiseComplement { override operator fun invoke(n: Int): Int { if (n == 0) return 1 var todo = n var bit = 1 var c = n while (todo != 0) { c = c xor bit bit = bit shl 1 todo = todo shr 1 } return c } } /** * Approach 2: Compute Bit Length and Construct 1-bits Bitmask * Time Complexity: O(1). * Space Complexity: O(1). */ class BitwiseComplementBitmask : BitwiseComplement { override operator fun invoke(n: Int): Int { if (n == 0) return 1 val l = ln(n.toDouble()).div(ln(2.0)).plus(1).toInt() val bitmask = 1.shl(l).minus(1) return bitmask xor n } } /** * Approach 3: Built-in Functions to Construct 1-bits Bitmask * Time Complexity: O(1), since we're doing not more than 32 iterations here. * Space Complexity: O(1). */ class BitwiseComplementBuiltInFunc : BitwiseComplement { override operator fun invoke(n: Int): Int { return if (n == 0) 1 else Integer.highestOneBit(n).shl(1).minus(n).minus(1) } } /** * Approach 4: highestOneBit OpenJDK algorithm from Hacker's Delight * Time Complexity: O(1). * Space Complexity: O(1). */ class HighestOneBit : BitwiseComplement { override operator fun invoke(n: Int): Int { if (n == 0) return 1 var bitmask: Int = n bitmask = bitmask or bitmask.shr(BIT_COUNT_POW) bitmask = bitmask or bitmask.shr(BIT_COUNT_POW_1) bitmask = bitmask or bitmask.shr(BIT_COUNT_POW_2) bitmask = bitmask or bitmask.shr(BIT_COUNT_POW_3) bitmask = bitmask or bitmask.shr(BIT_COUNT_POW_4) // flip all bits return bitmask xor n } companion object { private const val BIT_COUNT_POW = 1 private const val BIT_COUNT_POW_1 = 2 private const val BIT_COUNT_POW_2 = 4 private const val BIT_COUNT_POW_3 = 8 private const val BIT_COUNT_POW_4 = 16 } } class BitwiseComplementBruteForce : BitwiseComplement { override operator fun invoke(n: Int): Int { var x = 1 while (n > x) x = x * 2 + 1 return x - n } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
3,199
kotlab
Apache License 2.0
src/main/kotlin/g0901_1000/s0966_vowel_spellchecker/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g0901_1000.s0966_vowel_spellchecker // #Medium #Array #String #Hash_Table #2023_05_05_Time_371_ms_(100.00%)_Space_77.8_MB_(50.00%) class Solution { private var matched: HashSet<String>? = null private var capitalizations: HashMap<String, String>? = null private var vowelErrors: HashMap<String, String>? = null private fun isVowel(w: Char): Boolean { return w == 'a' || w == 'e' || w == 'i' || w == 'o' || w == 'u' } private fun removeVowels(word: String): String { val s = StringBuilder() for (w in word.toCharArray()) { s.append(if (isVowel(w)) '*' else w) } return s.toString() } private fun solveQuery(query: String): String? { if (matched!!.contains(query)) { return query } var word = query.lowercase() if (capitalizations!!.containsKey(word)) { return capitalizations!![word] } word = removeVowels(word) return if (vowelErrors!!.containsKey(word)) { vowelErrors!![word] } else "" } fun spellchecker(wordlist: Array<String>, queries: Array<String>): Array<String?> { val answer = arrayOfNulls<String>(queries.size) matched = HashSet() capitalizations = HashMap() vowelErrors = HashMap() for (word in wordlist) { matched!!.add(word) var s = word.lowercase() capitalizations!!.putIfAbsent(s, word) s = removeVowels(s) vowelErrors!!.putIfAbsent(s, word) } for (i in queries.indices) { answer[i] = solveQuery(queries[i]) } return answer } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,696
LeetCode-in-Kotlin
MIT License
src/main/kotlin/me/consuegra/algorithms/KMultiplyIntArray.kt
aconsuegra
91,884,046
false
{"Java": 113554, "Kotlin": 79568}
package me.consuegra.algorithms /** * Given an array of integers, return an array in which each position is the result of multiplying all other entries * in the array * <p> * Examples: * [1,2,3,4] -> [24,12,8,6] * [6,-4,0,5] -> [0,0,-120,0] */ class KMultiplyIntArray { fun multiplyIntArrayOption1(input: IntArray) : IntArray { val result = IntArray(input.size) for (i in 0 until input.size) { var product = 1 (0 until input.size) .filter { i != it } .forEach { product *= input[it] } result[i] = product } return result } fun multiplyIntArrayOption2(input: IntArray) : IntArray { val result = IntArray(input.size) var leftProduct = 1 for (i in 0 until input.size) { result[i] = leftProduct leftProduct *= input[i] } var rightProduct = 1 for (i in input.size - 1 downTo 0) { result[i] *= rightProduct rightProduct *= input[i] } return result } }
0
Java
0
7
7be2cbb64fe52c9990b209cae21859e54f16171b
1,096
algorithms-playground
MIT License
app/src/main/java/com/itscoder/ljuns/practise/algorithm/ShellSort.kt
ljuns
148,606,057
false
{"Java": 26841, "Kotlin": 25458}
package com.itscoder.ljuns.practise.algorithm /** * Created by ljuns at 2019/1/9. * I am just a developer. * 希尔排序 */ fun main(args: Array<String>) { val arr = intArrayOf(3, 1, 1, 6, 2, 4, 19) shellSort(arr) arr.forEach { println(it) } } /** * 3, 1, 1, 6, 2, 4, 19 * 1、gap = arr.size / 2,即分成 gap 组(偶数个元素是 gap 组,奇数个元素是 gap+1 组) * 2、每一组进行插入排序,插入排序就是后一个和前一个比较,后一个小就进入步骤 3 * 3、交换位置,交换位置后还需重新和前面的比较,因为交换位置后有可能比前面的还小 * 4、每次都是 gap /= 2 * 5、重复 1~4 */ fun shellSort(arr: IntArray) { var gap = arr.size / 2 // for(int gap = arr.size / 2; gap > 0; gap /= 2) for (i in (arr.size / 2) downTo 0 step gap) { for (i in (gap until arr.size).withIndex()) { var j = i.value while (j >= gap && arr[j] < arr[j - gap]) { // 交换位置 val temp = arr[j] arr[j] = arr[j - gap] arr[j - gap] = temp j -= gap } } // 每次都是 gap/2,叫做希尔增量 gap /= 2 } /*((arr.size / 2) downTo 0 step gap).forEach { item -> (gap until arr.size).forEachIndexed { key, index -> var j = index while (j >= gap && arr[j] < arr[j - gap]) { // 交换位置 val temp = arr[j] arr[j] = arr[j - gap] arr[j - gap] = temp j -= gap } } gap /= 2 }*/ }
0
Java
0
0
365062b38a7ac55468b202ebeff1b760663fc676
1,679
Practise
Apache License 2.0
src/main/kotlin/day04/day04.kt
andrew-suprun
725,670,189
false
{"Kotlin": 18354, "Python": 17857, "Dart": 8224}
package day04 import java.io.File fun main() { Part1("input.data").run() Part2("input.data").run() } data class Card(val matchingNumbers: Int, var copies: Int = 1) abstract class Day04(val fileName: String) { val cards = parseInput() fun run() { var result = 0 for ((idx, card) in cards.withIndex()) { for (idx2 in idx + 1..idx + card.matchingNumbers) { cards[idx2].copies += card.copies } result += score(card) } println(result) } abstract fun score(card: Card): Int private fun parseInput(): List<Card> { val cards = mutableListOf<Card>() for (line in File(fileName).readLines()) { val parts = line.split(": ", " | ") cards += Card(matchingNumbers = parseNumbers(parts[1]).intersect(parseNumbers(parts[2])).size) } return cards } private fun parseNumbers(numbers: String) = numbers.trim().split(Regex(" +")).toSet() } class Part1(fileName: String) : Day04(fileName) { override fun score(card: Card): Int { if (card.matchingNumbers == 0) return 0 var result = 1 repeat(card.matchingNumbers - 1) { result *= 2 } return result } } class Part2(fileName: String) : Day04(fileName) { override fun score(card: Card): Int = card.copies } // Part1: 25004 // Part2: 14427616
0
Kotlin
0
0
dd5f53e74e59ab0cab71ce7c53975695518cdbde
1,402
AoC-2023
The Unlicense
src/main/kotlin/days/Day9.kt
sicruse
315,469,617
false
null
package days class Day9 : Day(9) { private val codes: List<Long> by lazy { inputList.map { code -> code.toLong() } } private val codeAccumulation: List<Long> by lazy { var acc = 0L codes.map { code -> val result = code + acc acc += code result } } private val codeAccumulationSet: Set<Long> by lazy { codeAccumulation.toSet() } fun findWeakness(seedSize: Int): Long? { val data = codes.subList(seedSize, codes.size) val result = data.withIndex().find { (index, code) -> val preamble = codes.subList(index, index + seedSize).toSet() val found = preamble.find { seed -> val otherSeeds = preamble - seed val targetSeed = code - seed val found = otherSeeds.contains(targetSeed) found } found == null } return result?.value } fun findExploit(target: Long): Long? { var acc = codeAccumulation[0] var start = 1 for (code in codes.drop(1)) { acc += code start++ if ( codeAccumulationSet.contains(target + acc) ) break } val end = codeAccumulation.indexOf(target + acc) val contiguousRange = codes.subList(start, end + 1) val smallest = contiguousRange.minOrNull() val largest = contiguousRange.maxOrNull() return smallest?.plus(largest ?: 0) } @Throws override fun partOne(): Any { return findWeakness(25)!! } override fun partTwo(): Any { val target = findWeakness(25)!! return findExploit(target)!! } }
0
Kotlin
0
0
9a07af4879a6eca534c5dd7eb9fc60b71bfa2f0f
1,720
aoc-kotlin-2020
Creative Commons Zero v1.0 Universal
nebulosa-nova/src/main/kotlin/nebulosa/nova/almanac/Search.kt
tiagohm
568,578,345
false
{"Kotlin": 2031289, "TypeScript": 322187, "HTML": 164617, "SCSS": 10191, "Python": 2817, "JavaScript": 1119}
package nebulosa.nova.almanac import nebulosa.constants.DAYSEC /** * Returns evenly spaced numbers over a specified interval. */ fun evenlySpacedNumbers( start: Double, end: Double, n: Int, endpoint: Boolean = true, ): DoubleArray { val div = if (endpoint) n - 1 else n val res = DoubleArray(n) val step = (end - start) / div var c = start repeat(res.size) { res[it] = c c += step } if (endpoint) { res[res.size - 1] = end } return res } /** * Iterate evenly spaced numbers over a specified interval. */ inline fun evenlySpacedNumbers( start: Double, end: Double, n: Int, endpoint: Boolean = true, action: (Double) -> Unit, ) { val div = if (endpoint) n - 1 else n val step = (end - start) / div var c = start repeat(n) { action(c) c += step } if (endpoint) { action(end) } } /** * Computes the n-th discrete difference along the list and * returns indices that are non-zero. */ private fun IntArray.computeDiffAndReduceToIndices(): IntArray { val res = ArrayList<Int>(size - 1) for (i in 0 until size - 1) { val diff = this[i + 1] - this[i] if (diff != 0) res.add(i) } return IntArray(res.size) { res[it] } } /** * Find the times at which a discrete function of time changes value. * * This method is used to find instantaneous events like sunrise, * transits, and the seasons. */ fun findDiscrete( start: Double, end: Double, action: DiscreteFunction, epsilon: Double = 0.001 / DAYSEC, ): Pair<DoubleArray, IntArray> { val num = 8 require(start < end) { "your start time $start is later than your end time $end" } var times = evenlySpacedNumbers(start, end, ((end - start) / action.stepSize).toInt() + 2) while (true) { val y = IntArray(times.size) { action.compute(times[it]) } val indices = y.computeDiffAndReduceToIndices() if (indices.isEmpty()) return DoubleArray(0) to IntArray(0) val starts = DoubleArray(indices.size) { times[indices[it]] } val ends = DoubleArray(indices.size) { times[indices[it] + 1] } if (ends[0] - starts[0] > epsilon) { val size = indices.size * num if (size != times.size) times = DoubleArray(size) for (i in indices.indices) evenlySpacedNumbers(starts[i], ends[i], num).copyInto(times, i * num) } else { return ends to IntArray(indices.size) { y[indices[it] + 1] } } } }
0
Kotlin
0
1
de96a26e1a79c5b6f604d9af85311223cc28f264
2,543
nebulosa
MIT License
app/src/main/java/com/betulnecanli/kotlindatastructuresalgorithms/CodingPatterns/TopologicalSort.kt
betulnecanli
568,477,911
false
{"Kotlin": 167849}
/* Use this technique to find a linear ordering of elements that have dependencies on each other. */ //1. Tasks Scheduling import java.util.* fun canFinish(numCourses: Int, prerequisites: Array<IntArray>): Boolean { // Create an adjacency list to represent the directed graph val graph = Array(numCourses) { mutableListOf<Int>() } val inDegrees = IntArray(numCourses) // Populate the adjacency list and in-degrees array for (edge in prerequisites) { graph[edge[1]].add(edge[0]) inDegrees[edge[0]]++ } // Perform topological sorting using a queue val queue: Queue<Int> = LinkedList() for (i in 0 until numCourses) { if (inDegrees[i] == 0) { queue.offer(i) } } while (queue.isNotEmpty()) { val node = queue.poll() for (neighbor in graph[node]) { inDegrees[neighbor]-- if (inDegrees[neighbor] == 0) { queue.offer(neighbor) } } } // If there is any node left with in-degree greater than 0, it means there is a cycle for (inDegree in inDegrees) { if (inDegree > 0) { return false } } return true } fun main() { // Example usage val numCourses = 4 val prerequisites = arrayOf(intArrayOf(1, 0), intArrayOf(2, 1), intArrayOf(3, 2)) val result = canFinish(numCourses, prerequisites) println("Can finish tasks: $result") } //2. Alien Dictionary import java.util.* fun alienOrder(words: Array<String>): String { val graph = mutableMapOf<Char, MutableList<Char>>() val inDegrees = mutableMapOf<Char, Int>() // Initialize the graph and in-degrees for (word in words) { for (char in word) { graph[char] = mutableListOf() inDegrees[char] = 0 } } // Build the graph and in-degrees based on adjacent words for (i in 1 until words.size) { val word1 = words[i - 1] val word2 = words[i] val minLength = minOf(word1.length, word2.length) for (j in 0 until minLength) { val char1 = word1[j] val char2 = word2[j] if (char1 != char2) { graph[char1]?.add(char2) inDegrees[char2] = inDegrees.getOrDefault(char2, 0) + 1 break } } } // Perform topological sorting using a queue val result = StringBuilder() val queue: Queue<Char> = LinkedList() for (char in inDegrees.keys) { if (inDegrees[char] == 0) { queue.offer(char) } } while (queue.isNotEmpty()) { val current = queue.poll() result.append(current) for (neighbor in graph[current] ?: emptyList()) { inDegrees[neighbor] = inDegrees[neighbor]!! - 1 if (inDegrees[neighbor] == 0) { queue.offer(neighbor) } } } // Check for cycle (if not all characters are visited) return if (result.length == inDegrees.size) result.toString() else "" } fun main() { // Example usage val words = arrayOf("wrt", "wrf", "er", "ett", "rftt") val result = alienOrder(words) println("Alien Dictionary Order: $result") } /* Tasks Scheduling: The canFinish function determines whether it is possible to finish all tasks given the prerequisites. It uses topological sorting to check for cycles in a directed graph. Alien Dictionary: The alienOrder function determines the lexicographically smallest order of characters in an alien language based on a given list of words. It uses topological sorting to find the order of characters. */
2
Kotlin
2
40
70a4a311f0c57928a32d7b4d795f98db3bdbeb02
3,668
Kotlin-Data-Structures-Algorithms
Apache License 2.0
kotlin/src/Day05.kt
ekureina
433,709,362
false
{"Kotlin": 65477, "C": 12591, "Rust": 7560, "Makefile": 386}
import java.lang.Integer.parseInt import kotlin.math.abs enum class LineOrientation { VERTICAL, HORIZONTAL, DIAGONAL; } fun main() { data class Point(val x: Int, val y: Int) data class Line(val start: Point, val end: Point) { fun generateDiagonalPoints(start: Point, end: Point): List<Point> { val xSequence = if (start.x > end.x) { start.x downTo end.x } else { start.x..end.x } val ySequence = if (start.y > end.y) { start.y downTo end.y } else { start.y..end.y } return xSequence.zip(ySequence).map { (x, y) -> Point(x, y) } } fun orientation(): LineOrientation { return if (start.x == end.x) { LineOrientation.VERTICAL } else if (start.y == end.y) { LineOrientation.HORIZONTAL } else { LineOrientation.DIAGONAL } } fun slope(): Int { return (end.y - start.y)/(end.x - start.x) } fun minX(): Int = minOf(start.x, end.x) fun minY(): Int = minOf(start.y, end.y) fun maxX(): Int = maxOf(start.x, end.x) fun maxY(): Int = maxOf(start.y, end.y) private fun horizontalVerticalIntersect(horizontalLine: Line, verticalLine: Line): List<Point> { return if (verticalLine.start.x in (horizontalLine.minX()..horizontalLine.maxX()) && horizontalLine.start.y in (verticalLine.minY()..verticalLine.maxY())) { listOf(Point(verticalLine.start.x, horizontalLine.start.y)) } else { listOf() } } private fun verticalVerticalIntersect(verticalLine1: Line, verticalLine2: Line): List<Point> { return if (verticalLine1.start.x == verticalLine2.start.x) { val minIntersect = maxOf(verticalLine1.minY(), verticalLine2.minY()) val maxIntersect = minOf(verticalLine1.maxY(), verticalLine2.maxY()) (minIntersect..maxIntersect).map { y -> Point(verticalLine1.start.x, y) } } else { listOf() } } private fun horizontalHorizontalIntersect(horizontalLine1: Line, horizontalLine2: Line): List<Point> { return if (horizontalLine1.start.y == horizontalLine2.start.y) { val minIntersect = maxOf(horizontalLine1.minX(), horizontalLine2.minX()) val maxIntersect = minOf(horizontalLine1.maxX(), horizontalLine2.maxX()) (minIntersect..maxIntersect).map { x -> Point(x, horizontalLine1.start.y) } } else { listOf() } } private fun diagonalDiagonalIntersect(diagonalLine1: Line, diagonalLine2: Line): List<Point> { return if ((diagonalLine1.slope() > 0) xor (diagonalLine2.slope() > 0)) { if (diagonalLine1.start == diagonalLine2.start || diagonalLine1.start == diagonalLine2.end) { listOf(diagonalLine1.start) } else if (diagonalLine1.end == diagonalLine2.start || diagonalLine1.end == diagonalLine2.start) { listOf(diagonalLine1.end) } else { generateDiagonalPoints(diagonalLine1.start, diagonalLine1.end) .intersect(generateDiagonalPoints(diagonalLine2.start, diagonalLine2.end).toSet()).toList() } } else { // Same slope direction, can only intersect if they would be part of the same line. val calculatedDy = diagonalLine1.slope() * (diagonalLine1.end.x - diagonalLine2.end.x) if (calculatedDy == diagonalLine1.end.y - diagonalLine2.end.y) { generateDiagonalPoints(diagonalLine1.start, diagonalLine1.end) .intersect(generateDiagonalPoints(diagonalLine2.start, diagonalLine2.end).toSet()) .toList() } else { listOf() } } } private fun diagonalVerticalIntersect(diagonalLine: Line, verticalLine: Line): List<Point> { return if (verticalLine.start.x in (diagonalLine.minX()..diagonalLine.maxX())) { val potentialPoint = if (diagonalLine.slope() > 0) { Point(verticalLine.start.x, (verticalLine.start.x - diagonalLine.minX()) + diagonalLine.minY()) } else { Point(verticalLine.start.x, diagonalLine.maxY() - (verticalLine.start.x - diagonalLine.minX())) } if (potentialPoint.y in (verticalLine.minY()..verticalLine.maxY())) { listOf(potentialPoint) } else { listOf() } } else { listOf() } } private fun diagonalHorizontalIntersect(diagonalLine: Line, horizontalLine: Line): List<Point> { return if (horizontalLine.start.y in (diagonalLine.minY()..diagonalLine.maxY())) { val potentialPoint = if (diagonalLine.slope() > 0) { Point( (horizontalLine.start.y - diagonalLine.minY()) + diagonalLine.minX(), horizontalLine.start.y ) } else { Point( (diagonalLine.maxY() - horizontalLine.start.y) + diagonalLine.minX(), horizontalLine.start.y ) } if (potentialPoint.x in (horizontalLine.minX()..horizontalLine.maxX())) { listOf(potentialPoint) } else { listOf() } } else { listOf() } } fun intersection(other: Line): List<Point> { return when (orientation()) { LineOrientation.VERTICAL -> { when (other.orientation()) { LineOrientation.VERTICAL -> { verticalVerticalIntersect(this, other) } LineOrientation.HORIZONTAL -> { horizontalVerticalIntersect(other, this) } LineOrientation.DIAGONAL -> { diagonalVerticalIntersect(other, this) } } } LineOrientation.HORIZONTAL -> { when (other.orientation()) { LineOrientation.VERTICAL -> { horizontalVerticalIntersect(this, other) } LineOrientation.HORIZONTAL -> { horizontalHorizontalIntersect(this, other) } LineOrientation.DIAGONAL -> { diagonalHorizontalIntersect(other, this) } } } LineOrientation.DIAGONAL -> { when (other.orientation()) { LineOrientation.VERTICAL -> { diagonalVerticalIntersect(this, other) } LineOrientation.HORIZONTAL -> { diagonalHorizontalIntersect(this, other) } LineOrientation.DIAGONAL -> { diagonalDiagonalIntersect(this, other) } } } } } } fun part1(input: List<String>): Int { val straightLines = input.map { line -> val lineList = line.split(" -> ").take(2).map { point -> val pointList = point.split(",").take(2).map(::parseInt) Point(pointList[0], pointList[1]) } Line(lineList[0], lineList[1]) }.filterNot { it.orientation() == LineOrientation.DIAGONAL } return straightLines.asSequence().map { line -> straightLines.dropWhile { otherLine -> otherLine != line }.drop(1).map(line::intersection) }.flatten().flatten().distinct().count() } fun part2(input: List<String>): Int { val lines = input.map { line -> val lineList = line.split(" -> ").take(2).map { point -> val pointList = point.split(",").take(2).map(::parseInt) Point(pointList[0], pointList[1]) } Line(lineList[0], lineList[1]) } val dimensionality = lines.fold(Point(0,0)) { dimension, line -> Point(maxOf(dimension.x, line.maxX()), maxOf(dimension.y, line.maxY())) }.let { point -> Point(point.x + 1, point.y + 1) } return lines.asSequence().map { line -> lines.dropWhile { otherLine -> otherLine != line }.drop(1).map(line::intersection) }.flatten().flatten().distinct().count() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day05_test") check(part1(testInput) == 5) { "${part1(testInput)}" } val part2Res = part2(testInput) check(part2Res == 12) { "$part2Res" } val input = readInput("Day05") println(part1(input)) println(part2(input)) }
0
Kotlin
0
1
391d0017ba9c2494092d27d22d5fd9f73d0c8ded
9,561
aoc-2021
MIT License
src/main/kotlin/me/peckb/aoc/_2021/calendar/day05/Day05.kt
peckb1
433,943,215
false
{"Kotlin": 956135}
package me.peckb.aoc._2021.calendar.day05 import me.peckb.aoc.generators.InputGenerator.InputGeneratorFactory import javax.inject.Inject import kotlin.ranges.IntProgression.Companion.fromClosedRange data class Point(val x : Int, val y: Int) typealias Line = Pair<Point, Point> typealias Map = Array<Array<Int>> class Day05 @Inject constructor(private val generatorFactory: InputGeneratorFactory) { companion object { private const val MAP_SIZE = 1000 private fun createEmptyMap() = (0 until MAP_SIZE).map { Array(MAP_SIZE) { 0 } }.toTypedArray() } fun nonDiagonalOverlapCount(fileName: String) = generatorFactory.forFile(fileName).readAs(::line) { input -> val map = createEmptyMap() input.filter { it.isVerticalOrHorizontal() } .forEach { line -> adjustAreaWithNonDiagonal(map, line) } map.overlap() } fun fullOverlapCount(fileName: String) = generatorFactory.forFile(fileName).readAs(::line) { input -> val map = createEmptyMap() input.forEach { line -> if (line.isVerticalOrHorizontal()) { adjustAreaWithNonDiagonal(map, line) } else { adjustAreaWithDiagonal(map, line) } } map.overlap() } private fun adjustAreaWithNonDiagonal(area: Map, line: Pair<Point, Point>) { val sortedX = line.sortedX() val sortedY = line.sortedY() sortedX.forEach { x -> sortedY.forEach { y -> area[y][x]++ } } } private fun adjustAreaWithDiagonal(area: Map, line: Line) { val xStep = line.second.x.compareTo(line.first.x) val xProgression = fromClosedRange(line.first.x, line.second.x, xStep) val yStep = line.second.y.compareTo(line.first.y) val yProgression = fromClosedRange(line.first.y, line.second.y, yStep) xProgression.zip(yProgression).forEach { (x, y) -> area[y][x]++ } } private fun line(line: String): Line = line.split("->").let { coordinates -> val points = coordinates.flatMap { coordinateString -> coordinateString.trim() .split(",") .map { it.toInt() } .zipWithNext { x, y -> Point(x, y) } } points.first() to points.last() } private fun Line.isVerticalOrHorizontal() = first.x == second.x || first.y == second.y private fun Line.sortedX() = listOf(first.x, second.x).sorted().let { it.first() .. it.last() } private fun Line.sortedY() = listOf(first.y, second.y).sorted().let { it.first() .. it.last() } private fun Map.overlap() = sumOf { row -> row.count { it >= 2 } } }
0
Kotlin
1
3
2625719b657eb22c83af95abfb25eb275dbfee6a
2,508
advent-of-code
MIT License
src/main/kotlin/net/mguenther/adventofcode/day2/Day2.kt
mguenther
115,937,032
false
null
package net.mguenther.adventofcode.day2 import java.io.File /** * See http://adventofcode.com/2017/day/2 * * @author <NAME> (<EMAIL>) */ fun minmax(columns: List<String>): Pair<Int, Int> { val numbers = columns.map { it.toInt() } return Pair(numbers.min() ?: 0, numbers.max() ?: 0) } fun diff(minmax: Pair<Int, Int>): Int { return minmax.second - minmax.first } fun evenlyDivides(columns: List<String>): Int { var result: Int = 0 val numbers = columns.map { it.toInt() } for (i in 0 until numbers.size) { for (j in 0 until numbers.size) { if (i == j) continue val l = numbers.get(i) val r = numbers.get(j) if (l.rem(r) == 0) { result = l / r // there is only one such pair per row break } } } return result } fun main(args: Array<String>) { val rows = mutableListOf<String>() File("src/day2.input").useLines { lines -> lines.forEach { rows.add(it) }} println("Checksum is: " + rows .stream() .map { row -> minmax(row.split(" ")) } .map { minmax -> diff(minmax) } .reduce { t: Int, u: Int -> t + u }) println("Checksum is: " + rows .stream() .map { row -> evenlyDivides(row.split(" ")) } .reduce { t: Int, u: Int -> t + u }) }
0
Kotlin
0
0
c2f80c7edc81a4927b0537ca6b6a156cabb905ba
1,417
advent-of-code-2017
MIT License
src/main/kotlin/aoc2023/Day14.kt
Ceridan
725,711,266
false
{"Kotlin": 110767, "Shell": 1955}
package aoc2023 class Day14 { fun part1(input: String): Int = parseInput(input).tiltNorth() fun part2(input: String, cycles: Int): Int { val platform = parseInput(input) val loopCheckSize = 20 val cycleScores = mutableListOf<Int>() while (cycleScores.size <= cycles) { val score = platform.tiltCycle() cycleScores.add(score) val lastN = cycleScores.takeLast(loopCheckSize) val loop = cycleScores.dropLast(loopCheckSize).windowed(loopCheckSize, 1).withIndex() .firstOrNull { (_, vals) -> vals == lastN } loop?.let { val loopStart = it.index val loopSize = cycleScores.size - loopCheckSize - loopStart val finalIdx = (cycles - loopStart) % loopSize + loopStart - 1 return cycleScores[finalIdx] } } return cycleScores.last() } private fun parseInput(input: String): Platform { val lines = input.split("\n").filter { it.isNotEmpty() } val rows = lines.size val cols = lines[0].length val platform = mutableMapOf<Point, Char>() for (y in lines.indices) { for (x in lines[y].indices) { val ch = lines[y][x] if (ch != '.') platform[y to x] = ch } } return Platform(platform, rows = rows, cols = cols) } data class Platform(private val initialPlatform: Map<Point, Char>, private val rows: Int, private val cols: Int) { private var platform = initialPlatform fun tiltCycle(): Int { tiltNorth() tiltWest() tiltSouth() return tiltEast() } fun tiltNorth(): Int { val newPlatform = mutableMapOf<Point, Char>() var totalSum = 0 for (x in 0..<cols) { var hashRockIdx = -1 for (y in 0..<rows) { val ch = platform.getOrDefault(y to x, '.') if (ch == '#') { newPlatform[y to x] = ch hashRockIdx = y } else if (ch == 'O') { totalSum += rows - hashRockIdx - 1 hashRockIdx += 1 newPlatform[hashRockIdx to x] = ch } } } platform = newPlatform return totalSum } private fun tiltWest(): Int { val newPlatform = mutableMapOf<Point, Char>() var totalSum = 0 for (y in 0..<rows) { var hashRockIdx = -1 for (x in 0..<cols) { val ch = platform.getOrDefault(y to x, '.') if (ch == '#') { newPlatform[y to x] = ch hashRockIdx = x } else if (ch == 'O') { totalSum += rows - y hashRockIdx += 1 newPlatform[y to hashRockIdx] = ch } } } platform = newPlatform return totalSum } private fun tiltSouth(): Int { val newPlatform = mutableMapOf<Point, Char>() var totalSum = 0 for (x in 0..<cols) { var hashRockIdx = rows for (y in rows - 1 downTo 0) { val ch = platform.getOrDefault(y to x, '.') if (ch == '#') { newPlatform[y to x] = ch hashRockIdx = y } else if (ch == 'O') { totalSum += rows - hashRockIdx + 1 hashRockIdx -= 1 newPlatform[hashRockIdx to x] = ch } } } platform = newPlatform return totalSum } private fun tiltEast(): Int { val newPlatform = mutableMapOf<Point, Char>() var totalSum = 0 for (y in 0..<rows) { var hashRockIdx = cols for (x in cols - 1 downTo 0) { val ch = platform.getOrDefault(y to x, '.') if (ch == '#') { newPlatform[y to x] = ch hashRockIdx = x } else if (ch == 'O') { totalSum += rows - y hashRockIdx -= 1 newPlatform[y to hashRockIdx] = ch } } } platform = newPlatform return totalSum } } } fun main() { val day14 = Day14() val input = readInputAsString("day14.txt") println("14, part 1: ${day14.part1(input)}") println("14, part 2: ${day14.part2(input, cycles = 1000000000)}") }
0
Kotlin
0
0
18b97d650f4a90219bd6a81a8cf4d445d56ea9e8
4,970
advent-of-code-2023
MIT License
src/main/kotlin/Day10_1.kt
vincent-mercier
726,287,758
false
{"Kotlin": 37963}
import java.io.File import java.io.InputStream enum class Direction(val deltaY: Int, val deltaX: Int, val nextDirection: Map<Char, () -> Direction?>) { S( 0, 0, mapOf( 'S' to { S } ) ), UP( -1, 0, mapOf( '|' to { UP }, 'F' to { RIGHT }, '7' to { LEFT }, '.' to { null }, '-' to { null }, 'L' to { null }, 'J' to { null }, 'S' to { S } ) ), DOWN( 1, 0, mapOf( '|' to { DOWN }, 'J' to { LEFT }, 'L' to { RIGHT }, '.' to { null }, '-' to { null }, '7' to { null }, 'F' to { null }, 'S' to { S } ) ), LEFT( 0, -1, mapOf( '-' to { LEFT }, 'L' to { UP }, 'F' to { DOWN }, '.' to { null }, '|' to { null }, '7' to { null }, 'J' to { null }, 'S' to { S } ) ), RIGHT( 0, 1, mapOf( '-' to { RIGHT }, 'J' to { UP }, '7' to { DOWN }, '.' to { null }, '|' to { null }, 'L' to { null }, 'F' to { null }, 'S' to { S } ) ) } data class Point(val y: Int, val x: Int) { fun moveIn(direction: Direction, matrix: List<String>): Pair<Point, Direction?> { val newPoint = Point( y + direction.deltaY, x + direction.deltaX ) return newPoint to direction.nextDirection[matrix[newPoint.y][newPoint.x]]?.invoke() } companion object { fun fromCoords(coords: Pair<Int, Int>): Point { return Point(coords.first, coords.second) } } } fun main() { val inputStream: InputStream = File("./src/main/resources/day10.txt").inputStream() val matrix = inputStream.bufferedReader().readLines().toMutableList() val s = Point.fromCoords( matrix.mapIndexed {lineIndex, line -> val sIndex = line.mapIndexed { charIndex, char -> if (char == 'S') { charIndex } else { null } }.firstOrNull { it != null } if (sIndex != null) { lineIndex to sIndex } else { null } }.first { it != null }!! ) var steps = 0 var currentPosition = s var nextDirection = listOf(Direction.UP, Direction.DOWN, Direction.LEFT, Direction.RIGHT) .filter { s.moveIn(it, matrix).second != null } .first() do { steps++ val next = currentPosition.moveIn(nextDirection, matrix) currentPosition = next.first nextDirection = next.second!! } while (currentPosition != s) print(steps / 2.0) }
0
Kotlin
0
0
53b5d0a0bb65a77deb5153c8a912d292c628e048
2,997
advent-of-code-2023
MIT License
src/main/kotlin/ch/uzh/ifi/seal/bencher/analysis/coverage/Coverages.kt
chrstphlbr
227,602,878
false
{"Kotlin": 918163, "Java": 29153}
package ch.uzh.ifi.seal.bencher.analysis.coverage import arrow.core.zip import ch.uzh.ifi.seal.bencher.Method import ch.uzh.ifi.seal.bencher.analysis.change.* import ch.uzh.ifi.seal.bencher.analysis.coverage.computation.* data class Coverages( val coverages: Map<Method, Coverage> ) : CoverageComputation, CoverageOverlap by CoverageOverlapImpl(coverages.values) { override fun single(of: Method, unit: CoverageUnit): CoverageUnitResult { val mcs = coverages[of] ?: return CUF.notCovered(of, unit) return mcs.single(of, unit) } override fun all(removeDuplicates: Boolean): Set<CoverageUnitResult> = coverages.flatMap { it.value.all(removeDuplicates) }.toSet() fun onlyChangedCoverages( changes: Set<Change>, methodChangeAssessment: MethodChangeAssessment = FullMethodChangeAssessment, lineChangeAssessment: LineChangeAssessment = LineChangeAssessmentImpl ): Coverages { val newCovs: Map<Method, Coverage> = coverages.mapValues { (_, cs) -> val newUnits = cs.all() .filter { cur -> when (val u = cur.unit) { is CoverageUnitMethod -> methodChangeAssessment.methodChanged(u.method, changes) is CoverageUnitLine -> lineChangeAssessment.lineChanged(u.line, changes) } } .toSet() Coverage(of = cs.of, unitResults = newUnits) } return Coverages(newCovs) } override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as Coverages return equals(this, other) } } fun Iterable<Coverages>.merge(): Coverages = this.fold(Coverages(mapOf())) { acc, cov -> merge(acc, cov) } fun merge(cov1: Coverages, cov2: Coverages): Coverages { val c1 = cov1.coverages val c2 = cov2.coverages val intersectingKeys = c1.keys.intersect(c2.keys) if (intersectingKeys.isEmpty()) { // disjoint set of benchmarks -> return the union of the map return Coverages( coverages = c1 + c2 ) } // overlapping benchmark sets val newCovs = mutableMapOf<Method, Coverage>() // bc1 benchmarks that are not in bc2 newCovs.putAll(c1.filterKeys { intersectingKeys.contains(it) }) // bc2 benchmarks that are not in bc1 newCovs.putAll(c2.filterKeys { intersectingKeys.contains(it) }) // merge of benchmarks that are in both bc1 and bc2 newCovs.putAll( intersectingKeys.map { Pair(it, c1.getValue(it).union(c2.getValue(it))) } ) return Coverages( coverages = newCovs ) } fun equals(cov1: Coverages, cov2: Coverages): Boolean { // val cov1Sorted = cov1.coverages.toSortedMap(MethodComparator) // val cov2Sorted = cov2.coverages.toSortedMap(MethodComparator) cov1.coverages.zip(cov2.coverages).forEach { (bench, covs) -> val (c1, c2) = covs if (!(c1.of == bench && c2.of == bench)) { return false } if (c1 != c2) { return false } } return true }
0
Kotlin
2
4
06601fb4dda3b2996c2ba9b2cd612e667420006f
3,235
bencher
Apache License 2.0
src/Day11.kt
WilsonSunBritten
572,338,927
false
{"Kotlin": 40606}
import java.math.BigInteger enum class OPERATION { MULTIPLY, ADD } fun main() { fun part1(input: List<String>): Long { val monkeyList = input.joinToString("\n") { it }.split("\n\n").map { monkeyDefinition: String -> val monkeyDefinitionLines = monkeyDefinition.split("\n") val startingItems = monkeyDefinitionLines[1].split(": ")[1].split(", ").map { it.toInt()}.toMutableList() val operation = monkeyDefinitionLines[2].split("new = old ")[1].split(" ").let { operationSplit -> val operationType = when(operationSplit[0]) { "*" -> OPERATION.MULTIPLY "+" -> OPERATION.ADD else -> error("unknown op") } val value = operationSplit[1].toLongOrNull() when(operationType) { OPERATION.MULTIPLY -> { x: Long -> (x * (value ?: x)) } OPERATION.ADD -> { x: Long -> (x + (value ?: x)) } } } val test = monkeyDefinitionLines[3].split("Test: divisible by ")[1].toLong().let { {x: Long -> x % it == 0L }} val trueConditionDestination = monkeyDefinitionLines[4].split("throw to monkey ")[1].toInt() val falseConditionDestination = monkeyDefinitionLines[5].split("throw to monkey ")[1].toInt() Monkey(startingItems.map { it.toLong() }.toMutableList(), operation = operation, test, trueConditionDestination, falseConditionDestination) } (0 until 20).forEach { round -> monkeyList.forEach { monkey -> while(monkey.items.isNotEmpty()) { val item = monkey.items.removeFirst() val worry = item val postOperationWorry = monkey.operation.invoke(worry) val boredWorry = postOperationWorry.div(3) if (monkey.condition.invoke(boredWorry)) { monkeyList.get(monkey.trueDestination).items.add(boredWorry) } else { monkeyList.get(monkey.falseDestination).items.add(boredWorry) } monkey.itemInspections++ } } } return monkeyList.map { it.itemInspections }.sortedDescending().take(2).fold(1L) { acc, item -> acc * item } } fun part2(input: List<String>): Long { var commonMod = 1L val monkeyList = input.joinToString("\n") { it }.split("\n\n").map { monkeyDefinition: String -> val monkeyDefinitionLines = monkeyDefinition.split("\n") val startingItems = monkeyDefinitionLines[1].split(": ")[1].split(", ").map { it.toInt()}.toMutableList() val operation = monkeyDefinitionLines[2].split("new = old ")[1].split(" ").let { operationSplit -> val operationType = when(operationSplit[0]) { "*" -> OPERATION.MULTIPLY "+" -> OPERATION.ADD else -> error("unknown op") } val value = operationSplit[1].toLongOrNull() when(operationType) { OPERATION.MULTIPLY -> { x: Long -> x * (value ?: x) } OPERATION.ADD -> { x: Long -> x + (value ?: x) } } } val testMod = monkeyDefinitionLines[3].split("Test: divisible by ")[1].toLong() commonMod = commonMod * testMod val test = testMod.let { {x: Long -> x % it == 0L }} val trueConditionDestination = monkeyDefinitionLines[4].split("throw to monkey ")[1].toInt() val falseConditionDestination = monkeyDefinitionLines[5].split("throw to monkey ")[1].toInt() Monkey(startingItems.map { it.toLong() }.toMutableList(), operation = operation, test, trueConditionDestination, falseConditionDestination) } (0 until 10000).forEach { round -> monkeyList.forEach { monkey -> while(monkey.items.isNotEmpty()) { val item = monkey.items.removeFirst() val worry = item val postOperationWorry = monkey.operation.invoke(worry) val boredWorry = postOperationWorry % commonMod if (monkey.condition.invoke(boredWorry)) { monkeyList.get(monkey.trueDestination).items.add(boredWorry) } else { monkeyList.get(monkey.falseDestination).items.add(boredWorry) } monkey.itemInspections++ } } } println("Common mod: $commonMod") monkeyList.forEach { println(it.itemInspections) println(it.items) } return monkeyList.map { it.itemInspections }.sortedDescending().take(2).fold(1L) { acc, item -> acc * item } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day11_test") val input = readInput("Day11") val p1TestResult = part1(testInput) println(p1TestResult) check(p1TestResult == 10605L) println(part1(input)) println("Part 2") val p2TestResult = part2(testInput) println(p2TestResult) check(p2TestResult == 2713310158L) println(part2(input)) } data class Monkey( val items: MutableList<Long>, val operation: (Long) -> Long, val condition: (Long) -> Boolean, val trueDestination: Int, val falseDestination: Int, var itemInspections: Long = 0 )
0
Kotlin
0
0
363252ffd64c6dbdbef7fd847518b642ec47afb8
5,788
advent-of-code-2022-kotlin
Apache License 2.0
src/main/kotlin/com/nibado/projects/advent/y2018/Day12.kt
nielsutrecht
47,550,570
false
null
package com.nibado.projects.advent.y2018 import com.nibado.projects.advent.Day import com.nibado.projects.advent.resourceLines object Day12 : Day { private val regex = "([#.]{5}) => (#|.)".toRegex() private val input = resourceLines(2018, 12) private val instructions = input.drop(2).map(::parse).toMap() private val initial = input.first().removePrefix("initial state: ") private fun parse(line: String) = regex.matchEntire(line)?.groupValues?.drop(1) ?.let { it[0] as CharSequence to it[1].first() } ?: throw IllegalArgumentException() private fun next(current: Pair<Int, String>): Pair<Int, String> { val builder = StringBuilder(current.second) val dotsStart = with(builder) { val dotsStart = 5 - (0..4).takeWhile { this[it] == '.' }.count() val dotsEnd = 5 - (1..5).takeWhile { this[this.length - it] == '.' }.count() insert(0, ".".repeat(dotsStart)) append(".".repeat(dotsEnd)) dotsStart } return dotsStart + current.first to (sequenceOf('.', '.') + (2..builder.length - 3) .asSequence() .map { instructions.getOrDefault(builder.subSequence(it - 2, it + 3), '.') }) .joinToString("") } private fun simulate(state: Pair<Int, String>, times: Int): Pair<Int, String> = (1..times).fold(state) { a, _ -> next(a) } private fun count(current: Pair<Int, String>) = current.second.mapIndexed { index, c -> index - current.first to c } .sumBy { if (it.second == '#') it.first else 0 } override fun part1() = count(simulate(0 to initial, 20)) override fun part2(): Long { val state100 = simulate(0 to initial, 100) val state200 = simulate(state100, 100) val c1 = count(state100) val d = count(state200) - c1 return (50000000000 - 100) / 100L * d + c1 } }
1
Kotlin
0
15
b4221cdd75e07b2860abf6cdc27c165b979aa1c7
1,913
adventofcode
MIT License
src/day-4/part-2/solution-day-4-part-2.kts
d3ns0n
572,960,768
false
{"Kotlin": 31665}
import java.io.File fun splitAssignemntGroups(input: String): Pair<String, String> { val split = input.split(",") return Pair(split[0], split[1]) } fun splitAssignemntGroup(assignmentGroup: String): Pair<Int, Int> { val split = assignmentGroup.split("-") return Pair(split[0].toInt(), split[1].toInt()) } fun isFullyContained(assignmentGroup: Pair<String, String>): Boolean { val firstAssignment = splitAssignemntGroup(assignmentGroup.first) val secondAssignment = splitAssignemntGroup(assignmentGroup.second) return (firstAssignment.first in secondAssignment.first..secondAssignment.second && firstAssignment.second in secondAssignment.first..secondAssignment.second) || (secondAssignment.first in firstAssignment.first..firstAssignment.second && secondAssignment.second in firstAssignment.first..firstAssignment.second) } var result = File("../input.txt").readLines() .map { splitAssignemntGroups(it) } .map { isFullyContained(it) } .count { it } println(result) assert(result == 542)
0
Kotlin
0
0
8e8851403a44af233d00a53b03cf45c72f252045
1,077
advent-of-code-22
MIT License
src/main/kotlin/com/rtarita/days/Day1.kt
RaphaelTarita
724,581,070
false
{"Kotlin": 64943}
package com.rtarita.days import com.rtarita.structure.AoCDay import com.rtarita.util.day import kotlinx.datetime.LocalDate object Day1 : AoCDay { override val day: LocalDate = day(1) private enum class Digits(val spelling: String, val value: Int) { ONE("one", 1), TWO("two", 2), THREE("three", 3), FOUR("four", 4), FIVE("five", 5), SIX("six", 6), SEVEN("seven", 7), EIGHT("eight", 8), NINE("nine", 9); companion object { fun parse(spelling: String): Digits = entries.first { it.spelling == spelling } val spellings = entries.map { it.spelling } } } private fun String.parse(): Digits = Digits.parse(this) override fun executePart1(input: String): Any { return input.lineSequence() .sumOf { line -> val digits = line.filter { it.isDigit() } .map { it.digitToInt() } digits.first() * 10 + digits.last() } } override fun executePart2(input: String): Any { return input.lineSequence() .sumOf { line -> val firstSpelling = line.findAnyOf(Digits.spellings) val lastSpelling = line.findLastAnyOf(Digits.spellings) val firstDigit = line.indexOfFirst { it.isDigit() } val lastDigit = line.indexOfLast { it.isDigit() } val first = if (firstSpelling != null && (firstDigit == -1 || firstSpelling.first < firstDigit)) { firstSpelling.second.parse().value } else { line[firstDigit].digitToInt() } val last = if (lastSpelling != null && (lastDigit == -1 || lastSpelling.first > lastDigit)) { lastSpelling.second.parse().value } else { line[lastDigit].digitToInt() } first * 10 + last } } }
0
Kotlin
0
0
4691126d970ab0d5034239949bd399c8692f3bb1
1,999
AoC-2023
Apache License 2.0
src/datastructure/heap/Heap.kt
minielectron
332,678,510
false
{"Java": 127791, "Kotlin": 48336}
package datastructure.heap class Heap { private val heap = arrayListOf<Int>() fun getHeap(): List<Int> { return heap.toList() } fun getLeftChild(index: Int): Int { return 2 * index + 1 } fun getRightChild(index: Int): Int { return 2 * index + 2 } private fun getParentIndex(index: Int): Int { return (index - 1) / 2 } fun insert(item: Int) { heap.add(item) heapifyUp() } private fun heapifyUp() { // For max heap var index = heap.size - 1 // Start at the last element while (hasParent(index) && parent(index) < heap[index]) { // While we have a parent and it's greater than the current node // Swap the current node with its parent swap(getParentIndex(index), index) // Move up the tree index = getParentIndex(index) } } private fun heapifyDown() { // for min heap var index = heap.size - 1 // Start at the last element while (hasParent(index) && parent(index) > heap[index]) { // While we have a parent and it's greater than the current node // Swap the current node with its parent swap(getParentIndex(index), index) // Move up the tree index = getParentIndex(index) } } fun remove() : Int? { if (heap.isEmpty()) return null if (heap.size == 1){ return heap.removeAt(0) } val maxValue = heap[0] heap[0] = heap.removeAt(heap.size -1) sinkDown(0) return maxValue } fun findKthSmallest(nums: IntArray, k: Int): Int? { val heap = Heap() if (nums.isEmpty()) return null if (k < 0 || k> nums.size) return null if (nums.size == 1) return heap.remove() for (i in nums.indices) { heap.insert(nums[i]) } val size = nums.size var actaulK = size - k var ans = -1 while (actaulK >= 0) { ans = heap.remove()!! actaulK-- } return ans } private fun sinkDown(index: Int) { var index = index var maxIndex = index while (true) { val leftIndex: Int = getLeftChild(index) val rightIndex: Int = getRightChild(index) if (leftIndex < heap.size && heap[leftIndex] > heap[maxIndex]) { maxIndex = leftIndex } if (rightIndex < heap.size && heap[rightIndex] > heap[maxIndex]) { maxIndex = rightIndex } index = if (maxIndex != index) { swap(index, maxIndex) maxIndex } else { return } } } private fun hasParent(index: Int) = getParentIndex(index) >= 0 private fun parent(index: Int) = heap[getParentIndex(index)] private fun swap(i: Int, j: Int) { val temp = heap[i] heap[i] = heap[j] heap[j] = temp } override fun toString(): String { return "$heap" } } fun main() { val heap = Heap() // Test case 1 // Test case 1 val nums1 = intArrayOf(7, 10, 4, 3, 20, 15) val k1 = 3 println("Test case 1:") println("Expected output: 7") System.out.println("Actual output: " + heap.findKthSmallest(nums1, k1)) println() // Test case 2 // Test case 2 val nums2 = intArrayOf(2, 1, 3, 5, 6, 4) val k2 = 2 println("Test case 2:") println("Expected output: 2") System.out.println("Actual output: " + heap.findKthSmallest(nums2, k2)) println() // Test case 3 // Test case 3 val nums3 = intArrayOf(9, 3, 2, 11, 7, 10, 4, 5) val k3 = 5 println("Test case 3:") println("Expected output: 7") System.out.println("Actual output: " + heap.findKthSmallest(nums3, k3)) println() }
0
Java
0
0
f2aaff0a995071d6e188ee19f72b78d07688a672
3,907
data-structure-and-coding-problems
Apache License 2.0
src/main/kotlin/com/nibado/projects/advent/y2018/Day17.kt
nielsutrecht
47,550,570
false
null
package com.nibado.projects.advent.y2018 import com.nibado.projects.advent.Day import com.nibado.projects.advent.Point import com.nibado.projects.advent.Rectangle import com.nibado.projects.advent.collect.CharMap import com.nibado.projects.advent.resourceRegex import java.util.* import kotlin.math.max object Day17 : Day { private val regex = "(x|y)=([0-9]+), (x|y)=([0-9]+)\\.\\.([0-9]+)".toRegex() private val input = resourceRegex(2018, 17, regex) .map { it.drop(1) } .map { (a1, v1, a2, v2a, v2b) -> Scan(a1[0], v1.toInt(), a2[0], IntRange(v2a.toInt(), v2b.toInt())) } val map : CharMap by lazy { buildMap().also { flow(it) } } private fun buildMap(): CharMap { val max = input.map { it.rect().right }.reduce { a, p -> Point(max(a.x, p.x), max(a.y, p.y)) } val map = CharMap(max.x + 1, max.y + 1, '.', '#') for (s in input) { if (s.axis1 == 'x') { map.drawVertical(s.value1, s.value2) } else { map.drawHorizontal(s.value1, s.value2) } } return map } private fun flow(map: CharMap) { val down = Point(0, 1) val consider = Stack<Point>() consider += Point(500, 0) + down while (consider.isNotEmpty()) { val cur = consider.pop() map[cur] = '|' if (!map.inBounds(cur + down)) { continue } if (map.canPlace(cur + down)) { consider += cur + down continue } else { val flow = map.flow(cur) val c = if (flow.contained) '~' else '|' flow.points.forEach { map[it] = c } if (flow.contained) { if (map.inBounds(cur.up())) { consider += cur.up() } } else { consider += flow.points.filter { map.inBounds(it.down()) && map[it.down()] == '.' } } } } } private fun CharMap.flow(p: Point): Flow { val points = mutableListOf<Point>() points += p fun scan(p: Point, dir: Point, points: MutableList<Point>) : Boolean { var cur = p while(true) { cur += dir if(!inBounds(cur)) { return false } if(get(cur) == '#') { return true } val below = cur.down() if(inBounds(below) && get(below) in setOf('#', '~')) { points += cur } else if(get(below) != '|'){ points += cur return false } else { return false } } } val wallLeft = scan(p, Point(-1, 0), points) val wallRight = scan(p, Point(1, 0), points) return Flow(points, wallLeft && wallRight) } private fun CharMap.canPlace(p: Point) = inBounds(p) && this[p] == '.' private fun CharMap.minY() = map.points { c -> c == '#' }.minByOrNull { it.y }!!.y override fun part1() = map.minY().let { minY -> map.points { it == '~' || it == '|'}.count { it.y >= minY } } override fun part2() = map.minY().let { minY -> map.points { it == '~'}.count { it.y >= minY } } data class Scan(val axis1: Char, val value1: Int, val axis2: Char, val value2: IntRange) { fun rect() = if (axis1 == 'x') { Rectangle(Point(value1, value2.start), Point(value1, value2.endInclusive)) } else { Rectangle(Point(value2.start, value1), Point(value2.endInclusive, value1)) } } data class Flow(val points: List<Point>, val contained: Boolean) }
1
Kotlin
0
15
b4221cdd75e07b2860abf6cdc27c165b979aa1c7
3,878
adventofcode
MIT License
src/main/kotlin/Problem3.kt
jimmymorales
496,703,114
false
{"Kotlin": 67323}
import kotlin.math.sqrt /** * Largest prime factor * * The prime factors of 13195 are 5, 7, 13 and 29. * What is the largest prime factor of the number 600851475143 ? * * https://projecteuler.net/problem=3 */ fun main() { println(solution3(600851475143L)) } private fun solution3(n: Long): Long { var num = n var lastFactor = if (n % 2 == 0L) { num /= 2 while (num % 2 == 0L) { num /= 2 } 2L } else { 1L } var factor = 3L var maxFactor = sqrt(num.toDouble()).toLong() while (num > 1 && factor <= maxFactor) { if (num % factor == 0L) { num /= factor lastFactor = factor while (num % factor == 0L) { num /= factor } maxFactor = sqrt(num.toDouble()).toLong() } factor += 2 } return if (num == 1L) lastFactor else num }
0
Kotlin
0
0
e881cadf85377374e544af0a75cb073c6b496998
919
project-euler
MIT License
kotlinLeetCode/src/main/kotlin/leetcode/editor/cn/[45]跳跃游戏 II.kt
maoqitian
175,940,000
false
{"Kotlin": 354268, "Java": 297740, "C++": 634}
//给定一个非负整数数组,你最初位于数组的第一个位置。 // // 数组中的每个元素代表你在该位置可以跳跃的最大长度。 // // 你的目标是使用最少的跳跃次数到达数组的最后一个位置。 // // 假设你总是可以到达数组的最后一个位置。 // // // // 示例 1: // // //输入: [2,3,1,1,4] //输出: 2 //解释: 跳到最后一个位置的最小跳跃数是 2。 //  从下标为 0 跳到下标为 1 的位置,跳 1 步,然后跳 3 步到达数组的最后一个位置。 // // // 示例 2: // // //输入: [2,3,0,1,4] //输出: 2 // // // // // 提示: // // // 1 <= nums.length <= 1000 // 0 <= nums[i] <= 105 // // Related Topics 贪心算法 数组 动态规划 // 👍 1026 👎 0 //leetcode submit region begin(Prohibit modification and deletion) class Solution { fun jump(nums: IntArray): Int { var res = 0 var end = 0 //当前能走到的最大路径 var maxPair = 0 for ( i in 0 until nums.size-1){ //当前位置的值加上index表达能到达的最远位置 maxPair = Math.max(maxPair,nums[i]+i) if (end == i){ end = maxPair res++ } } return res } } //leetcode submit region end(Prohibit modification and deletion)
0
Kotlin
0
1
8a85996352a88bb9a8a6a2712dce3eac2e1c3463
1,376
MyLeetCode
Apache License 2.0
src/main/java/challenges/educative_grokking_coding_interview/fast_slow_pointers/_1/HappyNumber.kt
ShabanKamell
342,007,920
false
null
package challenges.educative_grokking_coding_interview.fast_slow_pointers._1 import challenges.util.PrintHyphens import kotlin.math.pow /** Write an algorithm to determine if a number nis happy. A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits. Repeat the process until the number equals 11 (where it will stay), or it loops endlessly in a cycle which does not include 11. Those numbers for which this process ends in 1 1 are happy. Return TRUE if n is a happy number, and FALSE if not. Time complexity: O(nlog(n)) Space complexity: O(1) https://www.educative.io/courses/grokking-coding-interview-patterns-java/RLDKqX6OJwY */ object HappyNumber { private fun sumOfSquaredDigits(number: Int): Int { var number = number var totalSum = 0 while (number != 0) { val digit = number % 10 number /= 10 totalSum += digit.toDouble().pow(2.0).toInt() } return totalSum } private fun isHappyNumber(n: Int): Boolean { var slowPointer = n var fastPointer = sumOfSquaredDigits(n) while (fastPointer != 1 && slowPointer != fastPointer) { slowPointer = sumOfSquaredDigits(slowPointer) fastPointer = sumOfSquaredDigits(sumOfSquaredDigits(fastPointer)) } return fastPointer == 1 } @JvmStatic fun main(args: Array<String>) { val a = intArrayOf(1, 5, 19, 25, 7) for (i in a.indices) { println((i + 1).toString() + ".\tInput Number: " + a[i]) val output = if (isHappyNumber(a[i])) "True" else "False" println("\n\tIs it a happy number? $output") println(PrintHyphens.repeat("-", 100)) } } }
0
Kotlin
0
0
ee06bebe0d3a7cd411d9ec7b7e317b48fe8c6d70
1,824
CodingChallenges
Apache License 2.0
plot-base/src/commonMain/kotlin/org/jetbrains/letsPlot/core/plot/base/stat/regression/RegressionUtil.kt
JetBrains
176,771,727
false
{"Kotlin": 6221641, "Python": 1158665, "Shell": 3495, "C": 3039, "JavaScript": 931, "Dockerfile": 94}
/* * Copyright (c) 2023. JetBrains s.r.o. * Use of this source code is governed by the MIT license that can be found in the LICENSE file. */ package org.jetbrains.letsPlot.core.plot.base.stat.regression import org.jetbrains.letsPlot.core.plot.base.stat.math3.Percentile import org.jetbrains.letsPlot.core.commons.data.SeriesUtil import kotlin.random.Random internal object RegressionUtil { // sample m data randomly fun <T> sampling(data: List<T>, m: Int): ArrayList<T> { val index = sampleInt(data.size, m) val result = ArrayList<T>() for (i in index) { result.add(data[i]) } return result } // sample m int from 0..n-1 private fun sampleInt(n: Int, m: Int): IntArray { if (n < m || m < 0) { error("Sample $m data from $n data is impossible!") } val perm = IntArray(n) for (i in 0 until n) { perm[i] = i } val result = IntArray(m) for (j in 0 until m) { val r = j + (Random.nextDouble() * (n - j)).toInt() result[j] = perm[r] perm[r] = perm[j] } return result } fun percentile(data: List<Double>, p: Double): Double { return Percentile.evaluate(data.toDoubleArray(), p * 100) } } fun sumOfSquaredDeviations(xVals: DoubleArray, meanX: Double): Double { return sumOfDeviationProducts(xVals, xVals, meanX, meanX) } fun sumOfDeviationProducts(xVals: DoubleArray, yVals: DoubleArray, meanX: Double, meanY: Double): Double { return (xVals zip yVals).sumOf { (x, y) -> (x - meanX) * (y - meanY) } } fun allFinite(xs: List<Double?>, ys: List<Double?>): Pair<DoubleArray, DoubleArray> { val tx = ArrayList<Double>() val ty = ArrayList<Double>() for ((x, y) in xs.asSequence().zip(ys.asSequence())) { if (SeriesUtil.allFinite(x, y)) { tx.add(x!!) ty.add(y!!) } } return Pair(tx.toDoubleArray(), ty.toDoubleArray()) } private fun finitePairs(xs: List<Double?>, ys: List<Double?>): ArrayList<Pair<Double, Double>> { val res = ArrayList<Pair<Double, Double>>() for ((x, y) in xs.asSequence().zip(ys.asSequence())) { if (SeriesUtil.allFinite(x, y)) { res.add(Pair(x!!, y!!)) } } return res } private fun averageByX(lst: List<Pair<Double, Double>>): Pair<List<Double>, List<Double>> { if (lst.isEmpty()) return Pair(ArrayList<Double>(), ArrayList<Double>()) val tx = ArrayList<Double>() val ty = ArrayList<Double>() var (prevX, sumY) = lst.first() var countY = 1 for ((x, y) in lst.asSequence().drop(1)) { if (x == prevX) { sumY += y ++countY } else { tx.add(prevX) ty.add(sumY.div(countY)) prevX = x sumY = y countY = 1 } } tx.add(prevX) ty.add(sumY.div(countY)) return Pair(tx, ty) } fun averageByX(xs: List<Double?>, ys: List<Double?>): Pair<DoubleArray, DoubleArray> { val tp = finitePairs(xs, ys) tp.sortBy { it.first } val res = averageByX(tp) return Pair(res.first.toDoubleArray(), res.second.toDoubleArray()) }
128
Kotlin
46
1,373
c61353ece18358ba6c6306a0f634e3b4b036577a
3,238
lets-plot
MIT License
dataStructuresAndAlgorithms/src/main/java/dev/funkymuse/datastructuresandalgorithms/linkedList/Extensions.kt
FunkyMuse
168,687,007
false
{"Kotlin": 1728251}
package dev.funkymuse.datastructuresandalgorithms.linkedList import dev.funkymuse.datastructuresandalgorithms.stack.Stack fun <T> LinkedList<T>.printInReverse() { val stack = Stack<T>() for (node in this) { stack.push(node) } var node = stack.pop() while (node != null) { println(node) node = stack.pop() } } fun <T> Node<T>.printInReverse() { this.next?.printInReverse() if (this.next != null) { print(" -> ") } print(this.value.toString()) } fun <T> LinkedList<T>.getMiddle(): Node<T>? { var slow = this.nodeAt(0) var fast = this.nodeAt(0) while (fast != null) { fast = fast.next if (fast != null) { fast = fast.next slow = slow?.next } } return slow } private fun <T> addInReverse(list: LinkedList<T>, node: Node<T>) { val next = node.next if (next != null) { addInReverse(list, next) } list.append(node.value) } fun <T> LinkedList<T>.reversed(): LinkedList<T> { val result = LinkedList<T>() val head = this.nodeAt(0) if (head != null) { addInReverse(result, head) } return result } private fun <T : Comparable<T>> append(result: LinkedList<T>, node: Node<T>): Node<T>? { result.append(node.value) return node.next } fun <T : Comparable<T>> LinkedList<T>.mergeSorted(otherList: LinkedList<T>): LinkedList<T> { if (this.isEmpty()) return otherList if (otherList.isEmpty()) return this val result = LinkedList<T>() var left = nodeAt(0) var right = otherList.nodeAt(0) while (left != null && right != null) { if (left.value < right.value) { left = append(result, left) } else { right = append(result, right) } } while (left != null) { left = append(result, left) } while (right != null) { right = append(result, right) } return result }
0
Kotlin
92
771
e2afb0cc98c92c80ddf2ec1c073d7ae4ecfcb6e1
1,961
KAHelpers
MIT License
aoc-2023/src/main/kotlin/nerok/aoc/aoc2023/day05/Day05.kt
nerok
572,862,875
false
{"Kotlin": 113337}
package nerok.aoc.aoc2023.day05 import nerok.aoc.utils.Input import nerok.aoc.utils.append import kotlin.time.DurationUnit import kotlin.time.measureTime fun main() { fun part1(input: String): Long { var seeds = emptyList<Long>().toMutableList() input.split("\n\n").forEach { block -> when { block.startsWith("seeds: ") -> { seeds = block.split(": ").last().split(" ").map { it.toLong() }.toList().toMutableList() //println("Seeds: $seeds") } block.startsWith("seed-to-soil map:") -> { val tmpList = emptyList<Long>().toMutableList() val removeSet = emptySet<Int>().toMutableSet() block.split("\n").drop(1).forEach {line -> val (dest, src, length) = line.split(" ").map { it.toLong() } seeds.forEachIndexed { index, seed -> if (seed in src..<(src+length)){ tmpList.add(dest+(seed-src)) removeSet.add(index) } } } removeSet.sortedDescending().forEach { seeds.removeAt(it) } seeds.addAll(tmpList) //println("Soil: $seeds") } block.startsWith("soil-to-fertilizer map:") -> { val tmpList = emptyList<Long>().toMutableList() val removeSet = emptySet<Int>().toMutableSet() block.split("\n").drop(1).forEach {line -> val (dest, src, length) = line.split(" ").map { it.toLong() } seeds.forEachIndexed { index, seed -> if (seed in src..<(src+length)){ tmpList.add(dest+(seed-src)) removeSet.add(index) } } } removeSet.sortedDescending().forEach { seeds.removeAt(it) } seeds.addAll(tmpList) //println("Fertilizer: $seeds") } block.startsWith("fertilizer-to-water map:") -> { val tmpList = emptyList<Long>().toMutableList() val removeSet = emptySet<Int>().toMutableSet() block.split("\n").drop(1).forEach {line -> val (dest, src, length) = line.split(" ").map { it.toLong() } seeds.forEachIndexed { index, seed -> if (seed in src..<(src+length)){ tmpList.add(dest+(seed-src)) removeSet.add(index) } } } removeSet.sortedDescending().forEach { seeds.removeAt(it) } seeds.addAll(tmpList) //println("Water: $seeds") } block.startsWith("water-to-light map:") -> { val tmpList = emptyList<Long>().toMutableList() val removeSet = emptySet<Int>().toMutableSet() block.split("\n").drop(1).forEach {line -> val (dest, src, length) = line.split(" ").map { it.toLong() } seeds.forEachIndexed { index, seed -> if (seed in src..<(src+length)){ tmpList.add(dest+(seed-src)) removeSet.add(index) } } } removeSet.sortedDescending().forEach { seeds.removeAt(it) } seeds.addAll(tmpList) //println("Light: $seeds") } block.startsWith("light-to-temperature map:") -> { val tmpList = emptyList<Long>().toMutableList() val removeSet = emptySet<Int>().toMutableSet() block.split("\n").drop(1).forEach {line -> val (dest, src, length) = line.split(" ").map { it.toLong() } seeds.forEachIndexed { index, seed -> if (seed in src..<(src+length)){ tmpList.add(dest+(seed-src)) removeSet.add(index) } } } removeSet.sortedDescending().forEach { seeds.removeAt(it) } seeds.addAll(tmpList) //println("Temperature: $seeds") } block.startsWith("temperature-to-humidity map:") -> { val tmpList = emptyList<Long>().toMutableList() val removeSet = emptySet<Int>().toMutableSet() block.split("\n").drop(1).forEach {line -> val (dest, src, length) = line.split(" ").map { it.toLong() } seeds.forEachIndexed { index, seed -> if (seed in src..<(src+length)){ tmpList.add(dest+(seed-src)) removeSet.add(index) } } } removeSet.sortedDescending().forEach { seeds.removeAt(it) } seeds.addAll(tmpList) //println("Humidity: $seeds") } block.startsWith("humidity-to-location map:") -> { val tmpList = emptyList<Long>().toMutableList() val removeSet = emptySet<Int>().toMutableSet() block.split("\n").drop(1).filter { it.isNotEmpty() }.forEach {line -> val (dest, src, length) = line.split(" ").map { it.toLong() } seeds.forEachIndexed { index, seed -> if (seed in src..<(src+length)){ tmpList.add(dest+(seed-src)) removeSet.add(index) } } } removeSet.sortedDescending().forEach { seeds.removeAt(it) } seeds.addAll(tmpList) //println("Location: $seeds") } } } return seeds.min() } fun Pair<Long,Long>.overlap(src: Long, size: Long): MutableList<Pair<Long, Long>> { val sizeValue = src+size-1 val secondValue = this.first+this.second-1 when { (secondValue<src) -> return emptyList<Pair<Long, Long>>().toMutableList() (this.first>sizeValue) -> return emptyList<Pair<Long, Long>>().toMutableList() (this.first<src) -> { if (secondValue<=sizeValue) return listOf((this.first to src-this.first), (src to (this.second-(src-this.first)))).toMutableList() return listOf((this.first to src-this.first), (sizeValue+1 to this.first+this.second-sizeValue+1), (src to size)).toMutableList() } (this.first==src) -> { if (secondValue<=sizeValue) return listOf((src to this.second)).toMutableList() return listOf((sizeValue+1 to secondValue-sizeValue), (src to size)).toMutableList() } (this.first>src) -> { if (secondValue<=sizeValue) return listOf(this).toMutableList() return listOf(sizeValue+1 to this.first+this.second-sizeValue-1, (this.first to (sizeValue-this.first)+1)).toMutableList() } } return emptyList<Pair<Long, Long>>().toMutableList() } fun iterate(block: String, seedList: List<Pair<Long,Long>>): List<Pair<Long,Long>> { val tmpList = emptyList<Pair<Long,Long>>().toMutableList() val seeds = seedList.toMutableList() block.split("\n").drop(1).filter{ it.isNotEmpty() }.forEach {line -> val (dest, src, length) = line.split(" ").map { it.toLong() } var i = 0 while (i < seeds.size) { val seed = seeds[i] val overlapList = seed.overlap(src, length) if (overlapList.isEmpty()) { ++i continue } seeds.removeAt(i) // Move actually overlapping range val overlapping = overlapList.removeLast() tmpList.add(dest+(overlapping.first-src) to overlapping.second) overlapList.forEach { seeds.append(it) } } } seeds.addAll(tmpList) return seeds } fun part2(input: String): Long { var seeds = emptyList<Pair<Long,Long>>() input.split("\n\n").map { it.trim() }.forEach { block -> when { block.startsWith("seeds: ") -> { seeds = block .split(": ") .last() .split(" ") .map { it.toLong() } .windowed(size = 2, step = 2) .map { it.first() to it.last() } //println("Seeds: $seeds") } block.startsWith("seed-to-soil map:") -> { seeds = iterate(block, seeds) //println("Soil: $seeds") } block.startsWith("soil-to-fertilizer map:") -> { seeds = iterate(block, seeds) //println("Fertilizer: $seeds") } block.startsWith("fertilizer-to-water map:") -> { seeds = iterate(block, seeds) //println("Water: $seeds") } block.startsWith("water-to-light map:") -> { seeds = iterate(block, seeds) //println("Light: $seeds") } block.startsWith("light-to-temperature map:") -> { seeds = iterate(block, seeds) //println("Temperature: $seeds") } block.startsWith("temperature-to-humidity map:") -> { seeds = iterate(block, seeds) //println("Humidity: $seeds") } block.startsWith("humidity-to-location map:") -> { seeds = iterate(block, seeds) //println("Location: $seeds") } } } return seeds.minOf { it.first } } // test if implementation meets criteria from the description, like: val testInput = Input.getInput("Day05_test") check(part1(testInput) == 35L) check(part2(testInput) == 46L) val input = Input.getInput("Day05") println("Part1:") println(measureTime { println(part1(input)) }.toString(DurationUnit.SECONDS, 3)) println("Part2:") println(measureTime { println(part2(input)) }.toString(DurationUnit.SECONDS, 3)) }
0
Kotlin
0
0
7553c28ac9053a70706c6af98b954fbdda6fb5d2
11,574
AOC
Apache License 2.0
kotlin/src/com/daily/algothrim/leetcode/medium/CombinationSum2.kt
idisfkj
291,855,545
false
null
package com.daily.algothrim.leetcode.medium /** * 40. 组合总和 II */ class CombinationSum2 { companion object { @JvmStatic fun main(args: Array<String>) { CombinationSum2().combinationSum2( intArrayOf(10, 1, 2, 7, 6, 1, 5), 8 ).forEach { it.forEach { item -> print(item) } println() } } } private val freq = ArrayList<Array<Int>>() private val ans = ArrayList<ArrayList<Int>>() private val sequence = ArrayList<Int>() fun combinationSum2(candidates: IntArray, target: Int): List<List<Int>> { candidates.sort() for (item in candidates) { val size = freq.size if (freq.isEmpty() || item != freq[size - 1][0]) { freq.add(arrayOf(item, 1)) } else { freq[size - 1][1]++ } } dfs(0, target) return ans } private fun dfs(pos: Int, rest: Int) { if (rest == 0) { ans.add(ArrayList(sequence)) return } if (pos == freq.size || rest < freq[pos][0]) return dfs(pos + 1, rest) val most = Math.min(rest / freq[pos][0], freq[pos][1]) for (i in 1..most) { sequence.add(freq[pos][0]) dfs(pos + 1, rest - i * freq[pos][0]) } for (i in 1..most) { sequence.remove(sequence[sequence.size - 1]) } } }
0
Kotlin
9
59
9de2b21d3bcd41cd03f0f7dd19136db93824a0fa
1,524
daily_algorithm
Apache License 2.0
2021/src/main/kotlin/de/skyrising/aoc2021/day16/solution.kt
skyrising
317,830,992
false
{"Kotlin": 411565}
package de.skyrising.aoc2021.day16 import de.skyrising.aoc.* import java.util.* val test = TestInput("CE00C43D881120") @PuzzleName("Packet Decoder") fun PuzzleInput.part1(): Any { val bytes = HexFormat.of().parseHex(chars.trimEnd()) val data = BitBuf(bytes) val packets = mutableListOf<Packet>() while (true) { val packet = readPacket(data) ?: break packets.add(packet) } return sumPacketVersions(packets) } fun PuzzleInput.part2(): Any? { val bytes = HexFormat.of().parseHex(chars.trimEnd()) val data = BitBuf(bytes) return readPacket(data)?.value() } private fun readPacket(data: BitBuf): Packet? { if (data.readAvailable() < 11) return null val version = data.readBits(3) val type = data.readBits(3) when (type) { 4 -> { var literal = 0L var c: Boolean do { val literalBits = data.readBits(5) c = (literalBits shr 4) != 0 literal = (literal shl 4) or (literalBits and 0xf).toLong() } while (c) return LiteralPacket(version, type, literal) } else -> { val lengthType = data.readBits(1) val packets = mutableListOf<Packet>() if (lengthType == 1) { val count = data.readBits(11) for (i in 0 until count) packets.add(readPacket(data)!!) } else { val length = data.readBits(15) val start = data.readerIndex while (data.readerIndex < start + length) { packets.add(readPacket(data)!!) } } return OperatorPacket(version, type, packets) } } } private fun sumPacketVersions(packets: List<Packet>): Int { var sum = 0 for (packet in packets) { sum += packet.version if (packet is OperatorPacket) { sum += sumPacketVersions(packet.subPackets) } } return sum } abstract class Packet(val version: Int, val type: Int) { override fun toString() = "Packet($version, $type)" abstract fun value(): Long } class LiteralPacket(version: Int, type: Int, val literal: Long) : Packet(version, type) { override fun toString() = "LiteralPacket($version, $literal)" override fun value() = literal } class OperatorPacket(version: Int, type: Int, val subPackets: List<Packet>) : Packet(version, type) { override fun toString(): String { return "OperatorPacket($version, $type)$subPackets" } override fun value(): Long { val values = subPackets.map(Packet::value) return when (type) { 0 -> values.reduce { a, b -> a + b } 1 -> values.reduce { a, b -> a * b } 2 -> values.minOf { it } 3 -> values.maxOf { it } 5 -> if (values[0] > values[1]) 1 else 0 6 -> if (values[0] < values[1]) 1 else 0 7 -> if (values[0] == values[1]) 1 else 0 else -> throw IllegalStateException("Unknown type $type") } } }
0
Kotlin
0
0
19599c1204f6994226d31bce27d8f01440322f39
3,087
aoc
MIT License
src/leetcodeProblem/leetcode/editor/en/BinaryTreeInorderTraversal.kt
faniabdullah
382,893,751
false
null
//Given the root of a binary tree, return the inorder traversal of its nodes' //values. // // // Example 1: // // //Input: root = [1,null,2,3] //Output: [1,3,2] // // // Example 2: // // //Input: root = [] //Output: [] // // // Example 3: // // //Input: root = [1] //Output: [1] // // // Example 4: // // //Input: root = [1,2] //Output: [2,1] // // // Example 5: // // //Input: root = [1,null,2] //Output: [1,2] // // // // Constraints: // // // The number of nodes in the tree is in the range [0, 100]. // -100 <= Node.val <= 100 // // // //Follow up: Recursive solution is trivial, could you do it iteratively? //Related Topics Stack Tree Depth-First Search Binary Tree 👍 6150 👎 259 package leetcodeProblem.leetcode.editor.en import data_structure.tree.TreeNode import java.util.* class BinaryTreeInorderTraversal { fun solution() { } //below code will be used for submission to leetcode (using plugin of course) //leetcode submit region begin(Prohibit modification and deletion) /** * Example: * var ti = TreeNode(5) * var v = ti.`val` * Definition for a binary tree node. * class TreeNode(var `val`: Int) { * var left: TreeNode? = null * var right: TreeNode? = nullg * } */ class Solution { private val listInOrder = mutableListOf<Int>() fun inorderTraversal(root: TreeNode?): List<Int> { fun recursive(r1: TreeNode?) { if (r1 == null) return if (r1.left != null) { recursive(r1.left) } listInOrder.add(r1.value) if (r1.right != null) { recursive(r1.right) } } fun iterative(r2: TreeNode?) { val stack = Stack<TreeNode>() var curr = r2 while (curr != null || !stack.isEmpty()) { while (curr != null) { stack.push(curr) curr = curr.left } curr = stack.pop() listInOrder.add(curr.value) curr = curr.right } } iterative(root) return listInOrder } } //leetcode submit region end(Prohibit modification and deletion) } fun main() {}
0
Kotlin
0
6
ecf14fe132824e944818fda1123f1c7796c30532
2,404
dsa-kotlin
MIT License
src/main/kotlin/day22.kt
Gitvert
725,292,325
false
{"Kotlin": 97000}
import kotlin.math.max import kotlin.math.min import kotlin.random.Random val random: Random = Random(1337) fun day22 (lines: List<String>) { val bricks = parseBricks(lines) val settledBricks = settleBricks(bricks.sortedBy { it.start.z }) removeBlocks(settledBricks) } fun removeBlocks(bricks: List<Brick>) { var safeToDisintegrate = 0 var totalFallen = 0 bricks.forEach { brick -> val settledBricks = settleBricks(bricks.filterNot { brick == it }).toMutableList() if (settledBricks == bricks.filterNot { brick == it }) { safeToDisintegrate++ } else { val unchanged = settledBricks.intersect(bricks.filterNot { brick == it }.toSet()).size totalFallen += settledBricks.size - unchanged } } println("Day 22 part 1: $safeToDisintegrate") println("Day 22 part 2: $totalFallen") println() } fun settleBricks(bricks: List<Brick>): List<Brick> { var settledBricks = bricks.toMutableList() val changedBricks = mutableListOf<Brick>() while (true) { for (i in settledBricks.indices) { val minZ = min(settledBricks[i].start.z, settledBricks[i].end.z) if (minZ == 1) { changedBricks.add(settledBricks[i]) continue } var isBlocked = false for (j in settledBricks.indices) { if (i == j) { continue } if (restsOn(settledBricks[i], settledBricks[j])) { isBlocked = true } } if (!isBlocked) { changedBricks.add(moveDown(settledBricks[i])) } else { changedBricks.add(settledBricks[i]) } } if (settledBricks == changedBricks) { break } settledBricks = changedBricks.toMutableList() changedBricks.clear() } return settledBricks } fun moveDown(brick: Brick): Brick { return Brick( Point(brick.start.x, brick.start.y, brick.start.z - 1), Point(brick.end.x, brick.end.y, brick.end.z - 1), brick.id, ) } fun restsOn(current: Brick, other: Brick): Boolean { val currentMinZ = min(current.start.z, current.end.z) val otherMaxZ = max(other.start.z, other.end.z) if (currentMinZ - 1 != otherMaxZ) { return false } val currentPositionsToCheck = generateAllPositionsToCheck(current) val otherPositionsToCheck = generateAllPositionsToCheck(other) return currentPositionsToCheck.any { it in otherPositionsToCheck.toSet() } } fun generateAllPositionsToCheck(brick: Brick): List<Pos> { val allPositions = mutableListOf<Pos>() if (brick.start.x == brick.end.x) { val from = min(brick.start.y, brick.end.y) val to = max(brick.start.y, brick.end.y) for (i in from..to) { allPositions.add(Pos(brick.start.x, i)) } } else if (brick.start.y == brick.end.y) { val from = min(brick.start.x, brick.end.x) val to = max(brick.start.x, brick.end.x) for (i in from..to) { allPositions.add(Pos(i, brick.start.y)) } } return allPositions } fun parseBricks(lines: List<String>): MutableList<Brick> { val bricks = mutableListOf<Brick>() lines.forEach { val startString = it.split("~")[0] val endString = it.split("~")[1] val startNumbers = startString.split(",") val endNumbers = endString.split(",") val start = Point(Integer.parseInt(startNumbers[0]), Integer.parseInt(startNumbers[1]), Integer.parseInt(startNumbers[2])) val end = Point(Integer.parseInt(endNumbers[0]), Integer.parseInt(endNumbers[1]), Integer.parseInt(endNumbers[2])) bricks.add(Brick(start, end, random.nextInt())) } return bricks } data class Brick(val start: Point, val end: Point, val id: Int) data class Point(val x: Int, val y: Int, val z: Int)
0
Kotlin
0
0
f204f09c94528f5cd83ce0149a254c4b0ca3bc91
4,061
advent_of_code_2023
MIT License
src/main/kotlin/com/vvv/engine/domain/Metadata.kt
vicol13
530,589,547
false
{"Kotlin": 40611, "Jupyter Notebook": 36031}
package com.vvv.engine.domain import java.util.* /** * This class represent container for data related to file * each file name has an associated LineMap in which * is contained data about occurrences of a word within file * * * as a chain this classes represent next structure of map * * { <word:String>: { * <file_1:String> : { * <line_1:Int>:[Index(1,10),Index(20,25)], * <line_2:Int>:[Index(5,15)]: * }:Map<String,LineMap> * }:Map<String,LineMap> * } */ class FileMap { private val map: MutableMap<String, LineMap> = mutableMapOf() fun update(fileName: String): LineMap { this.map.putIfAbsent(fileName, LineMap()) return this.map[fileName]!! } fun entries(): MutableSet<MutableMap.MutableEntry<String, LineMap>> { return this.map.entries } fun getOccurences(): Int { return map.values.sumOf { it.getOccurences() } } } /** * Class which act as container for holding information related * where a word is contained within a file here we have as * key number of line where we have word in file and a list of * Indexes which represent at which index word is in file */ class LineMap { private val map: TreeMap<Int, MutableList<Index>> = TreeMap() fun update(line: Int, index: Index) { this.map.putIfAbsent(line, mutableListOf()) this.map[line]!!.add(index) } fun update(line: Int, indexes: Iterable<Index>) { indexes.forEach { update(line, it) } } fun get(line: Int) = this.map[line] fun keys() = this.map.keys fun getOccurences(): Int { return map.values.sumOf { it.size } } }
0
Kotlin
0
1
534a40c5a4c0b02f1935ba4ea976d47cd8c43485
1,687
search-engine
MIT License
src/main/kotlin/dev/bogwalk/batch5/Problem56.kt
bog-walk
381,459,475
false
null
package dev.bogwalk.batch5 import dev.bogwalk.util.maths.powerDigitSum /** * Problem 56: Powerful Digit Sum * * https://projecteuler.net/problem=56 * * Goal: Considering natural numbers of the form a^b, where a, b < N, find the maximum digit sum. * * Constraints: 5 <= N <= 200 * * Googol: A massive number that is 1 followed by 100 zeroes, i.e. 10^100. Another unimaginably * large number is 100^100, which is 1 followed by 200 zeroes. Despite both their sizes, the sum * of each number's digits equals 1. * * e.g.: N = 5 * 4^4 = 256 -> 2 + 5 + 6 = 13 * max sum = 13 */ class PowerfulDigitSum { /** * Solution optimised by setting loop limits based on the pattern observed of the a, b * combinations that achieved the maximum digit sums: * * - a is never less than n / 2, even for outliers with large deltas, e.g. n = 42 achieved * max sum at 24^41. * * - b is never more than 5 digits less than [n], e.g. n = 100 achieved max sum at 99^95. */ fun maxDigitSum(n: Int): Int { var maxSum = 1 val minA = n / 2 val minB = maxOf(1, n - 5) for (a in minA until n) { for (b in minB until n) { maxSum = maxOf(maxSum, powerDigitSum(a, b)) } } return maxSum } }
0
Kotlin
0
0
62b33367e3d1e15f7ea872d151c3512f8c606ce7
1,330
project-euler-kotlin
MIT License
advent-of-code-2022/src/main/kotlin/Point.kt
yuriykulikov
159,951,728
false
{"Kotlin": 1666784, "Rust": 33275}
import kotlin.math.abs data class Point(val x: Int, val y: Int) { override fun hashCode(): Int { return x * 106039 + (y and 0xffff) } override fun equals(other: Any?): Boolean { return other is Point && other.x == x && other.y == y } } fun printMap( tiles: Map<Point, String>, ) { val maxX = tiles.keys.maxOf { it.x } val minX = tiles.keys.minOf { it.x } val maxY = tiles.keys.maxOf { it.y } val minY = tiles.keys.minOf { it.y } (minY..maxY) .map { y -> (minX..maxX).joinToString(separator = "") { x -> tiles[Point(x, y)] ?: " " } } .forEach { println(it) } } fun <T> mapContentToString( tiles: Map<Point, T>, invertedY: Boolean = true, prefixFun: (Int) -> String = { "" }, func: Point.(T?) -> String = { "${it ?: " "}" } ): String = buildString { val maxX = tiles.keys.maxOf { it.x } val minX = tiles.keys.minOf { it.x } val maxY = tiles.keys.maxOf { it.y } val minY = tiles.keys.minOf { it.y } (minY..maxY) .run { if (invertedY) sorted() else sortedDescending() } .map { y -> (minX..maxX).joinToString( prefix = prefixFun(y), separator = "", transform = { x -> func(Point(x, y), tiles[Point(x, y)]) }) } .forEach { append(it).append("\n") } } fun <T> printMap( tiles: Map<Point, T>, invertedY: Boolean = true, prefixFun: (Int) -> String = { "" }, func: Point.(T?) -> String = { "${it ?: " "}" } ) { val maxX = tiles.keys.maxOf { it.x } val minX = tiles.keys.minOf { it.x } val maxY = tiles.keys.maxOf { it.y } val minY = tiles.keys.minOf { it.y } (minY..maxY) .run { if (invertedY) sorted() else sortedDescending() } .map { y -> (minX..maxX).joinToString( prefix = prefixFun(y), separator = "", transform = { x -> func(Point(x, y), tiles[Point(x, y)]) }) } .forEach { println(it) } } fun parseMap(mapString: String): Map<Point, Char> { return mapString .lines() .mapIndexed { y, line -> line.mapIndexed { x, c -> Point(x, y) to c } } .flatten() .toMap() } operator fun Point.rangeTo(other: Point): List<Point> = when { x == other.x -> (y..other.y).map { Point(x, it) } y == other.y -> (x..other.x).map { Point(it, y) } else -> error("Cannot go from $this to $other") } fun Point.left(inc: Int = 1) = copy(x = x - inc) fun Point.right(inc: Int = 1) = copy(x = x + inc) fun Point.up(inc: Int = 1) = copy(y = y - inc) fun Point.down(inc: Int = 1) = copy(y = y + inc) operator fun Point.minus(other: Point) = Point(x - other.x, y - other.y) operator fun Point.plus(other: Point) = Point(x + other.x, y + other.y) fun Point.direction() = Point(x = x.compareTo(0), y = y.compareTo(0)) fun Point.manhattan(): Int = abs(x) + abs(y) fun Point.rotateCCW() = Point(x = -y, y = x) fun Point.rotateCW() = Point(x = y, y = -x)
0
Kotlin
0
1
f5efe2f0b6b09b0e41045dc7fda3a7565cb21db3
2,916
advent-of-code
MIT License
src/main/kotlin/leetcode/Problem2192.kt
fredyw
28,460,187
false
{"Java": 1280840, "Rust": 363472, "Kotlin": 148898, "Shell": 604}
package leetcode import java.util.* /** * https://leetcode.com/problems/all-ancestors-of-a-node-in-a-directed-acyclic-graph/ */ class Problem2192 { fun getAncestors(n: Int, edges: Array<IntArray>): List<List<Int>> { val adjList = reverse(n, edges) val answer = mutableListOf<List<Int>>() for (i in 0 until n) { val ancestors = mutableListOf<Int>() val visited = BooleanArray(n) getAncestors(i, adjList, ancestors, visited) ancestors.sort() answer += ancestors } return answer } private fun reverse(n: Int, edges: Array<IntArray>): Array<MutableList<Int>> { val adjList = Array<MutableList<Int>>(n) { mutableListOf() } for (edge in edges) { val from = edge[0] val to = edge[1] adjList[to].add(from) } return adjList } private fun getAncestors(i: Int, adjList: Array<MutableList<Int>>, ancestors: MutableList<Int>, visited: BooleanArray) { visited[i] = true for (adjacent in adjList[i]) { if (!visited[adjacent]) { ancestors += adjacent getAncestors(adjacent, adjList, ancestors, visited) } } } }
0
Java
1
4
a59d77c4fd00674426a5f4f7b9b009d9b8321d6d
1,302
leetcode
MIT License
solutions/src/AdjacentPairs.kt
JustAnotherSoftwareDeveloper
139,743,481
false
{"Kotlin": 305071, "Java": 14982}
/** * https://leetcode.com/problems/restore-the-array-from-adjacent-pairs/ */ class AdjacentPairs { fun restoreArray(adjacentPairs: Array<IntArray>): IntArray { val adjacentList = adjacentPairs.map { it.toList().sorted() }.map { Pair(it[0],it[1]) } val adjacentFreq = mutableMapOf<Int,Int>() adjacentPairs.forEach { adjacentFreq[it[0]] = adjacentFreq.getOrDefault(it[0],0)+1 adjacentFreq[it[1]] = adjacentFreq.getOrDefault(it[1],0)+1 } val adjacentMapForward = adjacentList.groupBy { it.first }.mapValues { it.value.map { p -> p.second }.toSet() } val adjacentMapBackwards = adjacentList.map { Pair(it.second,it.first) }.groupBy { it.first }.mapValues { it.value.map { p -> p.second }.toSet() } val firstValue = adjacentFreq.filter { it.value == 1 }.map { it.key }[0] var currentValue : Int? = firstValue val visited = mutableSetOf(firstValue) var returnList = mutableListOf<Int>() returnList.add(currentValue!!) visited.add(currentValue!!) while (currentValue != null) { val forward = adjacentMapForward[currentValue] val backward = adjacentMapBackwards[currentValue] val valueList = listOfNotNull(forward, backward).flatten().filter { it != null && !visited.contains(it) } if (valueList.isEmpty()) { currentValue = null } else { currentValue = valueList[0] returnList.add(currentValue) visited.add(currentValue) } } return returnList.toIntArray() } }
0
Kotlin
0
0
fa4a9089be4af420a4ad51938a276657b2e4301f
1,662
leetcode-solutions
MIT License
day21/src/main/kotlin/Main.kt
rstockbridge
159,586,951
false
null
import java.io.File import java.lang.IllegalStateException fun main() { val device = parseInput(readInputFile()) println("Part I: the solution is ${solvePartI(device)}.") println("Part II: the solution is ${solvePartII(device)}.") } fun readInputFile(): List<String> { return File(ClassLoader.getSystemResource("input.txt").file).readLines() } fun parseInput(input: List<String>): Device { val boundRegisterRegex = "#ip (\\d)".toRegex() val (boundRegister) = boundRegisterRegex.matchEntire(input[0])!!.destructured.toList().map(String::toInt) val instructionInput = input.toMutableList() instructionInput.removeAt(0) val instructionRegex = "([a-z]+) (\\d+) (\\d+) (\\d+)".toRegex() val instructions = instructionInput .map { instruction -> val (opcodeAsString, a, b, c) = instructionRegex.matchEntire(instruction)!!.destructured Instruction.fromInput(opcodeAsString, a.toInt(), b.toInt(), c.toInt()) } return Device(boundRegister = boundRegister, instructions = instructions) } fun solvePartI(device: Device): Int { // instruction 28 translates to if(r[5] == r[0]) then goto 31 (quit), so the program quits the first time r[0] = r[5] // quit once program hits instruction 28 while (device.instructionPointer != 28) { val instruction = device.instructions[device.instructionPointer] device.registers[device.boundRegister] = device.instructionPointer instruction.opcode.applyTo(device.registers, instruction.a, instruction.b, instruction.c) device.instructionPointer = device.registers[device.boundRegister] device.instructionPointer++ } // so return the value of r[5] the first time the program hits instruction 28 return device.registers[5] } fun solvePartII(device: Device): Int { // return the last non-repeated value of r[5] when the program hits instruction 28 val register5Values = mutableSetOf<Int>() var previousValue = -1 while (true) { if (device.instructionPointer == 28) { if (device.registers[5] !in register5Values) { previousValue = device.registers[5] register5Values.add(previousValue) } else { return previousValue } } val instruction = device.instructions[device.instructionPointer] device.registers[device.boundRegister] = device.instructionPointer instruction.opcode.applyTo(device.registers, instruction.a, instruction.b, instruction.c) device.instructionPointer = device.registers[device.boundRegister] device.instructionPointer++ } } data class Device(var registers: MutableList<Int> = mutableListOf(0, 0, 0, 0, 0, 0), val boundRegister: Int, var instructionPointer: Int = 0, val instructions: List<Instruction>) data class Instruction(val opcode: Opcode, val a: Int, val b: Int, val c: Int) { companion object { fun fromInput(opcodeString: String, a: Int, b: Int, c: Int): Instruction { val opcode = when (opcodeString) { "addr" -> Opcode.ADDR "addi" -> Opcode.ADDI "mulr" -> Opcode.MULR "muli" -> Opcode.MULI "banr" -> Opcode.BANR "bani" -> Opcode.BANI "borr" -> Opcode.BORR "bori" -> Opcode.BORI "setr" -> Opcode.SETR "seti" -> Opcode.SETI "gtir" -> Opcode.GTIR "gtri" -> Opcode.GTRI "gtrr" -> Opcode.GTRR "eqir" -> Opcode.EQIR "eqri" -> Opcode.EQRI "eqrr" -> Opcode.EQRR else -> { throw IllegalStateException("This line should not be reached.") } } return Instruction(opcode, a, b, c) } } }
0
Kotlin
0
0
c404f1c47c9dee266b2330ecae98471e19056549
3,985
AdventOfCode2018
MIT License
src/Day04.kt
drothmaler
572,899,837
false
{"Kotlin": 15196}
fun main() { fun cleaningRanges(input: Sequence<String>) = input .map { it.split(',').map { elfRange -> val (left, right) = elfRange.split('-').map(String::toInt) left..right } } fun part1(input: Sequence<String>) = cleaningRanges(input) .count { (left, right) -> (left.contains(right.first) && left.contains(right.last)) || (right.contains(left.first) && right.contains(left.last)) } fun part2(input: Sequence<String>) = cleaningRanges(input) .count { (left, right) -> left.contains(right.first) || left.contains(right.last) || right.contains(left.first) || right.contains(left.last) } // test if implementation meets criteria from the description, like: val testOutput = useSanitizedInput("Day04_test", ::part1) check(testOutput == 2) val testOutput2 = useSanitizedInput("Day04_test", ::part2) check(testOutput2 == 4) val output = useSanitizedInput("Day04", ::part1) println(output) val output2 = useSanitizedInput("Day04", ::part2) println(output2) }
0
Kotlin
0
0
1fa39ebe3e4a43e87f415acaf20a991c930eae1c
1,291
aoc-2022-in-kotlin
Apache License 2.0
src/main/kotlin/com/demonwav/mcdev/util/SemanticVersion.kt
Earthcomputer
240,984,777
true
{"Kotlin": 1282177, "Lex": 12961, "HTML": 10151, "Groovy": 4500, "Java": 948, "Shell": 798}
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2019 minecraft-dev * * MIT License */ package com.demonwav.mcdev.util import com.demonwav.mcdev.util.SemanticVersion.Companion.VersionPart.ReleasePart import com.demonwav.mcdev.util.SemanticVersion.Companion.VersionPart.TextPart /** * Represents a comparable and generalised "semantic version". * Each constituent part (delimited by periods in a version string) contributes * to the version ranking with decreasing priority from left to right. */ class SemanticVersion(private val parts: List<VersionPart>) : Comparable<SemanticVersion> { val versionString = parts.joinToString(".") { it.versionString } override fun compareTo(other: SemanticVersion): Int = naturalOrder<VersionPart>().lexicographical().compare(parts, other.parts) override fun equals(other: Any?) = when (other) { is SemanticVersion -> parts.size == other.parts.size && parts.zip(other.parts).all { (a, b) -> a == b } else -> false } override fun hashCode() = parts.hashCode() override fun toString() = versionString companion object { /** * The higher the priority value associated with a certain part, the higher it is ranked in comparisons. * Unknown parts will always be "rated" lower and equal among each other. */ val TEXT_PRIORITIES = mapOf( "snapshot" to 0, "rc" to 1, "pre" to 1 ) /** * All separators allowed between a number and a modifier (i.e. (numbered) text part). */ private val SEPARATORS = listOf('-', '_') /** * Creates a simple release version where each provided value forms a part (read from left to right). */ fun release(vararg parts: Int) = SemanticVersion(parts.map(::ReleasePart)) /** * Parses a version string into a comparable representation. * @throws IllegalArgumentException if any part of the version string cannot be parsed as integer or split into text parts. */ fun parse(value: String): SemanticVersion { fun parseInt(part: String): Int = if (part.all { it.isDigit() }) part.toInt() else throw IllegalArgumentException("Failed to parse version part as integer: $part") // We need to support pre-releases/RCs and snapshots as well fun parseTextPart(subParts: List<String>, separator: Char): VersionPart = if (subParts.size == 2) { val version = parseInt(subParts[0]) val (text, number) = subParts[1].span { !it.isDigit() } // Pure text parts always are considered older than numbered ones // Since we don't handle negative version numbers, -1 is guaranteed to be smaller than any numbered part val versionNumber = if (number.isEmpty()) -1 else parseInt(number) TextPart(version, separator, text, versionNumber) } else { throw IllegalArgumentException("Failed to split text version part into two: " + "${subParts.first()}$separator") } val parts = value.split('.').map { part -> val separator = SEPARATORS.find { it in part } if (separator != null) { parseTextPart(part.split(separator, limit = 2), separator) } else { ReleasePart(parseInt(part)) } } return SemanticVersion(parts) } sealed class VersionPart : Comparable<VersionPart> { abstract val versionString: String data class ReleasePart(val version: Int) : VersionPart() { override val versionString = version.toString() override fun compareTo(other: VersionPart) = when (other) { is ReleasePart -> version - other.version is TextPart -> if (version != other.version) version - other.version else 1 } } data class TextPart(val version: Int, val separator: Char, val text: String, val number: Int) : VersionPart() { private val priority = TEXT_PRIORITIES[text.toLowerCase()] ?: -1 override val versionString = "$version$separator$text${if (number == -1) "" else number.toString()}" override fun compareTo(other: VersionPart) = when (other) { is ReleasePart -> if (version != other.version) version - other.version else -1 is TextPart -> when { version != other.version -> version - other.version text != other.text -> priority - other.priority else -> number - other.number } } override fun hashCode(): Int { return version + 31 * text.hashCode() + 31 * number } override fun equals(other: Any?): Boolean { return when (other) { is TextPart -> other.version == version && other.text == text && other.number == number else -> false } } } } } }
3
Kotlin
2
23
ab8aaeb8804c7a8b2e439e063a73cb12d0a9d4b5
5,628
MinecraftDev
MIT License
kotlin/377.Combination Sum IV(组合总和 Ⅳ).kt
learningtheory
141,790,045
false
{"Python": 4025652, "C++": 1999023, "Java": 1995266, "JavaScript": 1990554, "C": 1979022, "Ruby": 1970980, "Scala": 1925110, "Kotlin": 1917691, "Go": 1898079, "Swift": 1827809, "HTML": 124958, "Shell": 7944}
/** <p> Given an integer array with all positive numbers and no duplicates, find the number of possible combinations that add up to a positive integer target.</p> <p><b>Example:</b> <pre> <i><b>nums</b></i> = [1, 2, 3] <i><b>target</b></i> = 4 The possible combination ways are: (1, 1, 1, 1) (1, 1, 2) (1, 2, 1) (1, 3) (2, 1, 1) (2, 2) (3, 1) Note that different sequences are counted as different combinations. Therefore the output is <i><b>7</i></b>. </pre> </p> <p><b>Follow up:</b><br /> What if negative numbers are allowed in the given array?<br /> How does it change the problem?<br /> What limitation we need to add to the question to allow negative numbers? </p> <p><b>Credits:</b><br />Special thanks to <a href="https://leetcode.com/pbrother/">@pbrother</a> for adding this problem and creating all test cases.</p><p>给定一个由正整数组成且不存在重复数字的数组,找出和为给定目标正整数的组合的个数。</p> <p><strong>示例:</strong></p> <pre> <em><strong>nums</strong></em> = [1, 2, 3] <em><strong>target</strong></em> = 4 所有可能的组合为: (1, 1, 1, 1) (1, 1, 2) (1, 2, 1) (1, 3) (2, 1, 1) (2, 2) (3, 1) 请注意,顺序不同的序列被视作不同的组合。 因此输出为 <strong>7</strong>。 </pre> <p><strong>进阶:</strong><br /> 如果给定的数组中含有负数会怎么样?<br /> 问题会产生什么变化?<br /> 我们需要在题目中添加什么限制来允许负数的出现?</p> <p><strong>致谢:</strong><br /> 特别感谢&nbsp;<a href="https://leetcode.com/pbrother/">@pbrother</a>&nbsp;添加此问题并创建所有测试用例。</p> <p>给定一个由正整数组成且不存在重复数字的数组,找出和为给定目标正整数的组合的个数。</p> <p><strong>示例:</strong></p> <pre> <em><strong>nums</strong></em> = [1, 2, 3] <em><strong>target</strong></em> = 4 所有可能的组合为: (1, 1, 1, 1) (1, 1, 2) (1, 2, 1) (1, 3) (2, 1, 1) (2, 2) (3, 1) 请注意,顺序不同的序列被视作不同的组合。 因此输出为 <strong>7</strong>。 </pre> <p><strong>进阶:</strong><br /> 如果给定的数组中含有负数会怎么样?<br /> 问题会产生什么变化?<br /> 我们需要在题目中添加什么限制来允许负数的出现?</p> <p><strong>致谢:</strong><br /> 特别感谢&nbsp;<a href="https://leetcode.com/pbrother/">@pbrother</a>&nbsp;添加此问题并创建所有测试用例。</p> **/ class Solution { fun combinationSum4(nums: IntArray, target: Int): Int { } }
0
Python
1
3
6731e128be0fd3c0bdfe885c1a409ac54b929597
2,570
leetcode
MIT License
src/main/kotlin/g0901_1000/s0949_largest_time_for_given_digits/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g0901_1000.s0949_largest_time_for_given_digits // #Medium #String #Enumeration #2023_05_01_Time_171_ms_(100.00%)_Space_36.6_MB_(100.00%) class Solution { fun largestTimeFromDigits(arr: IntArray): String { val buf = StringBuilder() var maxHour: String? = "" for (i in 0..3) { for (j in 0..3) { if (i != j) { val hour = getTime(arr, i, j, 23, false) val min = getTime(arr, i, j, 59, true) if (hour != null && min != null && hour > maxHour!!) { buf.setLength(0) buf.append(hour).append(':').append(min) maxHour = hour } } } } return buf.toString() } private fun getTime(arr: IntArray, i: Int, j: Int, limit: Int, exclude: Boolean): String? { var n1 = -1 var n2 = -1 for (k in 0..3) { if (exclude && k != i && k != j || !exclude && (k == i || k == j)) { if (n1 == -1) { n1 = arr[k] } else { n2 = arr[k] } } } var s1: String? = n1.toString() + n2 var s2: String? = n2.toString() + n1 var v1 = s1!!.toInt() if (v1 > limit) { v1 = -1 s1 = null } var v2 = s2!!.toInt() if (v2 > limit) { v2 = -1 s2 = null } return if (v1 >= v2) s1 else s2 } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,574
LeetCode-in-Kotlin
MIT License
src/main/kotlin/com/hj/leetcode/kotlin/problem790/Solution.kt
hj-core
534,054,064
false
{"Kotlin": 619841}
package com.hj.leetcode.kotlin.problem790 /** * LeetCode page: [790. Domino and Tromino Tiling](https://leetcode.com/problems/domino-and-tromino-tiling/); */ class Solution { /* Complexity: * Time O(n) and Space O(1); */ fun numTilings(n: Int): Int { val module = 1_000_000_007 // from the problem requirements; /* A valid tiling's start tile must be one of the following: * 1. a vertical domino; * 2. a stack of two horizontal dominoes; * 3. a tromino like 'L'; * 4. a tromino like upside down 'L'; * We can apply Dynamic Programming to solve the problem, the sub problems are the number of * tilings in each case for a segment start from index i. The original problem is the sum of * 4 cases with i equals 0. */ var case1 = 1L // initial value with i equals n - 1; var prevCase1 = 0L // initial value with i equals n; var case2 = 0L // initial value with i equals n - 1; var case3 = 0L // initial value with i equals n - 1; var case4 = 0L // initial value with i equals n - 1; for (i in n - 2 downTo 0) { val newCase1 = (case1 + case2 + case3 + case4) % module val newCase2 = case1 val newCase3 = (case4 + prevCase1) % module val newCase4 = (case3 + prevCase1) % module prevCase1 = case1 case1 = newCase1 case2 = newCase2 case3 = newCase3 case4 = newCase4 } return ((case1 + case2 + case3 + case4) % module).toInt() } }
1
Kotlin
0
1
14c033f2bf43d1c4148633a222c133d76986029c
1,618
hj-leetcode-kotlin
Apache License 2.0
2021/src/day07/day7.kt
scrubskip
160,313,272
false
{"Kotlin": 198319, "Python": 114888, "Dart": 86314}
package day07 import java.io.File import kotlin.math.abs fun main() { var positions = File("src/day07", "day7input.txt").readLines().single().split(",").map{it.toInt()} println(findLowestFuel(positions, ::calculateFuelLinear).first) } fun findLowestFuel(positions: List<Int>, calc : (List<Int>, Int) -> Int = ::calculateFuel) : Pair<Int, Int> { val positionsSorted = positions.sortedDescending() var min : Int = -1 var minIndex : Int = -1 for (i in 0..positionsSorted.first()) { var fuel = calc(positionsSorted, i) if (min == -1 || (fuel < min)) { min = fuel minIndex = i } } return Pair(min, minIndex) } fun calculateFuel(positions : List<Int>, endPosition: Int) : Int { return positions.sumOf { abs(it - endPosition) } } fun calculateFuelLinear(positions: List<Int>, endPosition: Int) : Int { val cost : MutableMap<Int, Int> = mutableMapOf(Pair(1,1)) return positions.sumOf { var distance = abs(it - endPosition) cost.getOrPut(distance) { (1 .. distance).sum() } } }
0
Kotlin
0
0
a5b7f69b43ad02b9356d19c15ce478866e6c38a1
1,105
adventofcode
Apache License 2.0
kotlin/src/com/daily/algothrim/leetcode/easy/LongestCommonPrefix.kt
idisfkj
291,855,545
false
null
package com.daily.algothrim.leetcode.easy /** * 14. 最长公共前缀 * * 编写一个函数来查找字符串数组中的最长公共前缀。 * 如果不存在公共前缀,返回空字符串 ""。 * * 示例 1: * * 输入:strs = ["flower","flow","flight"] * 输出:"fl" * 示例 2: * * 输入:strs = ["dog","racecar","car"] * 输出:"" * 解释:输入不存在公共前缀。 */ class LongestCommonPrefix { companion object { @JvmStatic fun main(args: Array<String>) { println( LongestCommonPrefix().longestCommonPrefix( arrayOf( "flower", "flow", "flight" ) ) ) println( LongestCommonPrefix().longestCommonPrefix( arrayOf( "dog", "racecar", "car" ) ) ) } } fun longestCommonPrefix(strs: Array<String>): String { if (strs.isEmpty()) return "" var result = strs[0] for (i in 1 until strs.size) { val length = Math.min(result.length, strs[i].length) var j = 0 while (j < length && result[j] == strs[i][j]) { j++ } result = result.substring(0, j) if (result.isEmpty()) break } return result } }
0
Kotlin
9
59
9de2b21d3bcd41cd03f0f7dd19136db93824a0fa
1,439
daily_algorithm
Apache License 2.0
src/main/kotlin/Day3.kt
corentinnormand
725,992,109
false
{"Kotlin": 40576}
class Day3 : Aoc("day3.txt") { override fun one() { val input = readFile("day3.txt").lines() val numbers = mutableListOf<Int>() for (i in 0..<input[0].length) { for (j in input.indices) { val c = input[j][i] if (!c.isDigit() && c != '.') { val adjacentNumbers = mutableSetOf<Int>() for (k in -1..1) { for (l in -1..1) { val adjacentToSymbol = input[j + l][i + k] if (adjacentToSymbol.isDigit()) { var number = adjacentToSymbol.toString() for (m in i + k - 1 downTo 0) { val left = input[j + l][m] if (left.isDigit()) { number = "${left}${number}" } else { break } } for (m in i + k + 1..<input.first().length) { val right = input[j + l][m] if (right.isDigit()) { number = "${number}${right}" } else { break } } adjacentNumbers.add(number.toInt()) } } } numbers.addAll(adjacentNumbers.toList()) } } } println(numbers.sum()) } override fun two() { val input = readFile("day3.txt").lines() val numbers = mutableListOf<Int>() for (i in 0..<input[0].length) { for (j in input.indices) { val c = input[j][i] if (!c.isDigit() && c == '*') { val adjacentNumbers = mutableSetOf<Int>() for (k in -1..1) { for (l in -1..1) { val adjacentToSymbol = input[j + l][i + k] if (adjacentToSymbol.isDigit()) { var number = adjacentToSymbol.toString() for (m in i + k - 1 downTo 0) { val left = input[j + l][m] if (left.isDigit()) { number = "${left}${number}" } else { break } } for (m in i + k + 1..<input.first().length) { val right = input[j + l][m] if (right.isDigit()) { number = "${number}${right}" } else { break } } adjacentNumbers.add(number.toInt()) } } } if (adjacentNumbers.size == 2) { numbers.add(adjacentNumbers.reduce { acc, i -> acc * i }) } } } } println(numbers.sum()) } }
0
Kotlin
0
0
2b177a98ab112850b0f985c5926d15493a9a1373
3,666
aoc_2023
Apache License 2.0
src/main/kotlin/Day6.kt
lanrete
244,431,253
false
null
data class Star(val name: String) { override fun toString(): String { return name } val orbitedBy: MutableSet<Star> = mutableSetOf() lateinit var parent: Star } object Day6 : Solver() { override val day: Int = 6 override val inputs: List<String> = getInput() private fun processInput(): Map<String, Star> { val stars: MutableMap<String, Star> = mutableMapOf() inputs.forEach { rule -> run { val (center, moon) = rule.split(")") val centerStar = stars.getOrPut(center, { Star(center) }) val moonStar = stars.getOrPut(moon, { Star(moon) }) centerStar.orbitedBy.add(moonStar) moonStar.parent = centerStar } } return stars } private val stars = processInput() private var starDepth: MutableMap<Star, Int> = mutableMapOf() private var starParentList: MutableMap<Star, List<Star>> = mutableMapOf() override fun question1(): String { fun getDepth(s: Star): Int { if (s == Star("COM")) { return 0 } val parent = s.parent val parentDepth = starDepth.getOrPut(parent, { getDepth(parent) }) return parentDepth + 1 } return stars.values.map { getDepth(it) }.reduce { a, b -> a + b }.toString() } override fun question2(): String { fun getParentList(s: Star): List<Star> { if (s == Star("COM")) { return mutableListOf() } val parent = s.parent val grandParent = starParentList.getOrPut(parent, { getParentList(parent) }) val parentList = grandParent.toMutableList() parentList.add(parent) return parentList } val parentSet = listOf("YOU", "SAN") .map { stars.getValue(it) } .map { getParentList(it) } .map { it.toSet() } val commonParent = parentSet.reduce { a, b -> a.intersect(b) } return parentSet .map { it.subtract(commonParent) } .map { it.size } .reduce { a, b -> a + b } .toString() } } fun main() { Day6.solveFirst() Day6.solveSecond() }
0
Kotlin
0
1
15125c807abe53230e8d0f0b2ca0e98ea72eb8fd
2,279
AoC2019-Kotlin
MIT License
src/main/kotlin/se/saidaspen/aoc/util/Lists.kt
saidaspen
354,930,478
false
{"Kotlin": 301372, "CSS": 530}
package se.saidaspen.aoc.util import java.util.* import kotlin.collections.ArrayDeque fun <E> permutations(list: List<E>, length: Int? = null): Sequence<List<E>> = sequence { val n = list.size val r = length ?: list.size val indices = list.indices.toMutableList() val cycles = (n downTo (n - r)).toMutableList() yield(indices.take(r).map { list[it] }) while (true) { var broke = false for (i in (r - 1) downTo 0) { cycles[i]-- if (cycles[i] == 0) { val end = indices[i] for (j in i until indices.size - 1) { indices[j] = indices[j + 1] } indices[indices.size - 1] = end cycles[i] = n - i } else { val j = cycles[i] val tmp = indices[i] indices[i] = indices[-j + indices.size] indices[-j + indices.size] = tmp yield(indices.take(r).map { list[it] }) broke = true break } } if (!broke) { break } } } fun <V> List<V>.permutations(): Sequence<List<V>> { val underlying = this val factorials = IntArray(underlying.size + 1) factorials[0] = 1 for (i in 1..underlying.size) { factorials[i] = factorials[i - 1] * i } return sequence { for (i in 0 until factorials[underlying.size]) { val temp = mutableListOf<V>() temp.addAll(underlying) val onePermutation = mutableListOf<V>() var positionCode = i for (position in underlying.size downTo 1) { val selected = positionCode / factorials[position - 1] onePermutation.add(temp[selected]) positionCode %= factorials[position - 1] temp.removeAt(selected) } yield(onePermutation) } } } inline fun <reified T> combinations(arr: Array<T>, m: Int) = sequence { val n = arr.size val result = Array(m) { arr[0] } val stack = LinkedList<Int>() stack.push(0) while (stack.isNotEmpty()) { var resIndex = stack.size - 1 var arrIndex = stack.pop() while (arrIndex < n) { result[resIndex++] = arr[arrIndex++] stack.push(arrIndex) if (resIndex == m) { yield(result.toList()) break } } } } fun <E> List<E>.toArrayDeque() = ArrayDeque(this) inline fun <T> ArrayDeque<T>.push(element: T) = addLast(element) // returns Unit inline fun <T> ArrayDeque<T>.pop() = removeLastOrNull() // returns T? fun <E> List<E>.histo() = this.groupingBy { it }.eachCount() fun <E> MutableList<E>.rotate(i: Int) = Collections.rotate(this, i) fun List<Int>.elemAdd(other: List<Int>) = this.mapIndexed { i, e -> e + other[i] } fun List<Int>.elemAdd(vararg other: Int) = this.mapIndexed { i, e -> e + other[i] } fun List<Int>.elemSubtract(other: List<Int>) = this.mapIndexed { i, e -> e - other[i] } fun <E> List<E>.subList(fromIndex: Int) = this.subList(fromIndex, this.size - 1)
0
Kotlin
0
1
be120257fbce5eda9b51d3d7b63b121824c6e877
3,173
adventofkotlin
MIT License
year2017/src/main/kotlin/net/olegg/aoc/year2017/day6/Day6.kt
0legg
110,665,187
false
{"Kotlin": 511989}
package net.olegg.aoc.year2017.day6 import net.olegg.aoc.someday.SomeDay import net.olegg.aoc.utils.parseInts import net.olegg.aoc.year2017.DayOf2017 /** * See [Year 2017, Day 6](https://adventofcode.com/2017/day/6) */ object Day6 : DayOf2017(6) { override fun first(): Any? { val blocks = data.parseInts("\t") val seen = mutableSetOf<List<Int>>() var curr = blocks var steps = 0 while (curr !in seen) { seen.add(curr) steps += 1 val max = curr.max() val position = curr.indexOfFirst { it == max } val add = max / curr.size val tail = max % curr.size curr = curr.mapIndexed { index, value -> return@mapIndexed add + (if (index == position) 0 else value) + (if (index in (position + 1)..(position + tail)) 1 else 0) + (if ((position + tail >= curr.size) && (index in 0..(position + tail) % curr.size)) 1 else 0) } } return steps } override fun second(): Any? { val blocks = data.parseInts("\t") val seen = mutableMapOf<List<Int>, Int>() var curr = blocks var steps = 0 while (curr !in seen) { seen[curr] = steps steps += 1 val max = curr.max() val position = curr.indexOfFirst { it == max } val add = max / curr.size val tail = max % curr.size curr = curr.mapIndexed { index, value -> return@mapIndexed add + (if (index == position) 0 else value) + (if (index in (position + 1)..(position + tail)) 1 else 0) + (if ((position + tail >= curr.size) && (index in 0..(position + tail) % curr.size)) 1 else 0) } } return steps - (seen[curr] ?: 0) } } fun main() = SomeDay.mainify(Day6)
0
Kotlin
1
7
e4a356079eb3a7f616f4c710fe1dfe781fc78b1a
1,725
adventofcode
MIT License
src/main/kotlin/days/Day16.kt
hughjdavey
433,597,582
false
{"Kotlin": 53042}
package days import util.Utils.takeWhileInclusive class Day16 : Day(16) { override fun partOne(): Any { return sumVersionNumbers(parse(hex2Bin(inputString.trim()))) } override fun partTwo(): Any { return calculatePacketExpression(parse(hex2Bin(inputString.trim()))) } fun sumVersionNumbers(packet: Packet, sum: Int = 0): Int { if (packet.subPackets.isEmpty()) { return packet.version + sum } return packet.subPackets.fold(packet.version + sum) { s, p -> s + sumVersionNumbers(p) } } fun calculatePacketExpression(packet: Packet, sum: Long = 0): Long { if (packet.typeId == 4) { return sum + packet.literalValue } return sum + when (packet.typeId) { 0 -> packet.subPackets.fold(0) { acc, sp -> acc + calculatePacketExpression(sp) } 1 -> packet.subPackets.fold(1) { acc, sp -> acc * calculatePacketExpression(sp) } 2 -> packet.subPackets.minOf { sp -> calculatePacketExpression(sp) } 3 -> packet.subPackets.maxOf { sp -> calculatePacketExpression(sp) } 5 -> if (calculatePacketExpression(packet.subPackets[0]) > calculatePacketExpression(packet.subPackets[1])) 1 else 0 6 -> if (calculatePacketExpression(packet.subPackets[0]) < calculatePacketExpression(packet.subPackets[1])) 1 else 0 7 -> if (calculatePacketExpression(packet.subPackets[0]) == calculatePacketExpression(packet.subPackets[1])) 1 else 0 else -> 0 } } fun parse(s: String): Packet { return getNextPacket(s).first } fun hex2Bin(hex: String): String { return hex.map { it.digitToInt(16).toString(2).padStart(4, '0') }.joinToString("") } private fun getNextPacket(s: String): Pair<Packet, String> { val (version, typeId) = s.substring(0, 3).toInt(2) to s.substring(3, 6).toInt(2) if (typeId == 4) { val remainder = s.substring(6) val content = remainder.chunked(5).takeWhileInclusive { it.startsWith('1') }.joinToString("") return Packet(version, typeId, content = content) to remainder.drop(content.length) } val lengthTypeId = s[6] return if (lengthTypeId == '0') { val subPacketsLength = s.substring(7, 22).toInt(2) val subPacketsAndRemainder = s.substring(22) val (extracted, remainder) = extractPacketsUntil(subPacketsAndRemainder) { length, _ -> length > subPacketsAndRemainder.length - subPacketsLength } Packet(version, typeId, subPackets = extracted.toMutableList()) to remainder } else { val subPacketsCount = s.substring(7, 18).toInt(2) val subPacketsAndRemainder = s.substring(18) val (extracted, remainder) = extractPacketsUntil(subPacketsAndRemainder) { _, count -> count < subPacketsCount } Packet(version, typeId, subPackets = extracted.toMutableList()) to remainder } } private fun extractPacketsUntil(s: String, condition: (len: Int, count: Int) -> Boolean): Pair<List<Packet>, String> { var counter = 0 var remainder = s val extracted = mutableListOf<Packet>() while (condition(remainder.length, counter++)) { val (packet, rem) = getNextPacket(remainder) extracted += packet remainder = rem } return extracted to remainder } data class Packet(val version: Int, val typeId: Int, val content: String = "", val subPackets: MutableList<Packet> = mutableListOf(), val ty: Int = 2) { val literalValue: Long by lazy { content.chunked(5).joinToString("") { it.drop(1) }.toLong(2) } } }
0
Kotlin
0
0
a3c2fe866f6b1811782d774a4317457f0882f5ef
3,740
aoc-2021
Creative Commons Zero v1.0 Universal
src/test/kotlin/Day21.kt
FredrikFolkesson
320,692,155
false
null
import org.junit.jupiter.api.Test import kotlin.test.assertEquals class Day21 { @Test fun `test demo input`() { val input = "mxmxvkd kfcds sqjhc nhms (contains dairy, fish)\n" + "trh fvjkl sbzzf mxmxvkd (contains dairy)\n" + "sqjhc fvjkl (contains soy)\n" + "sqjhc mxmxvkd sbzzf (contains fish)" println(countTimesNonAllergenicItemAppears(input)) } @Test fun `test real input`() { val input = readFileAsString("/Users/fredrikfolkesson/git/advent-of-code/inputs/input-day21.txt") println(countTimesNonAllergenicItemAppears(input)) } private fun countTimesNonAllergenicItemAppears(input: String): Int { val allIngredients = input.lines().map { parseFood(it) }.flatMap { it.values.first() }.toSet() val allergenMap = findAllergenMap(input) val nonAllergenics = allIngredients.filter { it !in allergenMap.values }.toSet() val allIngredientsList = input .lines() .map { parseFood(it) } .map { it.values.first() } val allIngredientsCount = mutableMapOf<String, Int>() allIngredientsList.forEach { it.forEach { ingredient -> allIngredientsCount[ingredient] = allIngredientsCount.getOrDefault(ingredient, 0) + 1 } } return allIngredientsCount.filter { it.key in nonAllergenics }.values.sum() } @Test fun `test demo input part 2`() { val input = "mxmxvkd kfcds sqjhc nhms (contains dairy, fish)\n" + "trh fvjkl sbzzf mxmxvkd (contains dairy)\n" + "sqjhc fvjkl (contains soy)\n" + "sqjhc mxmxvkd sbzzf (contains fish)" val allergenMap = findAllergenMap(input) println(allergenMap.toSortedMap().values.joinToString(",")) } @Test fun `test real input part 2`() { val input = readFileAsString("/Users/fredrikfolkesson/git/advent-of-code/inputs/input-day21.txt") val allergenMap = findAllergenMap(input) println(allergenMap.toSortedMap().values.joinToString(",")) } private fun findAllergenMap(foods: String): MutableMap<String, String> { val foundPossibleAllergens = mutableMapOf<String, MutableSet<String>>() //First remove intersections foods .lines() .map { parseFood(it) } .forEach { it.keys.forEach { key -> if (key in foundPossibleAllergens) { val currentPossibleAllergens = foundPossibleAllergens[key]!! foundPossibleAllergens[key] = currentPossibleAllergens.intersect(it.values.first()).toMutableSet() } else { //They are all the same foundPossibleAllergens[key] = it.values.first().toMutableSet() } } } val ingredientToAllergen = mutableMapOf<String,String>() while (foundPossibleAllergens.values.any { it.isNotEmpty() }) { val entryThatIsAnAllergen = foundPossibleAllergens.entries.first { it.value.size == 1 } val onlyOneIngredientForAllergen = entryThatIsAnAllergen.value.toList().first() ingredientToAllergen.put(entryThatIsAnAllergen.key,onlyOneIngredientForAllergen) foundPossibleAllergens.values.map { it.remove(onlyOneIngredientForAllergen) } } return ingredientToAllergen } @Test fun `test parse foodItem`() { assertEquals( mapOf( "fish" to setOf("mxmxvkd", "kfcds", "sqjhc", "nhms"), "dairy" to setOf("mxmxvkd", "kfcds", "sqjhc", "nhms") ), parseFood("mxmxvkd kfcds sqjhc nhms (contains dairy, fish)") ) assertEquals( mapOf("dairy" to setOf("trh", "fvjkl", "sbzzf", "mxmxvkd")), parseFood("trh fvjkl sbzzf mxmxvkd (contains dairy)") ) } private fun parseFood(input: String): Map<String, Set<String>> { val ingredients = input.split(" (contains ")[0].split(" ").toSet() return input.split(" (contains ")[1].replace(")", "").split(", ").map { it to ingredients }.toMap() } }
0
Kotlin
0
0
79a67f88e1fcf950e77459a4f3343353cfc1d48a
4,362
advent-of-code
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/DegreeOfArray.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.min /** * Degree of an Array * @see <a href="https://leetcode.com/problems/degree-of-an-array/">Source</a> */ object DegreeOfArray { fun findShortestSubArray(nums: IntArray): Int { if (nums.isEmpty()) return 0 val left: MutableMap<Int, Int> = HashMap() val right: MutableMap<Int, Int> = HashMap() val count: MutableMap<Int, Int> = HashMap() for (i in nums.indices) { val x = nums[i] if (left[x] == null) left[x] = i right[x] = i count[x] = count.getOrDefault(x, 0) + 1 } var ans: Int = nums.size val degree = count.values.max() for (x in count.keys) { if (count[x] == degree) { ans = min(ans, right.getOrDefault(x, 0) - left.getOrDefault(x, 0) + 1) } } return ans } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,519
kotlab
Apache License 2.0
src/questions/BestTimeStock.kt
realpacific
234,499,820
false
null
package questions import _utils.UseCommentAsDocumentation import utils.shouldBe import java.util.* /** * You are given an array prices where `prices[i]` is the price of a given stock on the ith day. * You want to maximize your profit by choosing a single day to buy one stock * and choosing a different day in the future to sell that stock. * Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0. * * [Source](https://leetcode.com/problems/best-time-to-buy-and-sell-stock/) * @see [BestTimeStockII] */ @UseCommentAsDocumentation private object BestTimeStock private fun maxProfit(prices: IntArray): Int { val maxPossibleSellPrice = Array<Int>(prices.size) { -1 } for (index in prices.lastIndex downTo 0) { // find the max sell price possible by filling in from the end // comparing max price in future and current price // for [3, 2, 6, 5, 0, 3] -> [6, 6, 6, 5, 3, 3] maxPossibleSellPrice[index] = maxOf(maxPossibleSellPrice.getOrNull(index + 1) ?: -1, prices[index]) } var result = 0 for (index in 0..prices.lastIndex) { val sellPrice = maxPossibleSellPrice[index] result = maxOf(sellPrice - prices[index], result) } return result } fun main() { maxProfit(intArrayOf(3, 2, 6, 5, 0, 3)) shouldBe 4 maxProfit(intArrayOf(7, 1, 5, 3, 6, 4)) shouldBe 5 maxProfit(intArrayOf(7, 6, 4, 3, 1)) shouldBe 0 }
4
Kotlin
5
93
22eef528ef1bea9b9831178b64ff2f5b1f61a51f
1,466
algorithms
MIT License
src/main/kotlin/com/leetcode/P48.kt
antop-dev
229,558,170
false
{"Kotlin": 695315, "Java": 213000}
package com.leetcode // https://github.com/antop-dev/algorithm/issues/280 class P48 { fun rotate(matrix: Array<IntArray>) { var p = 0 var length = matrix.size while (length > 1) { rotate(matrix, p++, length) length -= 2 } } private fun rotate(matrix: Array<IntArray>, p: Int, length: Int) { if (length == 1) return val max = p + length - 1 val list = mutableListOf<Int>() for (i in p until p + length) list += matrix[p][i] // 1 for (i in p + 1 until p + length) list += matrix[i][max] // 2 for (i in p + length - 2 downTo p) list += matrix[max][i] // 3 for (i in p + length - 2 downTo p + 1) list += matrix[i][p] // 4 repeat(length - 1) { list.add(0, list.removeAt(list.lastIndex)) } var k = 0 for (i in p until p + length) matrix[p][i] = list[k++] for (i in p + 1 until p + length) matrix[i][max] = list[k++] for (i in p + length - 2 downTo p) matrix[max][i] = list[k++] for (i in p + length - 2 downTo p + 1) matrix[i][p] = list[k++] } }
1
Kotlin
0
0
9a3e762af93b078a2abd0d97543123a06e327164
1,143
algorithm
MIT License
src/2021-Day04.kt
frozbiz
573,457,870
false
{"Kotlin": 124645}
class Board { fun callNumber(num: Int): Boolean { // println("${num} called") var win = false for (row in rows) { if (row.remove(num)) { win = row.isEmpty() // print("${num} found in row") // if (win) // print("-- win") // println() break } } for (col in cols) { if (col.remove(num)) { win = win || col.isEmpty() // print("${num} found in col") // if (col.isEmpty()) // print("-- win") // println() break } } return win } fun populateBoard(board: List<String>): Int { // flush any old values rows = mutableListOf<MutableSet<Int>>() cols = mutableListOf<MutableSet<Int>>() for (line in board) { if (line.isBlank()) { return rows.size + 1 } val nums = line.trim().split(Regex("\\D+")).map { it.toInt() } rows.add(nums.toMutableSet()) while (cols.size < nums.size) { cols.add(mutableSetOf()) } nums.forEachIndexed { ix, num -> cols[ix].add(num) } } return rows.size } fun score(): Int { return rows.map { it.sum() }.sum() } var rows = mutableListOf<MutableSet<Int>>() var cols = mutableListOf<MutableSet<Int>>() } fun main() { fun loadFromInput(input: List<String>): Pair<List<Int>, MutableList<Board>> { val guesses = input[0].trim().split(',').map { it.toInt() } val boards = mutableListOf<Board>() var ix = 2 // println("guesses: ${guesses}") while (ix < input.size) { val board = Board() ix += board.populateBoard(input.drop(ix)) boards.add(board) } return Pair(guesses, boards) } fun part1(input: List<String>): Int { val (guesses, boards) = loadFromInput(input) guesses.forEach { guess -> boards.forEach { if (it.callNumber(guess)) return it.score() * guess } } return 0 // not found } fun part2(input: List<String>): Int { val (guesses, boards) = loadFromInput(input) var lastScore = 0 for (guess in guesses) { boards.removeAll { val remove = it.callNumber(guess) if (remove) { lastScore = it.score() * guess } remove } if (boards.isEmpty()) break } return lastScore } // test if implementation meets criteria from the description, like: val testInput = listOf( "7,4,9,5,11,17,23,2,0,14,21,24,10,16,13,6,15,25,12,22,18,20,8,19,3,26,1\n", "\n", "22 13 17 11 0\n", " 8 2 23 4 24\n", "21 9 14 16 7\n", " 6 10 3 18 5\n", " 1 12 20 15 19\n", "\n", " 3 15 0 2 22\n", " 9 18 13 17 5\n", "19 8 7 25 23\n", "20 11 10 24 4\n", "14 21 16 12 6\n", "\n", "14 21 17 24 4\n", "10 16 15 9 19\n", "18 8 23 26 20\n", "22 11 13 6 5\n", " 2 0 12 3 7\n" ) val pt1_test = part1(testInput) println(pt1_test) check(pt1_test == 4512) val pt2_test = part2(testInput) println(pt2_test) check(pt2_test == 1924) val input = readInput("2021-day4") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
4feef3fa7cd5f3cea1957bed1d1ab5d1eb2bc388
3,617
2022-aoc-kotlin
Apache License 2.0
src/main/kotlin/Day8.kt
pavittr
317,532,861
false
null
import java.io.File import java.nio.charset.Charset fun main() { fun getAcc(inputDocs: List<String>): Pair<Int, Boolean> { val steps = inputDocs.mapIndexed { index, s -> Triple(index, s.split(" ")[0], s.split(" ")[1].toInt()) } val seen = mutableListOf<Triple<Int, String,Int>>() var step = steps[0] var acc = 0 while (!seen.contains(step)) { seen.add(step) if (step.second == "jmp") { val nextStep = step.first + step.third if (nextStep < steps.size) { step = steps[nextStep] } else { return Pair(acc, false) } } else { if (step.second == "acc") { acc += step.third } val nextStep = step.first + 1 if (nextStep < steps.size) { step = steps[nextStep] } else { return Pair(acc, false) } } } return Pair(acc, true) } val testDocs = File("test/day8").readLines(Charset.defaultCharset()) val puzzles = File("puzzles/day8").readLines(Charset.defaultCharset()) println(getAcc(testDocs)) println(getAcc(puzzles)) for (i in 0..testDocs.size) { val spareDocs = testDocs.mapIndexed { index, s -> var returnS = s ; if (index == i) {if (s.startsWith("jmp")) {returnS = s.replace("jmp", "nop")} else { returnS = s.replace("nop", "jmp") } } else {} ; returnS } val ans = getAcc(spareDocs) if (!ans.second) { println("Changing $i : ${ans.first}") } } for (i in 0..puzzles.size) { val spareDocs = puzzles.mapIndexed { index, s -> var returnS = s ; if (index == i) {if (s.startsWith("jmp")) {returnS = s.replace("jmp", "nop")} else { returnS = s.replace("nop", "jmp") } } else {} ; returnS } val ans = getAcc(spareDocs) if (!ans.second) { println("Changing $i : ${ans.first}") } } }
0
Kotlin
0
0
3d8c83a7fa8f5a8d0f129c20038e80a829ed7d04
2,082
aoc2020
Apache License 2.0
2017/src/main/java/p6/Problem6.kt
ununhexium
113,359,669
false
null
package p6 val input = """14 0 15 12 11 11 3 5 1 6 8 4 9 1 8 4""" fun main(args: Array<String>) { val ints = input.split(" ").map { it.toInt() } println(cycle(mutableListOf(0, 2, 7, 0))) println(cycle(ints.toMutableList())) } fun cycle(currentList: MutableList<Int>): Pair<Int, Int> { val lookup = HashSet<List<Int>>() val previous = ArrayList<List<Int>>() var cycles = 0 while (true) { val max = currentList.withIndex().maxBy { it.value }!! currentList[max.index] = 0 (1..max.value).forEach { currentList[(max.index + it) % currentList.size]++ } cycles++ if (lookup.contains(currentList)) break val copy = currentList.toList() lookup.add(copy) previous.add(copy) } val index = previous .mapIndexed { index, list -> index to list } .first { it.second == currentList } .first val interval = previous.size - index return cycles to interval }
6
Kotlin
0
0
d5c38e55b9574137ed6b351a64f80d764e7e61a9
925
adventofcode
The Unlicense
Algorithms/Search/Ice Cream Parlor/Solution.kt
ahmed-mahmoud-abo-elnaga
449,443,709
false
{"Kotlin": 14218}
/* Problem: https://www.hackerrank.com/challenges/ctci-ice-cream-parlor/problem Kotlin Language Version Tool Version : Android Studio Thoughts (Key points in algorithm): Keep track of the index and the complement value in a hasmap and as we can our input, check if we see a complement if we do see one then just print out its' index and our current index Time complexity: O(n) //The number of flavors we have to look at Space complexity: O(n) //The number of flavors we store the complement of */ object Main { fun whatFlavors(cost: Array<Int>, money: Int): Unit { var mapOfCost: HashMap<Int, Int> = HashMap() loop@ for (i in 0 until cost.size) { if (mapOfCost.containsKey(cost[i])) { println("${mapOfCost.get(cost[i])} ${i + 1}") break@loop } mapOfCost.put(money - cost[i], i + 1) } } fun main(args: Array<String>) { val t = readLine()!!.trim().toInt() for (tItr in 1..t) { val money = readLine()!!.trim().toInt() val n = readLine()!!.trim().toInt() val cost = readLine()!!.trimEnd().split(" ").map { it.toInt() }.toTypedArray() whatFlavors(cost, money) } } }
0
Kotlin
1
1
a65ee26d47b470b1cb2c1681e9d49fe48b7cb7fc
1,345
HackerRank
MIT License
src/Day01.kt
jamOne-
573,851,509
false
{"Kotlin": 20355}
fun main() { fun part1(input: List<String>): Int { val elves = readElves(input) return elves.max() } fun part2(input: List<String>): Int { val elves = readElves(input) val sortedElves = elves.sortedDescending() return sortedElves[0] + sortedElves[1] + sortedElves[2] } // 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)) } fun readElves(input: List<String>): MutableList<Int> { val elves = mutableListOf<Int>(); var currentElf = 0; for (line in input) { if (line.isEmpty()) { elves.add(currentElf); currentElf = 0; } else { currentElf += line.toInt(); } } elves.add(currentElf); return elves; }
0
Kotlin
0
0
77795045bc8e800190f00cd2051fe93eebad2aec
964
adventofcode2022
Apache License 2.0
src/main/kotlin/Day10.kt
Vampire
572,990,104
false
{"Kotlin": 57326}
import kotlin.math.abs fun main() { fun xValues(input: List<String>) = input .map { it.split(" ") } .flatMap { when (it.first()) { "noop" -> listOf(0) "addx" -> listOf(0, it.last().toInt()) else -> error("Unexpected instruction ${it.first()}") } } .let { it.toMutableList().apply { add(0, 1) } } .let { xChanges -> (1..xChanges.size).map { xChanges.take(it).sum() } } fun part1(input: List<String>) = xValues(input) .let { (20..220 step 40).map { cycle -> cycle * it[cycle - 1] } } .sum() fun part2(input: List<String>): String { val xValues = xValues(input) val output = StringBuilder() for (row in 0..5) { for (column in 0..39) { val cycle = (row * 40) + column + 1 output.append(if (abs(xValues[cycle - 1] - column) <= 1) '#' else '.') } output.append('\n') } return "$output" } val testInput = readStrings("Day10_test") check(part1(testInput) == 13_140) val input = readStrings("Day10") println(part1(input)) check( part2(testInput).trimIndent() == """ ##..##..##..##..##..##..##..##..##..##.. ###...###...###...###...###...###...###. ####....####....####....####....####.... #####.....#####.....#####.....#####..... ######......######......######......#### #######.......#######.......#######..... """.trimIndent() ) println(part2(input)) }
0
Kotlin
0
0
16a31a0b353f4b1ce3c6e9cdccbf8f0cadde1f1f
1,688
aoc-2022
Apache License 2.0